babylon.2.1-beta.debug.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  589. var d0 = Vector3.Dot(vector0, axis) - size;
  590. var d1 = Vector3.Dot(vector1, axis) - size;
  591. var s = d0 / (d0 - d1);
  592. return s;
  593. };
  594. Vector3.FromArray = function (array, offset) {
  595. if (!offset) {
  596. offset = 0;
  597. }
  598. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  599. };
  600. Vector3.FromArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  606. result.x = array[offset];
  607. result.y = array[offset + 1];
  608. result.z = array[offset + 2];
  609. };
  610. Vector3.FromFloatsToRef = function (x, y, z, result) {
  611. result.x = x;
  612. result.y = y;
  613. result.z = z;
  614. };
  615. Vector3.Zero = function () {
  616. return new Vector3(0, 0, 0);
  617. };
  618. Vector3.Up = function () {
  619. return new Vector3(0, 1.0, 0);
  620. };
  621. Vector3.TransformCoordinates = function (vector, transformation) {
  622. var result = Vector3.Zero();
  623. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  624. return result;
  625. };
  626. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  627. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  628. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  629. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  630. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  631. result.x = x / w;
  632. result.y = y / w;
  633. result.z = z / w;
  634. };
  635. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  636. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  637. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  638. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  639. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  640. result.x = rx / rw;
  641. result.y = ry / rw;
  642. result.z = rz / rw;
  643. };
  644. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  645. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  646. var m0 = SIMD.float32x4.load(transformation.m, 0);
  647. var m1 = SIMD.float32x4.load(transformation.m, 4);
  648. var m2 = SIMD.float32x4.load(transformation.m, 8);
  649. var m3 = SIMD.float32x4.load(transformation.m, 12);
  650. 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));
  651. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  652. SIMD.float32x4.storeXYZ(result._data, 0, r);
  653. };
  654. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  655. var v0 = SIMD.float32x4.splat(x);
  656. var v1 = SIMD.float32x4.splat(y);
  657. var v2 = SIMD.float32x4.splat(z);
  658. var m0 = SIMD.float32x4.load(transformation.m, 0);
  659. var m1 = SIMD.float32x4.load(transformation.m, 4);
  660. var m2 = SIMD.float32x4.load(transformation.m, 8);
  661. var m3 = SIMD.float32x4.load(transformation.m, 12);
  662. 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));
  663. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  664. SIMD.float32x4.storeXYZ(result._data, 0, r);
  665. };
  666. Vector3.TransformNormal = function (vector, transformation) {
  667. var result = Vector3.Zero();
  668. Vector3.TransformNormalToRef(vector, transformation, result);
  669. return result;
  670. };
  671. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  672. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  673. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  674. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  675. };
  676. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  677. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  678. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  679. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  680. };
  681. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  682. var squared = amount * amount;
  683. var cubed = amount * squared;
  684. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  685. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  686. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  687. return new Vector3(x, y, z);
  688. };
  689. Vector3.Clamp = function (value, min, max) {
  690. var x = value.x;
  691. x = (x > max.x) ? max.x : x;
  692. x = (x < min.x) ? min.x : x;
  693. var y = value.y;
  694. y = (y > max.y) ? max.y : y;
  695. y = (y < min.y) ? min.y : y;
  696. var z = value.z;
  697. z = (z > max.z) ? max.z : z;
  698. z = (z < min.z) ? min.z : z;
  699. return new Vector3(x, y, z);
  700. };
  701. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  702. var squared = amount * amount;
  703. var cubed = amount * squared;
  704. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  705. var part2 = (-2.0 * cubed) + (3.0 * squared);
  706. var part3 = (cubed - (2.0 * squared)) + amount;
  707. var part4 = cubed - squared;
  708. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  709. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  710. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Lerp = function (start, end, amount) {
  714. var x = start.x + ((end.x - start.x) * amount);
  715. var y = start.y + ((end.y - start.y) * amount);
  716. var z = start.z + ((end.z - start.z) * amount);
  717. return new Vector3(x, y, z);
  718. };
  719. Vector3.Dot = function (left, right) {
  720. return (left.x * right.x + left.y * right.y + left.z * right.z);
  721. };
  722. Vector3.Cross = function (left, right) {
  723. var result = Vector3.Zero();
  724. Vector3.CrossToRef(left, right, result);
  725. return result;
  726. };
  727. Vector3.CrossToRef = function (left, right, result) {
  728. result.x = left.y * right.z - left.z * right.y;
  729. result.y = left.z * right.x - left.x * right.z;
  730. result.z = left.x * right.y - left.y * right.x;
  731. };
  732. Vector3.Normalize = function (vector) {
  733. var result = Vector3.Zero();
  734. Vector3.NormalizeToRef(vector, result);
  735. return result;
  736. };
  737. Vector3.NormalizeToRef = function (vector, result) {
  738. result.copyFrom(vector);
  739. result.normalize();
  740. };
  741. Vector3.Project = function (vector, world, transform, viewport) {
  742. var cw = viewport.width;
  743. var ch = viewport.height;
  744. var cx = viewport.x;
  745. var cy = viewport.y;
  746. 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);
  747. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  748. return Vector3.TransformCoordinates(vector, finalMatrix);
  749. };
  750. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  751. var matrix = world.multiply(transform);
  752. matrix.invert();
  753. source.x = source.x / viewportWidth * 2 - 1;
  754. source.y = -(source.y / viewportHeight * 2 - 1);
  755. var vector = Vector3.TransformCoordinates(source, matrix);
  756. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  757. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  758. vector = vector.scale(1.0 / num);
  759. }
  760. return vector;
  761. };
  762. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  763. var matrix = world.multiply(view).multiply(projection);
  764. matrix.invert();
  765. source.x = source.x / viewportWidth * 2 - 1;
  766. source.y = -(source.y / viewportHeight * 2 - 1);
  767. var vector = Vector3.TransformCoordinates(source, matrix);
  768. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  769. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  770. vector = vector.scale(1.0 / num);
  771. }
  772. return vector;
  773. };
  774. Vector3.Minimize = function (left, right) {
  775. var min = left.clone();
  776. min.MinimizeInPlace(right);
  777. return min;
  778. };
  779. Vector3.Maximize = function (left, right) {
  780. var max = left.clone();
  781. max.MaximizeInPlace(right);
  782. return max;
  783. };
  784. Vector3.Distance = function (value1, value2) {
  785. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  786. };
  787. Vector3.DistanceSquared = function (value1, value2) {
  788. var x = value1.x - value2.x;
  789. var y = value1.y - value2.y;
  790. var z = value1.z - value2.z;
  791. return (x * x) + (y * y) + (z * z);
  792. };
  793. Vector3.Center = function (value1, value2) {
  794. var center = value1.add(value2);
  795. center.scaleInPlace(0.5);
  796. return center;
  797. };
  798. return Vector3;
  799. })();
  800. BABYLON.Vector3 = Vector3;
  801. //Vector4 class created for EulerAngle class conversion to Quaternion
  802. var Vector4 = (function () {
  803. function Vector4(x, y, z, w) {
  804. this.x = x;
  805. this.y = y;
  806. this.z = z;
  807. this.w = w;
  808. }
  809. Vector4.prototype.toString = function () {
  810. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  811. };
  812. // Operators
  813. Vector4.prototype.asArray = function () {
  814. var result = [];
  815. this.toArray(result, 0);
  816. return result;
  817. };
  818. Vector4.prototype.toArray = function (array, index) {
  819. if (index === undefined) {
  820. index = 0;
  821. }
  822. array[index] = this.x;
  823. array[index + 1] = this.y;
  824. array[index + 2] = this.z;
  825. array[index + 3] = this.w;
  826. return this;
  827. };
  828. Vector4.prototype.addInPlace = function (otherVector) {
  829. this.x += otherVector.x;
  830. this.y += otherVector.y;
  831. this.z += otherVector.z;
  832. this.w += otherVector.w;
  833. return this;
  834. };
  835. Vector4.prototype.add = function (otherVector) {
  836. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  837. };
  838. Vector4.prototype.addToRef = function (otherVector, result) {
  839. result.x = this.x + otherVector.x;
  840. result.y = this.y + otherVector.y;
  841. result.z = this.z + otherVector.z;
  842. result.w = this.w + otherVector.w;
  843. return this;
  844. };
  845. Vector4.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. this.z -= otherVector.z;
  849. this.w -= otherVector.w;
  850. return this;
  851. };
  852. Vector4.prototype.subtract = function (otherVector) {
  853. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  854. };
  855. Vector4.prototype.subtractToRef = function (otherVector, result) {
  856. result.x = this.x - otherVector.x;
  857. result.y = this.y - otherVector.y;
  858. result.z = this.z - otherVector.z;
  859. result.w = this.w - otherVector.w;
  860. return this;
  861. };
  862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  864. };
  865. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  866. result.x = this.x - x;
  867. result.y = this.y - y;
  868. result.z = this.z - z;
  869. result.w = this.w - w;
  870. return this;
  871. };
  872. Vector4.prototype.negate = function () {
  873. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  874. };
  875. Vector4.prototype.scaleInPlace = function (scale) {
  876. this.x *= scale;
  877. this.y *= scale;
  878. this.z *= scale;
  879. this.w *= scale;
  880. return this;
  881. };
  882. Vector4.prototype.scale = function (scale) {
  883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  884. };
  885. Vector4.prototype.scaleToRef = function (scale, result) {
  886. result.x = this.x * scale;
  887. result.y = this.y * scale;
  888. result.z = this.z * scale;
  889. result.w = this.w * scale;
  890. };
  891. Vector4.prototype.equals = function (otherVector) {
  892. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  893. };
  894. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  895. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  896. };
  897. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  898. return this.x === x && this.y === y && this.z === z && this.w === w;
  899. };
  900. Vector4.prototype.multiplyInPlace = function (otherVector) {
  901. this.x *= otherVector.x;
  902. this.y *= otherVector.y;
  903. this.z *= otherVector.z;
  904. this.w *= otherVector.w;
  905. return this;
  906. };
  907. Vector4.prototype.multiply = function (otherVector) {
  908. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  909. };
  910. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  911. result.x = this.x * otherVector.x;
  912. result.y = this.y * otherVector.y;
  913. result.z = this.z * otherVector.z;
  914. result.w = this.w * otherVector.w;
  915. return this;
  916. };
  917. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  918. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  919. };
  920. Vector4.prototype.divide = function (otherVector) {
  921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  922. };
  923. Vector4.prototype.divideToRef = function (otherVector, result) {
  924. result.x = this.x / otherVector.x;
  925. result.y = this.y / otherVector.y;
  926. result.z = this.z / otherVector.z;
  927. result.w = this.w / otherVector.w;
  928. return this;
  929. };
  930. Vector4.prototype.MinimizeInPlace = function (other) {
  931. if (other.x < this.x)
  932. this.x = other.x;
  933. if (other.y < this.y)
  934. this.y = other.y;
  935. if (other.z < this.z)
  936. this.z = other.z;
  937. if (other.w < this.w)
  938. this.w = other.w;
  939. return this;
  940. };
  941. Vector4.prototype.MaximizeInPlace = function (other) {
  942. if (other.x > this.x)
  943. this.x = other.x;
  944. if (other.y > this.y)
  945. this.y = other.y;
  946. if (other.z > this.z)
  947. this.z = other.z;
  948. if (other.w > this.w)
  949. this.w = other.w;
  950. return this;
  951. };
  952. // Properties
  953. Vector4.prototype.length = function () {
  954. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  955. };
  956. Vector4.prototype.lengthSquared = function () {
  957. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  958. };
  959. // Methods
  960. Vector4.prototype.normalize = function () {
  961. var len = this.length();
  962. if (len === 0)
  963. return this;
  964. var num = 1.0 / len;
  965. this.x *= num;
  966. this.y *= num;
  967. this.z *= num;
  968. this.w *= num;
  969. return this;
  970. };
  971. Vector4.prototype.clone = function () {
  972. return new Vector4(this.x, this.y, this.z, this.w);
  973. };
  974. Vector4.prototype.copyFrom = function (source) {
  975. this.x = source.x;
  976. this.y = source.y;
  977. this.z = source.z;
  978. this.w = source.w;
  979. return this;
  980. };
  981. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. this.w = w;
  986. return this;
  987. };
  988. // Statics
  989. Vector4.FromArray = function (array, offset) {
  990. if (!offset) {
  991. offset = 0;
  992. }
  993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  994. };
  995. Vector4.FromArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1002. result.x = array[offset];
  1003. result.y = array[offset + 1];
  1004. result.z = array[offset + 2];
  1005. result.w = array[offset + 3];
  1006. };
  1007. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1008. result.x = x;
  1009. result.y = y;
  1010. result.z = z;
  1011. result.w = w;
  1012. };
  1013. Vector4.Zero = function () {
  1014. return new Vector4(0, 0, 0, 0);
  1015. };
  1016. Vector4.Normalize = function (vector) {
  1017. var result = Vector4.Zero();
  1018. Vector4.NormalizeToRef(vector, result);
  1019. return result;
  1020. };
  1021. Vector4.NormalizeToRef = function (vector, result) {
  1022. result.copyFrom(vector);
  1023. result.normalize();
  1024. };
  1025. Vector4.Minimize = function (left, right) {
  1026. var min = left.clone();
  1027. min.MinimizeInPlace(right);
  1028. return min;
  1029. };
  1030. Vector4.Maximize = function (left, right) {
  1031. var max = left.clone();
  1032. max.MaximizeInPlace(right);
  1033. return max;
  1034. };
  1035. Vector4.Distance = function (value1, value2) {
  1036. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1037. };
  1038. Vector4.DistanceSquared = function (value1, value2) {
  1039. var x = value1.x - value2.x;
  1040. var y = value1.y - value2.y;
  1041. var z = value1.z - value2.z;
  1042. var w = value1.w - value2.w;
  1043. return (x * x) + (y * y) + (z * z) + (w * w);
  1044. };
  1045. Vector4.Center = function (value1, value2) {
  1046. var center = value1.add(value2);
  1047. center.scaleInPlace(0.5);
  1048. return center;
  1049. };
  1050. return Vector4;
  1051. })();
  1052. BABYLON.Vector4 = Vector4;
  1053. var Quaternion = (function () {
  1054. function Quaternion(x, y, z, w) {
  1055. if (x === void 0) { x = 0; }
  1056. if (y === void 0) { y = 0; }
  1057. if (z === void 0) { z = 0; }
  1058. if (w === void 0) { w = 1; }
  1059. this.x = x;
  1060. this.y = y;
  1061. this.z = z;
  1062. this.w = w;
  1063. }
  1064. Quaternion.prototype.toString = function () {
  1065. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1066. };
  1067. Quaternion.prototype.asArray = function () {
  1068. return [this.x, this.y, this.z, this.w];
  1069. };
  1070. Quaternion.prototype.equals = function (otherQuaternion) {
  1071. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1072. };
  1073. Quaternion.prototype.clone = function () {
  1074. return new Quaternion(this.x, this.y, this.z, this.w);
  1075. };
  1076. Quaternion.prototype.copyFrom = function (other) {
  1077. this.x = other.x;
  1078. this.y = other.y;
  1079. this.z = other.z;
  1080. this.w = other.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1084. this.x = x;
  1085. this.y = y;
  1086. this.z = z;
  1087. this.w = w;
  1088. return this;
  1089. };
  1090. Quaternion.prototype.add = function (other) {
  1091. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1092. };
  1093. Quaternion.prototype.subtract = function (other) {
  1094. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1095. };
  1096. Quaternion.prototype.scale = function (value) {
  1097. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1098. };
  1099. Quaternion.prototype.multiply = function (q1) {
  1100. var result = new Quaternion(0, 0, 0, 1.0);
  1101. this.multiplyToRef(q1, result);
  1102. return result;
  1103. };
  1104. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1105. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1106. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1107. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1108. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1109. return this;
  1110. };
  1111. Quaternion.prototype.length = function () {
  1112. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1113. };
  1114. Quaternion.prototype.normalize = function () {
  1115. var length = 1.0 / this.length();
  1116. this.x *= length;
  1117. this.y *= length;
  1118. this.z *= length;
  1119. this.w *= length;
  1120. return this;
  1121. };
  1122. Quaternion.prototype.toEulerAngles = function () {
  1123. var result = Vector3.Zero();
  1124. this.toEulerAnglesToRef(result);
  1125. return result;
  1126. };
  1127. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1128. //result is an EulerAngles in the in the z-x-z convention
  1129. var qx = this.x;
  1130. var qy = this.y;
  1131. var qz = this.z;
  1132. var qw = this.w;
  1133. var qxy = qx * qy;
  1134. var qxz = qx * qz;
  1135. var qwy = qw * qy;
  1136. var qwz = qw * qz;
  1137. var qwx = qw * qx;
  1138. var qyz = qy * qz;
  1139. var sqx = qx * qx;
  1140. var sqy = qy * qy;
  1141. var determinant = sqx + sqy;
  1142. if (determinant !== 0.000 && determinant !== 1.000) {
  1143. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1144. result.y = Math.acos(1 - 2 * determinant);
  1145. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1146. }
  1147. else {
  1148. if (determinant === 0.0) {
  1149. result.x = 0.0;
  1150. result.y = 0.0;
  1151. 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)
  1152. }
  1153. else {
  1154. 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)
  1155. result.y = Math.PI;
  1156. result.z = 0.0;
  1157. }
  1158. }
  1159. return this;
  1160. };
  1161. Quaternion.prototype.toRotationMatrix = function (result) {
  1162. var xx = this.x * this.x;
  1163. var yy = this.y * this.y;
  1164. var zz = this.z * this.z;
  1165. var xy = this.x * this.y;
  1166. var zw = this.z * this.w;
  1167. var zx = this.z * this.x;
  1168. var yw = this.y * this.w;
  1169. var yz = this.y * this.z;
  1170. var xw = this.x * this.w;
  1171. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1172. result.m[1] = 2.0 * (xy + zw);
  1173. result.m[2] = 2.0 * (zx - yw);
  1174. result.m[3] = 0;
  1175. result.m[4] = 2.0 * (xy - zw);
  1176. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1177. result.m[6] = 2.0 * (yz + xw);
  1178. result.m[7] = 0;
  1179. result.m[8] = 2.0 * (zx + yw);
  1180. result.m[9] = 2.0 * (yz - xw);
  1181. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1182. result.m[11] = 0;
  1183. result.m[12] = 0;
  1184. result.m[13] = 0;
  1185. result.m[14] = 0;
  1186. result.m[15] = 1.0;
  1187. return this;
  1188. };
  1189. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1190. Quaternion.FromRotationMatrixToRef(matrix, this);
  1191. return this;
  1192. };
  1193. // Statics
  1194. Quaternion.FromRotationMatrix = function (matrix) {
  1195. var result = new Quaternion();
  1196. Quaternion.FromRotationMatrixToRef(matrix, result);
  1197. return result;
  1198. };
  1199. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1200. var data = matrix.m;
  1201. var m11 = data[0], m12 = data[4], m13 = data[8];
  1202. var m21 = data[1], m22 = data[5], m23 = data[9];
  1203. var m31 = data[2], m32 = data[6], m33 = data[10];
  1204. var trace = m11 + m22 + m33;
  1205. var s;
  1206. if (trace > 0) {
  1207. s = 0.5 / Math.sqrt(trace + 1.0);
  1208. result.w = 0.25 / s;
  1209. result.x = (m32 - m23) * s;
  1210. result.y = (m13 - m31) * s;
  1211. result.z = (m21 - m12) * s;
  1212. }
  1213. else if (m11 > m22 && m11 > m33) {
  1214. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1215. result.w = (m32 - m23) / s;
  1216. result.x = 0.25 * s;
  1217. result.y = (m12 + m21) / s;
  1218. result.z = (m13 + m31) / s;
  1219. }
  1220. else if (m22 > m33) {
  1221. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1222. result.w = (m13 - m31) / s;
  1223. result.x = (m12 + m21) / s;
  1224. result.y = 0.25 * s;
  1225. result.z = (m23 + m32) / s;
  1226. }
  1227. else {
  1228. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1229. result.w = (m21 - m12) / s;
  1230. result.x = (m13 + m31) / s;
  1231. result.y = (m23 + m32) / s;
  1232. result.z = 0.25 * s;
  1233. }
  1234. };
  1235. Quaternion.Inverse = function (q) {
  1236. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1237. };
  1238. Quaternion.Identity = function () {
  1239. return new Quaternion(0, 0, 0, 1);
  1240. };
  1241. Quaternion.RotationAxis = function (axis, angle) {
  1242. var result = new Quaternion();
  1243. var sin = Math.sin(angle / 2);
  1244. result.w = Math.cos(angle / 2);
  1245. result.x = axis.x * sin;
  1246. result.y = axis.y * sin;
  1247. result.z = axis.z * sin;
  1248. return result;
  1249. };
  1250. Quaternion.FromArray = function (array, offset) {
  1251. if (!offset) {
  1252. offset = 0;
  1253. }
  1254. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1255. };
  1256. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1257. var result = new Quaternion();
  1258. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1259. return result;
  1260. };
  1261. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1262. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1263. var halfRoll = roll * 0.5;
  1264. var halfPitch = pitch * 0.5;
  1265. var halfYaw = yaw * 0.5;
  1266. var sinRoll = Math.sin(halfRoll);
  1267. var cosRoll = Math.cos(halfRoll);
  1268. var sinPitch = Math.sin(halfPitch);
  1269. var cosPitch = Math.cos(halfPitch);
  1270. var sinYaw = Math.sin(halfYaw);
  1271. var cosYaw = Math.cos(halfYaw);
  1272. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1273. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1274. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1275. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1276. };
  1277. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1278. var result = new Quaternion();
  1279. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1280. return result;
  1281. };
  1282. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1283. // Produces a quaternion from Euler angles in the z-x-z orientation
  1284. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1285. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1286. var halfBeta = beta * 0.5;
  1287. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1288. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1289. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1290. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1291. };
  1292. Quaternion.Slerp = function (left, right, amount) {
  1293. var num2;
  1294. var num3;
  1295. var num = amount;
  1296. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1297. var flag = false;
  1298. if (num4 < 0) {
  1299. flag = true;
  1300. num4 = -num4;
  1301. }
  1302. if (num4 > 0.999999) {
  1303. num3 = 1 - num;
  1304. num2 = flag ? -num : num;
  1305. }
  1306. else {
  1307. var num5 = Math.acos(num4);
  1308. var num6 = (1.0 / Math.sin(num5));
  1309. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1310. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1311. }
  1312. 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));
  1313. };
  1314. return Quaternion;
  1315. })();
  1316. BABYLON.Quaternion = Quaternion;
  1317. var Matrix = (function () {
  1318. function Matrix() {
  1319. this.m = new Float32Array(16);
  1320. }
  1321. // Properties
  1322. Matrix.prototype.isIdentity = function () {
  1323. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1324. return false;
  1325. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1326. return false;
  1327. return true;
  1328. };
  1329. Matrix.prototype.determinant = function () {
  1330. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1331. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1332. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1333. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1334. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1335. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1336. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1337. };
  1338. // Methods
  1339. Matrix.prototype.toArray = function () {
  1340. return this.m;
  1341. };
  1342. Matrix.prototype.asArray = function () {
  1343. return this.toArray();
  1344. };
  1345. Matrix.prototype.invert = function () {
  1346. this.invertToRef(this);
  1347. return this;
  1348. };
  1349. Matrix.prototype.invertToRef = function (other) {
  1350. var l1 = this.m[0];
  1351. var l2 = this.m[1];
  1352. var l3 = this.m[2];
  1353. var l4 = this.m[3];
  1354. var l5 = this.m[4];
  1355. var l6 = this.m[5];
  1356. var l7 = this.m[6];
  1357. var l8 = this.m[7];
  1358. var l9 = this.m[8];
  1359. var l10 = this.m[9];
  1360. var l11 = this.m[10];
  1361. var l12 = this.m[11];
  1362. var l13 = this.m[12];
  1363. var l14 = this.m[13];
  1364. var l15 = this.m[14];
  1365. var l16 = this.m[15];
  1366. var l17 = (l11 * l16) - (l12 * l15);
  1367. var l18 = (l10 * l16) - (l12 * l14);
  1368. var l19 = (l10 * l15) - (l11 * l14);
  1369. var l20 = (l9 * l16) - (l12 * l13);
  1370. var l21 = (l9 * l15) - (l11 * l13);
  1371. var l22 = (l9 * l14) - (l10 * l13);
  1372. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1373. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1374. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1375. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1376. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1377. var l28 = (l7 * l16) - (l8 * l15);
  1378. var l29 = (l6 * l16) - (l8 * l14);
  1379. var l30 = (l6 * l15) - (l7 * l14);
  1380. var l31 = (l5 * l16) - (l8 * l13);
  1381. var l32 = (l5 * l15) - (l7 * l13);
  1382. var l33 = (l5 * l14) - (l6 * l13);
  1383. var l34 = (l7 * l12) - (l8 * l11);
  1384. var l35 = (l6 * l12) - (l8 * l10);
  1385. var l36 = (l6 * l11) - (l7 * l10);
  1386. var l37 = (l5 * l12) - (l8 * l9);
  1387. var l38 = (l5 * l11) - (l7 * l9);
  1388. var l39 = (l5 * l10) - (l6 * l9);
  1389. other.m[0] = l23 * l27;
  1390. other.m[4] = l24 * l27;
  1391. other.m[8] = l25 * l27;
  1392. other.m[12] = l26 * l27;
  1393. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1394. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1395. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1396. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1397. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1398. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1399. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1400. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1401. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1402. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1403. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1404. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1405. return this;
  1406. };
  1407. Matrix.prototype.invertToRefSIMD = function (other) {
  1408. var src = this.m;
  1409. var dest = other.m;
  1410. var row0, row1, row2, row3;
  1411. var tmp1;
  1412. var minor0, minor1, minor2, minor3;
  1413. var det;
  1414. // Load the 4 rows
  1415. var src0 = SIMD.float32x4.load(src, 0);
  1416. var src1 = SIMD.float32x4.load(src, 4);
  1417. var src2 = SIMD.float32x4.load(src, 8);
  1418. var src3 = SIMD.float32x4.load(src, 12);
  1419. // Transpose the source matrix. Sort of. Not a true transpose operation
  1420. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1421. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1422. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1423. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1424. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1425. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1426. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1427. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1428. // This is a true transposition, but it will lead to an incorrect result
  1429. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1430. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1431. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1432. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1433. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1434. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1435. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1436. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1437. // ----
  1438. tmp1 = SIMD.float32x4.mul(row2, row3);
  1439. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1440. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1441. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1443. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1444. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1445. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. // ----
  1447. tmp1 = SIMD.float32x4.mul(row1, row2);
  1448. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1449. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1450. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1452. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1453. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1454. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1455. // ----
  1456. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1457. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1458. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1460. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1462. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1463. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1464. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1465. // ----
  1466. tmp1 = SIMD.float32x4.mul(row0, row1);
  1467. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1468. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1469. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1471. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1472. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1473. // ----
  1474. tmp1 = SIMD.float32x4.mul(row0, row3);
  1475. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1476. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1477. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1480. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1481. // ----
  1482. tmp1 = SIMD.float32x4.mul(row0, row2);
  1483. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1484. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1485. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1486. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1487. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1488. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1489. // Compute determinant
  1490. det = SIMD.float32x4.mul(row0, minor0);
  1491. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1492. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1493. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1494. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1495. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1496. // These shuffles aren't necessary if the faulty transposition is done
  1497. // up at the top of this function.
  1498. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1499. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1500. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1501. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1502. // Compute final values by multiplying with 1/det
  1503. minor0 = SIMD.float32x4.mul(det, minor0);
  1504. minor1 = SIMD.float32x4.mul(det, minor1);
  1505. minor2 = SIMD.float32x4.mul(det, minor2);
  1506. minor3 = SIMD.float32x4.mul(det, minor3);
  1507. SIMD.float32x4.store(dest, 0, minor0);
  1508. SIMD.float32x4.store(dest, 4, minor1);
  1509. SIMD.float32x4.store(dest, 8, minor2);
  1510. SIMD.float32x4.store(dest, 12, minor3);
  1511. return this;
  1512. };
  1513. Matrix.prototype.setTranslation = function (vector3) {
  1514. this.m[12] = vector3.x;
  1515. this.m[13] = vector3.y;
  1516. this.m[14] = vector3.z;
  1517. return this;
  1518. };
  1519. Matrix.prototype.multiply = function (other) {
  1520. var result = new Matrix();
  1521. this.multiplyToRef(other, result);
  1522. return result;
  1523. };
  1524. Matrix.prototype.copyFrom = function (other) {
  1525. for (var index = 0; index < 16; index++) {
  1526. this.m[index] = other.m[index];
  1527. }
  1528. return this;
  1529. };
  1530. Matrix.prototype.copyToArray = function (array, offset) {
  1531. if (offset === void 0) { offset = 0; }
  1532. for (var index = 0; index < 16; index++) {
  1533. array[offset + index] = this.m[index];
  1534. }
  1535. return this;
  1536. };
  1537. Matrix.prototype.multiplyToRef = function (other, result) {
  1538. this.multiplyToArray(other, result.m, 0);
  1539. return this;
  1540. };
  1541. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1542. var tm0 = this.m[0];
  1543. var tm1 = this.m[1];
  1544. var tm2 = this.m[2];
  1545. var tm3 = this.m[3];
  1546. var tm4 = this.m[4];
  1547. var tm5 = this.m[5];
  1548. var tm6 = this.m[6];
  1549. var tm7 = this.m[7];
  1550. var tm8 = this.m[8];
  1551. var tm9 = this.m[9];
  1552. var tm10 = this.m[10];
  1553. var tm11 = this.m[11];
  1554. var tm12 = this.m[12];
  1555. var tm13 = this.m[13];
  1556. var tm14 = this.m[14];
  1557. var tm15 = this.m[15];
  1558. var om0 = other.m[0];
  1559. var om1 = other.m[1];
  1560. var om2 = other.m[2];
  1561. var om3 = other.m[3];
  1562. var om4 = other.m[4];
  1563. var om5 = other.m[5];
  1564. var om6 = other.m[6];
  1565. var om7 = other.m[7];
  1566. var om8 = other.m[8];
  1567. var om9 = other.m[9];
  1568. var om10 = other.m[10];
  1569. var om11 = other.m[11];
  1570. var om12 = other.m[12];
  1571. var om13 = other.m[13];
  1572. var om14 = other.m[14];
  1573. var om15 = other.m[15];
  1574. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1575. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1576. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1577. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1578. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1579. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1580. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1581. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1582. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1583. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1584. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1585. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1586. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1587. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1588. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1589. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1590. return this;
  1591. };
  1592. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1593. if (offset === void 0) { offset = 0; }
  1594. var tm = this.m;
  1595. var om = other.m;
  1596. var om0 = SIMD.float32x4.load(om, 0);
  1597. var om1 = SIMD.float32x4.load(om, 4);
  1598. var om2 = SIMD.float32x4.load(om, 8);
  1599. var om3 = SIMD.float32x4.load(om, 12);
  1600. var tm0 = SIMD.float32x4.load(tm, 0);
  1601. 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)))));
  1602. var tm1 = SIMD.float32x4.load(tm, 4);
  1603. 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)))));
  1604. var tm2 = SIMD.float32x4.load(tm, 8);
  1605. 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)))));
  1606. var tm3 = SIMD.float32x4.load(tm, 12);
  1607. 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)))));
  1608. };
  1609. Matrix.prototype.equals = function (value) {
  1610. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1611. };
  1612. Matrix.prototype.clone = function () {
  1613. 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]);
  1614. };
  1615. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1616. translation.x = this.m[12];
  1617. translation.y = this.m[13];
  1618. translation.z = this.m[14];
  1619. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1620. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1621. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1622. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1623. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1624. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1625. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1626. rotation.x = 0;
  1627. rotation.y = 0;
  1628. rotation.z = 0;
  1629. rotation.w = 1;
  1630. return false;
  1631. }
  1632. 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);
  1633. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1634. return true;
  1635. };
  1636. // Statics
  1637. Matrix.FromArray = function (array, offset) {
  1638. var result = new Matrix();
  1639. if (!offset) {
  1640. offset = 0;
  1641. }
  1642. Matrix.FromArrayToRef(array, offset, result);
  1643. return result;
  1644. };
  1645. Matrix.FromArrayToRef = function (array, offset, result) {
  1646. for (var index = 0; index < 16; index++) {
  1647. result.m[index] = array[index + offset];
  1648. }
  1649. };
  1650. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1651. result.m[0] = initialM11;
  1652. result.m[1] = initialM12;
  1653. result.m[2] = initialM13;
  1654. result.m[3] = initialM14;
  1655. result.m[4] = initialM21;
  1656. result.m[5] = initialM22;
  1657. result.m[6] = initialM23;
  1658. result.m[7] = initialM24;
  1659. result.m[8] = initialM31;
  1660. result.m[9] = initialM32;
  1661. result.m[10] = initialM33;
  1662. result.m[11] = initialM34;
  1663. result.m[12] = initialM41;
  1664. result.m[13] = initialM42;
  1665. result.m[14] = initialM43;
  1666. result.m[15] = initialM44;
  1667. };
  1668. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1669. var result = new Matrix();
  1670. result.m[0] = initialM11;
  1671. result.m[1] = initialM12;
  1672. result.m[2] = initialM13;
  1673. result.m[3] = initialM14;
  1674. result.m[4] = initialM21;
  1675. result.m[5] = initialM22;
  1676. result.m[6] = initialM23;
  1677. result.m[7] = initialM24;
  1678. result.m[8] = initialM31;
  1679. result.m[9] = initialM32;
  1680. result.m[10] = initialM33;
  1681. result.m[11] = initialM34;
  1682. result.m[12] = initialM41;
  1683. result.m[13] = initialM42;
  1684. result.m[14] = initialM43;
  1685. result.m[15] = initialM44;
  1686. return result;
  1687. };
  1688. Matrix.Compose = function (scale, rotation, translation) {
  1689. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1690. var rotationMatrix = Matrix.Identity();
  1691. rotation.toRotationMatrix(rotationMatrix);
  1692. result = result.multiply(rotationMatrix);
  1693. result.setTranslation(translation);
  1694. return result;
  1695. };
  1696. Matrix.Identity = function () {
  1697. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1698. };
  1699. Matrix.IdentityToRef = function (result) {
  1700. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1701. };
  1702. Matrix.Zero = function () {
  1703. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1704. };
  1705. Matrix.RotationX = function (angle) {
  1706. var result = new Matrix();
  1707. Matrix.RotationXToRef(angle, result);
  1708. return result;
  1709. };
  1710. Matrix.Invert = function (source) {
  1711. var result = new Matrix();
  1712. source.invertToRef(result);
  1713. return result;
  1714. };
  1715. Matrix.RotationXToRef = function (angle, result) {
  1716. var s = Math.sin(angle);
  1717. var c = Math.cos(angle);
  1718. result.m[0] = 1.0;
  1719. result.m[15] = 1.0;
  1720. result.m[5] = c;
  1721. result.m[10] = c;
  1722. result.m[9] = -s;
  1723. result.m[6] = s;
  1724. result.m[1] = 0;
  1725. result.m[2] = 0;
  1726. result.m[3] = 0;
  1727. result.m[4] = 0;
  1728. result.m[7] = 0;
  1729. result.m[8] = 0;
  1730. result.m[11] = 0;
  1731. result.m[12] = 0;
  1732. result.m[13] = 0;
  1733. result.m[14] = 0;
  1734. };
  1735. Matrix.RotationY = function (angle) {
  1736. var result = new Matrix();
  1737. Matrix.RotationYToRef(angle, result);
  1738. return result;
  1739. };
  1740. Matrix.RotationYToRef = function (angle, result) {
  1741. var s = Math.sin(angle);
  1742. var c = Math.cos(angle);
  1743. result.m[5] = 1.0;
  1744. result.m[15] = 1.0;
  1745. result.m[0] = c;
  1746. result.m[2] = -s;
  1747. result.m[8] = s;
  1748. result.m[10] = c;
  1749. result.m[1] = 0;
  1750. result.m[3] = 0;
  1751. result.m[4] = 0;
  1752. result.m[6] = 0;
  1753. result.m[7] = 0;
  1754. result.m[9] = 0;
  1755. result.m[11] = 0;
  1756. result.m[12] = 0;
  1757. result.m[13] = 0;
  1758. result.m[14] = 0;
  1759. };
  1760. Matrix.RotationZ = function (angle) {
  1761. var result = new Matrix();
  1762. Matrix.RotationZToRef(angle, result);
  1763. return result;
  1764. };
  1765. Matrix.RotationZToRef = function (angle, result) {
  1766. var s = Math.sin(angle);
  1767. var c = Math.cos(angle);
  1768. result.m[10] = 1.0;
  1769. result.m[15] = 1.0;
  1770. result.m[0] = c;
  1771. result.m[1] = s;
  1772. result.m[4] = -s;
  1773. result.m[5] = c;
  1774. result.m[2] = 0;
  1775. result.m[3] = 0;
  1776. result.m[6] = 0;
  1777. result.m[7] = 0;
  1778. result.m[8] = 0;
  1779. result.m[9] = 0;
  1780. result.m[11] = 0;
  1781. result.m[12] = 0;
  1782. result.m[13] = 0;
  1783. result.m[14] = 0;
  1784. };
  1785. Matrix.RotationAxis = function (axis, angle) {
  1786. var s = Math.sin(-angle);
  1787. var c = Math.cos(-angle);
  1788. var c1 = 1 - c;
  1789. axis.normalize();
  1790. var result = Matrix.Zero();
  1791. result.m[0] = (axis.x * axis.x) * c1 + c;
  1792. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1793. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1794. result.m[3] = 0.0;
  1795. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1796. result.m[5] = (axis.y * axis.y) * c1 + c;
  1797. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1798. result.m[7] = 0.0;
  1799. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1800. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1801. result.m[10] = (axis.z * axis.z) * c1 + c;
  1802. result.m[11] = 0.0;
  1803. result.m[15] = 1.0;
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1807. var result = new Matrix();
  1808. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1809. return result;
  1810. };
  1811. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1812. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1813. this._tempQuaternion.toRotationMatrix(result);
  1814. };
  1815. Matrix.Scaling = function (x, y, z) {
  1816. var result = Matrix.Zero();
  1817. Matrix.ScalingToRef(x, y, z, result);
  1818. return result;
  1819. };
  1820. Matrix.ScalingToRef = function (x, y, z, result) {
  1821. result.m[0] = x;
  1822. result.m[1] = 0;
  1823. result.m[2] = 0;
  1824. result.m[3] = 0;
  1825. result.m[4] = 0;
  1826. result.m[5] = y;
  1827. result.m[6] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[9] = 0;
  1831. result.m[10] = z;
  1832. result.m[11] = 0;
  1833. result.m[12] = 0;
  1834. result.m[13] = 0;
  1835. result.m[14] = 0;
  1836. result.m[15] = 1.0;
  1837. };
  1838. Matrix.Translation = function (x, y, z) {
  1839. var result = Matrix.Identity();
  1840. Matrix.TranslationToRef(x, y, z, result);
  1841. return result;
  1842. };
  1843. Matrix.TranslationToRef = function (x, y, z, result) {
  1844. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1845. };
  1846. Matrix.LookAtLH = function (eye, target, up) {
  1847. var result = Matrix.Zero();
  1848. Matrix.LookAtLHToRef(eye, target, up, result);
  1849. return result;
  1850. };
  1851. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1852. // Z axis
  1853. target.subtractToRef(eye, this._zAxis);
  1854. this._zAxis.normalize();
  1855. // X axis
  1856. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1857. this._xAxis.normalize();
  1858. // Y axis
  1859. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1860. this._yAxis.normalize();
  1861. // Eye angles
  1862. var ex = -Vector3.Dot(this._xAxis, eye);
  1863. var ey = -Vector3.Dot(this._yAxis, eye);
  1864. var ez = -Vector3.Dot(this._zAxis, eye);
  1865. 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);
  1866. };
  1867. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1868. var out = result.m;
  1869. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1870. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1871. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1872. // cc.kmVec3Subtract(f, pCenter, pEye);
  1873. var f = SIMD.float32x4.sub(center, eye);
  1874. // cc.kmVec3Normalize(f, f);
  1875. var tmp = SIMD.float32x4.mul(f, f);
  1876. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1877. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1878. // cc.kmVec3Assign(up, pUp);
  1879. // cc.kmVec3Normalize(up, up);
  1880. tmp = SIMD.float32x4.mul(up, up);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1883. // cc.kmVec3Cross(s, f, up);
  1884. 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)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1889. // cc.kmVec3Cross(u, s, f);
  1890. 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)));
  1891. // cc.kmVec3Normalize(s, s);
  1892. tmp = SIMD.float32x4.mul(s, s);
  1893. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1894. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1895. var zero = SIMD.float32x4.splat(0.0);
  1896. s = SIMD.float32x4.neg(s);
  1897. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1898. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1899. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1900. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1901. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1902. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1903. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1904. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1905. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1906. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1907. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1908. var b3 = SIMD.float32x4.neg(eye);
  1909. b3 = SIMD.float32x4.withW(b3, 1.0);
  1910. 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)))));
  1911. 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)))));
  1912. 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)))));
  1913. 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)))));
  1914. };
  1915. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1916. var matrix = Matrix.Zero();
  1917. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1918. return matrix;
  1919. };
  1920. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1921. var hw = 2.0 / width;
  1922. var hh = 2.0 / height;
  1923. var id = 1.0 / (zfar - znear);
  1924. var nid = znear / (znear - zfar);
  1925. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1926. };
  1927. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1928. var matrix = Matrix.Zero();
  1929. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1930. return matrix;
  1931. };
  1932. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1933. result.m[0] = 2.0 / (right - left);
  1934. result.m[1] = result.m[2] = result.m[3] = 0;
  1935. result.m[5] = 2.0 / (top - bottom);
  1936. result.m[4] = result.m[6] = result.m[7] = 0;
  1937. result.m[10] = -1.0 / (znear - zfar);
  1938. result.m[8] = result.m[9] = result.m[11] = 0;
  1939. result.m[12] = (left + right) / (left - right);
  1940. result.m[13] = (top + bottom) / (bottom - top);
  1941. result.m[14] = znear / (znear - zfar);
  1942. result.m[15] = 1.0;
  1943. };
  1944. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1945. var matrix = Matrix.Zero();
  1946. matrix.m[0] = (2.0 * znear) / width;
  1947. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1948. matrix.m[5] = (2.0 * znear) / height;
  1949. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1950. matrix.m[10] = -zfar / (znear - zfar);
  1951. matrix.m[8] = matrix.m[9] = 0.0;
  1952. matrix.m[11] = 1.0;
  1953. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1954. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1955. return matrix;
  1956. };
  1957. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1958. var matrix = Matrix.Zero();
  1959. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1960. return matrix;
  1961. };
  1962. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1963. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1964. var tan = 1.0 / (Math.tan(fov * 0.5));
  1965. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1966. if (v_fixed) {
  1967. result.m[0] = tan / aspect;
  1968. }
  1969. else {
  1970. result.m[0] = tan;
  1971. }
  1972. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1973. if (v_fixed) {
  1974. result.m[5] = tan;
  1975. }
  1976. else {
  1977. result.m[5] = tan * aspect;
  1978. }
  1979. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1980. result.m[8] = result.m[9] = 0.0;
  1981. result.m[10] = -zfar / (znear - zfar);
  1982. result.m[11] = 1.0;
  1983. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1984. result.m[14] = (znear * zfar) / (znear - zfar);
  1985. };
  1986. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1987. var cw = viewport.width;
  1988. var ch = viewport.height;
  1989. var cx = viewport.x;
  1990. var cy = viewport.y;
  1991. 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);
  1992. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1993. };
  1994. Matrix.Transpose = function (matrix) {
  1995. var result = new Matrix();
  1996. result.m[0] = matrix.m[0];
  1997. result.m[1] = matrix.m[4];
  1998. result.m[2] = matrix.m[8];
  1999. result.m[3] = matrix.m[12];
  2000. result.m[4] = matrix.m[1];
  2001. result.m[5] = matrix.m[5];
  2002. result.m[6] = matrix.m[9];
  2003. result.m[7] = matrix.m[13];
  2004. result.m[8] = matrix.m[2];
  2005. result.m[9] = matrix.m[6];
  2006. result.m[10] = matrix.m[10];
  2007. result.m[11] = matrix.m[14];
  2008. result.m[12] = matrix.m[3];
  2009. result.m[13] = matrix.m[7];
  2010. result.m[14] = matrix.m[11];
  2011. result.m[15] = matrix.m[15];
  2012. return result;
  2013. };
  2014. Matrix.Reflection = function (plane) {
  2015. var matrix = new Matrix();
  2016. Matrix.ReflectionToRef(plane, matrix);
  2017. return matrix;
  2018. };
  2019. Matrix.ReflectionToRef = function (plane, result) {
  2020. plane.normalize();
  2021. var x = plane.normal.x;
  2022. var y = plane.normal.y;
  2023. var z = plane.normal.z;
  2024. var temp = -2 * x;
  2025. var temp2 = -2 * y;
  2026. var temp3 = -2 * z;
  2027. result.m[0] = (temp * x) + 1;
  2028. result.m[1] = temp2 * x;
  2029. result.m[2] = temp3 * x;
  2030. result.m[3] = 0.0;
  2031. result.m[4] = temp * y;
  2032. result.m[5] = (temp2 * y) + 1;
  2033. result.m[6] = temp3 * y;
  2034. result.m[7] = 0.0;
  2035. result.m[8] = temp * z;
  2036. result.m[9] = temp2 * z;
  2037. result.m[10] = (temp3 * z) + 1;
  2038. result.m[11] = 0.0;
  2039. result.m[12] = temp * plane.d;
  2040. result.m[13] = temp2 * plane.d;
  2041. result.m[14] = temp3 * plane.d;
  2042. result.m[15] = 1.0;
  2043. };
  2044. Matrix._tempQuaternion = new Quaternion();
  2045. Matrix._xAxis = Vector3.Zero();
  2046. Matrix._yAxis = Vector3.Zero();
  2047. Matrix._zAxis = Vector3.Zero();
  2048. return Matrix;
  2049. })();
  2050. BABYLON.Matrix = Matrix;
  2051. var Plane = (function () {
  2052. function Plane(a, b, c, d) {
  2053. this.normal = new Vector3(a, b, c);
  2054. this.d = d;
  2055. }
  2056. Plane.prototype.asArray = function () {
  2057. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2058. };
  2059. // Methods
  2060. Plane.prototype.clone = function () {
  2061. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2062. };
  2063. Plane.prototype.normalize = function () {
  2064. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2065. var magnitude = 0;
  2066. if (norm !== 0) {
  2067. magnitude = 1.0 / norm;
  2068. }
  2069. this.normal.x *= magnitude;
  2070. this.normal.y *= magnitude;
  2071. this.normal.z *= magnitude;
  2072. this.d *= magnitude;
  2073. return this;
  2074. };
  2075. Plane.prototype.transform = function (transformation) {
  2076. var transposedMatrix = Matrix.Transpose(transformation);
  2077. var x = this.normal.x;
  2078. var y = this.normal.y;
  2079. var z = this.normal.z;
  2080. var d = this.d;
  2081. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2082. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2083. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2084. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2085. return new Plane(normalX, normalY, normalZ, finalD);
  2086. };
  2087. Plane.prototype.dotCoordinate = function (point) {
  2088. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2089. };
  2090. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2091. var x1 = point2.x - point1.x;
  2092. var y1 = point2.y - point1.y;
  2093. var z1 = point2.z - point1.z;
  2094. var x2 = point3.x - point1.x;
  2095. var y2 = point3.y - point1.y;
  2096. var z2 = point3.z - point1.z;
  2097. var yz = (y1 * z2) - (z1 * y2);
  2098. var xz = (z1 * x2) - (x1 * z2);
  2099. var xy = (x1 * y2) - (y1 * x2);
  2100. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2101. var invPyth;
  2102. if (pyth !== 0) {
  2103. invPyth = 1.0 / pyth;
  2104. }
  2105. else {
  2106. invPyth = 0;
  2107. }
  2108. this.normal.x = yz * invPyth;
  2109. this.normal.y = xz * invPyth;
  2110. this.normal.z = xy * invPyth;
  2111. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2112. return this;
  2113. };
  2114. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2115. var dot = Vector3.Dot(this.normal, direction);
  2116. return (dot <= epsilon);
  2117. };
  2118. Plane.prototype.signedDistanceTo = function (point) {
  2119. return Vector3.Dot(point, this.normal) + this.d;
  2120. };
  2121. // Statics
  2122. Plane.FromArray = function (array) {
  2123. return new Plane(array[0], array[1], array[2], array[3]);
  2124. };
  2125. Plane.FromPoints = function (point1, point2, point3) {
  2126. var result = new Plane(0, 0, 0, 0);
  2127. result.copyFromPoints(point1, point2, point3);
  2128. return result;
  2129. };
  2130. Plane.FromPositionAndNormal = function (origin, normal) {
  2131. var result = new Plane(0, 0, 0, 0);
  2132. normal.normalize();
  2133. result.normal = normal;
  2134. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2135. return result;
  2136. };
  2137. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2138. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2139. return Vector3.Dot(point, normal) + d;
  2140. };
  2141. return Plane;
  2142. })();
  2143. BABYLON.Plane = Plane;
  2144. var Viewport = (function () {
  2145. function Viewport(x, y, width, height) {
  2146. this.x = x;
  2147. this.y = y;
  2148. this.width = width;
  2149. this.height = height;
  2150. }
  2151. Viewport.prototype.toGlobal = function (engine) {
  2152. var width = engine.getRenderWidth();
  2153. var height = engine.getRenderHeight();
  2154. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2155. };
  2156. return Viewport;
  2157. })();
  2158. BABYLON.Viewport = Viewport;
  2159. var Frustum = (function () {
  2160. function Frustum() {
  2161. }
  2162. Frustum.GetPlanes = function (transform) {
  2163. var frustumPlanes = [];
  2164. for (var index = 0; index < 6; index++) {
  2165. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2166. }
  2167. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2168. return frustumPlanes;
  2169. };
  2170. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2171. // Near
  2172. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2173. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2174. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2175. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2176. frustumPlanes[0].normalize();
  2177. // Far
  2178. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2179. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2180. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2181. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2182. frustumPlanes[1].normalize();
  2183. // Left
  2184. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2185. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2186. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2187. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2188. frustumPlanes[2].normalize();
  2189. // Right
  2190. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2191. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2192. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2193. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2194. frustumPlanes[3].normalize();
  2195. // Top
  2196. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2197. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2198. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2199. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2200. frustumPlanes[4].normalize();
  2201. // Bottom
  2202. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2203. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2204. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2205. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2206. frustumPlanes[5].normalize();
  2207. };
  2208. return Frustum;
  2209. })();
  2210. BABYLON.Frustum = Frustum;
  2211. var Ray = (function () {
  2212. function Ray(origin, direction, length) {
  2213. if (length === void 0) { length = Number.MAX_VALUE; }
  2214. this.origin = origin;
  2215. this.direction = direction;
  2216. this.length = length;
  2217. }
  2218. // Methods
  2219. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2220. var d = 0.0;
  2221. var maxValue = Number.MAX_VALUE;
  2222. if (Math.abs(this.direction.x) < 0.0000001) {
  2223. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2224. return false;
  2225. }
  2226. }
  2227. else {
  2228. var inv = 1.0 / this.direction.x;
  2229. var min = (minimum.x - this.origin.x) * inv;
  2230. var max = (maximum.x - this.origin.x) * inv;
  2231. if (max === -Infinity) {
  2232. max = Infinity;
  2233. }
  2234. if (min > max) {
  2235. var temp = min;
  2236. min = max;
  2237. max = temp;
  2238. }
  2239. d = Math.max(min, d);
  2240. maxValue = Math.min(max, maxValue);
  2241. if (d > maxValue) {
  2242. return false;
  2243. }
  2244. }
  2245. if (Math.abs(this.direction.y) < 0.0000001) {
  2246. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2247. return false;
  2248. }
  2249. }
  2250. else {
  2251. inv = 1.0 / this.direction.y;
  2252. min = (minimum.y - this.origin.y) * inv;
  2253. max = (maximum.y - this.origin.y) * inv;
  2254. if (max === -Infinity) {
  2255. max = Infinity;
  2256. }
  2257. if (min > max) {
  2258. temp = min;
  2259. min = max;
  2260. max = temp;
  2261. }
  2262. d = Math.max(min, d);
  2263. maxValue = Math.min(max, maxValue);
  2264. if (d > maxValue) {
  2265. return false;
  2266. }
  2267. }
  2268. if (Math.abs(this.direction.z) < 0.0000001) {
  2269. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2270. return false;
  2271. }
  2272. }
  2273. else {
  2274. inv = 1.0 / this.direction.z;
  2275. min = (minimum.z - this.origin.z) * inv;
  2276. max = (maximum.z - this.origin.z) * inv;
  2277. if (max === -Infinity) {
  2278. max = Infinity;
  2279. }
  2280. if (min > max) {
  2281. temp = min;
  2282. min = max;
  2283. max = temp;
  2284. }
  2285. d = Math.max(min, d);
  2286. maxValue = Math.min(max, maxValue);
  2287. if (d > maxValue) {
  2288. return false;
  2289. }
  2290. }
  2291. return true;
  2292. };
  2293. Ray.prototype.intersectsBox = function (box) {
  2294. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2295. };
  2296. Ray.prototype.intersectsSphere = function (sphere) {
  2297. var x = sphere.center.x - this.origin.x;
  2298. var y = sphere.center.y - this.origin.y;
  2299. var z = sphere.center.z - this.origin.z;
  2300. var pyth = (x * x) + (y * y) + (z * z);
  2301. var rr = sphere.radius * sphere.radius;
  2302. if (pyth <= rr) {
  2303. return true;
  2304. }
  2305. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2306. if (dot < 0.0) {
  2307. return false;
  2308. }
  2309. var temp = pyth - (dot * dot);
  2310. return temp <= rr;
  2311. };
  2312. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2313. if (!this._edge1) {
  2314. this._edge1 = Vector3.Zero();
  2315. this._edge2 = Vector3.Zero();
  2316. this._pvec = Vector3.Zero();
  2317. this._tvec = Vector3.Zero();
  2318. this._qvec = Vector3.Zero();
  2319. }
  2320. vertex1.subtractToRef(vertex0, this._edge1);
  2321. vertex2.subtractToRef(vertex0, this._edge2);
  2322. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2323. var det = Vector3.Dot(this._edge1, this._pvec);
  2324. if (det === 0) {
  2325. return null;
  2326. }
  2327. var invdet = 1 / det;
  2328. this.origin.subtractToRef(vertex0, this._tvec);
  2329. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2330. if (bu < 0 || bu > 1.0) {
  2331. return null;
  2332. }
  2333. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2334. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2335. if (bv < 0 || bu + bv > 1.0) {
  2336. return null;
  2337. }
  2338. //check if the distance is longer than the predefined length.
  2339. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2340. if (distance > this.length) {
  2341. return null;
  2342. }
  2343. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2344. };
  2345. // Statics
  2346. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2347. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2348. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2349. var direction = end.subtract(start);
  2350. direction.normalize();
  2351. return new Ray(start, direction);
  2352. };
  2353. /**
  2354. * 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
  2355. * transformed to the given world matrix.
  2356. * @param origin The origin point
  2357. * @param end The end point
  2358. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2359. */
  2360. Ray.CreateNewFromTo = function (origin, end, world) {
  2361. if (world === void 0) { world = Matrix.Identity(); }
  2362. var direction = end.subtract(origin);
  2363. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2364. direction.normalize();
  2365. return Ray.Transform(new Ray(origin, direction, length), world);
  2366. };
  2367. Ray.Transform = function (ray, matrix) {
  2368. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2369. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2370. return new Ray(newOrigin, newDirection, ray.length);
  2371. };
  2372. return Ray;
  2373. })();
  2374. BABYLON.Ray = Ray;
  2375. (function (Space) {
  2376. Space[Space["LOCAL"] = 0] = "LOCAL";
  2377. Space[Space["WORLD"] = 1] = "WORLD";
  2378. })(BABYLON.Space || (BABYLON.Space = {}));
  2379. var Space = BABYLON.Space;
  2380. var Axis = (function () {
  2381. function Axis() {
  2382. }
  2383. Axis.X = new Vector3(1, 0, 0);
  2384. Axis.Y = new Vector3(0, 1, 0);
  2385. Axis.Z = new Vector3(0, 0, 1);
  2386. return Axis;
  2387. })();
  2388. BABYLON.Axis = Axis;
  2389. ;
  2390. var BezierCurve = (function () {
  2391. function BezierCurve() {
  2392. }
  2393. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2394. // Extract X (which is equal to time here)
  2395. var f0 = 1 - 3 * x2 + 3 * x1;
  2396. var f1 = 3 * x2 - 6 * x1;
  2397. var f2 = 3 * x1;
  2398. var refinedT = t;
  2399. for (var i = 0; i < 5; i++) {
  2400. var refinedT2 = refinedT * refinedT;
  2401. var refinedT3 = refinedT2 * refinedT;
  2402. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2403. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2404. refinedT -= (x - t) * slope;
  2405. refinedT = Math.min(1, Math.max(0, refinedT));
  2406. }
  2407. // Resolve cubic bezier for the given x
  2408. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2409. };
  2410. return BezierCurve;
  2411. })();
  2412. BABYLON.BezierCurve = BezierCurve;
  2413. (function (Orientation) {
  2414. Orientation[Orientation["CW"] = 0] = "CW";
  2415. Orientation[Orientation["CCW"] = 1] = "CCW";
  2416. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2417. var Orientation = BABYLON.Orientation;
  2418. var Angle = (function () {
  2419. function Angle(radians) {
  2420. var _this = this;
  2421. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2422. this.radians = function () { return _this._radians; };
  2423. this._radians = radians;
  2424. if (this._radians < 0)
  2425. this._radians += (2 * Math.PI);
  2426. }
  2427. Angle.BetweenTwoPoints = function (a, b) {
  2428. var delta = b.subtract(a);
  2429. var theta = Math.atan2(delta.y, delta.x);
  2430. return new Angle(theta);
  2431. };
  2432. Angle.FromRadians = function (radians) {
  2433. return new Angle(radians);
  2434. };
  2435. Angle.FromDegrees = function (degrees) {
  2436. return new Angle(degrees * Math.PI / 180);
  2437. };
  2438. return Angle;
  2439. })();
  2440. BABYLON.Angle = Angle;
  2441. var Arc2 = (function () {
  2442. function Arc2(startPoint, midPoint, endPoint) {
  2443. this.startPoint = startPoint;
  2444. this.midPoint = midPoint;
  2445. this.endPoint = endPoint;
  2446. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2447. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2448. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2449. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2450. 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);
  2451. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2452. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2453. var a1 = this.startAngle.degrees();
  2454. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2455. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2456. // angles correction
  2457. if (a2 - a1 > +180.0)
  2458. a2 -= 360.0;
  2459. if (a2 - a1 < -180.0)
  2460. a2 += 360.0;
  2461. if (a3 - a2 > +180.0)
  2462. a3 -= 360.0;
  2463. if (a3 - a2 < -180.0)
  2464. a3 += 360.0;
  2465. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2466. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2467. }
  2468. return Arc2;
  2469. })();
  2470. BABYLON.Arc2 = Arc2;
  2471. var PathCursor = (function () {
  2472. function PathCursor(path) {
  2473. this.path = path;
  2474. this._onchange = new Array();
  2475. this.value = 0;
  2476. this.animations = new Array();
  2477. }
  2478. PathCursor.prototype.getPoint = function () {
  2479. var point = this.path.getPointAtLengthPosition(this.value);
  2480. return new Vector3(point.x, 0, point.y);
  2481. };
  2482. PathCursor.prototype.moveAhead = function (step) {
  2483. if (step === void 0) { step = 0.002; }
  2484. this.move(step);
  2485. return this;
  2486. };
  2487. PathCursor.prototype.moveBack = function (step) {
  2488. if (step === void 0) { step = 0.002; }
  2489. this.move(-step);
  2490. return this;
  2491. };
  2492. PathCursor.prototype.move = function (step) {
  2493. if (Math.abs(step) > 1) {
  2494. throw "step size should be less than 1.";
  2495. }
  2496. this.value += step;
  2497. this.ensureLimits();
  2498. this.raiseOnChange();
  2499. return this;
  2500. };
  2501. PathCursor.prototype.ensureLimits = function () {
  2502. while (this.value > 1) {
  2503. this.value -= 1;
  2504. }
  2505. while (this.value < 0) {
  2506. this.value += 1;
  2507. }
  2508. return this;
  2509. };
  2510. // used by animation engine
  2511. PathCursor.prototype.markAsDirty = function (propertyName) {
  2512. this.ensureLimits();
  2513. this.raiseOnChange();
  2514. return this;
  2515. };
  2516. PathCursor.prototype.raiseOnChange = function () {
  2517. var _this = this;
  2518. this._onchange.forEach(function (f) { return f(_this); });
  2519. return this;
  2520. };
  2521. PathCursor.prototype.onchange = function (f) {
  2522. this._onchange.push(f);
  2523. return this;
  2524. };
  2525. return PathCursor;
  2526. })();
  2527. BABYLON.PathCursor = PathCursor;
  2528. var Path2 = (function () {
  2529. function Path2(x, y) {
  2530. this._points = new Array();
  2531. this._length = 0;
  2532. this.closed = false;
  2533. this._points.push(new Vector2(x, y));
  2534. }
  2535. Path2.prototype.addLineTo = function (x, y) {
  2536. if (closed) {
  2537. BABYLON.Tools.Error("cannot add lines to closed paths");
  2538. return this;
  2539. }
  2540. var newPoint = new Vector2(x, y);
  2541. var previousPoint = this._points[this._points.length - 1];
  2542. this._points.push(newPoint);
  2543. this._length += newPoint.subtract(previousPoint).length();
  2544. return this;
  2545. };
  2546. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2547. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2548. if (closed) {
  2549. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2550. return this;
  2551. }
  2552. var startPoint = this._points[this._points.length - 1];
  2553. var midPoint = new Vector2(midX, midY);
  2554. var endPoint = new Vector2(endX, endY);
  2555. var arc = new Arc2(startPoint, midPoint, endPoint);
  2556. var increment = arc.angle.radians() / numberOfSegments;
  2557. if (arc.orientation === 0 /* CW */)
  2558. increment *= -1;
  2559. var currentAngle = arc.startAngle.radians() + increment;
  2560. for (var i = 0; i < numberOfSegments; i++) {
  2561. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2562. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2563. this.addLineTo(x, y);
  2564. currentAngle += increment;
  2565. }
  2566. return this;
  2567. };
  2568. Path2.prototype.close = function () {
  2569. this.closed = true;
  2570. return this;
  2571. };
  2572. Path2.prototype.length = function () {
  2573. var result = this._length;
  2574. if (!this.closed) {
  2575. var lastPoint = this._points[this._points.length - 1];
  2576. var firstPoint = this._points[0];
  2577. result += (firstPoint.subtract(lastPoint).length());
  2578. }
  2579. return result;
  2580. };
  2581. Path2.prototype.getPoints = function () {
  2582. return this._points;
  2583. };
  2584. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2585. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2586. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2587. return Vector2.Zero();
  2588. }
  2589. var lengthPosition = normalizedLengthPosition * this.length();
  2590. var previousOffset = 0;
  2591. for (var i = 0; i < this._points.length; i++) {
  2592. var j = (i + 1) % this._points.length;
  2593. var a = this._points[i];
  2594. var b = this._points[j];
  2595. var bToA = b.subtract(a);
  2596. var nextOffset = (bToA.length() + previousOffset);
  2597. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2598. var dir = bToA.normalize();
  2599. var localOffset = lengthPosition - previousOffset;
  2600. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2601. }
  2602. previousOffset = nextOffset;
  2603. }
  2604. BABYLON.Tools.Error("internal error");
  2605. return Vector2.Zero();
  2606. };
  2607. Path2.StartingAt = function (x, y) {
  2608. return new Path2(x, y);
  2609. };
  2610. return Path2;
  2611. })();
  2612. BABYLON.Path2 = Path2;
  2613. var Path3D = (function () {
  2614. function Path3D(path) {
  2615. this.path = path;
  2616. this._curve = new Array();
  2617. this._distances = new Array();
  2618. this._tangents = new Array();
  2619. this._normals = new Array();
  2620. this._binormals = new Array();
  2621. this._curve = path.slice(); // copy array
  2622. this._compute();
  2623. }
  2624. Path3D.prototype.getCurve = function () {
  2625. return this._curve;
  2626. };
  2627. Path3D.prototype.getTangents = function () {
  2628. return this._tangents;
  2629. };
  2630. Path3D.prototype.getNormals = function () {
  2631. return this._normals;
  2632. };
  2633. Path3D.prototype.getBinormals = function () {
  2634. return this._binormals;
  2635. };
  2636. Path3D.prototype.getDistances = function () {
  2637. return this._distances;
  2638. };
  2639. Path3D.prototype.update = function (path) {
  2640. for (var i = 0; i < path.length; i++) {
  2641. this._curve[i] = path[i];
  2642. }
  2643. this._compute();
  2644. return this;
  2645. };
  2646. // private function compute() : computes tangents, normals and binormals
  2647. Path3D.prototype._compute = function () {
  2648. var l = this._curve.length;
  2649. // first and last tangents
  2650. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2651. this._tangents[0].normalize();
  2652. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2653. this._tangents[l - 1].normalize();
  2654. // normals and binormals at first point : arbitrary vector with _normalVector()
  2655. var tg0 = this._tangents[0];
  2656. var pp0 = this._normalVector(this._curve[0], tg0);
  2657. this._normals[0] = pp0;
  2658. this._normals[0].normalize();
  2659. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2660. this._normals[0].normalize();
  2661. this._distances[0] = 0;
  2662. // normals and binormals : next points
  2663. var prev; // previous vector (segment)
  2664. var cur; // current vector (segment)
  2665. var curTang; // current tangent
  2666. var prevNorm; // previous normal
  2667. var prevBinor; // previous binormal
  2668. for (var i = 1; i < l; i++) {
  2669. // tangents
  2670. prev = this._curve[i].subtract(this._curve[i - 1]);
  2671. if (i < l - 1) {
  2672. cur = this._curve[i + 1].subtract(this._curve[i]);
  2673. this._tangents[i] = prev.add(cur);
  2674. this._tangents[i].normalize();
  2675. }
  2676. this._distances[i] = this._distances[i - 1] + prev.length();
  2677. // normals and binormals
  2678. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2679. curTang = this._tangents[i];
  2680. prevNorm = this._normals[i - 1];
  2681. prevBinor = this._binormals[i - 1];
  2682. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2683. this._normals[i].normalize();
  2684. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2685. this._binormals[i].normalize();
  2686. }
  2687. };
  2688. // private function normalVector(v0, vt) :
  2689. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2690. Path3D.prototype._normalVector = function (v0, vt) {
  2691. var point;
  2692. if (vt.x !== 1) {
  2693. point = new Vector3(1, 0, 0);
  2694. }
  2695. else if (vt.y !== 1) {
  2696. point = new Vector3(0, 1, 0);
  2697. }
  2698. else if (vt.z !== 1) {
  2699. point = new Vector3(0, 0, 1);
  2700. }
  2701. var normal0 = Vector3.Cross(vt, point);
  2702. normal0.normalize();
  2703. return normal0;
  2704. };
  2705. return Path3D;
  2706. })();
  2707. BABYLON.Path3D = Path3D;
  2708. var Curve3 = (function () {
  2709. function Curve3(points) {
  2710. this._points = points;
  2711. }
  2712. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2713. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2714. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2715. var bez = new Array();
  2716. var step = 1 / nbPoints;
  2717. var equation = function (t, val0, val1, val2) {
  2718. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2719. return res;
  2720. };
  2721. for (var i = 0; i <= 1; i += step) {
  2722. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2723. }
  2724. return new Curve3(bez);
  2725. };
  2726. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2727. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2728. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2729. var bez = new Array();
  2730. var step = 1 / nbPoints;
  2731. var equation = function (t, val0, val1, val2, val3) {
  2732. 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;
  2733. return res;
  2734. };
  2735. for (var i = 0; i <= 1; i += step) {
  2736. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2737. }
  2738. return new Curve3(bez);
  2739. };
  2740. Curve3.prototype.getPoints = function () {
  2741. return this._points;
  2742. };
  2743. Curve3.prototype.continue = function (curve) {
  2744. var lastPoint = this._points[this._points.length - 1];
  2745. var continuedPoints = this._points.slice();
  2746. var curvePoints = curve.getPoints();
  2747. for (var i = 1; i < curvePoints.length; i++) {
  2748. continuedPoints.push(curvePoints[i].add(lastPoint));
  2749. }
  2750. return new Curve3(continuedPoints);
  2751. };
  2752. return Curve3;
  2753. })();
  2754. BABYLON.Curve3 = Curve3;
  2755. // Vertex formats
  2756. var PositionNormalVertex = (function () {
  2757. function PositionNormalVertex(position, normal) {
  2758. if (position === void 0) { position = Vector3.Zero(); }
  2759. if (normal === void 0) { normal = Vector3.Up(); }
  2760. this.position = position;
  2761. this.normal = normal;
  2762. }
  2763. PositionNormalVertex.prototype.clone = function () {
  2764. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2765. };
  2766. return PositionNormalVertex;
  2767. })();
  2768. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2769. var PositionNormalTextureVertex = (function () {
  2770. function PositionNormalTextureVertex(position, normal, uv) {
  2771. if (position === void 0) { position = Vector3.Zero(); }
  2772. if (normal === void 0) { normal = Vector3.Up(); }
  2773. if (uv === void 0) { uv = Vector2.Zero(); }
  2774. this.position = position;
  2775. this.normal = normal;
  2776. this.uv = uv;
  2777. }
  2778. PositionNormalTextureVertex.prototype.clone = function () {
  2779. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2780. };
  2781. return PositionNormalTextureVertex;
  2782. })();
  2783. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2784. // SIMD
  2785. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2786. var previousInvertToRef = Matrix.prototype.invertToRef;
  2787. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2788. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2789. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2790. var SIMDHelper = (function () {
  2791. function SIMDHelper() {
  2792. }
  2793. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2794. get: function () {
  2795. return SIMDHelper._isEnabled;
  2796. },
  2797. enumerable: true,
  2798. configurable: true
  2799. });
  2800. SIMDHelper.DisableSIMD = function () {
  2801. // Replace functions
  2802. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2803. Matrix.prototype.invertToRef = previousInvertToRef;
  2804. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2805. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2806. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2807. SIMDHelper._isEnabled = false;
  2808. };
  2809. SIMDHelper.EnableSIMD = function () {
  2810. if (window.SIMD === undefined) {
  2811. return;
  2812. }
  2813. // Replace functions
  2814. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2815. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2816. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2817. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2818. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2819. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2820. get: function () {
  2821. return this._data[0];
  2822. },
  2823. set: function (value) {
  2824. if (!this._data) {
  2825. this._data = new Float32Array(3);
  2826. }
  2827. this._data[0] = value;
  2828. }
  2829. });
  2830. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2831. get: function () {
  2832. return this._data[1];
  2833. },
  2834. set: function (value) {
  2835. this._data[1] = value;
  2836. }
  2837. });
  2838. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2839. get: function () {
  2840. return this._data[2];
  2841. },
  2842. set: function (value) {
  2843. this._data[2] = value;
  2844. }
  2845. });
  2846. SIMDHelper._isEnabled = true;
  2847. };
  2848. SIMDHelper._isEnabled = false;
  2849. return SIMDHelper;
  2850. })();
  2851. BABYLON.SIMDHelper = SIMDHelper;
  2852. if (window.SIMD !== undefined) {
  2853. SIMDHelper.EnableSIMD();
  2854. }
  2855. })(BABYLON || (BABYLON = {}));
  2856. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2857. (function (BABYLON) {
  2858. // Screenshots
  2859. var screenshotCanvas;
  2860. var cloneValue = function (source, destinationObject) {
  2861. if (!source)
  2862. return null;
  2863. if (source instanceof BABYLON.Mesh) {
  2864. return null;
  2865. }
  2866. if (source instanceof BABYLON.SubMesh) {
  2867. return source.clone(destinationObject);
  2868. }
  2869. else if (source.clone) {
  2870. return source.clone();
  2871. }
  2872. return null;
  2873. };
  2874. var Tools = (function () {
  2875. function Tools() {
  2876. }
  2877. Tools.GetFilename = function (path) {
  2878. var index = path.lastIndexOf("/");
  2879. if (index < 0)
  2880. return path;
  2881. return path.substring(index + 1);
  2882. };
  2883. Tools.GetDOMTextContent = function (element) {
  2884. var result = "";
  2885. var child = element.firstChild;
  2886. while (child) {
  2887. if (child.nodeType === 3) {
  2888. result += child.textContent;
  2889. }
  2890. child = child.nextSibling;
  2891. }
  2892. return result;
  2893. };
  2894. Tools.ToDegrees = function (angle) {
  2895. return angle * 180 / Math.PI;
  2896. };
  2897. Tools.ToRadians = function (angle) {
  2898. return angle * Math.PI / 180;
  2899. };
  2900. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2901. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2902. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2903. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2904. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2907. }
  2908. return {
  2909. minimum: minimum,
  2910. maximum: maximum
  2911. };
  2912. };
  2913. Tools.ExtractMinAndMax = function (positions, start, count) {
  2914. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2915. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2916. for (var index = start; index < start + count; index++) {
  2917. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2918. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2919. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2920. }
  2921. return {
  2922. minimum: minimum,
  2923. maximum: maximum
  2924. };
  2925. };
  2926. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2927. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2928. return undefined;
  2929. return Array.isArray(obj) ? obj : [obj];
  2930. };
  2931. // Misc.
  2932. Tools.GetPointerPrefix = function () {
  2933. var eventPrefix = "pointer";
  2934. // Check if hand.js is referenced or if the browser natively supports pointer events
  2935. if (!navigator.pointerEnabled) {
  2936. eventPrefix = "mouse";
  2937. }
  2938. return eventPrefix;
  2939. };
  2940. Tools.QueueNewFrame = function (func) {
  2941. if (window.requestAnimationFrame)
  2942. window.requestAnimationFrame(func);
  2943. else if (window.msRequestAnimationFrame)
  2944. window.msRequestAnimationFrame(func);
  2945. else if (window.webkitRequestAnimationFrame)
  2946. window.webkitRequestAnimationFrame(func);
  2947. else if (window.mozRequestAnimationFrame)
  2948. window.mozRequestAnimationFrame(func);
  2949. else if (window.oRequestAnimationFrame)
  2950. window.oRequestAnimationFrame(func);
  2951. else {
  2952. window.setTimeout(func, 16);
  2953. }
  2954. };
  2955. Tools.RequestFullscreen = function (element) {
  2956. if (element.requestFullscreen)
  2957. element.requestFullscreen();
  2958. else if (element.msRequestFullscreen)
  2959. element.msRequestFullscreen();
  2960. else if (element.webkitRequestFullscreen)
  2961. element.webkitRequestFullscreen();
  2962. else if (element.mozRequestFullScreen)
  2963. element.mozRequestFullScreen();
  2964. };
  2965. Tools.ExitFullscreen = function () {
  2966. if (document.exitFullscreen) {
  2967. document.exitFullscreen();
  2968. }
  2969. else if (document.mozCancelFullScreen) {
  2970. document.mozCancelFullScreen();
  2971. }
  2972. else if (document.webkitCancelFullScreen) {
  2973. document.webkitCancelFullScreen();
  2974. }
  2975. else if (document.msCancelFullScreen) {
  2976. document.msCancelFullScreen();
  2977. }
  2978. };
  2979. // External files
  2980. Tools.CleanUrl = function (url) {
  2981. url = url.replace(/#/mg, "%23");
  2982. return url;
  2983. };
  2984. Tools.LoadImage = function (url, onload, onerror, database) {
  2985. url = Tools.CleanUrl(url);
  2986. var img = new Image();
  2987. if (url.substr(0, 5) !== "data:")
  2988. img.crossOrigin = 'anonymous';
  2989. img.onload = function () {
  2990. onload(img);
  2991. };
  2992. img.onerror = function (err) {
  2993. onerror(img, err);
  2994. };
  2995. var noIndexedDB = function () {
  2996. img.src = url;
  2997. };
  2998. var loadFromIndexedDB = function () {
  2999. database.loadImageFromDB(url, img);
  3000. };
  3001. //ANY database to do!
  3002. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  3003. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3004. }
  3005. else {
  3006. if (url.indexOf("file:") === -1) {
  3007. noIndexedDB();
  3008. }
  3009. else {
  3010. try {
  3011. var textureName = url.substring(5);
  3012. var blobURL;
  3013. try {
  3014. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  3015. }
  3016. catch (ex) {
  3017. // Chrome doesn't support oneTimeOnly parameter
  3018. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  3019. }
  3020. img.src = blobURL;
  3021. }
  3022. catch (e) {
  3023. Tools.Log("Error while trying to load texture: " + textureName);
  3024. img.src = null;
  3025. }
  3026. }
  3027. }
  3028. return img;
  3029. };
  3030. //ANY
  3031. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3032. url = Tools.CleanUrl(url);
  3033. var noIndexedDB = function () {
  3034. var request = new XMLHttpRequest();
  3035. var loadUrl = Tools.BaseUrl + url;
  3036. request.open('GET', loadUrl, true);
  3037. if (useArrayBuffer) {
  3038. request.responseType = "arraybuffer";
  3039. }
  3040. request.onprogress = progressCallBack;
  3041. request.onreadystatechange = function () {
  3042. if (request.readyState === 4) {
  3043. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3044. callback(!useArrayBuffer ? request.responseText : request.response);
  3045. }
  3046. else {
  3047. if (onError) {
  3048. onError();
  3049. }
  3050. else {
  3051. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3052. }
  3053. }
  3054. }
  3055. };
  3056. request.send(null);
  3057. };
  3058. var loadFromIndexedDB = function () {
  3059. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3060. };
  3061. if (url.indexOf("file:") !== -1) {
  3062. var fileName = url.substring(5);
  3063. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3064. }
  3065. else {
  3066. // Caching all files
  3067. if (database && database.enableSceneOffline) {
  3068. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3069. }
  3070. else {
  3071. noIndexedDB();
  3072. }
  3073. }
  3074. };
  3075. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3076. var reader = new FileReader();
  3077. reader.onload = function (e) {
  3078. //target doesn't have result from ts 1.3
  3079. callback(e.target['result']);
  3080. };
  3081. reader.onprogress = progressCallback;
  3082. reader.readAsDataURL(fileToLoad);
  3083. };
  3084. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3085. var reader = new FileReader();
  3086. reader.onerror = function (e) {
  3087. Tools.Log("Error while reading file: " + fileToLoad.name);
  3088. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3089. };
  3090. reader.onload = function (e) {
  3091. //target doesn't have result from ts 1.3
  3092. callback(e.target['result']);
  3093. };
  3094. reader.onprogress = progressCallBack;
  3095. if (!useArrayBuffer) {
  3096. // Asynchronous read
  3097. reader.readAsText(fileToLoad);
  3098. }
  3099. else {
  3100. reader.readAsArrayBuffer(fileToLoad);
  3101. }
  3102. };
  3103. // Misc.
  3104. Tools.Clamp = function (value, min, max) {
  3105. if (min === void 0) { min = 0; }
  3106. if (max === void 0) { max = 1; }
  3107. return Math.min(max, Math.max(min, value));
  3108. };
  3109. // Returns -1 when value is a negative number and
  3110. // +1 when value is a positive number.
  3111. Tools.Sign = function (value) {
  3112. value = +value; // convert to a number
  3113. if (value === 0 || isNaN(value))
  3114. return value;
  3115. return value > 0 ? 1 : -1;
  3116. };
  3117. Tools.Format = function (value, decimals) {
  3118. if (decimals === void 0) { decimals = 2; }
  3119. return value.toFixed(decimals);
  3120. };
  3121. Tools.CheckExtends = function (v, min, max) {
  3122. if (v.x < min.x)
  3123. min.x = v.x;
  3124. if (v.y < min.y)
  3125. min.y = v.y;
  3126. if (v.z < min.z)
  3127. min.z = v.z;
  3128. if (v.x > max.x)
  3129. max.x = v.x;
  3130. if (v.y > max.y)
  3131. max.y = v.y;
  3132. if (v.z > max.z)
  3133. max.z = v.z;
  3134. };
  3135. Tools.WithinEpsilon = function (a, b, epsilon) {
  3136. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3137. var num = a - b;
  3138. return -epsilon <= num && num <= epsilon;
  3139. };
  3140. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3141. for (var prop in source) {
  3142. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3143. continue;
  3144. }
  3145. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3146. continue;
  3147. }
  3148. var sourceValue = source[prop];
  3149. var typeOfSourceValue = typeof sourceValue;
  3150. if (typeOfSourceValue === "function") {
  3151. continue;
  3152. }
  3153. if (typeOfSourceValue === "object") {
  3154. if (sourceValue instanceof Array) {
  3155. destination[prop] = [];
  3156. if (sourceValue.length > 0) {
  3157. if (typeof sourceValue[0] == "object") {
  3158. for (var index = 0; index < sourceValue.length; index++) {
  3159. var clonedValue = cloneValue(sourceValue[index], destination);
  3160. if (destination[prop].indexOf(clonedValue) === -1) {
  3161. destination[prop].push(clonedValue);
  3162. }
  3163. }
  3164. }
  3165. else {
  3166. destination[prop] = sourceValue.slice(0);
  3167. }
  3168. }
  3169. }
  3170. else {
  3171. destination[prop] = cloneValue(sourceValue, destination);
  3172. }
  3173. }
  3174. else {
  3175. destination[prop] = sourceValue;
  3176. }
  3177. }
  3178. };
  3179. Tools.IsEmpty = function (obj) {
  3180. for (var i in obj) {
  3181. return false;
  3182. }
  3183. return true;
  3184. };
  3185. Tools.RegisterTopRootEvents = function (events) {
  3186. for (var index = 0; index < events.length; index++) {
  3187. var event = events[index];
  3188. window.addEventListener(event.name, event.handler, false);
  3189. try {
  3190. if (window.parent) {
  3191. window.parent.addEventListener(event.name, event.handler, false);
  3192. }
  3193. }
  3194. catch (e) {
  3195. }
  3196. }
  3197. };
  3198. Tools.UnregisterTopRootEvents = function (events) {
  3199. for (var index = 0; index < events.length; index++) {
  3200. var event = events[index];
  3201. window.removeEventListener(event.name, event.handler);
  3202. try {
  3203. if (window.parent) {
  3204. window.parent.removeEventListener(event.name, event.handler);
  3205. }
  3206. }
  3207. catch (e) {
  3208. }
  3209. }
  3210. };
  3211. Tools.DumpFramebuffer = function (width, height, engine) {
  3212. // Read the contents of the framebuffer
  3213. var numberOfChannelsByLine = width * 4;
  3214. var halfHeight = height / 2;
  3215. //Reading datas from WebGL
  3216. var data = engine.readPixels(0, 0, width, height);
  3217. for (var i = 0; i < halfHeight; i++) {
  3218. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3219. var currentCell = j + i * numberOfChannelsByLine;
  3220. var targetLine = height - i - 1;
  3221. var targetCell = j + targetLine * numberOfChannelsByLine;
  3222. var temp = data[currentCell];
  3223. data[currentCell] = data[targetCell];
  3224. data[targetCell] = temp;
  3225. }
  3226. }
  3227. // Create a 2D canvas to store the result
  3228. if (!screenshotCanvas) {
  3229. screenshotCanvas = document.createElement('canvas');
  3230. }
  3231. screenshotCanvas.width = width;
  3232. screenshotCanvas.height = height;
  3233. var context = screenshotCanvas.getContext('2d');
  3234. // Copy the pixels to a 2D canvas
  3235. var imageData = context.createImageData(width, height);
  3236. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3237. var castData = imageData.data;
  3238. castData.set(data);
  3239. context.putImageData(imageData, 0, 0);
  3240. var base64Image = screenshotCanvas.toDataURL();
  3241. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3242. if (("download" in document.createElement("a"))) {
  3243. var a = window.document.createElement("a");
  3244. a.href = base64Image;
  3245. var date = new Date();
  3246. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3247. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3248. window.document.body.appendChild(a);
  3249. a.addEventListener("click", function () {
  3250. a.parentElement.removeChild(a);
  3251. });
  3252. a.click();
  3253. }
  3254. else {
  3255. var newWindow = window.open("");
  3256. var img = newWindow.document.createElement("img");
  3257. img.src = base64Image;
  3258. newWindow.document.body.appendChild(img);
  3259. }
  3260. };
  3261. Tools.CreateScreenshot = function (engine, camera, size) {
  3262. var width;
  3263. var height;
  3264. var scene = camera.getScene();
  3265. var previousCamera = null;
  3266. if (scene.activeCamera !== camera) {
  3267. previousCamera = scene.activeCamera;
  3268. scene.activeCamera = camera;
  3269. }
  3270. //If a precision value is specified
  3271. if (size.precision) {
  3272. width = Math.round(engine.getRenderWidth() * size.precision);
  3273. height = Math.round(width / engine.getAspectRatio(camera));
  3274. size = { width: width, height: height };
  3275. }
  3276. else if (size.width && size.height) {
  3277. width = size.width;
  3278. height = size.height;
  3279. }
  3280. else if (size.width && !size.height) {
  3281. width = size.width;
  3282. height = Math.round(width / engine.getAspectRatio(camera));
  3283. size = { width: width, height: height };
  3284. }
  3285. else if (size.height && !size.width) {
  3286. height = size.height;
  3287. width = Math.round(height * engine.getAspectRatio(camera));
  3288. size = { width: width, height: height };
  3289. }
  3290. else if (!isNaN(size)) {
  3291. height = size;
  3292. width = size;
  3293. }
  3294. else {
  3295. Tools.Error("Invalid 'size' parameter !");
  3296. return;
  3297. }
  3298. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3299. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3300. texture.renderList = scene.meshes;
  3301. texture.onAfterRender = function () {
  3302. Tools.DumpFramebuffer(width, height, engine);
  3303. };
  3304. scene.incrementRenderId();
  3305. texture.render(true);
  3306. texture.dispose();
  3307. if (previousCamera) {
  3308. scene.activeCamera = previousCamera;
  3309. }
  3310. };
  3311. // XHR response validator for local file scenario
  3312. Tools.ValidateXHRData = function (xhr, dataType) {
  3313. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3314. if (dataType === void 0) { dataType = 7; }
  3315. try {
  3316. if (dataType & 1) {
  3317. if (xhr.responseText && xhr.responseText.length > 0) {
  3318. return true;
  3319. }
  3320. else if (dataType === 1) {
  3321. return false;
  3322. }
  3323. }
  3324. if (dataType & 2) {
  3325. // Check header width and height since there is no "TGA" magic number
  3326. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3327. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3328. return true;
  3329. }
  3330. else if (dataType === 2) {
  3331. return false;
  3332. }
  3333. }
  3334. if (dataType & 4) {
  3335. // Check for the "DDS" magic number
  3336. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3337. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3338. return true;
  3339. }
  3340. else {
  3341. return false;
  3342. }
  3343. }
  3344. }
  3345. catch (e) {
  3346. }
  3347. return false;
  3348. };
  3349. Object.defineProperty(Tools, "NoneLogLevel", {
  3350. get: function () {
  3351. return Tools._NoneLogLevel;
  3352. },
  3353. enumerable: true,
  3354. configurable: true
  3355. });
  3356. Object.defineProperty(Tools, "MessageLogLevel", {
  3357. get: function () {
  3358. return Tools._MessageLogLevel;
  3359. },
  3360. enumerable: true,
  3361. configurable: true
  3362. });
  3363. Object.defineProperty(Tools, "WarningLogLevel", {
  3364. get: function () {
  3365. return Tools._WarningLogLevel;
  3366. },
  3367. enumerable: true,
  3368. configurable: true
  3369. });
  3370. Object.defineProperty(Tools, "ErrorLogLevel", {
  3371. get: function () {
  3372. return Tools._ErrorLogLevel;
  3373. },
  3374. enumerable: true,
  3375. configurable: true
  3376. });
  3377. Object.defineProperty(Tools, "AllLogLevel", {
  3378. get: function () {
  3379. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3380. },
  3381. enumerable: true,
  3382. configurable: true
  3383. });
  3384. Tools._AddLogEntry = function (entry) {
  3385. Tools._LogCache = entry + Tools._LogCache;
  3386. if (Tools.OnNewCacheEntry) {
  3387. Tools.OnNewCacheEntry(entry);
  3388. }
  3389. };
  3390. Tools._FormatMessage = function (message) {
  3391. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3392. var date = new Date();
  3393. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3394. };
  3395. Tools._LogDisabled = function (message) {
  3396. // nothing to do
  3397. };
  3398. Tools._LogEnabled = function (message) {
  3399. var formattedMessage = Tools._FormatMessage(message);
  3400. console.log("BJS - " + formattedMessage);
  3401. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3402. Tools._AddLogEntry(entry);
  3403. };
  3404. Tools._WarnDisabled = function (message) {
  3405. // nothing to do
  3406. };
  3407. Tools._WarnEnabled = function (message) {
  3408. var formattedMessage = Tools._FormatMessage(message);
  3409. console.warn("BJS - " + formattedMessage);
  3410. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3411. Tools._AddLogEntry(entry);
  3412. };
  3413. Tools._ErrorDisabled = function (message) {
  3414. // nothing to do
  3415. };
  3416. Tools._ErrorEnabled = function (message) {
  3417. var formattedMessage = Tools._FormatMessage(message);
  3418. console.error("BJS - " + formattedMessage);
  3419. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3420. Tools._AddLogEntry(entry);
  3421. };
  3422. Object.defineProperty(Tools, "LogCache", {
  3423. get: function () {
  3424. return Tools._LogCache;
  3425. },
  3426. enumerable: true,
  3427. configurable: true
  3428. });
  3429. Object.defineProperty(Tools, "LogLevels", {
  3430. set: function (level) {
  3431. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3432. Tools.Log = Tools._LogEnabled;
  3433. }
  3434. else {
  3435. Tools.Log = Tools._LogDisabled;
  3436. }
  3437. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3438. Tools.Warn = Tools._WarnEnabled;
  3439. }
  3440. else {
  3441. Tools.Warn = Tools._WarnDisabled;
  3442. }
  3443. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3444. Tools.Error = Tools._ErrorEnabled;
  3445. }
  3446. else {
  3447. Tools.Error = Tools._ErrorDisabled;
  3448. }
  3449. },
  3450. enumerable: true,
  3451. configurable: true
  3452. });
  3453. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3454. get: function () {
  3455. return Tools._PerformanceNoneLogLevel;
  3456. },
  3457. enumerable: true,
  3458. configurable: true
  3459. });
  3460. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3461. get: function () {
  3462. return Tools._PerformanceUserMarkLogLevel;
  3463. },
  3464. enumerable: true,
  3465. configurable: true
  3466. });
  3467. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3468. get: function () {
  3469. return Tools._PerformanceConsoleLogLevel;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3475. set: function (level) {
  3476. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3477. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3478. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3479. return;
  3480. }
  3481. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3482. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3483. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3484. return;
  3485. }
  3486. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3487. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3488. },
  3489. enumerable: true,
  3490. configurable: true
  3491. });
  3492. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3493. };
  3494. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3495. };
  3496. Tools._StartUserMark = function (counterName, condition) {
  3497. if (condition === void 0) { condition = true; }
  3498. if (!condition || !Tools._performance.mark) {
  3499. return;
  3500. }
  3501. Tools._performance.mark(counterName + "-Begin");
  3502. };
  3503. Tools._EndUserMark = function (counterName, condition) {
  3504. if (condition === void 0) { condition = true; }
  3505. if (!condition || !Tools._performance.mark) {
  3506. return;
  3507. }
  3508. Tools._performance.mark(counterName + "-End");
  3509. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3510. };
  3511. Tools._StartPerformanceConsole = function (counterName, condition) {
  3512. if (condition === void 0) { condition = true; }
  3513. if (!condition) {
  3514. return;
  3515. }
  3516. Tools._StartUserMark(counterName, condition);
  3517. if (console.time) {
  3518. console.time(counterName);
  3519. }
  3520. };
  3521. Tools._EndPerformanceConsole = function (counterName, condition) {
  3522. if (condition === void 0) { condition = true; }
  3523. if (!condition) {
  3524. return;
  3525. }
  3526. Tools._EndUserMark(counterName, condition);
  3527. if (console.time) {
  3528. console.timeEnd(counterName);
  3529. }
  3530. };
  3531. Object.defineProperty(Tools, "Now", {
  3532. get: function () {
  3533. if (window.performance && window.performance.now) {
  3534. return window.performance.now();
  3535. }
  3536. return new Date().getTime();
  3537. },
  3538. enumerable: true,
  3539. configurable: true
  3540. });
  3541. // Deprecated
  3542. Tools.GetFps = function () {
  3543. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3544. return 0;
  3545. };
  3546. Tools.BaseUrl = "";
  3547. Tools.GetExponantOfTwo = function (value, max) {
  3548. var count = 1;
  3549. do {
  3550. count *= 2;
  3551. } while (count < value);
  3552. if (count > max)
  3553. count = max;
  3554. return count;
  3555. };
  3556. // Logs
  3557. Tools._NoneLogLevel = 0;
  3558. Tools._MessageLogLevel = 1;
  3559. Tools._WarningLogLevel = 2;
  3560. Tools._ErrorLogLevel = 4;
  3561. Tools._LogCache = "";
  3562. Tools.Log = Tools._LogEnabled;
  3563. Tools.Warn = Tools._WarnEnabled;
  3564. Tools.Error = Tools._ErrorEnabled;
  3565. // Performances
  3566. Tools._PerformanceNoneLogLevel = 0;
  3567. Tools._PerformanceUserMarkLogLevel = 1;
  3568. Tools._PerformanceConsoleLogLevel = 2;
  3569. Tools._performance = window.performance;
  3570. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3571. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3572. return Tools;
  3573. })();
  3574. BABYLON.Tools = Tools;
  3575. /**
  3576. * An implementation of a loop for asynchronous functions.
  3577. */
  3578. var AsyncLoop = (function () {
  3579. /**
  3580. * Constroctor.
  3581. * @param iterations the number of iterations.
  3582. * @param _fn the function to run each iteration
  3583. * @param _successCallback the callback that will be called upon succesful execution
  3584. * @param offset starting offset.
  3585. */
  3586. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3587. if (offset === void 0) { offset = 0; }
  3588. this.iterations = iterations;
  3589. this._fn = _fn;
  3590. this._successCallback = _successCallback;
  3591. this.index = offset - 1;
  3592. this._done = false;
  3593. }
  3594. /**
  3595. * Execute the next iteration. Must be called after the last iteration was finished.
  3596. */
  3597. AsyncLoop.prototype.executeNext = function () {
  3598. if (!this._done) {
  3599. if (this.index + 1 < this.iterations) {
  3600. ++this.index;
  3601. this._fn(this);
  3602. }
  3603. else {
  3604. this.breakLoop();
  3605. }
  3606. }
  3607. };
  3608. /**
  3609. * Break the loop and run the success callback.
  3610. */
  3611. AsyncLoop.prototype.breakLoop = function () {
  3612. this._done = true;
  3613. this._successCallback();
  3614. };
  3615. /**
  3616. * Helper function
  3617. */
  3618. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3619. if (offset === void 0) { offset = 0; }
  3620. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3621. loop.executeNext();
  3622. return loop;
  3623. };
  3624. /**
  3625. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3626. * @param iterations total number of iterations
  3627. * @param syncedIterations number of synchronous iterations in each async iteration.
  3628. * @param fn the function to call each iteration.
  3629. * @param callback a success call back that will be called when iterating stops.
  3630. * @param breakFunction a break condition (optional)
  3631. * @param timeout timeout settings for the setTimeout function. default - 0.
  3632. * @constructor
  3633. */
  3634. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3635. if (timeout === void 0) { timeout = 0; }
  3636. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3637. if (breakFunction && breakFunction())
  3638. loop.breakLoop();
  3639. else {
  3640. setTimeout(function () {
  3641. for (var i = 0; i < syncedIterations; ++i) {
  3642. var iteration = (loop.index * syncedIterations) + i;
  3643. if (iteration >= iterations)
  3644. break;
  3645. fn(iteration);
  3646. if (breakFunction && breakFunction()) {
  3647. loop.breakLoop();
  3648. break;
  3649. }
  3650. }
  3651. loop.executeNext();
  3652. }, timeout);
  3653. }
  3654. }, callback);
  3655. };
  3656. return AsyncLoop;
  3657. })();
  3658. BABYLON.AsyncLoop = AsyncLoop;
  3659. })(BABYLON || (BABYLON = {}));
  3660. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3661. (function (BABYLON) {
  3662. var _DepthCullingState = (function () {
  3663. function _DepthCullingState() {
  3664. this._isDepthTestDirty = false;
  3665. this._isDepthMaskDirty = false;
  3666. this._isDepthFuncDirty = false;
  3667. this._isCullFaceDirty = false;
  3668. this._isCullDirty = false;
  3669. this._isZOffsetDirty = false;
  3670. }
  3671. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3672. get: function () {
  3673. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3674. },
  3675. enumerable: true,
  3676. configurable: true
  3677. });
  3678. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3679. get: function () {
  3680. return this._zOffset;
  3681. },
  3682. set: function (value) {
  3683. if (this._zOffset === value) {
  3684. return;
  3685. }
  3686. this._zOffset = value;
  3687. this._isZOffsetDirty = true;
  3688. },
  3689. enumerable: true,
  3690. configurable: true
  3691. });
  3692. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3693. get: function () {
  3694. return this._cullFace;
  3695. },
  3696. set: function (value) {
  3697. if (this._cullFace === value) {
  3698. return;
  3699. }
  3700. this._cullFace = value;
  3701. this._isCullFaceDirty = true;
  3702. },
  3703. enumerable: true,
  3704. configurable: true
  3705. });
  3706. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3707. get: function () {
  3708. return this._cull;
  3709. },
  3710. set: function (value) {
  3711. if (this._cull === value) {
  3712. return;
  3713. }
  3714. this._cull = value;
  3715. this._isCullDirty = true;
  3716. },
  3717. enumerable: true,
  3718. configurable: true
  3719. });
  3720. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3721. get: function () {
  3722. return this._depthFunc;
  3723. },
  3724. set: function (value) {
  3725. if (this._depthFunc === value) {
  3726. return;
  3727. }
  3728. this._depthFunc = value;
  3729. this._isDepthFuncDirty = true;
  3730. },
  3731. enumerable: true,
  3732. configurable: true
  3733. });
  3734. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3735. get: function () {
  3736. return this._depthMask;
  3737. },
  3738. set: function (value) {
  3739. if (this._depthMask === value) {
  3740. return;
  3741. }
  3742. this._depthMask = value;
  3743. this._isDepthMaskDirty = true;
  3744. },
  3745. enumerable: true,
  3746. configurable: true
  3747. });
  3748. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3749. get: function () {
  3750. return this._depthTest;
  3751. },
  3752. set: function (value) {
  3753. if (this._depthTest === value) {
  3754. return;
  3755. }
  3756. this._depthTest = value;
  3757. this._isDepthTestDirty = true;
  3758. },
  3759. enumerable: true,
  3760. configurable: true
  3761. });
  3762. _DepthCullingState.prototype.reset = function () {
  3763. this._depthMask = true;
  3764. this._depthTest = true;
  3765. this._depthFunc = null;
  3766. this._cull = null;
  3767. this._cullFace = null;
  3768. this._zOffset = 0;
  3769. this._isDepthTestDirty = true;
  3770. this._isDepthMaskDirty = true;
  3771. this._isDepthFuncDirty = false;
  3772. this._isCullFaceDirty = false;
  3773. this._isCullDirty = false;
  3774. this._isZOffsetDirty = false;
  3775. };
  3776. _DepthCullingState.prototype.apply = function (gl) {
  3777. if (!this.isDirty) {
  3778. return;
  3779. }
  3780. // Cull
  3781. if (this._isCullDirty) {
  3782. if (this.cull) {
  3783. gl.enable(gl.CULL_FACE);
  3784. }
  3785. else {
  3786. gl.disable(gl.CULL_FACE);
  3787. }
  3788. this._isCullDirty = false;
  3789. }
  3790. // Cull face
  3791. if (this._isCullFaceDirty) {
  3792. gl.cullFace(this.cullFace);
  3793. this._isCullFaceDirty = false;
  3794. }
  3795. // Depth mask
  3796. if (this._isDepthMaskDirty) {
  3797. gl.depthMask(this.depthMask);
  3798. this._isDepthMaskDirty = false;
  3799. }
  3800. // Depth test
  3801. if (this._isDepthTestDirty) {
  3802. if (this.depthTest) {
  3803. gl.enable(gl.DEPTH_TEST);
  3804. }
  3805. else {
  3806. gl.disable(gl.DEPTH_TEST);
  3807. }
  3808. this._isDepthTestDirty = false;
  3809. }
  3810. // Depth func
  3811. if (this._isDepthFuncDirty) {
  3812. gl.depthFunc(this.depthFunc);
  3813. this._isDepthFuncDirty = false;
  3814. }
  3815. // zOffset
  3816. if (this._isZOffsetDirty) {
  3817. if (this.zOffset) {
  3818. gl.enable(gl.POLYGON_OFFSET_FILL);
  3819. gl.polygonOffset(this.zOffset, 0);
  3820. }
  3821. else {
  3822. gl.disable(gl.POLYGON_OFFSET_FILL);
  3823. }
  3824. this._isZOffsetDirty = false;
  3825. }
  3826. };
  3827. return _DepthCullingState;
  3828. })();
  3829. BABYLON._DepthCullingState = _DepthCullingState;
  3830. var _AlphaState = (function () {
  3831. function _AlphaState() {
  3832. this._isAlphaBlendDirty = false;
  3833. this._isBlendFunctionParametersDirty = false;
  3834. this._alphaBlend = false;
  3835. this._blendFunctionParameters = new Array(4);
  3836. }
  3837. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3838. get: function () {
  3839. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3840. },
  3841. enumerable: true,
  3842. configurable: true
  3843. });
  3844. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3845. get: function () {
  3846. return this._alphaBlend;
  3847. },
  3848. set: function (value) {
  3849. if (this._alphaBlend === value) {
  3850. return;
  3851. }
  3852. this._alphaBlend = value;
  3853. this._isAlphaBlendDirty = true;
  3854. },
  3855. enumerable: true,
  3856. configurable: true
  3857. });
  3858. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3859. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3860. return;
  3861. }
  3862. this._blendFunctionParameters[0] = value0;
  3863. this._blendFunctionParameters[1] = value1;
  3864. this._blendFunctionParameters[2] = value2;
  3865. this._blendFunctionParameters[3] = value3;
  3866. this._isBlendFunctionParametersDirty = true;
  3867. };
  3868. _AlphaState.prototype.reset = function () {
  3869. this._alphaBlend = false;
  3870. this._blendFunctionParameters[0] = null;
  3871. this._blendFunctionParameters[1] = null;
  3872. this._blendFunctionParameters[2] = null;
  3873. this._blendFunctionParameters[3] = null;
  3874. this._isAlphaBlendDirty = true;
  3875. this._isBlendFunctionParametersDirty = false;
  3876. };
  3877. _AlphaState.prototype.apply = function (gl) {
  3878. if (!this.isDirty) {
  3879. return;
  3880. }
  3881. // Alpha blend
  3882. if (this._isAlphaBlendDirty) {
  3883. if (this._alphaBlend) {
  3884. gl.enable(gl.BLEND);
  3885. }
  3886. else {
  3887. gl.disable(gl.BLEND);
  3888. }
  3889. this._isAlphaBlendDirty = false;
  3890. }
  3891. // Alpha function
  3892. if (this._isBlendFunctionParametersDirty) {
  3893. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3894. this._isBlendFunctionParametersDirty = false;
  3895. }
  3896. };
  3897. return _AlphaState;
  3898. })();
  3899. BABYLON._AlphaState = _AlphaState;
  3900. var compileShader = function (gl, source, type, defines) {
  3901. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3902. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3903. gl.compileShader(shader);
  3904. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3905. throw new Error(gl.getShaderInfoLog(shader));
  3906. }
  3907. return shader;
  3908. };
  3909. var getWebGLTextureType = function (gl, type) {
  3910. var textureType = gl.UNSIGNED_BYTE;
  3911. if (type === Engine.TEXTURETYPE_FLOAT)
  3912. textureType = gl.FLOAT;
  3913. return textureType;
  3914. };
  3915. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3916. var magFilter = gl.NEAREST;
  3917. var minFilter = gl.NEAREST;
  3918. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3919. magFilter = gl.LINEAR;
  3920. if (generateMipMaps) {
  3921. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3922. }
  3923. else {
  3924. minFilter = gl.LINEAR;
  3925. }
  3926. }
  3927. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3928. magFilter = gl.LINEAR;
  3929. if (generateMipMaps) {
  3930. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3931. }
  3932. else {
  3933. minFilter = gl.LINEAR;
  3934. }
  3935. }
  3936. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3937. magFilter = gl.NEAREST;
  3938. if (generateMipMaps) {
  3939. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3940. }
  3941. else {
  3942. minFilter = gl.NEAREST;
  3943. }
  3944. }
  3945. return {
  3946. min: minFilter,
  3947. mag: magFilter
  3948. };
  3949. };
  3950. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3952. var engine = scene.getEngine();
  3953. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3954. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3955. gl.bindTexture(gl.TEXTURE_2D, texture);
  3956. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3957. texture._baseWidth = width;
  3958. texture._baseHeight = height;
  3959. texture._width = potWidth;
  3960. texture._height = potHeight;
  3961. texture.isReady = true;
  3962. processFunction(potWidth, potHeight);
  3963. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3965. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3966. if (!noMipmap && !isCompressed) {
  3967. gl.generateMipmap(gl.TEXTURE_2D);
  3968. }
  3969. gl.bindTexture(gl.TEXTURE_2D, null);
  3970. engine._activeTexturesCache = [];
  3971. texture.samplingMode = samplingMode;
  3972. scene._removePendingData(texture);
  3973. };
  3974. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3975. var onload = function () {
  3976. loadedImages[index] = img;
  3977. loadedImages._internalCount++;
  3978. scene._removePendingData(img);
  3979. if (loadedImages._internalCount === 6) {
  3980. onfinish(loadedImages);
  3981. }
  3982. };
  3983. var onerror = function () {
  3984. scene._removePendingData(img);
  3985. };
  3986. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3987. scene._addPendingData(img);
  3988. };
  3989. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3990. var loadedImages = [];
  3991. loadedImages._internalCount = 0;
  3992. for (var index = 0; index < 6; index++) {
  3993. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3994. }
  3995. };
  3996. var EngineCapabilities = (function () {
  3997. function EngineCapabilities() {
  3998. }
  3999. return EngineCapabilities;
  4000. })();
  4001. BABYLON.EngineCapabilities = EngineCapabilities;
  4002. /**
  4003. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  4004. */
  4005. var Engine = (function () {
  4006. /**
  4007. * @constructor
  4008. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  4009. * @param {boolean} [antialias] - enable antialias
  4010. * @param options - further options to be sent to the getContext function
  4011. */
  4012. function Engine(canvas, antialias, options) {
  4013. var _this = this;
  4014. // Public members
  4015. this.isFullscreen = false;
  4016. this.isPointerLock = false;
  4017. this.cullBackFaces = true;
  4018. this.renderEvenInBackground = true;
  4019. this.scenes = new Array();
  4020. this._windowIsBackground = false;
  4021. this._loadingDivBackgroundColor = "black";
  4022. this._drawCalls = 0;
  4023. this._renderingQueueLaunched = false;
  4024. this._activeRenderLoops = [];
  4025. // FPS
  4026. this.fpsRange = 60;
  4027. this.previousFramesDuration = [];
  4028. this.fps = 60;
  4029. this.deltaTime = 0;
  4030. // States
  4031. this._depthCullingState = new _DepthCullingState();
  4032. this._alphaState = new _AlphaState();
  4033. this._alphaMode = Engine.ALPHA_DISABLE;
  4034. // Cache
  4035. this._loadedTexturesCache = new Array();
  4036. this._activeTexturesCache = new Array();
  4037. this._compiledEffects = {};
  4038. this._uintIndicesCurrentlySet = false;
  4039. this._renderingCanvas = canvas;
  4040. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4041. options = options || {};
  4042. options.antialias = antialias;
  4043. try {
  4044. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4045. }
  4046. catch (e) {
  4047. throw new Error("WebGL not supported");
  4048. }
  4049. if (!this._gl) {
  4050. throw new Error("WebGL not supported");
  4051. }
  4052. this._onBlur = function () {
  4053. _this._windowIsBackground = true;
  4054. };
  4055. this._onFocus = function () {
  4056. _this._windowIsBackground = false;
  4057. };
  4058. window.addEventListener("blur", this._onBlur);
  4059. window.addEventListener("focus", this._onFocus);
  4060. // Viewport
  4061. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4062. this.resize();
  4063. // Caps
  4064. this._caps = new EngineCapabilities();
  4065. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4066. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4067. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4068. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4069. // Infos
  4070. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4071. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4072. if (rendererInfo != null) {
  4073. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4074. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4075. }
  4076. if (!this._glVendor) {
  4077. this._glVendor = "Unknown vendor";
  4078. }
  4079. if (!this._glRenderer) {
  4080. this._glRenderer = "Unknown renderer";
  4081. }
  4082. // Extensions
  4083. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4084. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4085. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4086. 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');
  4087. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4088. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4089. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4090. this._caps.highPrecisionShaderSupported = true;
  4091. if (this._gl.getShaderPrecisionFormat) {
  4092. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  4093. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  4094. }
  4095. // Depth buffer
  4096. this.setDepthBuffer(true);
  4097. this.setDepthFunctionToLessOrEqual();
  4098. this.setDepthWrite(true);
  4099. // Fullscreen
  4100. this._onFullscreenChange = function () {
  4101. if (document.fullscreen !== undefined) {
  4102. _this.isFullscreen = document.fullscreen;
  4103. }
  4104. else if (document.mozFullScreen !== undefined) {
  4105. _this.isFullscreen = document.mozFullScreen;
  4106. }
  4107. else if (document.webkitIsFullScreen !== undefined) {
  4108. _this.isFullscreen = document.webkitIsFullScreen;
  4109. }
  4110. else if (document.msIsFullScreen !== undefined) {
  4111. _this.isFullscreen = document.msIsFullScreen;
  4112. }
  4113. // Pointer lock
  4114. if (_this.isFullscreen && _this._pointerLockRequested) {
  4115. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4116. if (canvas.requestPointerLock) {
  4117. canvas.requestPointerLock();
  4118. }
  4119. }
  4120. };
  4121. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4122. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4123. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4124. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4125. // Pointer lock
  4126. this._onPointerLockChange = function () {
  4127. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4128. };
  4129. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4130. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4131. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4132. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4133. if (!Engine.audioEngine) {
  4134. Engine.audioEngine = new BABYLON.AudioEngine();
  4135. }
  4136. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4137. }
  4138. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4139. get: function () {
  4140. return Engine._ALPHA_DISABLE;
  4141. },
  4142. enumerable: true,
  4143. configurable: true
  4144. });
  4145. Object.defineProperty(Engine, "ALPHA_ADD", {
  4146. get: function () {
  4147. return Engine._ALPHA_ADD;
  4148. },
  4149. enumerable: true,
  4150. configurable: true
  4151. });
  4152. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4153. get: function () {
  4154. return Engine._ALPHA_COMBINE;
  4155. },
  4156. enumerable: true,
  4157. configurable: true
  4158. });
  4159. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4160. get: function () {
  4161. return Engine._DELAYLOADSTATE_NONE;
  4162. },
  4163. enumerable: true,
  4164. configurable: true
  4165. });
  4166. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4167. get: function () {
  4168. return Engine._DELAYLOADSTATE_LOADED;
  4169. },
  4170. enumerable: true,
  4171. configurable: true
  4172. });
  4173. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4174. get: function () {
  4175. return Engine._DELAYLOADSTATE_LOADING;
  4176. },
  4177. enumerable: true,
  4178. configurable: true
  4179. });
  4180. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4181. get: function () {
  4182. return Engine._DELAYLOADSTATE_NOTLOADED;
  4183. },
  4184. enumerable: true,
  4185. configurable: true
  4186. });
  4187. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4188. get: function () {
  4189. return Engine._TEXTUREFORMAT_ALPHA;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4195. get: function () {
  4196. return Engine._TEXTUREFORMAT_LUMINANCE;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4202. get: function () {
  4203. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4204. },
  4205. enumerable: true,
  4206. configurable: true
  4207. });
  4208. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4209. get: function () {
  4210. return Engine._TEXTUREFORMAT_RGB;
  4211. },
  4212. enumerable: true,
  4213. configurable: true
  4214. });
  4215. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4216. get: function () {
  4217. return Engine._TEXTUREFORMAT_RGBA;
  4218. },
  4219. enumerable: true,
  4220. configurable: true
  4221. });
  4222. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4223. get: function () {
  4224. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4225. },
  4226. enumerable: true,
  4227. configurable: true
  4228. });
  4229. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4230. get: function () {
  4231. return Engine._TEXTURETYPE_FLOAT;
  4232. },
  4233. enumerable: true,
  4234. configurable: true
  4235. });
  4236. Object.defineProperty(Engine, "Version", {
  4237. get: function () {
  4238. return "2.1.0 beta";
  4239. },
  4240. enumerable: true,
  4241. configurable: true
  4242. });
  4243. Engine.prototype._prepareWorkingCanvas = function () {
  4244. if (this._workingCanvas) {
  4245. return;
  4246. }
  4247. this._workingCanvas = document.createElement("canvas");
  4248. this._workingContext = this._workingCanvas.getContext("2d");
  4249. };
  4250. Engine.prototype.getGlInfo = function () {
  4251. return {
  4252. vendor: this._glVendor,
  4253. renderer: this._glRenderer,
  4254. version: this._glVersion
  4255. };
  4256. };
  4257. Engine.prototype.getAspectRatio = function (camera) {
  4258. var viewport = camera.viewport;
  4259. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4260. };
  4261. Engine.prototype.getRenderWidth = function () {
  4262. if (this._currentRenderTarget) {
  4263. return this._currentRenderTarget._width;
  4264. }
  4265. return this._renderingCanvas.width;
  4266. };
  4267. Engine.prototype.getRenderHeight = function () {
  4268. if (this._currentRenderTarget) {
  4269. return this._currentRenderTarget._height;
  4270. }
  4271. return this._renderingCanvas.height;
  4272. };
  4273. Engine.prototype.getRenderingCanvas = function () {
  4274. return this._renderingCanvas;
  4275. };
  4276. Engine.prototype.getRenderingCanvasClientRect = function () {
  4277. return this._renderingCanvas.getBoundingClientRect();
  4278. };
  4279. Engine.prototype.setHardwareScalingLevel = function (level) {
  4280. this._hardwareScalingLevel = level;
  4281. this.resize();
  4282. };
  4283. Engine.prototype.getHardwareScalingLevel = function () {
  4284. return this._hardwareScalingLevel;
  4285. };
  4286. Engine.prototype.getLoadedTexturesCache = function () {
  4287. return this._loadedTexturesCache;
  4288. };
  4289. Engine.prototype.getCaps = function () {
  4290. return this._caps;
  4291. };
  4292. Object.defineProperty(Engine.prototype, "drawCalls", {
  4293. get: function () {
  4294. return this._drawCalls;
  4295. },
  4296. enumerable: true,
  4297. configurable: true
  4298. });
  4299. // Methods
  4300. Engine.prototype.resetDrawCalls = function () {
  4301. this._drawCalls = 0;
  4302. };
  4303. Engine.prototype.setDepthFunctionToGreater = function () {
  4304. this._depthCullingState.depthFunc = this._gl.GREATER;
  4305. };
  4306. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4307. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4308. };
  4309. Engine.prototype.setDepthFunctionToLess = function () {
  4310. this._depthCullingState.depthFunc = this._gl.LESS;
  4311. };
  4312. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4313. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4314. };
  4315. /**
  4316. * stop executing a render loop function and remove it from the execution array
  4317. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4318. */
  4319. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4320. if (!renderFunction) {
  4321. this._activeRenderLoops = [];
  4322. return;
  4323. }
  4324. var index = this._activeRenderLoops.indexOf(renderFunction);
  4325. if (index >= 0) {
  4326. this._activeRenderLoops.splice(index, 1);
  4327. }
  4328. };
  4329. Engine.prototype._renderLoop = function () {
  4330. var _this = this;
  4331. var shouldRender = true;
  4332. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4333. shouldRender = false;
  4334. }
  4335. if (shouldRender) {
  4336. // Start new frame
  4337. this.beginFrame();
  4338. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4339. var renderFunction = this._activeRenderLoops[index];
  4340. renderFunction();
  4341. }
  4342. // Present
  4343. this.endFrame();
  4344. }
  4345. if (this._activeRenderLoops.length > 0) {
  4346. // Register new frame
  4347. BABYLON.Tools.QueueNewFrame(function () {
  4348. _this._renderLoop();
  4349. });
  4350. }
  4351. else {
  4352. this._renderingQueueLaunched = false;
  4353. }
  4354. };
  4355. /**
  4356. * Register and execute a render loop. The engine can have more than one render function.
  4357. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4358. * @example
  4359. * engine.runRenderLoop(function () {
  4360. * scene.render()
  4361. * })
  4362. */
  4363. Engine.prototype.runRenderLoop = function (renderFunction) {
  4364. var _this = this;
  4365. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4366. return;
  4367. }
  4368. this._activeRenderLoops.push(renderFunction);
  4369. if (!this._renderingQueueLaunched) {
  4370. this._renderingQueueLaunched = true;
  4371. BABYLON.Tools.QueueNewFrame(function () {
  4372. _this._renderLoop();
  4373. });
  4374. }
  4375. };
  4376. /**
  4377. * Toggle full screen mode.
  4378. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4379. */
  4380. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4381. if (this.isFullscreen) {
  4382. BABYLON.Tools.ExitFullscreen();
  4383. }
  4384. else {
  4385. this._pointerLockRequested = requestPointerLock;
  4386. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4387. }
  4388. };
  4389. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4390. this.applyStates();
  4391. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4392. if (this._depthCullingState.depthMask) {
  4393. this._gl.clearDepth(1.0);
  4394. }
  4395. var mode = 0;
  4396. if (backBuffer)
  4397. mode |= this._gl.COLOR_BUFFER_BIT;
  4398. if (depthStencil && this._depthCullingState.depthMask)
  4399. mode |= this._gl.DEPTH_BUFFER_BIT;
  4400. this._gl.clear(mode);
  4401. };
  4402. /**
  4403. * Set the WebGL's viewport
  4404. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4405. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4406. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4407. */
  4408. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4409. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  4410. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  4411. var x = viewport.x || 0;
  4412. var y = viewport.y || 0;
  4413. this._cachedViewport = viewport;
  4414. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4415. };
  4416. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4417. this._cachedViewport = null;
  4418. this._gl.viewport(x, y, width, height);
  4419. };
  4420. Engine.prototype.beginFrame = function () {
  4421. this._measureFps();
  4422. };
  4423. Engine.prototype.endFrame = function () {
  4424. //this.flushFramebuffer();
  4425. };
  4426. /**
  4427. * resize the view according to the canvas' size.
  4428. * @example
  4429. * window.addEventListener("resize", function () {
  4430. * engine.resize();
  4431. * });
  4432. */
  4433. Engine.prototype.resize = function () {
  4434. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  4435. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  4436. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  4437. };
  4438. /**
  4439. * force a specific size of the canvas
  4440. * @param {number} width - the new canvas' width
  4441. * @param {number} height - the new canvas' height
  4442. */
  4443. Engine.prototype.setSize = function (width, height) {
  4444. this._renderingCanvas.width = width;
  4445. this._renderingCanvas.height = height;
  4446. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4447. };
  4448. Engine.prototype.bindFramebuffer = function (texture) {
  4449. this._currentRenderTarget = texture;
  4450. var gl = this._gl;
  4451. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4452. this._gl.viewport(0, 0, texture._width, texture._height);
  4453. this.wipeCaches();
  4454. };
  4455. Engine.prototype.unBindFramebuffer = function (texture) {
  4456. this._currentRenderTarget = null;
  4457. if (texture.generateMipMaps) {
  4458. var gl = this._gl;
  4459. gl.bindTexture(gl.TEXTURE_2D, texture);
  4460. gl.generateMipmap(gl.TEXTURE_2D);
  4461. gl.bindTexture(gl.TEXTURE_2D, null);
  4462. }
  4463. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4464. };
  4465. Engine.prototype.flushFramebuffer = function () {
  4466. this._gl.flush();
  4467. };
  4468. Engine.prototype.restoreDefaultFramebuffer = function () {
  4469. this._currentRenderTarget = null;
  4470. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4471. this.setViewport(this._cachedViewport);
  4472. this.wipeCaches();
  4473. };
  4474. // VBOs
  4475. Engine.prototype._resetVertexBufferBinding = function () {
  4476. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4477. this._cachedVertexBuffers = null;
  4478. };
  4479. Engine.prototype.createVertexBuffer = function (vertices) {
  4480. var vbo = this._gl.createBuffer();
  4481. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4482. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4483. this._resetVertexBufferBinding();
  4484. vbo.references = 1;
  4485. return vbo;
  4486. };
  4487. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4488. var vbo = this._gl.createBuffer();
  4489. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4490. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4491. this._resetVertexBufferBinding();
  4492. vbo.references = 1;
  4493. return vbo;
  4494. };
  4495. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4496. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4497. if (offset === undefined) {
  4498. offset = 0;
  4499. }
  4500. if (vertices instanceof Float32Array) {
  4501. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4502. }
  4503. else {
  4504. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4505. }
  4506. this._resetVertexBufferBinding();
  4507. };
  4508. Engine.prototype._resetIndexBufferBinding = function () {
  4509. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4510. this._cachedIndexBuffer = null;
  4511. };
  4512. Engine.prototype.createIndexBuffer = function (indices) {
  4513. var vbo = this._gl.createBuffer();
  4514. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4515. // Check for 32 bits indices
  4516. var arrayBuffer;
  4517. var need32Bits = false;
  4518. if (this._caps.uintIndices) {
  4519. for (var index = 0; index < indices.length; index++) {
  4520. if (indices[index] > 65535) {
  4521. need32Bits = true;
  4522. break;
  4523. }
  4524. }
  4525. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4526. }
  4527. else {
  4528. arrayBuffer = new Uint16Array(indices);
  4529. }
  4530. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4531. this._resetIndexBufferBinding();
  4532. vbo.references = 1;
  4533. vbo.is32Bits = need32Bits;
  4534. return vbo;
  4535. };
  4536. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4537. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4538. this._cachedVertexBuffers = vertexBuffer;
  4539. this._cachedEffectForVertexBuffers = effect;
  4540. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4541. var offset = 0;
  4542. for (var index = 0; index < vertexDeclaration.length; index++) {
  4543. var order = effect.getAttributeLocation(index);
  4544. if (order >= 0) {
  4545. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4546. }
  4547. offset += vertexDeclaration[index] * 4;
  4548. }
  4549. }
  4550. if (this._cachedIndexBuffer !== indexBuffer) {
  4551. this._cachedIndexBuffer = indexBuffer;
  4552. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4553. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4554. }
  4555. };
  4556. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4557. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4558. this._cachedVertexBuffers = vertexBuffers;
  4559. this._cachedEffectForVertexBuffers = effect;
  4560. var attributes = effect.getAttributesNames();
  4561. for (var index = 0; index < attributes.length; index++) {
  4562. var order = effect.getAttributeLocation(index);
  4563. if (order >= 0) {
  4564. var vertexBuffer = vertexBuffers[attributes[index]];
  4565. if (!vertexBuffer) {
  4566. continue;
  4567. }
  4568. var stride = vertexBuffer.getStrideSize();
  4569. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4570. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4571. }
  4572. }
  4573. }
  4574. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4575. this._cachedIndexBuffer = indexBuffer;
  4576. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4577. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4578. }
  4579. };
  4580. Engine.prototype._releaseBuffer = function (buffer) {
  4581. buffer.references--;
  4582. if (buffer.references === 0) {
  4583. this._gl.deleteBuffer(buffer);
  4584. return true;
  4585. }
  4586. return false;
  4587. };
  4588. Engine.prototype.createInstancesBuffer = function (capacity) {
  4589. var buffer = this._gl.createBuffer();
  4590. buffer.capacity = capacity;
  4591. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4592. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4593. return buffer;
  4594. };
  4595. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4596. this._gl.deleteBuffer(buffer);
  4597. };
  4598. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4599. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4600. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4601. for (var index = 0; index < 4; index++) {
  4602. var offsetLocation = offsetLocations[index];
  4603. this._gl.enableVertexAttribArray(offsetLocation);
  4604. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4605. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4606. }
  4607. };
  4608. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4609. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4610. for (var index = 0; index < 4; index++) {
  4611. var offsetLocation = offsetLocations[index];
  4612. this._gl.disableVertexAttribArray(offsetLocation);
  4613. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4614. }
  4615. };
  4616. Engine.prototype.applyStates = function () {
  4617. this._depthCullingState.apply(this._gl);
  4618. this._alphaState.apply(this._gl);
  4619. };
  4620. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4621. // Apply states
  4622. this.applyStates();
  4623. this._drawCalls++;
  4624. // Render
  4625. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4626. if (instancesCount) {
  4627. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4628. return;
  4629. }
  4630. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4631. };
  4632. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4633. // Apply states
  4634. this.applyStates();
  4635. this._drawCalls++;
  4636. if (instancesCount) {
  4637. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4638. return;
  4639. }
  4640. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4641. };
  4642. // Shaders
  4643. Engine.prototype._releaseEffect = function (effect) {
  4644. if (this._compiledEffects[effect._key]) {
  4645. delete this._compiledEffects[effect._key];
  4646. if (effect.getProgram()) {
  4647. this._gl.deleteProgram(effect.getProgram());
  4648. }
  4649. }
  4650. };
  4651. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4652. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4653. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4654. var name = vertex + "+" + fragment + "@" + defines;
  4655. if (this._compiledEffects[name]) {
  4656. return this._compiledEffects[name];
  4657. }
  4658. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4659. effect._key = name;
  4660. this._compiledEffects[name] = effect;
  4661. return effect;
  4662. };
  4663. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4664. if (uniformsNames === void 0) { uniformsNames = []; }
  4665. if (samplers === void 0) { samplers = []; }
  4666. if (defines === void 0) { defines = ""; }
  4667. return this.createEffect({
  4668. vertex: "particles",
  4669. fragmentElement: fragmentName
  4670. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4671. };
  4672. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4673. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4674. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4675. var shaderProgram = this._gl.createProgram();
  4676. this._gl.attachShader(shaderProgram, vertexShader);
  4677. this._gl.attachShader(shaderProgram, fragmentShader);
  4678. this._gl.linkProgram(shaderProgram);
  4679. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4680. if (!linked) {
  4681. var error = this._gl.getProgramInfoLog(shaderProgram);
  4682. if (error) {
  4683. throw new Error(error);
  4684. }
  4685. }
  4686. this._gl.deleteShader(vertexShader);
  4687. this._gl.deleteShader(fragmentShader);
  4688. return shaderProgram;
  4689. };
  4690. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4691. var results = [];
  4692. for (var index = 0; index < uniformsNames.length; index++) {
  4693. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4694. }
  4695. return results;
  4696. };
  4697. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4698. var results = [];
  4699. for (var index = 0; index < attributesNames.length; index++) {
  4700. try {
  4701. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4702. }
  4703. catch (e) {
  4704. results.push(-1);
  4705. }
  4706. }
  4707. return results;
  4708. };
  4709. Engine.prototype.enableEffect = function (effect) {
  4710. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4711. if (effect && effect.onBind) {
  4712. effect.onBind(effect);
  4713. }
  4714. return;
  4715. }
  4716. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4717. // Use program
  4718. this._gl.useProgram(effect.getProgram());
  4719. for (var i in this._vertexAttribArrays) {
  4720. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4721. continue;
  4722. }
  4723. this._vertexAttribArrays[i] = false;
  4724. this._gl.disableVertexAttribArray(i);
  4725. }
  4726. var attributesCount = effect.getAttributesCount();
  4727. for (var index = 0; index < attributesCount; index++) {
  4728. // Attributes
  4729. var order = effect.getAttributeLocation(index);
  4730. if (order >= 0) {
  4731. this._vertexAttribArrays[order] = true;
  4732. this._gl.enableVertexAttribArray(order);
  4733. }
  4734. }
  4735. this._currentEffect = effect;
  4736. if (effect.onBind) {
  4737. effect.onBind(effect);
  4738. }
  4739. };
  4740. Engine.prototype.setArray = function (uniform, array) {
  4741. if (!uniform)
  4742. return;
  4743. this._gl.uniform1fv(uniform, array);
  4744. };
  4745. Engine.prototype.setArray2 = function (uniform, array) {
  4746. if (!uniform || array.length % 2 !== 0)
  4747. return;
  4748. this._gl.uniform2fv(uniform, array);
  4749. };
  4750. Engine.prototype.setArray3 = function (uniform, array) {
  4751. if (!uniform || array.length % 3 !== 0)
  4752. return;
  4753. this._gl.uniform3fv(uniform, array);
  4754. };
  4755. Engine.prototype.setArray4 = function (uniform, array) {
  4756. if (!uniform || array.length % 4 !== 0)
  4757. return;
  4758. this._gl.uniform4fv(uniform, array);
  4759. };
  4760. Engine.prototype.setMatrices = function (uniform, matrices) {
  4761. if (!uniform)
  4762. return;
  4763. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4764. };
  4765. Engine.prototype.setMatrix = function (uniform, matrix) {
  4766. if (!uniform)
  4767. return;
  4768. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4769. };
  4770. Engine.prototype.setFloat = function (uniform, value) {
  4771. if (!uniform)
  4772. return;
  4773. this._gl.uniform1f(uniform, value);
  4774. };
  4775. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4776. if (!uniform)
  4777. return;
  4778. this._gl.uniform2f(uniform, x, y);
  4779. };
  4780. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4781. if (!uniform)
  4782. return;
  4783. this._gl.uniform3f(uniform, x, y, z);
  4784. };
  4785. Engine.prototype.setBool = function (uniform, bool) {
  4786. if (!uniform)
  4787. return;
  4788. this._gl.uniform1i(uniform, bool);
  4789. };
  4790. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4791. if (!uniform)
  4792. return;
  4793. this._gl.uniform4f(uniform, x, y, z, w);
  4794. };
  4795. Engine.prototype.setColor3 = function (uniform, color3) {
  4796. if (!uniform)
  4797. return;
  4798. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4799. };
  4800. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4801. if (!uniform)
  4802. return;
  4803. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4804. };
  4805. // States
  4806. Engine.prototype.setState = function (culling, zOffset, force) {
  4807. if (zOffset === void 0) { zOffset = 0; }
  4808. // Culling
  4809. if (this._depthCullingState.cull !== culling || force) {
  4810. if (culling) {
  4811. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4812. this._depthCullingState.cull = true;
  4813. }
  4814. else {
  4815. this._depthCullingState.cull = false;
  4816. }
  4817. }
  4818. // Z offset
  4819. this._depthCullingState.zOffset = zOffset;
  4820. };
  4821. Engine.prototype.setDepthBuffer = function (enable) {
  4822. this._depthCullingState.depthTest = enable;
  4823. };
  4824. Engine.prototype.getDepthWrite = function () {
  4825. return this._depthCullingState.depthMask;
  4826. };
  4827. Engine.prototype.setDepthWrite = function (enable) {
  4828. this._depthCullingState.depthMask = enable;
  4829. };
  4830. Engine.prototype.setColorWrite = function (enable) {
  4831. this._gl.colorMask(enable, enable, enable, enable);
  4832. };
  4833. Engine.prototype.setAlphaMode = function (mode) {
  4834. switch (mode) {
  4835. case Engine.ALPHA_DISABLE:
  4836. this.setDepthWrite(true);
  4837. this._alphaState.alphaBlend = false;
  4838. break;
  4839. case Engine.ALPHA_COMBINE:
  4840. this.setDepthWrite(false);
  4841. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4842. this._alphaState.alphaBlend = true;
  4843. break;
  4844. case Engine.ALPHA_ADD:
  4845. this.setDepthWrite(false);
  4846. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4847. this._alphaState.alphaBlend = true;
  4848. break;
  4849. }
  4850. this._alphaMode = mode;
  4851. };
  4852. Engine.prototype.getAlphaMode = function () {
  4853. return this._alphaMode;
  4854. };
  4855. Engine.prototype.setAlphaTesting = function (enable) {
  4856. this._alphaTest = enable;
  4857. };
  4858. Engine.prototype.getAlphaTesting = function () {
  4859. return this._alphaTest;
  4860. };
  4861. // Textures
  4862. Engine.prototype.wipeCaches = function () {
  4863. this._activeTexturesCache = [];
  4864. this._currentEffect = null;
  4865. this._depthCullingState.reset();
  4866. this._alphaState.reset();
  4867. this._cachedVertexBuffers = null;
  4868. this._cachedIndexBuffer = null;
  4869. this._cachedEffectForVertexBuffers = null;
  4870. };
  4871. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4872. var gl = this._gl;
  4873. gl.bindTexture(gl.TEXTURE_2D, texture);
  4874. var magFilter = gl.NEAREST;
  4875. var minFilter = gl.NEAREST;
  4876. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4877. magFilter = gl.LINEAR;
  4878. minFilter = gl.LINEAR;
  4879. }
  4880. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4881. magFilter = gl.LINEAR;
  4882. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4883. }
  4884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4886. gl.bindTexture(gl.TEXTURE_2D, null);
  4887. texture.samplingMode = samplingMode;
  4888. };
  4889. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4890. var _this = this;
  4891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4892. if (onLoad === void 0) { onLoad = null; }
  4893. if (onError === void 0) { onError = null; }
  4894. if (buffer === void 0) { buffer = null; }
  4895. var texture = this._gl.createTexture();
  4896. var extension;
  4897. var fromData = false;
  4898. if (url.substr(0, 5) === "data:") {
  4899. fromData = true;
  4900. }
  4901. if (!fromData)
  4902. extension = url.substr(url.length - 4, 4).toLowerCase();
  4903. else {
  4904. var oldUrl = url;
  4905. fromData = oldUrl.split(':');
  4906. url = oldUrl;
  4907. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4908. }
  4909. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4910. var isTGA = (extension === ".tga");
  4911. scene._addPendingData(texture);
  4912. texture.url = url;
  4913. texture.noMipmap = noMipmap;
  4914. texture.references = 1;
  4915. this._loadedTexturesCache.push(texture);
  4916. var onerror = function () {
  4917. scene._removePendingData(texture);
  4918. if (onError) {
  4919. onError();
  4920. }
  4921. };
  4922. if (isTGA) {
  4923. var callback = function (arrayBuffer) {
  4924. var data = new Uint8Array(arrayBuffer);
  4925. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4926. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4927. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4928. if (onLoad) {
  4929. onLoad();
  4930. }
  4931. }, samplingMode);
  4932. };
  4933. if (!(fromData instanceof Array))
  4934. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4935. callback(arrayBuffer);
  4936. }, onerror, scene.database, true);
  4937. else
  4938. callback(buffer);
  4939. }
  4940. else if (isDDS) {
  4941. callback = function (data) {
  4942. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4943. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4944. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4945. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4946. if (onLoad) {
  4947. onLoad();
  4948. }
  4949. }, samplingMode);
  4950. };
  4951. if (!(fromData instanceof Array))
  4952. BABYLON.Tools.LoadFile(url, function (data) {
  4953. callback(data);
  4954. }, onerror, scene.database, true);
  4955. else
  4956. callback(buffer);
  4957. }
  4958. else {
  4959. var onload = function (img) {
  4960. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4961. var isPot = (img.width === potWidth && img.height === potHeight);
  4962. if (!isPot) {
  4963. _this._prepareWorkingCanvas();
  4964. _this._workingCanvas.width = potWidth;
  4965. _this._workingCanvas.height = potHeight;
  4966. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4967. _this._workingContext.imageSmoothingEnabled = false;
  4968. _this._workingContext.mozImageSmoothingEnabled = false;
  4969. _this._workingContext.oImageSmoothingEnabled = false;
  4970. _this._workingContext.webkitImageSmoothingEnabled = false;
  4971. _this._workingContext.msImageSmoothingEnabled = false;
  4972. }
  4973. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4974. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4975. _this._workingContext.imageSmoothingEnabled = true;
  4976. _this._workingContext.mozImageSmoothingEnabled = true;
  4977. _this._workingContext.oImageSmoothingEnabled = true;
  4978. _this._workingContext.webkitImageSmoothingEnabled = true;
  4979. _this._workingContext.msImageSmoothingEnabled = true;
  4980. }
  4981. }
  4982. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4983. if (onLoad) {
  4984. onLoad();
  4985. }
  4986. }, samplingMode);
  4987. };
  4988. if (!(fromData instanceof Array))
  4989. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4990. else
  4991. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4992. }
  4993. return texture;
  4994. };
  4995. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4996. var texture = this._gl.createTexture();
  4997. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4998. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4999. // Format
  5000. var internalFormat = this._gl.RGBA;
  5001. switch (format) {
  5002. case Engine.TEXTUREFORMAT_ALPHA:
  5003. internalFormat = this._gl.ALPHA;
  5004. break;
  5005. case Engine.TEXTUREFORMAT_LUMINANCE:
  5006. internalFormat = this._gl.LUMINANCE;
  5007. break;
  5008. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5009. internalFormat = this._gl.LUMINANCE_ALPHA;
  5010. break;
  5011. case Engine.TEXTUREFORMAT_RGB:
  5012. internalFormat = this._gl.RGB;
  5013. break;
  5014. case Engine.TEXTUREFORMAT_RGBA:
  5015. internalFormat = this._gl.RGBA;
  5016. break;
  5017. }
  5018. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  5019. if (generateMipMaps) {
  5020. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5021. }
  5022. // Filters
  5023. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  5024. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5025. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5026. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5027. this._activeTexturesCache = [];
  5028. texture._baseWidth = width;
  5029. texture._baseHeight = height;
  5030. texture._width = width;
  5031. texture._height = height;
  5032. texture.isReady = true;
  5033. texture.references = 1;
  5034. texture.samplingMode = samplingMode;
  5035. this._loadedTexturesCache.push(texture);
  5036. return texture;
  5037. };
  5038. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5039. var texture = this._gl.createTexture();
  5040. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5041. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5042. this._activeTexturesCache = [];
  5043. texture._baseWidth = width;
  5044. texture._baseHeight = height;
  5045. texture._width = width;
  5046. texture._height = height;
  5047. texture.isReady = false;
  5048. texture.generateMipMaps = generateMipMaps;
  5049. texture.references = 1;
  5050. texture.samplingMode = samplingMode;
  5051. this.updateTextureSamplingMode(samplingMode, texture);
  5052. this._loadedTexturesCache.push(texture);
  5053. return texture;
  5054. };
  5055. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5056. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5057. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5058. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5059. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5060. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5061. };
  5062. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5063. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5064. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5065. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5066. if (texture.generateMipMaps) {
  5067. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5068. }
  5069. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5070. this._activeTexturesCache = [];
  5071. texture.isReady = true;
  5072. };
  5073. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5074. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5075. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5076. // Scale the video if it is a NPOT using the current working canvas
  5077. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5078. if (!texture._workingCanvas) {
  5079. texture._workingCanvas = document.createElement("canvas");
  5080. texture._workingContext = texture._workingCanvas.getContext("2d");
  5081. texture._workingCanvas.width = texture._width;
  5082. texture._workingCanvas.height = texture._height;
  5083. }
  5084. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5085. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5086. }
  5087. else {
  5088. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5089. }
  5090. if (texture.generateMipMaps) {
  5091. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5092. }
  5093. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5094. this._activeTexturesCache = [];
  5095. texture.isReady = true;
  5096. };
  5097. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5098. // old version had a "generateMipMaps" arg instead of options.
  5099. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5100. // in the same way, generateDepthBuffer is defaulted to true
  5101. var generateMipMaps = false;
  5102. var generateDepthBuffer = true;
  5103. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5104. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5105. if (options !== undefined) {
  5106. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5107. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5108. type = options.type === undefined ? type : options.type;
  5109. if (options.samplingMode !== undefined) {
  5110. samplingMode = options.samplingMode;
  5111. }
  5112. if (type === Engine.TEXTURETYPE_FLOAT) {
  5113. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5114. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5115. }
  5116. }
  5117. var gl = this._gl;
  5118. var texture = gl.createTexture();
  5119. gl.bindTexture(gl.TEXTURE_2D, texture);
  5120. var width = size.width || size;
  5121. var height = size.height || size;
  5122. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5123. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5124. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5125. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5126. }
  5127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5129. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5130. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5131. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5132. var depthBuffer;
  5133. // Create the depth buffer
  5134. if (generateDepthBuffer) {
  5135. depthBuffer = gl.createRenderbuffer();
  5136. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5137. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5138. }
  5139. // Create the framebuffer
  5140. var framebuffer = gl.createFramebuffer();
  5141. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5142. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5143. if (generateDepthBuffer) {
  5144. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5145. }
  5146. // Unbind
  5147. gl.bindTexture(gl.TEXTURE_2D, null);
  5148. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5149. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5150. texture._framebuffer = framebuffer;
  5151. if (generateDepthBuffer) {
  5152. texture._depthBuffer = depthBuffer;
  5153. }
  5154. texture._width = width;
  5155. texture._height = height;
  5156. texture.isReady = true;
  5157. texture.generateMipMaps = generateMipMaps;
  5158. texture.references = 1;
  5159. texture.samplingMode = samplingMode;
  5160. this._activeTexturesCache = [];
  5161. this._loadedTexturesCache.push(texture);
  5162. return texture;
  5163. };
  5164. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5165. var _this = this;
  5166. var gl = this._gl;
  5167. var texture = gl.createTexture();
  5168. texture.isCube = true;
  5169. texture.url = rootUrl;
  5170. texture.references = 1;
  5171. this._loadedTexturesCache.push(texture);
  5172. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5173. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5174. if (isDDS) {
  5175. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5176. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5177. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5178. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5179. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5180. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5181. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5182. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5183. }
  5184. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5185. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5186. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5187. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5188. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5189. _this._activeTexturesCache = [];
  5190. texture._width = info.width;
  5191. texture._height = info.height;
  5192. texture.isReady = true;
  5193. }, null, null, true);
  5194. }
  5195. else {
  5196. cascadeLoad(rootUrl, scene, function (imgs) {
  5197. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5198. var height = width;
  5199. _this._prepareWorkingCanvas();
  5200. _this._workingCanvas.width = width;
  5201. _this._workingCanvas.height = height;
  5202. var faces = [
  5203. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5204. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5205. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5206. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5207. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5208. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5209. ];
  5210. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5211. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5212. for (var index = 0; index < faces.length; index++) {
  5213. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5214. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5215. }
  5216. if (!noMipmap) {
  5217. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5218. }
  5219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5221. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5222. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5223. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5224. _this._activeTexturesCache = [];
  5225. texture._width = width;
  5226. texture._height = height;
  5227. texture.isReady = true;
  5228. }, extensions);
  5229. }
  5230. return texture;
  5231. };
  5232. Engine.prototype._releaseTexture = function (texture) {
  5233. var gl = this._gl;
  5234. if (texture._framebuffer) {
  5235. gl.deleteFramebuffer(texture._framebuffer);
  5236. }
  5237. if (texture._depthBuffer) {
  5238. gl.deleteRenderbuffer(texture._depthBuffer);
  5239. }
  5240. gl.deleteTexture(texture);
  5241. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5242. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5243. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5244. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5245. this._activeTexturesCache[channel] = null;
  5246. }
  5247. var index = this._loadedTexturesCache.indexOf(texture);
  5248. if (index !== -1) {
  5249. this._loadedTexturesCache.splice(index, 1);
  5250. }
  5251. };
  5252. Engine.prototype.bindSamplers = function (effect) {
  5253. this._gl.useProgram(effect.getProgram());
  5254. var samplers = effect.getSamplers();
  5255. for (var index = 0; index < samplers.length; index++) {
  5256. var uniform = effect.getUniform(samplers[index]);
  5257. this._gl.uniform1i(uniform, index);
  5258. }
  5259. this._currentEffect = null;
  5260. };
  5261. Engine.prototype._bindTexture = function (channel, texture) {
  5262. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5263. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5264. this._activeTexturesCache[channel] = null;
  5265. };
  5266. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5267. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5268. };
  5269. Engine.prototype.setTexture = function (channel, texture) {
  5270. if (channel < 0) {
  5271. return;
  5272. }
  5273. // Not ready?
  5274. if (!texture || !texture.isReady()) {
  5275. if (this._activeTexturesCache[channel] != null) {
  5276. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5277. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5278. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5279. this._activeTexturesCache[channel] = null;
  5280. }
  5281. return;
  5282. }
  5283. // Video
  5284. if (texture instanceof BABYLON.VideoTexture) {
  5285. if (texture.update()) {
  5286. this._activeTexturesCache[channel] = null;
  5287. }
  5288. }
  5289. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5290. texture.delayLoad();
  5291. return;
  5292. }
  5293. if (this._activeTexturesCache[channel] === texture) {
  5294. return;
  5295. }
  5296. this._activeTexturesCache[channel] = texture;
  5297. var internalTexture = texture.getInternalTexture();
  5298. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5299. if (internalTexture.isCube) {
  5300. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5301. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5302. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5303. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5304. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5305. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5306. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5307. }
  5308. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5309. }
  5310. else {
  5311. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5312. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5313. internalTexture._cachedWrapU = texture.wrapU;
  5314. switch (texture.wrapU) {
  5315. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5316. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5317. break;
  5318. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5319. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5320. break;
  5321. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5322. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5323. break;
  5324. }
  5325. }
  5326. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5327. internalTexture._cachedWrapV = texture.wrapV;
  5328. switch (texture.wrapV) {
  5329. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5331. break;
  5332. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5333. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5334. break;
  5335. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5336. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5337. break;
  5338. }
  5339. }
  5340. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5341. }
  5342. };
  5343. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5344. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5345. var value = texture.anisotropicFilteringLevel;
  5346. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5347. value = 1;
  5348. }
  5349. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5350. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5351. texture._cachedAnisotropicFilteringLevel = value;
  5352. }
  5353. };
  5354. Engine.prototype.readPixels = function (x, y, width, height) {
  5355. var data = new Uint8Array(height * width * 4);
  5356. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5357. return data;
  5358. };
  5359. // Dispose
  5360. Engine.prototype.dispose = function () {
  5361. this.hideLoadingUI();
  5362. this.stopRenderLoop();
  5363. while (this.scenes.length) {
  5364. this.scenes[0].dispose();
  5365. }
  5366. // Release audio engine
  5367. Engine.audioEngine.dispose();
  5368. for (var name in this._compiledEffects) {
  5369. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5370. }
  5371. for (var i in this._vertexAttribArrays) {
  5372. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5373. continue;
  5374. }
  5375. this._gl.disableVertexAttribArray(i);
  5376. }
  5377. // Events
  5378. window.removeEventListener("blur", this._onBlur);
  5379. window.removeEventListener("focus", this._onFocus);
  5380. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5381. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5382. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5383. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5384. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5385. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5386. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5387. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5388. };
  5389. // Loading screen
  5390. Engine.prototype.displayLoadingUI = function () {
  5391. var _this = this;
  5392. this._loadingDiv = document.createElement("div");
  5393. this._loadingDiv.style.opacity = "0";
  5394. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5395. // Loading text
  5396. this._loadingTextDiv = document.createElement("div");
  5397. this._loadingTextDiv.style.position = "absolute";
  5398. this._loadingTextDiv.style.left = "0";
  5399. this._loadingTextDiv.style.top = "50%";
  5400. this._loadingTextDiv.style.marginTop = "80px";
  5401. this._loadingTextDiv.style.width = "100%";
  5402. this._loadingTextDiv.style.height = "20px";
  5403. this._loadingTextDiv.style.fontFamily = "Arial";
  5404. this._loadingTextDiv.style.fontSize = "14px";
  5405. this._loadingTextDiv.style.color = "white";
  5406. this._loadingTextDiv.style.textAlign = "center";
  5407. this._loadingTextDiv.innerHTML = "Loading";
  5408. this._loadingDiv.appendChild(this._loadingTextDiv);
  5409. // Loading img
  5410. var imgBack = new Image();
  5411. 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==";
  5412. imgBack.style.position = "absolute";
  5413. imgBack.style.left = "50%";
  5414. imgBack.style.top = "50%";
  5415. imgBack.style.marginLeft = "-50px";
  5416. imgBack.style.marginTop = "-50px";
  5417. imgBack.style.transition = "transform 1.0s ease";
  5418. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5419. var deg = 360;
  5420. var onTransitionEnd = function () {
  5421. deg += 360;
  5422. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5423. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5424. };
  5425. imgBack.addEventListener("transitionend", onTransitionEnd);
  5426. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5427. this._loadingDiv.appendChild(imgBack);
  5428. // front image
  5429. var imgFront = new Image();
  5430. 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=";
  5431. imgFront.style.position = "absolute";
  5432. imgFront.style.left = "50%";
  5433. imgFront.style.top = "50%";
  5434. imgFront.style.marginLeft = "-50px";
  5435. imgFront.style.marginTop = "-50px";
  5436. this._loadingDiv.appendChild(imgFront);
  5437. // Resize
  5438. this._resizeLoadingUI = function () {
  5439. var canvasRect = _this.getRenderingCanvasClientRect();
  5440. _this._loadingDiv.style.position = "absolute";
  5441. _this._loadingDiv.style.left = canvasRect.left + "px";
  5442. _this._loadingDiv.style.top = canvasRect.top + "px";
  5443. _this._loadingDiv.style.width = canvasRect.width + "px";
  5444. _this._loadingDiv.style.height = canvasRect.height + "px";
  5445. };
  5446. this._resizeLoadingUI();
  5447. window.addEventListener("resize", this._resizeLoadingUI);
  5448. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5449. document.body.appendChild(this._loadingDiv);
  5450. setTimeout(function () {
  5451. _this._loadingDiv.style.opacity = "1";
  5452. imgBack.style.transform = "rotateZ(360deg)";
  5453. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5454. }, 0);
  5455. };
  5456. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5457. set: function (text) {
  5458. if (!this._loadingDiv) {
  5459. return;
  5460. }
  5461. this._loadingTextDiv.innerHTML = text;
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5467. get: function () {
  5468. return this._loadingDivBackgroundColor;
  5469. },
  5470. set: function (color) {
  5471. this._loadingDivBackgroundColor = color;
  5472. if (!this._loadingDiv) {
  5473. return;
  5474. }
  5475. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Engine.prototype.hideLoadingUI = function () {
  5481. var _this = this;
  5482. if (!this._loadingDiv) {
  5483. return;
  5484. }
  5485. var onTransitionEnd = function () {
  5486. if (!_this._loadingDiv) {
  5487. return;
  5488. }
  5489. document.body.removeChild(_this._loadingDiv);
  5490. window.removeEventListener("resize", _this._resizeLoadingUI);
  5491. _this._loadingDiv = null;
  5492. };
  5493. this._loadingDiv.style.opacity = "0";
  5494. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5495. };
  5496. // FPS
  5497. Engine.prototype.getFps = function () {
  5498. return this.fps;
  5499. };
  5500. Engine.prototype.getDeltaTime = function () {
  5501. return this.deltaTime;
  5502. };
  5503. Engine.prototype._measureFps = function () {
  5504. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5505. var length = this.previousFramesDuration.length;
  5506. if (length >= 2) {
  5507. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5508. }
  5509. if (length >= this.fpsRange) {
  5510. if (length > this.fpsRange) {
  5511. this.previousFramesDuration.splice(0, 1);
  5512. length = this.previousFramesDuration.length;
  5513. }
  5514. var sum = 0;
  5515. for (var id = 0; id < length - 1; id++) {
  5516. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5517. }
  5518. this.fps = 1000.0 / (sum / (length - 1));
  5519. }
  5520. };
  5521. // Statics
  5522. Engine.isSupported = function () {
  5523. try {
  5524. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5525. if (navigator.isCocoonJS) {
  5526. return true;
  5527. }
  5528. var tempcanvas = document.createElement("canvas");
  5529. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5530. return gl != null && !!window.WebGLRenderingContext;
  5531. }
  5532. catch (e) {
  5533. return false;
  5534. }
  5535. };
  5536. // Const statics
  5537. Engine._ALPHA_DISABLE = 0;
  5538. Engine._ALPHA_ADD = 1;
  5539. Engine._ALPHA_COMBINE = 2;
  5540. Engine._DELAYLOADSTATE_NONE = 0;
  5541. Engine._DELAYLOADSTATE_LOADED = 1;
  5542. Engine._DELAYLOADSTATE_LOADING = 2;
  5543. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5544. Engine._TEXTUREFORMAT_ALPHA = 0;
  5545. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5546. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5547. Engine._TEXTUREFORMAT_RGB = 4;
  5548. Engine._TEXTUREFORMAT_RGBA = 4;
  5549. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5550. Engine._TEXTURETYPE_FLOAT = 1;
  5551. // Updatable statics so stick with vars here
  5552. Engine.Epsilon = 0.001;
  5553. Engine.CollisionsEpsilon = 0.001;
  5554. Engine.ShadersRepository = "Babylon/Shaders/";
  5555. return Engine;
  5556. })();
  5557. BABYLON.Engine = Engine;
  5558. })(BABYLON || (BABYLON = {}));
  5559. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5560. (function (BABYLON) {
  5561. /**
  5562. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5563. */
  5564. var Node = (function () {
  5565. /**
  5566. * @constructor
  5567. * @param {string} name - the name and id to be given to this node
  5568. * @param {BABYLON.Scene} the scene this node will be added to
  5569. */
  5570. function Node(name, scene) {
  5571. this.state = "";
  5572. this.animations = new Array();
  5573. this._childrenFlag = -1;
  5574. this._isEnabled = true;
  5575. this._isReady = true;
  5576. this._currentRenderId = -1;
  5577. this._parentRenderId = -1;
  5578. this.name = name;
  5579. this.id = name;
  5580. this._scene = scene;
  5581. this._initCache();
  5582. }
  5583. Node.prototype.getScene = function () {
  5584. return this._scene;
  5585. };
  5586. Node.prototype.getEngine = function () {
  5587. return this._scene.getEngine();
  5588. };
  5589. // override it in derived class
  5590. Node.prototype.getWorldMatrix = function () {
  5591. return BABYLON.Matrix.Identity();
  5592. };
  5593. // override it in derived class if you add new variables to the cache
  5594. // and call the parent class method
  5595. Node.prototype._initCache = function () {
  5596. this._cache = {};
  5597. this._cache.parent = undefined;
  5598. };
  5599. Node.prototype.updateCache = function (force) {
  5600. if (!force && this.isSynchronized())
  5601. return;
  5602. this._cache.parent = this.parent;
  5603. this._updateCache();
  5604. };
  5605. // override it in derived class if you add new variables to the cache
  5606. // and call the parent class method if !ignoreParentClass
  5607. Node.prototype._updateCache = function (ignoreParentClass) {
  5608. };
  5609. // override it in derived class if you add new variables to the cache
  5610. Node.prototype._isSynchronized = function () {
  5611. return true;
  5612. };
  5613. Node.prototype._markSyncedWithParent = function () {
  5614. this._parentRenderId = this.parent._currentRenderId;
  5615. };
  5616. Node.prototype.isSynchronizedWithParent = function () {
  5617. if (!this.parent) {
  5618. return true;
  5619. }
  5620. if (this._parentRenderId !== this.parent._currentRenderId) {
  5621. return false;
  5622. }
  5623. return this.parent.isSynchronized();
  5624. };
  5625. Node.prototype.isSynchronized = function (updateCache) {
  5626. var check = this.hasNewParent();
  5627. check = check || !this.isSynchronizedWithParent();
  5628. check = check || !this._isSynchronized();
  5629. if (updateCache)
  5630. this.updateCache(true);
  5631. return !check;
  5632. };
  5633. Node.prototype.hasNewParent = function (update) {
  5634. if (this._cache.parent === this.parent)
  5635. return false;
  5636. if (update)
  5637. this._cache.parent = this.parent;
  5638. return true;
  5639. };
  5640. /**
  5641. * Is this node ready to be used/rendered
  5642. * @return {boolean} is it ready
  5643. */
  5644. Node.prototype.isReady = function () {
  5645. return this._isReady;
  5646. };
  5647. /**
  5648. * Is this node enabled.
  5649. * If the node has a parent and is enabled, the parent will be inspected as well.
  5650. * @return {boolean} whether this node (and its parent) is enabled.
  5651. * @see setEnabled
  5652. */
  5653. Node.prototype.isEnabled = function () {
  5654. if (!this._isEnabled) {
  5655. return false;
  5656. }
  5657. if (this.parent) {
  5658. return this.parent.isEnabled();
  5659. }
  5660. return true;
  5661. };
  5662. /**
  5663. * Set the enabled state of this node.
  5664. * @param {boolean} value - the new enabled state
  5665. * @see isEnabled
  5666. */
  5667. Node.prototype.setEnabled = function (value) {
  5668. this._isEnabled = value;
  5669. };
  5670. /**
  5671. * Is this node a descendant of the given node.
  5672. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5673. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5674. * @see parent
  5675. */
  5676. Node.prototype.isDescendantOf = function (ancestor) {
  5677. if (this.parent) {
  5678. if (this.parent === ancestor) {
  5679. return true;
  5680. }
  5681. return this.parent.isDescendantOf(ancestor);
  5682. }
  5683. return false;
  5684. };
  5685. Node.prototype._getDescendants = function (list, results) {
  5686. for (var index = 0; index < list.length; index++) {
  5687. var item = list[index];
  5688. if (item.isDescendantOf(this)) {
  5689. results.push(item);
  5690. }
  5691. }
  5692. };
  5693. /**
  5694. * Will return all nodes that have this node as parent.
  5695. * @return {BABYLON.Node[]} all children nodes of all types.
  5696. */
  5697. Node.prototype.getDescendants = function () {
  5698. var results = [];
  5699. this._getDescendants(this._scene.meshes, results);
  5700. this._getDescendants(this._scene.lights, results);
  5701. this._getDescendants(this._scene.cameras, results);
  5702. return results;
  5703. };
  5704. Node.prototype._setReady = function (state) {
  5705. if (state == this._isReady) {
  5706. return;
  5707. }
  5708. if (!state) {
  5709. this._isReady = false;
  5710. return;
  5711. }
  5712. this._isReady = true;
  5713. if (this.onReady) {
  5714. this.onReady(this);
  5715. }
  5716. };
  5717. return Node;
  5718. })();
  5719. BABYLON.Node = Node;
  5720. })(BABYLON || (BABYLON = {}));
  5721. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5722. (function (BABYLON) {
  5723. var BoundingSphere = (function () {
  5724. function BoundingSphere(minimum, maximum) {
  5725. this.minimum = minimum;
  5726. this.maximum = maximum;
  5727. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5728. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5729. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5730. this.radius = distance * 0.5;
  5731. this.centerWorld = BABYLON.Vector3.Zero();
  5732. this._update(BABYLON.Matrix.Identity());
  5733. }
  5734. // Methods
  5735. BoundingSphere.prototype._update = function (world) {
  5736. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5737. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5738. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5739. };
  5740. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5741. for (var i = 0; i < 6; i++) {
  5742. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5743. return false;
  5744. }
  5745. return true;
  5746. };
  5747. BoundingSphere.prototype.intersectsPoint = function (point) {
  5748. var x = this.centerWorld.x - point.x;
  5749. var y = this.centerWorld.y - point.y;
  5750. var z = this.centerWorld.z - point.z;
  5751. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5752. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5753. return false;
  5754. return true;
  5755. };
  5756. // Statics
  5757. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5758. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5759. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5760. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5761. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5762. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5763. return false;
  5764. return true;
  5765. };
  5766. return BoundingSphere;
  5767. })();
  5768. BABYLON.BoundingSphere = BoundingSphere;
  5769. })(BABYLON || (BABYLON = {}));
  5770. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5771. (function (BABYLON) {
  5772. var BoundingBox = (function () {
  5773. function BoundingBox(minimum, maximum) {
  5774. this.minimum = minimum;
  5775. this.maximum = maximum;
  5776. this.vectors = new Array();
  5777. this.vectorsWorld = new Array();
  5778. // Bounding vectors
  5779. this.vectors.push(this.minimum.clone());
  5780. this.vectors.push(this.maximum.clone());
  5781. this.vectors.push(this.minimum.clone());
  5782. this.vectors[2].x = this.maximum.x;
  5783. this.vectors.push(this.minimum.clone());
  5784. this.vectors[3].y = this.maximum.y;
  5785. this.vectors.push(this.minimum.clone());
  5786. this.vectors[4].z = this.maximum.z;
  5787. this.vectors.push(this.maximum.clone());
  5788. this.vectors[5].z = this.minimum.z;
  5789. this.vectors.push(this.maximum.clone());
  5790. this.vectors[6].x = this.minimum.x;
  5791. this.vectors.push(this.maximum.clone());
  5792. this.vectors[7].y = this.minimum.y;
  5793. // OBB
  5794. this.center = this.maximum.add(this.minimum).scale(0.5);
  5795. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5796. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5797. for (var index = 0; index < this.vectors.length; index++) {
  5798. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5799. }
  5800. this.minimumWorld = BABYLON.Vector3.Zero();
  5801. this.maximumWorld = BABYLON.Vector3.Zero();
  5802. this._update(BABYLON.Matrix.Identity());
  5803. }
  5804. // Methods
  5805. BoundingBox.prototype.getWorldMatrix = function () {
  5806. return this._worldMatrix;
  5807. };
  5808. BoundingBox.prototype._update = function (world) {
  5809. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5810. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5811. for (var index = 0; index < this.vectors.length; index++) {
  5812. var v = this.vectorsWorld[index];
  5813. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5814. if (v.x < this.minimumWorld.x)
  5815. this.minimumWorld.x = v.x;
  5816. if (v.y < this.minimumWorld.y)
  5817. this.minimumWorld.y = v.y;
  5818. if (v.z < this.minimumWorld.z)
  5819. this.minimumWorld.z = v.z;
  5820. if (v.x > this.maximumWorld.x)
  5821. this.maximumWorld.x = v.x;
  5822. if (v.y > this.maximumWorld.y)
  5823. this.maximumWorld.y = v.y;
  5824. if (v.z > this.maximumWorld.z)
  5825. this.maximumWorld.z = v.z;
  5826. }
  5827. // OBB
  5828. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5829. this.center.scaleInPlace(0.5);
  5830. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5831. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5832. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5833. this._worldMatrix = world;
  5834. };
  5835. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5836. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5837. };
  5838. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5839. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5840. };
  5841. BoundingBox.prototype.intersectsPoint = function (point) {
  5842. var delta = BABYLON.Engine.Epsilon;
  5843. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5844. return false;
  5845. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5846. return false;
  5847. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5848. return false;
  5849. return true;
  5850. };
  5851. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5852. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5853. };
  5854. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5855. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5856. return false;
  5857. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5858. return false;
  5859. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5860. return false;
  5861. return true;
  5862. };
  5863. // Statics
  5864. BoundingBox.Intersects = function (box0, box1) {
  5865. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5866. return false;
  5867. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5868. return false;
  5869. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5870. return false;
  5871. return true;
  5872. };
  5873. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5874. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5875. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5876. return (num <= (sphereRadius * sphereRadius));
  5877. };
  5878. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5879. for (var p = 0; p < 6; p++) {
  5880. for (var i = 0; i < 8; i++) {
  5881. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5882. return false;
  5883. }
  5884. }
  5885. }
  5886. return true;
  5887. };
  5888. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5889. for (var p = 0; p < 6; p++) {
  5890. var inCount = 8;
  5891. for (var i = 0; i < 8; i++) {
  5892. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5893. --inCount;
  5894. }
  5895. else {
  5896. break;
  5897. }
  5898. }
  5899. if (inCount === 0)
  5900. return false;
  5901. }
  5902. return true;
  5903. };
  5904. return BoundingBox;
  5905. })();
  5906. BABYLON.BoundingBox = BoundingBox;
  5907. })(BABYLON || (BABYLON = {}));
  5908. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5909. (function (BABYLON) {
  5910. var computeBoxExtents = function (axis, box) {
  5911. var p = BABYLON.Vector3.Dot(box.center, axis);
  5912. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5913. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5914. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5915. var r = r0 + r1 + r2;
  5916. return {
  5917. min: p - r,
  5918. max: p + r
  5919. };
  5920. };
  5921. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5922. var axisOverlap = function (axis, box0, box1) {
  5923. var result0 = computeBoxExtents(axis, box0);
  5924. var result1 = computeBoxExtents(axis, box1);
  5925. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5926. };
  5927. var BoundingInfo = (function () {
  5928. function BoundingInfo(minimum, maximum) {
  5929. this.minimum = minimum;
  5930. this.maximum = maximum;
  5931. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5932. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5933. }
  5934. // Methods
  5935. BoundingInfo.prototype._update = function (world) {
  5936. this.boundingBox._update(world);
  5937. this.boundingSphere._update(world);
  5938. };
  5939. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5940. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5941. return false;
  5942. return this.boundingBox.isInFrustum(frustumPlanes);
  5943. };
  5944. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5945. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5946. };
  5947. BoundingInfo.prototype._checkCollision = function (collider) {
  5948. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5949. };
  5950. BoundingInfo.prototype.intersectsPoint = function (point) {
  5951. if (!this.boundingSphere.centerWorld) {
  5952. return false;
  5953. }
  5954. if (!this.boundingSphere.intersectsPoint(point)) {
  5955. return false;
  5956. }
  5957. if (!this.boundingBox.intersectsPoint(point)) {
  5958. return false;
  5959. }
  5960. return true;
  5961. };
  5962. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5963. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5964. return false;
  5965. }
  5966. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5967. return false;
  5968. }
  5969. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5970. return false;
  5971. }
  5972. if (!precise) {
  5973. return true;
  5974. }
  5975. var box0 = this.boundingBox;
  5976. var box1 = boundingInfo.boundingBox;
  5977. if (!axisOverlap(box0.directions[0], box0, box1))
  5978. return false;
  5979. if (!axisOverlap(box0.directions[1], box0, box1))
  5980. return false;
  5981. if (!axisOverlap(box0.directions[2], box0, box1))
  5982. return false;
  5983. if (!axisOverlap(box1.directions[0], box0, box1))
  5984. return false;
  5985. if (!axisOverlap(box1.directions[1], box0, box1))
  5986. return false;
  5987. if (!axisOverlap(box1.directions[2], box0, box1))
  5988. return false;
  5989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5990. return false;
  5991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5992. return false;
  5993. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5994. return false;
  5995. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5996. return false;
  5997. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5998. return false;
  5999. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  6000. return false;
  6001. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  6002. return false;
  6003. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  6004. return false;
  6005. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  6006. return false;
  6007. return true;
  6008. };
  6009. return BoundingInfo;
  6010. })();
  6011. BABYLON.BoundingInfo = BoundingInfo;
  6012. })(BABYLON || (BABYLON = {}));
  6013. //# sourceMappingURL=babylon.boundingInfo.js.map
  6014. var BABYLON;
  6015. (function (BABYLON) {
  6016. var Light = (function (_super) {
  6017. __extends(Light, _super);
  6018. function Light(name, scene) {
  6019. _super.call(this, name, scene);
  6020. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  6021. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  6022. this.intensity = 1.0;
  6023. this.range = Number.MAX_VALUE;
  6024. this.includeOnlyWithLayerMask = 0;
  6025. this.includedOnlyMeshes = new Array();
  6026. this.excludedMeshes = new Array();
  6027. this.excludeWithLayerMask = 0;
  6028. this._excludedMeshesIds = new Array();
  6029. this._includedOnlyMeshesIds = new Array();
  6030. scene.addLight(this);
  6031. }
  6032. Light.prototype.getShadowGenerator = function () {
  6033. return this._shadowGenerator;
  6034. };
  6035. Light.prototype.getAbsolutePosition = function () {
  6036. return BABYLON.Vector3.Zero();
  6037. };
  6038. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6039. };
  6040. Light.prototype._getWorldMatrix = function () {
  6041. return BABYLON.Matrix.Identity();
  6042. };
  6043. Light.prototype.canAffectMesh = function (mesh) {
  6044. if (!mesh) {
  6045. return true;
  6046. }
  6047. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6048. return false;
  6049. }
  6050. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6051. return false;
  6052. }
  6053. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  6054. return false;
  6055. }
  6056. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  6057. return false;
  6058. }
  6059. return true;
  6060. };
  6061. Light.prototype.getWorldMatrix = function () {
  6062. this._currentRenderId = this.getScene().getRenderId();
  6063. var worldMatrix = this._getWorldMatrix();
  6064. if (this.parent && this.parent.getWorldMatrix) {
  6065. if (!this._parentedWorldMatrix) {
  6066. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6067. }
  6068. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6069. this._markSyncedWithParent();
  6070. return this._parentedWorldMatrix;
  6071. }
  6072. return worldMatrix;
  6073. };
  6074. Light.prototype.dispose = function () {
  6075. if (this._shadowGenerator) {
  6076. this._shadowGenerator.dispose();
  6077. this._shadowGenerator = null;
  6078. }
  6079. // Remove from scene
  6080. this.getScene().removeLight(this);
  6081. };
  6082. return Light;
  6083. })(BABYLON.Node);
  6084. BABYLON.Light = Light;
  6085. })(BABYLON || (BABYLON = {}));
  6086. //# sourceMappingURL=babylon.light.js.map
  6087. var BABYLON;
  6088. (function (BABYLON) {
  6089. var PointLight = (function (_super) {
  6090. __extends(PointLight, _super);
  6091. function PointLight(name, position, scene) {
  6092. _super.call(this, name, scene);
  6093. this.position = position;
  6094. }
  6095. PointLight.prototype.getAbsolutePosition = function () {
  6096. return this._transformedPosition ? this._transformedPosition : this.position;
  6097. };
  6098. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6099. if (this.parent && this.parent.getWorldMatrix) {
  6100. if (!this._transformedPosition) {
  6101. this._transformedPosition = BABYLON.Vector3.Zero();
  6102. }
  6103. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6104. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6105. return;
  6106. }
  6107. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6108. };
  6109. PointLight.prototype.getShadowGenerator = function () {
  6110. return null;
  6111. };
  6112. PointLight.prototype._getWorldMatrix = function () {
  6113. if (!this._worldMatrix) {
  6114. this._worldMatrix = BABYLON.Matrix.Identity();
  6115. }
  6116. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6117. return this._worldMatrix;
  6118. };
  6119. return PointLight;
  6120. })(BABYLON.Light);
  6121. BABYLON.PointLight = PointLight;
  6122. })(BABYLON || (BABYLON = {}));
  6123. //# sourceMappingURL=babylon.pointLight.js.map
  6124. var BABYLON;
  6125. (function (BABYLON) {
  6126. var SpotLight = (function (_super) {
  6127. __extends(SpotLight, _super);
  6128. function SpotLight(name, position, direction, angle, exponent, scene) {
  6129. _super.call(this, name, scene);
  6130. this.position = position;
  6131. this.direction = direction;
  6132. this.angle = angle;
  6133. this.exponent = exponent;
  6134. }
  6135. SpotLight.prototype.getAbsolutePosition = function () {
  6136. return this.transformedPosition ? this.transformedPosition : this.position;
  6137. };
  6138. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6139. var activeCamera = this.getScene().activeCamera;
  6140. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6141. };
  6142. SpotLight.prototype.supportsVSM = function () {
  6143. return true;
  6144. };
  6145. SpotLight.prototype.needRefreshPerFrame = function () {
  6146. return false;
  6147. };
  6148. SpotLight.prototype.setDirectionToTarget = function (target) {
  6149. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6150. return this.direction;
  6151. };
  6152. SpotLight.prototype.computeTransformedPosition = function () {
  6153. if (this.parent && this.parent.getWorldMatrix) {
  6154. if (!this.transformedPosition) {
  6155. this.transformedPosition = BABYLON.Vector3.Zero();
  6156. }
  6157. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6158. return true;
  6159. }
  6160. return false;
  6161. };
  6162. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6163. var normalizeDirection;
  6164. if (this.parent && this.parent.getWorldMatrix) {
  6165. if (!this._transformedDirection) {
  6166. this._transformedDirection = BABYLON.Vector3.Zero();
  6167. }
  6168. this.computeTransformedPosition();
  6169. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6170. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6171. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6172. }
  6173. else {
  6174. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6175. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6176. }
  6177. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6178. };
  6179. SpotLight.prototype._getWorldMatrix = function () {
  6180. if (!this._worldMatrix) {
  6181. this._worldMatrix = BABYLON.Matrix.Identity();
  6182. }
  6183. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6184. return this._worldMatrix;
  6185. };
  6186. return SpotLight;
  6187. })(BABYLON.Light);
  6188. BABYLON.SpotLight = SpotLight;
  6189. })(BABYLON || (BABYLON = {}));
  6190. //# sourceMappingURL=babylon.spotLight.js.map
  6191. var BABYLON;
  6192. (function (BABYLON) {
  6193. var DirectionalLight = (function (_super) {
  6194. __extends(DirectionalLight, _super);
  6195. function DirectionalLight(name, direction, scene) {
  6196. _super.call(this, name, scene);
  6197. this.direction = direction;
  6198. this.shadowOrthoScale = 0.5;
  6199. this.position = direction.scale(-1);
  6200. }
  6201. DirectionalLight.prototype.getAbsolutePosition = function () {
  6202. return this.transformedPosition ? this.transformedPosition : this.position;
  6203. };
  6204. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6205. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6206. return this.direction;
  6207. };
  6208. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6209. var orthoLeft = Number.MAX_VALUE;
  6210. var orthoRight = Number.MIN_VALUE;
  6211. var orthoTop = Number.MIN_VALUE;
  6212. var orthoBottom = Number.MAX_VALUE;
  6213. var tempVector3 = BABYLON.Vector3.Zero();
  6214. var activeCamera = this.getScene().activeCamera;
  6215. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6216. var mesh = renderList[meshIndex];
  6217. if (!mesh) {
  6218. continue;
  6219. }
  6220. var boundingInfo = mesh.getBoundingInfo();
  6221. if (!boundingInfo) {
  6222. continue;
  6223. }
  6224. var boundingBox = boundingInfo.boundingBox;
  6225. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6226. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6227. if (tempVector3.x < orthoLeft)
  6228. orthoLeft = tempVector3.x;
  6229. if (tempVector3.y < orthoBottom)
  6230. orthoBottom = tempVector3.y;
  6231. if (tempVector3.x > orthoRight)
  6232. orthoRight = tempVector3.x;
  6233. if (tempVector3.y > orthoTop)
  6234. orthoTop = tempVector3.y;
  6235. }
  6236. }
  6237. var xOffset = orthoRight - orthoLeft;
  6238. var yOffset = orthoTop - orthoBottom;
  6239. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6240. };
  6241. DirectionalLight.prototype.supportsVSM = function () {
  6242. return true;
  6243. };
  6244. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6245. return true;
  6246. };
  6247. DirectionalLight.prototype.computeTransformedPosition = function () {
  6248. if (this.parent && this.parent.getWorldMatrix) {
  6249. if (!this.transformedPosition) {
  6250. this.transformedPosition = BABYLON.Vector3.Zero();
  6251. }
  6252. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6253. return true;
  6254. }
  6255. return false;
  6256. };
  6257. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6258. if (this.parent && this.parent.getWorldMatrix) {
  6259. if (!this._transformedDirection) {
  6260. this._transformedDirection = BABYLON.Vector3.Zero();
  6261. }
  6262. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6263. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6264. return;
  6265. }
  6266. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6267. };
  6268. DirectionalLight.prototype._getWorldMatrix = function () {
  6269. if (!this._worldMatrix) {
  6270. this._worldMatrix = BABYLON.Matrix.Identity();
  6271. }
  6272. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6273. return this._worldMatrix;
  6274. };
  6275. return DirectionalLight;
  6276. })(BABYLON.Light);
  6277. BABYLON.DirectionalLight = DirectionalLight;
  6278. })(BABYLON || (BABYLON = {}));
  6279. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6280. (function (BABYLON) {
  6281. var ShadowGenerator = (function () {
  6282. function ShadowGenerator(mapSize, light) {
  6283. var _this = this;
  6284. // Members
  6285. this._filter = ShadowGenerator.FILTER_NONE;
  6286. this.blurScale = 2;
  6287. this._blurBoxOffset = 0;
  6288. this._bias = 0.00005;
  6289. this._darkness = 0;
  6290. this._transparencyShadow = false;
  6291. this._viewMatrix = BABYLON.Matrix.Zero();
  6292. this._projectionMatrix = BABYLON.Matrix.Zero();
  6293. this._transformMatrix = BABYLON.Matrix.Zero();
  6294. this._worldViewProjection = BABYLON.Matrix.Zero();
  6295. this._light = light;
  6296. this._scene = light.getScene();
  6297. this._mapSize = mapSize;
  6298. light._shadowGenerator = this;
  6299. // Render target
  6300. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6301. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6302. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6303. this._shadowMap.anisotropicFilteringLevel = 1;
  6304. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6305. this._shadowMap.renderParticles = false;
  6306. this._shadowMap.onAfterUnbind = function () {
  6307. if (!_this.useBlurVarianceShadowMap) {
  6308. return;
  6309. }
  6310. if (!_this._shadowMap2) {
  6311. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6312. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6313. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6314. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6315. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6316. _this._downSamplePostprocess.onApply = function (effect) {
  6317. effect.setTexture("textureSampler", _this._shadowMap);
  6318. };
  6319. _this.blurBoxOffset = 1;
  6320. }
  6321. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6322. };
  6323. // Custom render function
  6324. var renderSubMesh = function (subMesh) {
  6325. var mesh = subMesh.getRenderingMesh();
  6326. var scene = _this._scene;
  6327. var engine = scene.getEngine();
  6328. // Culling
  6329. engine.setState(subMesh.getMaterial().backFaceCulling);
  6330. // Managing instances
  6331. var batch = mesh._getInstancesRenderList(subMesh._id);
  6332. if (batch.mustReturn) {
  6333. return;
  6334. }
  6335. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6336. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6337. engine.enableEffect(_this._effect);
  6338. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6339. var material = subMesh.getMaterial();
  6340. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6341. // Alpha test
  6342. if (material && material.needAlphaTesting()) {
  6343. var alphaTexture = material.getAlphaTestTexture();
  6344. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6345. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6346. }
  6347. // Bones
  6348. if (mesh.useBones) {
  6349. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6350. }
  6351. // Draw
  6352. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6353. }
  6354. else {
  6355. // Need to reset refresh rate of the shadowMap
  6356. _this._shadowMap.resetRefreshCounter();
  6357. }
  6358. };
  6359. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6360. var index;
  6361. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6362. renderSubMesh(opaqueSubMeshes.data[index]);
  6363. }
  6364. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6365. renderSubMesh(alphaTestSubMeshes.data[index]);
  6366. }
  6367. if (_this._transparencyShadow) {
  6368. for (index = 0; index < transparentSubMeshes.length; index++) {
  6369. renderSubMesh(transparentSubMeshes.data[index]);
  6370. }
  6371. }
  6372. };
  6373. this._shadowMap.onClear = function (engine) {
  6374. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6375. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6376. }
  6377. else {
  6378. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6379. }
  6380. };
  6381. }
  6382. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6383. // Static
  6384. get: function () {
  6385. return ShadowGenerator._FILTER_NONE;
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6391. get: function () {
  6392. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6393. },
  6394. enumerable: true,
  6395. configurable: true
  6396. });
  6397. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6398. get: function () {
  6399. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6400. },
  6401. enumerable: true,
  6402. configurable: true
  6403. });
  6404. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6405. get: function () {
  6406. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6407. },
  6408. enumerable: true,
  6409. configurable: true
  6410. });
  6411. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6412. get: function () {
  6413. return this._bias;
  6414. },
  6415. set: function (bias) {
  6416. this._bias = bias;
  6417. },
  6418. enumerable: true,
  6419. configurable: true
  6420. });
  6421. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6422. get: function () {
  6423. return this._blurBoxOffset;
  6424. },
  6425. set: function (value) {
  6426. var _this = this;
  6427. if (this._blurBoxOffset === value) {
  6428. return;
  6429. }
  6430. this._blurBoxOffset = value;
  6431. if (this._boxBlurPostprocess) {
  6432. this._boxBlurPostprocess.dispose();
  6433. }
  6434. 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);
  6435. this._boxBlurPostprocess.onApply = function (effect) {
  6436. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6437. };
  6438. },
  6439. enumerable: true,
  6440. configurable: true
  6441. });
  6442. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6443. get: function () {
  6444. return this._filter;
  6445. },
  6446. set: function (value) {
  6447. if (this._filter === value) {
  6448. return;
  6449. }
  6450. this._filter = value;
  6451. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6452. this._shadowMap.anisotropicFilteringLevel = 16;
  6453. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6454. }
  6455. else {
  6456. this._shadowMap.anisotropicFilteringLevel = 1;
  6457. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6458. }
  6459. },
  6460. enumerable: true,
  6461. configurable: true
  6462. });
  6463. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6464. get: function () {
  6465. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6466. },
  6467. set: function (value) {
  6468. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6469. },
  6470. enumerable: true,
  6471. configurable: true
  6472. });
  6473. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6474. get: function () {
  6475. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6476. },
  6477. set: function (value) {
  6478. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6479. },
  6480. enumerable: true,
  6481. configurable: true
  6482. });
  6483. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6484. get: function () {
  6485. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6486. },
  6487. set: function (value) {
  6488. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6489. },
  6490. enumerable: true,
  6491. configurable: true
  6492. });
  6493. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6494. var defines = [];
  6495. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6496. defines.push("#define VSM");
  6497. }
  6498. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6499. var mesh = subMesh.getMesh();
  6500. var material = subMesh.getMaterial();
  6501. // Alpha test
  6502. if (material && material.needAlphaTesting()) {
  6503. defines.push("#define ALPHATEST");
  6504. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6505. attribs.push(BABYLON.VertexBuffer.UVKind);
  6506. defines.push("#define UV1");
  6507. }
  6508. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6509. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6510. defines.push("#define UV2");
  6511. }
  6512. }
  6513. // Bones
  6514. if (mesh.useBones) {
  6515. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6516. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6517. defines.push("#define BONES");
  6518. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6519. }
  6520. // Instances
  6521. if (useInstances) {
  6522. defines.push("#define INSTANCES");
  6523. attribs.push("world0");
  6524. attribs.push("world1");
  6525. attribs.push("world2");
  6526. attribs.push("world3");
  6527. }
  6528. // Get correct effect
  6529. var join = defines.join("\n");
  6530. if (this._cachedDefines !== join) {
  6531. this._cachedDefines = join;
  6532. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6533. }
  6534. return this._effect.isReady();
  6535. };
  6536. ShadowGenerator.prototype.getShadowMap = function () {
  6537. return this._shadowMap;
  6538. };
  6539. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6540. if (this._shadowMap2) {
  6541. return this._shadowMap2;
  6542. }
  6543. return this._shadowMap;
  6544. };
  6545. ShadowGenerator.prototype.getLight = function () {
  6546. return this._light;
  6547. };
  6548. // Methods
  6549. ShadowGenerator.prototype.getTransformMatrix = function () {
  6550. var scene = this._scene;
  6551. if (this._currentRenderID === scene.getRenderId()) {
  6552. return this._transformMatrix;
  6553. }
  6554. this._currentRenderID = scene.getRenderId();
  6555. var lightPosition = this._light.position;
  6556. var lightDirection = this._light.direction;
  6557. if (this._light.computeTransformedPosition()) {
  6558. lightPosition = this._light.transformedPosition;
  6559. }
  6560. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6561. this._cachedPosition = lightPosition.clone();
  6562. this._cachedDirection = lightDirection.clone();
  6563. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6564. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6565. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6566. }
  6567. return this._transformMatrix;
  6568. };
  6569. ShadowGenerator.prototype.getDarkness = function () {
  6570. return this._darkness;
  6571. };
  6572. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6573. if (darkness >= 1.0)
  6574. this._darkness = 1.0;
  6575. else if (darkness <= 0.0)
  6576. this._darkness = 0.0;
  6577. else
  6578. this._darkness = darkness;
  6579. };
  6580. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6581. this._transparencyShadow = hasShadow;
  6582. };
  6583. ShadowGenerator.prototype._packHalf = function (depth) {
  6584. var scale = depth * 255.0;
  6585. var fract = scale - Math.floor(scale);
  6586. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6587. };
  6588. ShadowGenerator.prototype.dispose = function () {
  6589. this._shadowMap.dispose();
  6590. if (this._shadowMap2) {
  6591. this._shadowMap2.dispose();
  6592. }
  6593. if (this._downSamplePostprocess) {
  6594. this._downSamplePostprocess.dispose();
  6595. }
  6596. if (this._boxBlurPostprocess) {
  6597. this._boxBlurPostprocess.dispose();
  6598. }
  6599. };
  6600. ShadowGenerator._FILTER_NONE = 0;
  6601. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6602. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6603. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6604. return ShadowGenerator;
  6605. })();
  6606. BABYLON.ShadowGenerator = ShadowGenerator;
  6607. })(BABYLON || (BABYLON = {}));
  6608. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6609. var BABYLON;
  6610. (function (BABYLON) {
  6611. var HemisphericLight = (function (_super) {
  6612. __extends(HemisphericLight, _super);
  6613. function HemisphericLight(name, direction, scene) {
  6614. _super.call(this, name, scene);
  6615. this.direction = direction;
  6616. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6617. }
  6618. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6619. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6620. return this.direction;
  6621. };
  6622. HemisphericLight.prototype.getShadowGenerator = function () {
  6623. return null;
  6624. };
  6625. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6626. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6627. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6628. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6629. };
  6630. HemisphericLight.prototype._getWorldMatrix = function () {
  6631. if (!this._worldMatrix) {
  6632. this._worldMatrix = BABYLON.Matrix.Identity();
  6633. }
  6634. return this._worldMatrix;
  6635. };
  6636. return HemisphericLight;
  6637. })(BABYLON.Light);
  6638. BABYLON.HemisphericLight = HemisphericLight;
  6639. })(BABYLON || (BABYLON = {}));
  6640. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6641. (function (BABYLON) {
  6642. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6643. if (boxMin.x > sphereCenter.x + sphereRadius)
  6644. return false;
  6645. if (sphereCenter.x - sphereRadius > boxMax.x)
  6646. return false;
  6647. if (boxMin.y > sphereCenter.y + sphereRadius)
  6648. return false;
  6649. if (sphereCenter.y - sphereRadius > boxMax.y)
  6650. return false;
  6651. if (boxMin.z > sphereCenter.z + sphereRadius)
  6652. return false;
  6653. if (sphereCenter.z - sphereRadius > boxMax.z)
  6654. return false;
  6655. return true;
  6656. };
  6657. var getLowestRoot = function (a, b, c, maxR) {
  6658. var determinant = b * b - 4.0 * a * c;
  6659. var result = { root: 0, found: false };
  6660. if (determinant < 0)
  6661. return result;
  6662. var sqrtD = Math.sqrt(determinant);
  6663. var r1 = (-b - sqrtD) / (2.0 * a);
  6664. var r2 = (-b + sqrtD) / (2.0 * a);
  6665. if (r1 > r2) {
  6666. var temp = r2;
  6667. r2 = r1;
  6668. r1 = temp;
  6669. }
  6670. if (r1 > 0 && r1 < maxR) {
  6671. result.root = r1;
  6672. result.found = true;
  6673. return result;
  6674. }
  6675. if (r2 > 0 && r2 < maxR) {
  6676. result.root = r2;
  6677. result.found = true;
  6678. return result;
  6679. }
  6680. return result;
  6681. };
  6682. var Collider = (function () {
  6683. function Collider() {
  6684. this.radius = new BABYLON.Vector3(1, 1, 1);
  6685. this.retry = 0;
  6686. this.basePointWorld = BABYLON.Vector3.Zero();
  6687. this.velocityWorld = BABYLON.Vector3.Zero();
  6688. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6689. this._collisionPoint = BABYLON.Vector3.Zero();
  6690. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6691. this._tempVector = BABYLON.Vector3.Zero();
  6692. this._tempVector2 = BABYLON.Vector3.Zero();
  6693. this._tempVector3 = BABYLON.Vector3.Zero();
  6694. this._tempVector4 = BABYLON.Vector3.Zero();
  6695. this._edge = BABYLON.Vector3.Zero();
  6696. this._baseToVertex = BABYLON.Vector3.Zero();
  6697. this._destinationPoint = BABYLON.Vector3.Zero();
  6698. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6699. this._displacementVector = BABYLON.Vector3.Zero();
  6700. }
  6701. // Methods
  6702. Collider.prototype._initialize = function (source, dir, e) {
  6703. this.velocity = dir;
  6704. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6705. this.basePoint = source;
  6706. source.multiplyToRef(this.radius, this.basePointWorld);
  6707. dir.multiplyToRef(this.radius, this.velocityWorld);
  6708. this.velocityWorldLength = this.velocityWorld.length();
  6709. this.epsilon = e;
  6710. this.collisionFound = false;
  6711. };
  6712. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6713. pa.subtractToRef(point, this._tempVector);
  6714. pb.subtractToRef(point, this._tempVector2);
  6715. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6716. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6717. if (d < 0)
  6718. return false;
  6719. pc.subtractToRef(point, this._tempVector3);
  6720. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6721. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6722. if (d < 0)
  6723. return false;
  6724. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6725. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6726. return d >= 0;
  6727. };
  6728. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6729. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6730. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6731. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6732. return false;
  6733. }
  6734. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6735. return false;
  6736. return true;
  6737. };
  6738. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6739. var t0;
  6740. var embeddedInPlane = false;
  6741. if (!subMesh._trianglePlanes) {
  6742. subMesh._trianglePlanes = [];
  6743. }
  6744. if (!subMesh._trianglePlanes[faceIndex]) {
  6745. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6746. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6747. }
  6748. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6749. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6750. return;
  6751. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6752. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6753. if (normalDotVelocity == 0) {
  6754. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6755. return;
  6756. embeddedInPlane = true;
  6757. t0 = 0;
  6758. }
  6759. else {
  6760. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6761. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6762. if (t0 > t1) {
  6763. var temp = t1;
  6764. t1 = t0;
  6765. t0 = temp;
  6766. }
  6767. if (t0 > 1.0 || t1 < 0.0)
  6768. return;
  6769. if (t0 < 0)
  6770. t0 = 0;
  6771. if (t0 > 1.0)
  6772. t0 = 1.0;
  6773. }
  6774. this._collisionPoint.copyFromFloats(0, 0, 0);
  6775. var found = false;
  6776. var t = 1.0;
  6777. if (!embeddedInPlane) {
  6778. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6779. this.velocity.scaleToRef(t0, this._tempVector);
  6780. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6781. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6782. found = true;
  6783. t = t0;
  6784. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6785. }
  6786. }
  6787. if (!found) {
  6788. var velocitySquaredLength = this.velocity.lengthSquared();
  6789. var a = velocitySquaredLength;
  6790. this.basePoint.subtractToRef(p1, this._tempVector);
  6791. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6792. var c = this._tempVector.lengthSquared() - 1.0;
  6793. var lowestRoot = getLowestRoot(a, b, c, t);
  6794. if (lowestRoot.found) {
  6795. t = lowestRoot.root;
  6796. found = true;
  6797. this._collisionPoint.copyFrom(p1);
  6798. }
  6799. this.basePoint.subtractToRef(p2, this._tempVector);
  6800. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6801. c = this._tempVector.lengthSquared() - 1.0;
  6802. lowestRoot = getLowestRoot(a, b, c, t);
  6803. if (lowestRoot.found) {
  6804. t = lowestRoot.root;
  6805. found = true;
  6806. this._collisionPoint.copyFrom(p2);
  6807. }
  6808. this.basePoint.subtractToRef(p3, this._tempVector);
  6809. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6810. c = this._tempVector.lengthSquared() - 1.0;
  6811. lowestRoot = getLowestRoot(a, b, c, t);
  6812. if (lowestRoot.found) {
  6813. t = lowestRoot.root;
  6814. found = true;
  6815. this._collisionPoint.copyFrom(p3);
  6816. }
  6817. p2.subtractToRef(p1, this._edge);
  6818. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6819. var edgeSquaredLength = this._edge.lengthSquared();
  6820. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6821. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6822. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6823. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6824. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6825. lowestRoot = getLowestRoot(a, b, c, t);
  6826. if (lowestRoot.found) {
  6827. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6828. if (f >= 0.0 && f <= 1.0) {
  6829. t = lowestRoot.root;
  6830. found = true;
  6831. this._edge.scaleInPlace(f);
  6832. p1.addToRef(this._edge, this._collisionPoint);
  6833. }
  6834. }
  6835. p3.subtractToRef(p2, this._edge);
  6836. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6837. edgeSquaredLength = this._edge.lengthSquared();
  6838. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6839. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6840. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6841. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6842. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6843. lowestRoot = getLowestRoot(a, b, c, t);
  6844. if (lowestRoot.found) {
  6845. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6846. if (f >= 0.0 && f <= 1.0) {
  6847. t = lowestRoot.root;
  6848. found = true;
  6849. this._edge.scaleInPlace(f);
  6850. p2.addToRef(this._edge, this._collisionPoint);
  6851. }
  6852. }
  6853. p1.subtractToRef(p3, this._edge);
  6854. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6855. edgeSquaredLength = this._edge.lengthSquared();
  6856. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6857. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6858. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6859. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6860. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6861. lowestRoot = getLowestRoot(a, b, c, t);
  6862. if (lowestRoot.found) {
  6863. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6864. if (f >= 0.0 && f <= 1.0) {
  6865. t = lowestRoot.root;
  6866. found = true;
  6867. this._edge.scaleInPlace(f);
  6868. p3.addToRef(this._edge, this._collisionPoint);
  6869. }
  6870. }
  6871. }
  6872. if (found) {
  6873. var distToCollision = t * this.velocity.length();
  6874. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6875. if (!this.intersectionPoint) {
  6876. this.intersectionPoint = this._collisionPoint.clone();
  6877. }
  6878. else {
  6879. this.intersectionPoint.copyFrom(this._collisionPoint);
  6880. }
  6881. this.nearestDistance = distToCollision;
  6882. this.collisionFound = true;
  6883. this.collidedMesh = subMesh.getMesh();
  6884. }
  6885. }
  6886. };
  6887. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6888. for (var i = indexStart; i < indexEnd; i += 3) {
  6889. var p1 = pts[indices[i] - decal];
  6890. var p2 = pts[indices[i + 1] - decal];
  6891. var p3 = pts[indices[i + 2] - decal];
  6892. this._testTriangle(i, subMesh, p3, p2, p1);
  6893. }
  6894. };
  6895. Collider.prototype._getResponse = function (pos, vel) {
  6896. pos.addToRef(vel, this._destinationPoint);
  6897. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6898. this.basePoint.addToRef(vel, pos);
  6899. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6900. this._slidePlaneNormal.normalize();
  6901. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6902. pos.addInPlace(this._displacementVector);
  6903. this.intersectionPoint.addInPlace(this._displacementVector);
  6904. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6905. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6906. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6907. };
  6908. return Collider;
  6909. })();
  6910. BABYLON.Collider = Collider;
  6911. })(BABYLON || (BABYLON = {}));
  6912. //# sourceMappingURL=babylon.collider.js.map
  6913. var BABYLON;
  6914. (function (BABYLON) {
  6915. var Camera = (function (_super) {
  6916. __extends(Camera, _super);
  6917. function Camera(name, position, scene) {
  6918. _super.call(this, name, scene);
  6919. this.position = position;
  6920. // Members
  6921. this.upVector = BABYLON.Vector3.Up();
  6922. this.orthoLeft = null;
  6923. this.orthoRight = null;
  6924. this.orthoBottom = null;
  6925. this.orthoTop = null;
  6926. this.fov = 0.8;
  6927. this.minZ = 1.0;
  6928. this.maxZ = 10000.0;
  6929. this.inertia = 0.9;
  6930. this.mode = Camera.PERSPECTIVE_CAMERA;
  6931. this.isIntermediate = false;
  6932. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6933. this.subCameras = [];
  6934. this.layerMask = 0xFFFFFFFF;
  6935. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6936. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6937. this._projectionMatrix = new BABYLON.Matrix();
  6938. this._postProcesses = new Array();
  6939. this._postProcessesTakenIndices = [];
  6940. this._activeMeshes = new BABYLON.SmartArray(256);
  6941. this._globalPosition = BABYLON.Vector3.Zero();
  6942. scene.addCamera(this);
  6943. if (!scene.activeCamera) {
  6944. scene.activeCamera = this;
  6945. }
  6946. }
  6947. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6948. get: function () {
  6949. return Camera._PERSPECTIVE_CAMERA;
  6950. },
  6951. enumerable: true,
  6952. configurable: true
  6953. });
  6954. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6955. get: function () {
  6956. return Camera._ORTHOGRAPHIC_CAMERA;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6962. get: function () {
  6963. return Camera._FOVMODE_VERTICAL_FIXED;
  6964. },
  6965. enumerable: true,
  6966. configurable: true
  6967. });
  6968. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6969. get: function () {
  6970. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6971. },
  6972. enumerable: true,
  6973. configurable: true
  6974. });
  6975. Object.defineProperty(Camera.prototype, "globalPosition", {
  6976. get: function () {
  6977. return this._globalPosition;
  6978. },
  6979. enumerable: true,
  6980. configurable: true
  6981. });
  6982. Camera.prototype.getActiveMeshes = function () {
  6983. return this._activeMeshes;
  6984. };
  6985. Camera.prototype.isActiveMesh = function (mesh) {
  6986. return (this._activeMeshes.indexOf(mesh) !== -1);
  6987. };
  6988. //Cache
  6989. Camera.prototype._initCache = function () {
  6990. _super.prototype._initCache.call(this);
  6991. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6992. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6993. this._cache.mode = undefined;
  6994. this._cache.minZ = undefined;
  6995. this._cache.maxZ = undefined;
  6996. this._cache.fov = undefined;
  6997. this._cache.aspectRatio = undefined;
  6998. this._cache.orthoLeft = undefined;
  6999. this._cache.orthoRight = undefined;
  7000. this._cache.orthoBottom = undefined;
  7001. this._cache.orthoTop = undefined;
  7002. this._cache.renderWidth = undefined;
  7003. this._cache.renderHeight = undefined;
  7004. };
  7005. Camera.prototype._updateCache = function (ignoreParentClass) {
  7006. if (!ignoreParentClass) {
  7007. _super.prototype._updateCache.call(this);
  7008. }
  7009. var engine = this.getEngine();
  7010. this._cache.position.copyFrom(this.position);
  7011. this._cache.upVector.copyFrom(this.upVector);
  7012. this._cache.mode = this.mode;
  7013. this._cache.minZ = this.minZ;
  7014. this._cache.maxZ = this.maxZ;
  7015. this._cache.fov = this.fov;
  7016. this._cache.aspectRatio = engine.getAspectRatio(this);
  7017. this._cache.orthoLeft = this.orthoLeft;
  7018. this._cache.orthoRight = this.orthoRight;
  7019. this._cache.orthoBottom = this.orthoBottom;
  7020. this._cache.orthoTop = this.orthoTop;
  7021. this._cache.renderWidth = engine.getRenderWidth();
  7022. this._cache.renderHeight = engine.getRenderHeight();
  7023. };
  7024. Camera.prototype._updateFromScene = function () {
  7025. this.updateCache();
  7026. this._update();
  7027. };
  7028. // Synchronized
  7029. //public isSynchronizedWithParent(): boolean {
  7030. // return false;
  7031. //}
  7032. Camera.prototype._isSynchronized = function () {
  7033. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  7034. };
  7035. Camera.prototype._isSynchronizedViewMatrix = function () {
  7036. if (!_super.prototype._isSynchronized.call(this))
  7037. return false;
  7038. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  7039. };
  7040. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7041. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7042. if (!check) {
  7043. return false;
  7044. }
  7045. var engine = this.getEngine();
  7046. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7047. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7048. }
  7049. else {
  7050. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  7051. }
  7052. return check;
  7053. };
  7054. // Controls
  7055. Camera.prototype.attachControl = function (element) {
  7056. };
  7057. Camera.prototype.detachControl = function (element) {
  7058. };
  7059. Camera.prototype._update = function () {
  7060. };
  7061. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7062. if (insertAt === void 0) { insertAt = null; }
  7063. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7064. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7065. return 0;
  7066. }
  7067. if (insertAt == null || insertAt < 0) {
  7068. this._postProcesses.push(postProcess);
  7069. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7070. return this._postProcesses.length - 1;
  7071. }
  7072. var add = 0;
  7073. if (this._postProcesses[insertAt]) {
  7074. var start = this._postProcesses.length - 1;
  7075. for (var i = start; i >= insertAt + 1; --i) {
  7076. this._postProcesses[i + 1] = this._postProcesses[i];
  7077. }
  7078. add = 1;
  7079. }
  7080. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7081. if (this._postProcessesTakenIndices[i] < insertAt) {
  7082. continue;
  7083. }
  7084. start = this._postProcessesTakenIndices.length - 1;
  7085. for (var j = start; j >= i; --j) {
  7086. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7087. }
  7088. this._postProcessesTakenIndices[i] = insertAt;
  7089. break;
  7090. }
  7091. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7092. this._postProcessesTakenIndices.push(insertAt);
  7093. }
  7094. var result = insertAt + add;
  7095. this._postProcesses[result] = postProcess;
  7096. return result;
  7097. };
  7098. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7099. if (atIndices === void 0) { atIndices = null; }
  7100. var result = [];
  7101. if (!atIndices) {
  7102. var length = this._postProcesses.length;
  7103. for (var i = 0; i < length; i++) {
  7104. if (this._postProcesses[i] !== postProcess) {
  7105. continue;
  7106. }
  7107. delete this._postProcesses[i];
  7108. var index = this._postProcessesTakenIndices.indexOf(i);
  7109. this._postProcessesTakenIndices.splice(index, 1);
  7110. }
  7111. }
  7112. else {
  7113. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7114. for (i = 0; i < atIndices.length; i++) {
  7115. var foundPostProcess = this._postProcesses[atIndices[i]];
  7116. if (foundPostProcess !== postProcess) {
  7117. result.push(i);
  7118. continue;
  7119. }
  7120. delete this._postProcesses[atIndices[i]];
  7121. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7122. this._postProcessesTakenIndices.splice(index, 1);
  7123. }
  7124. }
  7125. return result;
  7126. };
  7127. Camera.prototype.getWorldMatrix = function () {
  7128. if (!this._worldMatrix) {
  7129. this._worldMatrix = BABYLON.Matrix.Identity();
  7130. }
  7131. var viewMatrix = this.getViewMatrix();
  7132. viewMatrix.invertToRef(this._worldMatrix);
  7133. return this._worldMatrix;
  7134. };
  7135. Camera.prototype._getViewMatrix = function () {
  7136. return BABYLON.Matrix.Identity();
  7137. };
  7138. Camera.prototype.getViewMatrix = function () {
  7139. this._computedViewMatrix = this._computeViewMatrix();
  7140. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  7141. this._globalPosition.copyFrom(this.position);
  7142. return this._computedViewMatrix;
  7143. }
  7144. if (!this._worldMatrix) {
  7145. this._worldMatrix = BABYLON.Matrix.Identity();
  7146. }
  7147. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7148. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7149. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7150. this._computedViewMatrix.invert();
  7151. this._currentRenderId = this.getScene().getRenderId();
  7152. this._markSyncedWithParent();
  7153. return this._computedViewMatrix;
  7154. };
  7155. Camera.prototype._computeViewMatrix = function (force) {
  7156. if (!force && this._isSynchronizedViewMatrix()) {
  7157. return this._computedViewMatrix;
  7158. }
  7159. this._computedViewMatrix = this._getViewMatrix();
  7160. this._currentRenderId = this.getScene().getRenderId();
  7161. return this._computedViewMatrix;
  7162. };
  7163. Camera.prototype.getProjectionMatrix = function (force) {
  7164. if (!force && this._isSynchronizedProjectionMatrix()) {
  7165. return this._projectionMatrix;
  7166. }
  7167. var engine = this.getEngine();
  7168. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7169. if (this.minZ <= 0) {
  7170. this.minZ = 0.1;
  7171. }
  7172. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7173. return this._projectionMatrix;
  7174. }
  7175. var halfWidth = engine.getRenderWidth() / 2.0;
  7176. var halfHeight = engine.getRenderHeight() / 2.0;
  7177. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7178. return this._projectionMatrix;
  7179. };
  7180. Camera.prototype.dispose = function () {
  7181. // Remove from scene
  7182. this.getScene().removeCamera(this);
  7183. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7184. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7185. }
  7186. };
  7187. // Statics
  7188. Camera._PERSPECTIVE_CAMERA = 0;
  7189. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7190. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7191. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7192. return Camera;
  7193. })(BABYLON.Node);
  7194. BABYLON.Camera = Camera;
  7195. })(BABYLON || (BABYLON = {}));
  7196. //# sourceMappingURL=babylon.camera.js.map
  7197. var BABYLON;
  7198. (function (BABYLON) {
  7199. var TargetCamera = (function (_super) {
  7200. __extends(TargetCamera, _super);
  7201. function TargetCamera(name, position, scene) {
  7202. _super.call(this, name, position, scene);
  7203. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7204. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7205. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7206. this.speed = 2.0;
  7207. this.noRotationConstraint = false;
  7208. this.lockedTarget = null;
  7209. this._currentTarget = BABYLON.Vector3.Zero();
  7210. this._viewMatrix = BABYLON.Matrix.Zero();
  7211. this._camMatrix = BABYLON.Matrix.Zero();
  7212. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7213. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7214. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7215. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7216. this._lookAtTemp = BABYLON.Matrix.Zero();
  7217. this._tempMatrix = BABYLON.Matrix.Zero();
  7218. }
  7219. TargetCamera.prototype._getLockedTargetPosition = function () {
  7220. if (!this.lockedTarget) {
  7221. return null;
  7222. }
  7223. return this.lockedTarget.position || this.lockedTarget;
  7224. };
  7225. // Cache
  7226. TargetCamera.prototype._initCache = function () {
  7227. _super.prototype._initCache.call(this);
  7228. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7229. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7230. };
  7231. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7232. if (!ignoreParentClass) {
  7233. _super.prototype._updateCache.call(this);
  7234. }
  7235. var lockedTargetPosition = this._getLockedTargetPosition();
  7236. if (!lockedTargetPosition) {
  7237. this._cache.lockedTarget = null;
  7238. }
  7239. else {
  7240. if (!this._cache.lockedTarget) {
  7241. this._cache.lockedTarget = lockedTargetPosition.clone();
  7242. }
  7243. else {
  7244. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7245. }
  7246. }
  7247. this._cache.rotation.copyFrom(this.rotation);
  7248. };
  7249. // Synchronized
  7250. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7251. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7252. return false;
  7253. }
  7254. var lockedTargetPosition = this._getLockedTargetPosition();
  7255. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7256. };
  7257. // Methods
  7258. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7259. var engine = this.getEngine();
  7260. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7261. };
  7262. // Target
  7263. TargetCamera.prototype.setTarget = function (target) {
  7264. this.upVector.normalize();
  7265. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7266. this._camMatrix.invert();
  7267. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7268. var vDir = target.subtract(this.position);
  7269. if (vDir.x >= 0.0) {
  7270. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7271. }
  7272. else {
  7273. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7274. }
  7275. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7276. if (isNaN(this.rotation.x)) {
  7277. this.rotation.x = 0;
  7278. }
  7279. if (isNaN(this.rotation.y)) {
  7280. this.rotation.y = 0;
  7281. }
  7282. if (isNaN(this.rotation.z)) {
  7283. this.rotation.z = 0;
  7284. }
  7285. };
  7286. TargetCamera.prototype.getTarget = function () {
  7287. return this._currentTarget;
  7288. };
  7289. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7290. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7291. };
  7292. TargetCamera.prototype._updatePosition = function () {
  7293. this.position.addInPlace(this.cameraDirection);
  7294. };
  7295. TargetCamera.prototype._update = function () {
  7296. var needToMove = this._decideIfNeedsToMove();
  7297. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7298. // Move
  7299. if (needToMove) {
  7300. this._updatePosition();
  7301. }
  7302. // Rotate
  7303. if (needToRotate) {
  7304. this.rotation.x += this.cameraRotation.x;
  7305. this.rotation.y += this.cameraRotation.y;
  7306. if (!this.noRotationConstraint) {
  7307. var limit = (Math.PI / 2) * 0.95;
  7308. if (this.rotation.x > limit)
  7309. this.rotation.x = limit;
  7310. if (this.rotation.x < -limit)
  7311. this.rotation.x = -limit;
  7312. }
  7313. }
  7314. // Inertia
  7315. if (needToMove) {
  7316. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7317. this.cameraDirection.x = 0;
  7318. }
  7319. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7320. this.cameraDirection.y = 0;
  7321. }
  7322. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7323. this.cameraDirection.z = 0;
  7324. }
  7325. this.cameraDirection.scaleInPlace(this.inertia);
  7326. }
  7327. if (needToRotate) {
  7328. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7329. this.cameraRotation.x = 0;
  7330. }
  7331. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7332. this.cameraRotation.y = 0;
  7333. }
  7334. this.cameraRotation.scaleInPlace(this.inertia);
  7335. }
  7336. };
  7337. TargetCamera.prototype._getViewMatrix = function () {
  7338. if (!this.lockedTarget) {
  7339. // Compute
  7340. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7341. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7342. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7343. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7344. this._lookAtTemp.invert();
  7345. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7346. }
  7347. else {
  7348. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7349. }
  7350. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7351. // Computing target and final matrix
  7352. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7353. }
  7354. else {
  7355. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7356. }
  7357. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7358. return this._viewMatrix;
  7359. };
  7360. return TargetCamera;
  7361. })(BABYLON.Camera);
  7362. BABYLON.TargetCamera = TargetCamera;
  7363. })(BABYLON || (BABYLON = {}));
  7364. //# sourceMappingURL=babylon.targetCamera.js.map
  7365. var BABYLON;
  7366. (function (BABYLON) {
  7367. var FollowCamera = (function (_super) {
  7368. __extends(FollowCamera, _super);
  7369. function FollowCamera(name, position, scene) {
  7370. _super.call(this, name, position, scene);
  7371. this.radius = 12;
  7372. this.rotationOffset = 0;
  7373. this.heightOffset = 4;
  7374. this.cameraAcceleration = 0.05;
  7375. this.maxCameraSpeed = 20;
  7376. }
  7377. FollowCamera.prototype.getRadians = function (degrees) {
  7378. return degrees * Math.PI / 180;
  7379. };
  7380. FollowCamera.prototype.follow = function (cameraTarget) {
  7381. if (!cameraTarget)
  7382. return;
  7383. var yRotation;
  7384. if (cameraTarget.rotationQuaternion) {
  7385. var rotMatrix = new BABYLON.Matrix();
  7386. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  7387. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  7388. }
  7389. else {
  7390. yRotation = cameraTarget.rotation.y;
  7391. }
  7392. var radians = this.getRadians(this.rotationOffset) + yRotation;
  7393. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7394. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7395. var dx = targetX - this.position.x;
  7396. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7397. var dz = (targetZ) - this.position.z;
  7398. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7399. var vy = dy * this.cameraAcceleration;
  7400. var vz = dz * this.cameraAcceleration * 2;
  7401. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7402. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7403. }
  7404. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7405. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7406. }
  7407. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7408. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7409. }
  7410. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7411. this.setTarget(cameraTarget.position);
  7412. };
  7413. FollowCamera.prototype._update = function () {
  7414. _super.prototype._update.call(this);
  7415. this.follow(this.target);
  7416. };
  7417. return FollowCamera;
  7418. })(BABYLON.TargetCamera);
  7419. BABYLON.FollowCamera = FollowCamera;
  7420. })(BABYLON || (BABYLON = {}));
  7421. //# sourceMappingURL=babylon.followCamera.js.map
  7422. var BABYLON;
  7423. (function (BABYLON) {
  7424. var FreeCamera = (function (_super) {
  7425. __extends(FreeCamera, _super);
  7426. function FreeCamera(name, position, scene) {
  7427. _super.call(this, name, position, scene);
  7428. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7429. this.keysUp = [38];
  7430. this.keysDown = [40];
  7431. this.keysLeft = [37];
  7432. this.keysRight = [39];
  7433. this.checkCollisions = false;
  7434. this.applyGravity = false;
  7435. this.angularSensibility = 2000.0;
  7436. this._keys = [];
  7437. this._collider = new BABYLON.Collider();
  7438. this._needMoveForGravity = true;
  7439. this._oldPosition = BABYLON.Vector3.Zero();
  7440. this._diffPosition = BABYLON.Vector3.Zero();
  7441. this._newPosition = BABYLON.Vector3.Zero();
  7442. }
  7443. // Controls
  7444. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7445. var _this = this;
  7446. var previousPosition;
  7447. var engine = this.getEngine();
  7448. if (this._attachedElement) {
  7449. return;
  7450. }
  7451. this._attachedElement = element;
  7452. if (this._onMouseDown === undefined) {
  7453. this._onMouseDown = function (evt) {
  7454. previousPosition = {
  7455. x: evt.clientX,
  7456. y: evt.clientY
  7457. };
  7458. if (!noPreventDefault) {
  7459. evt.preventDefault();
  7460. }
  7461. };
  7462. this._onMouseUp = function (evt) {
  7463. previousPosition = null;
  7464. if (!noPreventDefault) {
  7465. evt.preventDefault();
  7466. }
  7467. };
  7468. this._onMouseOut = function (evt) {
  7469. previousPosition = null;
  7470. _this._keys = [];
  7471. if (!noPreventDefault) {
  7472. evt.preventDefault();
  7473. }
  7474. };
  7475. this._onMouseMove = function (evt) {
  7476. if (!previousPosition && !engine.isPointerLock) {
  7477. return;
  7478. }
  7479. var offsetX;
  7480. var offsetY;
  7481. if (!engine.isPointerLock) {
  7482. offsetX = evt.clientX - previousPosition.x;
  7483. offsetY = evt.clientY - previousPosition.y;
  7484. }
  7485. else {
  7486. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7487. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7488. }
  7489. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7490. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7491. previousPosition = {
  7492. x: evt.clientX,
  7493. y: evt.clientY
  7494. };
  7495. if (!noPreventDefault) {
  7496. evt.preventDefault();
  7497. }
  7498. };
  7499. this._onKeyDown = function (evt) {
  7500. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7501. var index = _this._keys.indexOf(evt.keyCode);
  7502. if (index === -1) {
  7503. _this._keys.push(evt.keyCode);
  7504. }
  7505. if (!noPreventDefault) {
  7506. evt.preventDefault();
  7507. }
  7508. }
  7509. };
  7510. this._onKeyUp = function (evt) {
  7511. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7512. var index = _this._keys.indexOf(evt.keyCode);
  7513. if (index >= 0) {
  7514. _this._keys.splice(index, 1);
  7515. }
  7516. if (!noPreventDefault) {
  7517. evt.preventDefault();
  7518. }
  7519. }
  7520. };
  7521. this._onLostFocus = function () {
  7522. _this._keys = [];
  7523. };
  7524. this._reset = function () {
  7525. _this._keys = [];
  7526. previousPosition = null;
  7527. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7528. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7529. };
  7530. }
  7531. element.addEventListener("mousedown", this._onMouseDown, false);
  7532. element.addEventListener("mouseup", this._onMouseUp, false);
  7533. element.addEventListener("mouseout", this._onMouseOut, false);
  7534. element.addEventListener("mousemove", this._onMouseMove, false);
  7535. BABYLON.Tools.RegisterTopRootEvents([
  7536. { name: "keydown", handler: this._onKeyDown },
  7537. { name: "keyup", handler: this._onKeyUp },
  7538. { name: "blur", handler: this._onLostFocus }
  7539. ]);
  7540. };
  7541. FreeCamera.prototype.detachControl = function (element) {
  7542. if (this._attachedElement != element) {
  7543. return;
  7544. }
  7545. element.removeEventListener("mousedown", this._onMouseDown);
  7546. element.removeEventListener("mouseup", this._onMouseUp);
  7547. element.removeEventListener("mouseout", this._onMouseOut);
  7548. element.removeEventListener("mousemove", this._onMouseMove);
  7549. BABYLON.Tools.UnregisterTopRootEvents([
  7550. { name: "keydown", handler: this._onKeyDown },
  7551. { name: "keyup", handler: this._onKeyUp },
  7552. { name: "blur", handler: this._onLostFocus }
  7553. ]);
  7554. this._attachedElement = null;
  7555. if (this._reset) {
  7556. this._reset();
  7557. }
  7558. };
  7559. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7560. var globalPosition;
  7561. if (this.parent) {
  7562. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7563. }
  7564. else {
  7565. globalPosition = this.position;
  7566. }
  7567. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7568. this._collider.radius = this.ellipsoid;
  7569. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7570. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7571. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7572. this.position.addInPlace(this._diffPosition);
  7573. if (this.onCollide) {
  7574. this.onCollide(this._collider.collidedMesh);
  7575. }
  7576. }
  7577. };
  7578. FreeCamera.prototype._checkInputs = function () {
  7579. if (!this._localDirection) {
  7580. this._localDirection = BABYLON.Vector3.Zero();
  7581. this._transformedDirection = BABYLON.Vector3.Zero();
  7582. }
  7583. for (var index = 0; index < this._keys.length; index++) {
  7584. var keyCode = this._keys[index];
  7585. var speed = this._computeLocalCameraSpeed();
  7586. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7587. this._localDirection.copyFromFloats(-speed, 0, 0);
  7588. }
  7589. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7590. this._localDirection.copyFromFloats(0, 0, speed);
  7591. }
  7592. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7593. this._localDirection.copyFromFloats(speed, 0, 0);
  7594. }
  7595. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7596. this._localDirection.copyFromFloats(0, 0, -speed);
  7597. }
  7598. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7599. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7600. this.cameraDirection.addInPlace(this._transformedDirection);
  7601. }
  7602. };
  7603. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7604. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7605. };
  7606. FreeCamera.prototype._updatePosition = function () {
  7607. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7608. this._collideWithWorld(this.cameraDirection);
  7609. if (this.applyGravity) {
  7610. var oldPosition = this.position;
  7611. this._collideWithWorld(this.getScene().gravity);
  7612. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7613. }
  7614. }
  7615. else {
  7616. this.position.addInPlace(this.cameraDirection);
  7617. }
  7618. };
  7619. FreeCamera.prototype._update = function () {
  7620. this._checkInputs();
  7621. _super.prototype._update.call(this);
  7622. };
  7623. return FreeCamera;
  7624. })(BABYLON.TargetCamera);
  7625. BABYLON.FreeCamera = FreeCamera;
  7626. })(BABYLON || (BABYLON = {}));
  7627. //# sourceMappingURL=babylon.freeCamera.js.map
  7628. var BABYLON;
  7629. (function (BABYLON) {
  7630. // We're mainly based on the logic defined into the FreeCamera code
  7631. var TouchCamera = (function (_super) {
  7632. __extends(TouchCamera, _super);
  7633. function TouchCamera(name, position, scene) {
  7634. _super.call(this, name, position, scene);
  7635. this._offsetX = null;
  7636. this._offsetY = null;
  7637. this._pointerCount = 0;
  7638. this._pointerPressed = [];
  7639. this.angularSensibility = 200000.0;
  7640. this.moveSensibility = 500.0;
  7641. }
  7642. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7643. var _this = this;
  7644. var previousPosition;
  7645. if (this._attachedCanvas) {
  7646. return;
  7647. }
  7648. this._attachedCanvas = canvas;
  7649. if (this._onPointerDown === undefined) {
  7650. this._onPointerDown = function (evt) {
  7651. if (!noPreventDefault) {
  7652. evt.preventDefault();
  7653. }
  7654. _this._pointerPressed.push(evt.pointerId);
  7655. if (_this._pointerPressed.length !== 1) {
  7656. return;
  7657. }
  7658. previousPosition = {
  7659. x: evt.clientX,
  7660. y: evt.clientY
  7661. };
  7662. };
  7663. this._onPointerUp = function (evt) {
  7664. if (!noPreventDefault) {
  7665. evt.preventDefault();
  7666. }
  7667. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7668. if (index === -1) {
  7669. return;
  7670. }
  7671. _this._pointerPressed.splice(index, 1);
  7672. if (index != 0) {
  7673. return;
  7674. }
  7675. previousPosition = null;
  7676. _this._offsetX = null;
  7677. _this._offsetY = null;
  7678. };
  7679. this._onPointerMove = function (evt) {
  7680. if (!noPreventDefault) {
  7681. evt.preventDefault();
  7682. }
  7683. if (!previousPosition) {
  7684. return;
  7685. }
  7686. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7687. if (index != 0) {
  7688. return;
  7689. }
  7690. _this._offsetX = evt.clientX - previousPosition.x;
  7691. _this._offsetY = -(evt.clientY - previousPosition.y);
  7692. };
  7693. this._onLostFocus = function () {
  7694. _this._offsetX = null;
  7695. _this._offsetY = null;
  7696. };
  7697. }
  7698. canvas.addEventListener("pointerdown", this._onPointerDown);
  7699. canvas.addEventListener("pointerup", this._onPointerUp);
  7700. canvas.addEventListener("pointerout", this._onPointerUp);
  7701. canvas.addEventListener("pointermove", this._onPointerMove);
  7702. BABYLON.Tools.RegisterTopRootEvents([
  7703. { name: "blur", handler: this._onLostFocus }
  7704. ]);
  7705. };
  7706. TouchCamera.prototype.detachControl = function (canvas) {
  7707. if (this._attachedCanvas != canvas) {
  7708. return;
  7709. }
  7710. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7711. canvas.removeEventListener("pointerup", this._onPointerUp);
  7712. canvas.removeEventListener("pointerout", this._onPointerUp);
  7713. canvas.removeEventListener("pointermove", this._onPointerMove);
  7714. BABYLON.Tools.UnregisterTopRootEvents([
  7715. { name: "blur", handler: this._onLostFocus }
  7716. ]);
  7717. this._attachedCanvas = null;
  7718. };
  7719. TouchCamera.prototype._checkInputs = function () {
  7720. if (!this._offsetX) {
  7721. return;
  7722. }
  7723. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7724. if (this._pointerPressed.length > 1) {
  7725. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7726. }
  7727. else {
  7728. var speed = this._computeLocalCameraSpeed();
  7729. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7730. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7731. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7732. }
  7733. };
  7734. return TouchCamera;
  7735. })(BABYLON.FreeCamera);
  7736. BABYLON.TouchCamera = TouchCamera;
  7737. })(BABYLON || (BABYLON = {}));
  7738. //# sourceMappingURL=babylon.touchCamera.js.map
  7739. var BABYLON;
  7740. (function (BABYLON) {
  7741. // We're mainly based on the logic defined into the FreeCamera code
  7742. var DeviceOrientationCamera = (function (_super) {
  7743. __extends(DeviceOrientationCamera, _super);
  7744. function DeviceOrientationCamera(name, position, scene) {
  7745. var _this = this;
  7746. _super.call(this, name, position, scene);
  7747. this._offsetX = null;
  7748. this._offsetY = null;
  7749. this._orientationGamma = 0;
  7750. this._orientationBeta = 0;
  7751. this._initialOrientationGamma = 0;
  7752. this._initialOrientationBeta = 0;
  7753. this.angularSensibility = 10000.0;
  7754. this.moveSensibility = 50.0;
  7755. window.addEventListener("resize", function () {
  7756. _this._initialOrientationGamma = null;
  7757. }, false);
  7758. }
  7759. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7760. var _this = this;
  7761. if (this._attachedCanvas) {
  7762. return;
  7763. }
  7764. this._attachedCanvas = canvas;
  7765. if (!this._orientationChanged) {
  7766. this._orientationChanged = function (evt) {
  7767. if (!_this._initialOrientationGamma) {
  7768. _this._initialOrientationGamma = evt.gamma;
  7769. _this._initialOrientationBeta = evt.beta;
  7770. }
  7771. _this._orientationGamma = evt.gamma;
  7772. _this._orientationBeta = evt.beta;
  7773. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7774. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7775. };
  7776. }
  7777. window.addEventListener("deviceorientation", this._orientationChanged);
  7778. };
  7779. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7780. if (this._attachedCanvas != canvas) {
  7781. return;
  7782. }
  7783. window.removeEventListener("deviceorientation", this._orientationChanged);
  7784. this._attachedCanvas = null;
  7785. this._orientationGamma = 0;
  7786. this._orientationBeta = 0;
  7787. this._initialOrientationGamma = 0;
  7788. this._initialOrientationBeta = 0;
  7789. };
  7790. DeviceOrientationCamera.prototype._checkInputs = function () {
  7791. if (!this._offsetX) {
  7792. return;
  7793. }
  7794. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7795. var speed = this._computeLocalCameraSpeed();
  7796. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7797. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7798. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7799. };
  7800. return DeviceOrientationCamera;
  7801. })(BABYLON.FreeCamera);
  7802. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7803. })(BABYLON || (BABYLON = {}));
  7804. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7805. var BABYLON;
  7806. (function (BABYLON) {
  7807. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7808. var ArcRotateCamera = (function (_super) {
  7809. __extends(ArcRotateCamera, _super);
  7810. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7811. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7812. this.alpha = alpha;
  7813. this.beta = beta;
  7814. this.radius = radius;
  7815. this.target = target;
  7816. this.inertialAlphaOffset = 0;
  7817. this.inertialBetaOffset = 0;
  7818. this.inertialRadiusOffset = 0;
  7819. this.lowerAlphaLimit = null;
  7820. this.upperAlphaLimit = null;
  7821. this.lowerBetaLimit = 0.01;
  7822. this.upperBetaLimit = Math.PI;
  7823. this.lowerRadiusLimit = null;
  7824. this.upperRadiusLimit = null;
  7825. this.angularSensibility = 1000.0;
  7826. this.wheelPrecision = 3.0;
  7827. this.pinchPrecision = 2.0;
  7828. this.keysUp = [38];
  7829. this.keysDown = [40];
  7830. this.keysLeft = [37];
  7831. this.keysRight = [39];
  7832. this.zoomOnFactor = 1;
  7833. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7834. this._keys = [];
  7835. this._viewMatrix = new BABYLON.Matrix();
  7836. this.checkCollisions = false;
  7837. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7838. this._collider = new BABYLON.Collider();
  7839. this._previousPosition = BABYLON.Vector3.Zero();
  7840. this._collisionVelocity = BABYLON.Vector3.Zero();
  7841. this._newPosition = BABYLON.Vector3.Zero();
  7842. if (!this.target) {
  7843. this.target = BABYLON.Vector3.Zero();
  7844. }
  7845. this.getViewMatrix();
  7846. }
  7847. ArcRotateCamera.prototype._getTargetPosition = function () {
  7848. return this.target.position || this.target;
  7849. };
  7850. // Cache
  7851. ArcRotateCamera.prototype._initCache = function () {
  7852. _super.prototype._initCache.call(this);
  7853. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7854. this._cache.alpha = undefined;
  7855. this._cache.beta = undefined;
  7856. this._cache.radius = undefined;
  7857. this._cache.targetScreenOffset = undefined;
  7858. };
  7859. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7860. if (!ignoreParentClass) {
  7861. _super.prototype._updateCache.call(this);
  7862. }
  7863. this._cache.target.copyFrom(this._getTargetPosition());
  7864. this._cache.alpha = this.alpha;
  7865. this._cache.beta = this.beta;
  7866. this._cache.radius = this.radius;
  7867. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7868. };
  7869. // Synchronized
  7870. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7871. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7872. return false;
  7873. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  7874. };
  7875. // Methods
  7876. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7877. var _this = this;
  7878. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7879. var previousPinchDistance = 0;
  7880. var pointers = new BABYLON.SmartCollection();
  7881. if (this._attachedElement) {
  7882. return;
  7883. }
  7884. this._attachedElement = element;
  7885. var engine = this.getEngine();
  7886. if (this._onPointerDown === undefined) {
  7887. this._onPointerDown = function (evt) {
  7888. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7889. cacheSoloPointer = pointers.item(evt.pointerId);
  7890. if (!noPreventDefault) {
  7891. evt.preventDefault();
  7892. }
  7893. };
  7894. this._onPointerUp = function (evt) {
  7895. cacheSoloPointer = null;
  7896. previousPinchDistance = 0;
  7897. pointers.remove(evt.pointerId);
  7898. if (!noPreventDefault) {
  7899. evt.preventDefault();
  7900. }
  7901. };
  7902. this._onPointerMove = function (evt) {
  7903. if (!noPreventDefault) {
  7904. evt.preventDefault();
  7905. }
  7906. switch (pointers.count) {
  7907. case 1:
  7908. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7909. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7910. var offsetX = evt.clientX - cacheSoloPointer.x;
  7911. var offsetY = evt.clientY - cacheSoloPointer.y;
  7912. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7913. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7914. //pointers.item(evt.pointerId).x = evt.clientX;
  7915. //pointers.item(evt.pointerId).y = evt.clientY;
  7916. cacheSoloPointer.x = evt.clientX;
  7917. cacheSoloPointer.y = evt.clientY;
  7918. break;
  7919. case 2:
  7920. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7921. pointers.item(evt.pointerId).x = evt.clientX;
  7922. pointers.item(evt.pointerId).y = evt.clientY;
  7923. var direction = 1;
  7924. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7925. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7926. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7927. if (previousPinchDistance === 0) {
  7928. previousPinchDistance = pinchSquaredDistance;
  7929. return;
  7930. }
  7931. if (pinchSquaredDistance !== previousPinchDistance) {
  7932. if (pinchSquaredDistance > previousPinchDistance) {
  7933. direction = -1;
  7934. }
  7935. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7936. previousPinchDistance = pinchSquaredDistance;
  7937. }
  7938. break;
  7939. default:
  7940. if (pointers.item(evt.pointerId)) {
  7941. pointers.item(evt.pointerId).x = evt.clientX;
  7942. pointers.item(evt.pointerId).y = evt.clientY;
  7943. }
  7944. }
  7945. };
  7946. this._onMouseMove = function (evt) {
  7947. if (!engine.isPointerLock) {
  7948. return;
  7949. }
  7950. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7951. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7952. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7953. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7954. if (!noPreventDefault) {
  7955. evt.preventDefault();
  7956. }
  7957. };
  7958. this._wheel = function (event) {
  7959. var delta = 0;
  7960. if (event.wheelDelta) {
  7961. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7962. }
  7963. else if (event.detail) {
  7964. delta = -event.detail / _this.wheelPrecision;
  7965. }
  7966. if (delta)
  7967. _this.inertialRadiusOffset += delta;
  7968. if (event.preventDefault) {
  7969. if (!noPreventDefault) {
  7970. event.preventDefault();
  7971. }
  7972. }
  7973. };
  7974. this._onKeyDown = function (evt) {
  7975. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7976. var index = _this._keys.indexOf(evt.keyCode);
  7977. if (index === -1) {
  7978. _this._keys.push(evt.keyCode);
  7979. }
  7980. if (evt.preventDefault) {
  7981. if (!noPreventDefault) {
  7982. evt.preventDefault();
  7983. }
  7984. }
  7985. }
  7986. };
  7987. this._onKeyUp = function (evt) {
  7988. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7989. var index = _this._keys.indexOf(evt.keyCode);
  7990. if (index >= 0) {
  7991. _this._keys.splice(index, 1);
  7992. }
  7993. if (evt.preventDefault) {
  7994. if (!noPreventDefault) {
  7995. evt.preventDefault();
  7996. }
  7997. }
  7998. }
  7999. };
  8000. this._onLostFocus = function () {
  8001. _this._keys = [];
  8002. pointers.empty();
  8003. previousPinchDistance = 0;
  8004. cacheSoloPointer = null;
  8005. };
  8006. this._onGestureStart = function (e) {
  8007. if (window.MSGesture === undefined) {
  8008. return;
  8009. }
  8010. if (!_this._MSGestureHandler) {
  8011. _this._MSGestureHandler = new MSGesture();
  8012. _this._MSGestureHandler.target = element;
  8013. }
  8014. _this._MSGestureHandler.addPointer(e.pointerId);
  8015. };
  8016. this._onGesture = function (e) {
  8017. _this.radius *= e.scale;
  8018. if (e.preventDefault) {
  8019. if (!noPreventDefault) {
  8020. e.stopPropagation();
  8021. e.preventDefault();
  8022. }
  8023. }
  8024. };
  8025. this._reset = function () {
  8026. _this._keys = [];
  8027. _this.inertialAlphaOffset = 0;
  8028. _this.inertialBetaOffset = 0;
  8029. _this.inertialRadiusOffset = 0;
  8030. pointers.empty();
  8031. previousPinchDistance = 0;
  8032. cacheSoloPointer = null;
  8033. };
  8034. }
  8035. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8036. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8037. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  8038. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8039. element.addEventListener("mousemove", this._onMouseMove, false);
  8040. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  8041. element.addEventListener("MSGestureChange", this._onGesture, false);
  8042. element.addEventListener('mousewheel', this._wheel, false);
  8043. element.addEventListener('DOMMouseScroll', this._wheel, false);
  8044. BABYLON.Tools.RegisterTopRootEvents([
  8045. { name: "keydown", handler: this._onKeyDown },
  8046. { name: "keyup", handler: this._onKeyUp },
  8047. { name: "blur", handler: this._onLostFocus }
  8048. ]);
  8049. };
  8050. ArcRotateCamera.prototype.detachControl = function (element) {
  8051. if (this._attachedElement !== element) {
  8052. return;
  8053. }
  8054. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8055. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8056. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8057. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8058. element.removeEventListener("mousemove", this._onMouseMove);
  8059. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8060. element.removeEventListener("MSGestureChange", this._onGesture);
  8061. element.removeEventListener('mousewheel', this._wheel);
  8062. element.removeEventListener('DOMMouseScroll', this._wheel);
  8063. BABYLON.Tools.UnregisterTopRootEvents([
  8064. { name: "keydown", handler: this._onKeyDown },
  8065. { name: "keyup", handler: this._onKeyUp },
  8066. { name: "blur", handler: this._onLostFocus }
  8067. ]);
  8068. this._MSGestureHandler = null;
  8069. this._attachedElement = null;
  8070. if (this._reset) {
  8071. this._reset();
  8072. }
  8073. };
  8074. ArcRotateCamera.prototype._update = function () {
  8075. for (var index = 0; index < this._keys.length; index++) {
  8076. var keyCode = this._keys[index];
  8077. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8078. this.inertialAlphaOffset -= 0.01;
  8079. }
  8080. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8081. this.inertialBetaOffset -= 0.01;
  8082. }
  8083. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8084. this.inertialAlphaOffset += 0.01;
  8085. }
  8086. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8087. this.inertialBetaOffset += 0.01;
  8088. }
  8089. }
  8090. // Inertia
  8091. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8092. this.alpha += this.inertialAlphaOffset;
  8093. this.beta += this.inertialBetaOffset;
  8094. this.radius -= this.inertialRadiusOffset;
  8095. this.inertialAlphaOffset *= this.inertia;
  8096. this.inertialBetaOffset *= this.inertia;
  8097. this.inertialRadiusOffset *= this.inertia;
  8098. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8099. this.inertialAlphaOffset = 0;
  8100. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8101. this.inertialBetaOffset = 0;
  8102. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8103. this.inertialRadiusOffset = 0;
  8104. }
  8105. // Limits
  8106. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8107. this.alpha = this.lowerAlphaLimit;
  8108. }
  8109. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8110. this.alpha = this.upperAlphaLimit;
  8111. }
  8112. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8113. this.beta = this.lowerBetaLimit;
  8114. }
  8115. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8116. this.beta = this.upperBetaLimit;
  8117. }
  8118. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8119. this.radius = this.lowerRadiusLimit;
  8120. }
  8121. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8122. this.radius = this.upperRadiusLimit;
  8123. }
  8124. };
  8125. ArcRotateCamera.prototype.setPosition = function (position) {
  8126. var radiusv3 = position.subtract(this._getTargetPosition());
  8127. this.radius = radiusv3.length();
  8128. // Alpha
  8129. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8130. if (radiusv3.z < 0) {
  8131. this.alpha = 2 * Math.PI - this.alpha;
  8132. }
  8133. // Beta
  8134. this.beta = Math.acos(radiusv3.y / this.radius);
  8135. };
  8136. ArcRotateCamera.prototype._getViewMatrix = function () {
  8137. // Compute
  8138. var cosa = Math.cos(this.alpha);
  8139. var sina = Math.sin(this.alpha);
  8140. var cosb = Math.cos(this.beta);
  8141. var sinb = Math.sin(this.beta);
  8142. var target = this._getTargetPosition();
  8143. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8144. if (this.checkCollisions) {
  8145. this._collider.radius = this.collisionRadius;
  8146. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8147. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8148. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8149. this.position.copyFrom(this._previousPosition);
  8150. this.alpha = this._previousAlpha;
  8151. this.beta = this._previousBeta;
  8152. this.radius = this._previousRadius;
  8153. if (this.onCollide) {
  8154. this.onCollide(this._collider.collidedMesh);
  8155. }
  8156. }
  8157. }
  8158. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8159. this._previousAlpha = this.alpha;
  8160. this._previousBeta = this.beta;
  8161. this._previousRadius = this.radius;
  8162. this._previousPosition.copyFrom(this.position);
  8163. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8164. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8165. return this._viewMatrix;
  8166. };
  8167. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8168. meshes = meshes || this.getScene().meshes;
  8169. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8170. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8171. this.radius = distance * this.zoomOnFactor;
  8172. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8173. };
  8174. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8175. var meshesOrMinMaxVector;
  8176. var distance;
  8177. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8178. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8179. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8180. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8181. }
  8182. else {
  8183. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8184. distance = meshesOrMinMaxVectorAndDistance.distance;
  8185. }
  8186. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8187. this.maxZ = distance * 2;
  8188. };
  8189. return ArcRotateCamera;
  8190. })(BABYLON.Camera);
  8191. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8192. })(BABYLON || (BABYLON = {}));
  8193. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8194. (function (BABYLON) {
  8195. /**
  8196. * Represents a scene to be rendered by the engine.
  8197. * @see http://doc.babylonjs.com/page.php?p=21911
  8198. */
  8199. var Scene = (function () {
  8200. /**
  8201. * @constructor
  8202. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8203. */
  8204. function Scene(engine) {
  8205. // Members
  8206. this.autoClear = true;
  8207. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8208. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8209. this.forceWireframe = false;
  8210. this.forcePointsCloud = false;
  8211. this.forceShowBoundingBoxes = false;
  8212. this.animationsEnabled = true;
  8213. 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
  8214. // Fog
  8215. /**
  8216. * is fog enabled on this scene.
  8217. * @type {boolean}
  8218. */
  8219. this.fogEnabled = true;
  8220. this.fogMode = Scene.FOGMODE_NONE;
  8221. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8222. this.fogDensity = 0.1;
  8223. this.fogStart = 0;
  8224. this.fogEnd = 1000.0;
  8225. // Lights
  8226. /**
  8227. * is shadow enabled on this scene.
  8228. * @type {boolean}
  8229. */
  8230. this.shadowsEnabled = true;
  8231. /**
  8232. * is light enabled on this scene.
  8233. * @type {boolean}
  8234. */
  8235. this.lightsEnabled = true;
  8236. /**
  8237. * All of the lights added to this scene.
  8238. * @see BABYLON.Light
  8239. * @type {BABYLON.Light[]}
  8240. */
  8241. this.lights = new Array();
  8242. // Cameras
  8243. /**
  8244. * All of the cameras added to this scene.
  8245. * @see BABYLON.Camera
  8246. * @type {BABYLON.Camera[]}
  8247. */
  8248. this.cameras = new Array();
  8249. this.activeCameras = new Array();
  8250. // Meshes
  8251. /**
  8252. * All of the (abstract) meshes added to this scene.
  8253. * @see BABYLON.AbstractMesh
  8254. * @type {BABYLON.AbstractMesh[]}
  8255. */
  8256. this.meshes = new Array();
  8257. // Geometries
  8258. this._geometries = new Array();
  8259. this.materials = new Array();
  8260. this.multiMaterials = new Array();
  8261. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8262. // Textures
  8263. this.texturesEnabled = true;
  8264. this.textures = new Array();
  8265. // Particles
  8266. this.particlesEnabled = true;
  8267. this.particleSystems = new Array();
  8268. // Sprites
  8269. this.spritesEnabled = true;
  8270. this.spriteManagers = new Array();
  8271. // Layers
  8272. this.layers = new Array();
  8273. // Skeletons
  8274. this.skeletonsEnabled = true;
  8275. this.skeletons = new Array();
  8276. // Lens flares
  8277. this.lensFlaresEnabled = true;
  8278. this.lensFlareSystems = new Array();
  8279. // Collisions
  8280. this.collisionsEnabled = true;
  8281. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8282. // Postprocesses
  8283. this.postProcessesEnabled = true;
  8284. // Customs render targets
  8285. this.renderTargetsEnabled = true;
  8286. this.dumpNextRenderTargets = false;
  8287. this.customRenderTargets = new Array();
  8288. // Imported meshes
  8289. this.importedMeshesFiles = new Array();
  8290. this._actionManagers = new Array();
  8291. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8292. // Procedural textures
  8293. this.proceduralTexturesEnabled = true;
  8294. this._proceduralTextures = new Array();
  8295. this.soundTracks = new Array();
  8296. this._audioEnabled = true;
  8297. this._headphone = false;
  8298. this._totalVertices = 0;
  8299. this._activeIndices = 0;
  8300. this._activeParticles = 0;
  8301. this._lastFrameDuration = 0;
  8302. this._evaluateActiveMeshesDuration = 0;
  8303. this._renderTargetsDuration = 0;
  8304. this._particlesDuration = 0;
  8305. this._renderDuration = 0;
  8306. this._spritesDuration = 0;
  8307. this._animationRatio = 0;
  8308. this._renderId = 0;
  8309. this._executeWhenReadyTimeoutId = -1;
  8310. this._toBeDisposed = new BABYLON.SmartArray(256);
  8311. this._onReadyCallbacks = new Array();
  8312. this._pendingData = []; //ANY
  8313. this._onBeforeRenderCallbacks = new Array();
  8314. this._onAfterRenderCallbacks = new Array();
  8315. this._activeMeshes = new BABYLON.SmartArray(256);
  8316. this._processedMaterials = new BABYLON.SmartArray(256);
  8317. this._renderTargets = new BABYLON.SmartArray(256);
  8318. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8319. this._activeSkeletons = new BABYLON.SmartArray(32);
  8320. this._activeBones = 0;
  8321. this._activeAnimatables = new Array();
  8322. this._transformMatrix = BABYLON.Matrix.Zero();
  8323. this._scaledPosition = BABYLON.Vector3.Zero();
  8324. this._scaledVelocity = BABYLON.Vector3.Zero();
  8325. this._uniqueIdCounter = 0;
  8326. this._engine = engine;
  8327. engine.scenes.push(this);
  8328. this._renderingManager = new BABYLON.RenderingManager(this);
  8329. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8330. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8331. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8332. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8333. this.attachControl();
  8334. this._debugLayer = new BABYLON.DebugLayer(this);
  8335. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8336. //simplification queue
  8337. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8338. }
  8339. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8340. get: function () {
  8341. return Scene._FOGMODE_NONE;
  8342. },
  8343. enumerable: true,
  8344. configurable: true
  8345. });
  8346. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8347. get: function () {
  8348. return Scene._FOGMODE_EXP;
  8349. },
  8350. enumerable: true,
  8351. configurable: true
  8352. });
  8353. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8354. get: function () {
  8355. return Scene._FOGMODE_EXP2;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8361. get: function () {
  8362. return Scene._FOGMODE_LINEAR;
  8363. },
  8364. enumerable: true,
  8365. configurable: true
  8366. });
  8367. Object.defineProperty(Scene.prototype, "debugLayer", {
  8368. // Properties
  8369. get: function () {
  8370. return this._debugLayer;
  8371. },
  8372. enumerable: true,
  8373. configurable: true
  8374. });
  8375. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8376. /**
  8377. * The mesh that is currently under the pointer.
  8378. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8379. */
  8380. get: function () {
  8381. return this._meshUnderPointer;
  8382. },
  8383. enumerable: true,
  8384. configurable: true
  8385. });
  8386. Object.defineProperty(Scene.prototype, "pointerX", {
  8387. /**
  8388. * Current on-screen X position of the pointer
  8389. * @return {number} X position of the pointer
  8390. */
  8391. get: function () {
  8392. return this._pointerX;
  8393. },
  8394. enumerable: true,
  8395. configurable: true
  8396. });
  8397. Object.defineProperty(Scene.prototype, "pointerY", {
  8398. /**
  8399. * Current on-screen Y position of the pointer
  8400. * @return {number} Y position of the pointer
  8401. */
  8402. get: function () {
  8403. return this._pointerY;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Scene.prototype.getCachedMaterial = function () {
  8409. return this._cachedMaterial;
  8410. };
  8411. Scene.prototype.getBoundingBoxRenderer = function () {
  8412. return this._boundingBoxRenderer;
  8413. };
  8414. Scene.prototype.getOutlineRenderer = function () {
  8415. return this._outlineRenderer;
  8416. };
  8417. Scene.prototype.getEngine = function () {
  8418. return this._engine;
  8419. };
  8420. Scene.prototype.getTotalVertices = function () {
  8421. return this._totalVertices;
  8422. };
  8423. Scene.prototype.getActiveIndices = function () {
  8424. return this._activeIndices;
  8425. };
  8426. Scene.prototype.getActiveParticles = function () {
  8427. return this._activeParticles;
  8428. };
  8429. Scene.prototype.getActiveBones = function () {
  8430. return this._activeBones;
  8431. };
  8432. // Stats
  8433. Scene.prototype.getLastFrameDuration = function () {
  8434. return this._lastFrameDuration;
  8435. };
  8436. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8437. return this._evaluateActiveMeshesDuration;
  8438. };
  8439. Scene.prototype.getActiveMeshes = function () {
  8440. return this._activeMeshes;
  8441. };
  8442. Scene.prototype.getRenderTargetsDuration = function () {
  8443. return this._renderTargetsDuration;
  8444. };
  8445. Scene.prototype.getRenderDuration = function () {
  8446. return this._renderDuration;
  8447. };
  8448. Scene.prototype.getParticlesDuration = function () {
  8449. return this._particlesDuration;
  8450. };
  8451. Scene.prototype.getSpritesDuration = function () {
  8452. return this._spritesDuration;
  8453. };
  8454. Scene.prototype.getAnimationRatio = function () {
  8455. return this._animationRatio;
  8456. };
  8457. Scene.prototype.getRenderId = function () {
  8458. return this._renderId;
  8459. };
  8460. Scene.prototype.incrementRenderId = function () {
  8461. this._renderId++;
  8462. };
  8463. Scene.prototype._updatePointerPosition = function (evt) {
  8464. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8465. this._pointerX = evt.clientX - canvasRect.left;
  8466. this._pointerY = evt.clientY - canvasRect.top;
  8467. if (this.cameraToUseForPointers) {
  8468. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8469. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8470. }
  8471. };
  8472. // Pointers handling
  8473. Scene.prototype.attachControl = function () {
  8474. var _this = this;
  8475. this._onPointerMove = function (evt) {
  8476. var canvas = _this._engine.getRenderingCanvas();
  8477. _this._updatePointerPosition(evt);
  8478. 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);
  8479. if (pickResult.hit) {
  8480. _this._meshUnderPointer = pickResult.pickedMesh;
  8481. _this.setPointerOverMesh(pickResult.pickedMesh);
  8482. canvas.style.cursor = "pointer";
  8483. }
  8484. else {
  8485. _this.setPointerOverMesh(null);
  8486. canvas.style.cursor = "";
  8487. _this._meshUnderPointer = null;
  8488. }
  8489. };
  8490. this._onPointerDown = function (evt) {
  8491. var predicate = null;
  8492. if (!_this.onPointerDown) {
  8493. predicate = function (mesh) {
  8494. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8495. };
  8496. }
  8497. _this._updatePointerPosition(evt);
  8498. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8499. if (pickResult.hit) {
  8500. if (pickResult.pickedMesh.actionManager) {
  8501. switch (evt.button) {
  8502. case 0:
  8503. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8504. break;
  8505. case 1:
  8506. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8507. break;
  8508. case 2:
  8509. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8510. break;
  8511. }
  8512. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8513. }
  8514. }
  8515. if (_this.onPointerDown) {
  8516. _this.onPointerDown(evt, pickResult);
  8517. }
  8518. };
  8519. this._onKeyDown = function (evt) {
  8520. if (_this.actionManager) {
  8521. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8522. }
  8523. };
  8524. this._onKeyUp = function (evt) {
  8525. if (_this.actionManager) {
  8526. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8527. }
  8528. };
  8529. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8530. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8531. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8532. BABYLON.Tools.RegisterTopRootEvents([
  8533. { name: "keydown", handler: this._onKeyDown },
  8534. { name: "keyup", handler: this._onKeyUp }
  8535. ]);
  8536. };
  8537. Scene.prototype.detachControl = function () {
  8538. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8539. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8540. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8541. BABYLON.Tools.UnregisterTopRootEvents([
  8542. { name: "keydown", handler: this._onKeyDown },
  8543. { name: "keyup", handler: this._onKeyUp }
  8544. ]);
  8545. };
  8546. // Ready
  8547. Scene.prototype.isReady = function () {
  8548. if (this._pendingData.length > 0) {
  8549. return false;
  8550. }
  8551. for (var index = 0; index < this._geometries.length; index++) {
  8552. var geometry = this._geometries[index];
  8553. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8554. return false;
  8555. }
  8556. }
  8557. for (index = 0; index < this.meshes.length; index++) {
  8558. var mesh = this.meshes[index];
  8559. if (!mesh.isReady()) {
  8560. return false;
  8561. }
  8562. var mat = mesh.material;
  8563. if (mat) {
  8564. if (!mat.isReady(mesh)) {
  8565. return false;
  8566. }
  8567. }
  8568. }
  8569. return true;
  8570. };
  8571. Scene.prototype.resetCachedMaterial = function () {
  8572. this._cachedMaterial = null;
  8573. };
  8574. Scene.prototype.registerBeforeRender = function (func) {
  8575. this._onBeforeRenderCallbacks.push(func);
  8576. };
  8577. Scene.prototype.unregisterBeforeRender = function (func) {
  8578. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8579. if (index > -1) {
  8580. this._onBeforeRenderCallbacks.splice(index, 1);
  8581. }
  8582. };
  8583. Scene.prototype.registerAfterRender = function (func) {
  8584. this._onAfterRenderCallbacks.push(func);
  8585. };
  8586. Scene.prototype.unregisterAfterRender = function (func) {
  8587. var index = this._onAfterRenderCallbacks.indexOf(func);
  8588. if (index > -1) {
  8589. this._onAfterRenderCallbacks.splice(index, 1);
  8590. }
  8591. };
  8592. Scene.prototype._addPendingData = function (data) {
  8593. this._pendingData.push(data);
  8594. };
  8595. Scene.prototype._removePendingData = function (data) {
  8596. var index = this._pendingData.indexOf(data);
  8597. if (index !== -1) {
  8598. this._pendingData.splice(index, 1);
  8599. }
  8600. };
  8601. Scene.prototype.getWaitingItemsCount = function () {
  8602. return this._pendingData.length;
  8603. };
  8604. /**
  8605. * Registers a function to be executed when the scene is ready.
  8606. * @param {Function} func - the function to be executed.
  8607. */
  8608. Scene.prototype.executeWhenReady = function (func) {
  8609. var _this = this;
  8610. this._onReadyCallbacks.push(func);
  8611. if (this._executeWhenReadyTimeoutId !== -1) {
  8612. return;
  8613. }
  8614. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8615. _this._checkIsReady();
  8616. }, 150);
  8617. };
  8618. Scene.prototype._checkIsReady = function () {
  8619. var _this = this;
  8620. if (this.isReady()) {
  8621. this._onReadyCallbacks.forEach(function (func) {
  8622. func();
  8623. });
  8624. this._onReadyCallbacks = [];
  8625. this._executeWhenReadyTimeoutId = -1;
  8626. return;
  8627. }
  8628. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8629. _this._checkIsReady();
  8630. }, 150);
  8631. };
  8632. // Animations
  8633. /**
  8634. * Will start the animation sequence of a given target
  8635. * @param target - the target
  8636. * @param {number} from - from which frame should animation start
  8637. * @param {number} to - till which frame should animation run.
  8638. * @param {boolean} [loop] - should the animation loop
  8639. * @param {number} [speedRatio] - the speed in which to run the animation
  8640. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8641. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8642. * @return {BABYLON.Animatable} the animatable object created for this animation
  8643. * @see BABYLON.Animatable
  8644. * @see http://doc.babylonjs.com/page.php?p=22081
  8645. */
  8646. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8647. if (speedRatio === undefined) {
  8648. speedRatio = 1.0;
  8649. }
  8650. this.stopAnimation(target);
  8651. if (!animatable) {
  8652. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8653. }
  8654. // Local animations
  8655. if (target.animations) {
  8656. animatable.appendAnimations(target, target.animations);
  8657. }
  8658. // Children animations
  8659. if (target.getAnimatables) {
  8660. var animatables = target.getAnimatables();
  8661. for (var index = 0; index < animatables.length; index++) {
  8662. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8663. }
  8664. }
  8665. return animatable;
  8666. };
  8667. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8668. if (speedRatio === undefined) {
  8669. speedRatio = 1.0;
  8670. }
  8671. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8672. return animatable;
  8673. };
  8674. Scene.prototype.getAnimatableByTarget = function (target) {
  8675. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8676. if (this._activeAnimatables[index].target === target) {
  8677. return this._activeAnimatables[index];
  8678. }
  8679. }
  8680. return null;
  8681. };
  8682. /**
  8683. * Will stop the animation of the given target
  8684. * @param target - the target
  8685. * @see beginAnimation
  8686. */
  8687. Scene.prototype.stopAnimation = function (target) {
  8688. var animatable = this.getAnimatableByTarget(target);
  8689. if (animatable) {
  8690. animatable.stop();
  8691. }
  8692. };
  8693. Scene.prototype._animate = function () {
  8694. if (!this.animationsEnabled) {
  8695. return;
  8696. }
  8697. if (!this._animationStartDate) {
  8698. this._animationStartDate = BABYLON.Tools.Now;
  8699. }
  8700. // Getting time
  8701. var now = BABYLON.Tools.Now;
  8702. var delay = now - this._animationStartDate;
  8703. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8704. this._activeAnimatables[index]._animate(delay);
  8705. }
  8706. };
  8707. // Matrix
  8708. Scene.prototype.getViewMatrix = function () {
  8709. return this._viewMatrix;
  8710. };
  8711. Scene.prototype.getProjectionMatrix = function () {
  8712. return this._projectionMatrix;
  8713. };
  8714. Scene.prototype.getTransformMatrix = function () {
  8715. return this._transformMatrix;
  8716. };
  8717. Scene.prototype.setTransformMatrix = function (view, projection) {
  8718. this._viewMatrix = view;
  8719. this._projectionMatrix = projection;
  8720. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8721. };
  8722. // Methods
  8723. Scene.prototype.addMesh = function (newMesh) {
  8724. newMesh.uniqueId = this._uniqueIdCounter++;
  8725. var position = this.meshes.push(newMesh);
  8726. if (this.onNewMeshAdded) {
  8727. this.onNewMeshAdded(newMesh, position, this);
  8728. }
  8729. };
  8730. Scene.prototype.removeMesh = function (toRemove) {
  8731. var index = this.meshes.indexOf(toRemove);
  8732. if (index !== -1) {
  8733. // Remove from the scene if mesh found
  8734. this.meshes.splice(index, 1);
  8735. }
  8736. if (this.onMeshRemoved) {
  8737. this.onMeshRemoved(toRemove);
  8738. }
  8739. return index;
  8740. };
  8741. Scene.prototype.removeLight = function (toRemove) {
  8742. var index = this.lights.indexOf(toRemove);
  8743. if (index !== -1) {
  8744. // Remove from the scene if mesh found
  8745. this.lights.splice(index, 1);
  8746. }
  8747. if (this.onLightRemoved) {
  8748. this.onLightRemoved(toRemove);
  8749. }
  8750. return index;
  8751. };
  8752. Scene.prototype.removeCamera = function (toRemove) {
  8753. var index = this.cameras.indexOf(toRemove);
  8754. if (index !== -1) {
  8755. // Remove from the scene if mesh found
  8756. this.cameras.splice(index, 1);
  8757. }
  8758. // Remove from activeCameras
  8759. var index2 = this.activeCameras.indexOf(toRemove);
  8760. if (index2 !== -1) {
  8761. // Remove from the scene if mesh found
  8762. this.activeCameras.splice(index2, 1);
  8763. }
  8764. // Reset the activeCamera
  8765. if (this.activeCamera === toRemove) {
  8766. if (this.cameras.length > 0) {
  8767. this.activeCamera = this.cameras[0];
  8768. }
  8769. else {
  8770. this.activeCamera = null;
  8771. }
  8772. }
  8773. if (this.onCameraRemoved) {
  8774. this.onCameraRemoved(toRemove);
  8775. }
  8776. return index;
  8777. };
  8778. Scene.prototype.addLight = function (newLight) {
  8779. newLight.uniqueId = this._uniqueIdCounter++;
  8780. var position = this.lights.push(newLight);
  8781. if (this.onNewLightAdded) {
  8782. this.onNewLightAdded(newLight, position, this);
  8783. }
  8784. };
  8785. Scene.prototype.addCamera = function (newCamera) {
  8786. newCamera.uniqueId = this._uniqueIdCounter++;
  8787. var position = this.cameras.push(newCamera);
  8788. if (this.onNewCameraAdded) {
  8789. this.onNewCameraAdded(newCamera, position, this);
  8790. }
  8791. };
  8792. /**
  8793. * sets the active camera of the scene using its ID
  8794. * @param {string} id - the camera's ID
  8795. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8796. * @see activeCamera
  8797. */
  8798. Scene.prototype.setActiveCameraByID = function (id) {
  8799. var camera = this.getCameraByID(id);
  8800. if (camera) {
  8801. this.activeCamera = camera;
  8802. return camera;
  8803. }
  8804. return null;
  8805. };
  8806. /**
  8807. * sets the active camera of the scene using its name
  8808. * @param {string} name - the camera's name
  8809. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8810. * @see activeCamera
  8811. */
  8812. Scene.prototype.setActiveCameraByName = function (name) {
  8813. var camera = this.getCameraByName(name);
  8814. if (camera) {
  8815. this.activeCamera = camera;
  8816. return camera;
  8817. }
  8818. return null;
  8819. };
  8820. /**
  8821. * get a material using its id
  8822. * @param {string} the material's ID
  8823. * @return {BABYLON.Material|null} the material or null if none found.
  8824. */
  8825. Scene.prototype.getMaterialByID = function (id) {
  8826. for (var index = 0; index < this.materials.length; index++) {
  8827. if (this.materials[index].id === id) {
  8828. return this.materials[index];
  8829. }
  8830. }
  8831. return null;
  8832. };
  8833. /**
  8834. * get a material using its name
  8835. * @param {string} the material's name
  8836. * @return {BABYLON.Material|null} the material or null if none found.
  8837. */
  8838. Scene.prototype.getMaterialByName = function (name) {
  8839. for (var index = 0; index < this.materials.length; index++) {
  8840. if (this.materials[index].name === name) {
  8841. return this.materials[index];
  8842. }
  8843. }
  8844. return null;
  8845. };
  8846. Scene.prototype.getCameraByID = function (id) {
  8847. for (var index = 0; index < this.cameras.length; index++) {
  8848. if (this.cameras[index].id === id) {
  8849. return this.cameras[index];
  8850. }
  8851. }
  8852. return null;
  8853. };
  8854. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8855. for (var index = 0; index < this.cameras.length; index++) {
  8856. if (this.cameras[index].uniqueId === uniqueId) {
  8857. return this.cameras[index];
  8858. }
  8859. }
  8860. return null;
  8861. };
  8862. /**
  8863. * get a camera using its name
  8864. * @param {string} the camera's name
  8865. * @return {BABYLON.Camera|null} the camera or null if none found.
  8866. */
  8867. Scene.prototype.getCameraByName = function (name) {
  8868. for (var index = 0; index < this.cameras.length; index++) {
  8869. if (this.cameras[index].name === name) {
  8870. return this.cameras[index];
  8871. }
  8872. }
  8873. return null;
  8874. };
  8875. /**
  8876. * get a light node using its name
  8877. * @param {string} the light's name
  8878. * @return {BABYLON.Light|null} the light or null if none found.
  8879. */
  8880. Scene.prototype.getLightByName = function (name) {
  8881. for (var index = 0; index < this.lights.length; index++) {
  8882. if (this.lights[index].name === name) {
  8883. return this.lights[index];
  8884. }
  8885. }
  8886. return null;
  8887. };
  8888. /**
  8889. * get a light node using its ID
  8890. * @param {string} the light's id
  8891. * @return {BABYLON.Light|null} the light or null if none found.
  8892. */
  8893. Scene.prototype.getLightByID = function (id) {
  8894. for (var index = 0; index < this.lights.length; index++) {
  8895. if (this.lights[index].id === id) {
  8896. return this.lights[index];
  8897. }
  8898. }
  8899. return null;
  8900. };
  8901. /**
  8902. * get a light node using its scene-generated unique ID
  8903. * @param {number} the light's unique id
  8904. * @return {BABYLON.Light|null} the light or null if none found.
  8905. */
  8906. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8907. for (var index = 0; index < this.lights.length; index++) {
  8908. if (this.lights[index].uniqueId === uniqueId) {
  8909. return this.lights[index];
  8910. }
  8911. }
  8912. return null;
  8913. };
  8914. /**
  8915. * get a geometry using its ID
  8916. * @param {string} the geometry's id
  8917. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8918. */
  8919. Scene.prototype.getGeometryByID = function (id) {
  8920. for (var index = 0; index < this._geometries.length; index++) {
  8921. if (this._geometries[index].id === id) {
  8922. return this._geometries[index];
  8923. }
  8924. }
  8925. return null;
  8926. };
  8927. /**
  8928. * add a new geometry to this scene.
  8929. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8930. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8931. * @return {boolean} was the geometry added or not
  8932. */
  8933. Scene.prototype.pushGeometry = function (geometry, force) {
  8934. if (!force && this.getGeometryByID(geometry.id)) {
  8935. return false;
  8936. }
  8937. this._geometries.push(geometry);
  8938. if (this.onGeometryAdded) {
  8939. this.onGeometryAdded(geometry);
  8940. }
  8941. return true;
  8942. };
  8943. /**
  8944. * Removes an existing geometry
  8945. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  8946. * @return {boolean} was the geometry removed or not
  8947. */
  8948. Scene.prototype.removeGeometry = function (geometry) {
  8949. var index = this._geometries.indexOf(geometry);
  8950. if (index > -1) {
  8951. this._geometries.splice(index, 1);
  8952. if (this.onGeometryRemoved) {
  8953. this.onGeometryRemoved(geometry);
  8954. }
  8955. return true;
  8956. }
  8957. return false;
  8958. };
  8959. Scene.prototype.getGeometries = function () {
  8960. return this._geometries;
  8961. };
  8962. /**
  8963. * Get the first added mesh found of a given ID
  8964. * @param {string} id - the id to search for
  8965. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8966. */
  8967. Scene.prototype.getMeshByID = function (id) {
  8968. for (var index = 0; index < this.meshes.length; index++) {
  8969. if (this.meshes[index].id === id) {
  8970. return this.meshes[index];
  8971. }
  8972. }
  8973. return null;
  8974. };
  8975. /**
  8976. * Get a mesh with its auto-generated unique id
  8977. * @param {number} uniqueId - the unique id to search for
  8978. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8979. */
  8980. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  8981. for (var index = 0; index < this.meshes.length; index++) {
  8982. if (this.meshes[index].uniqueId === uniqueId) {
  8983. return this.meshes[index];
  8984. }
  8985. }
  8986. return null;
  8987. };
  8988. /**
  8989. * Get a the last added mesh found of a given ID
  8990. * @param {string} id - the id to search for
  8991. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8992. */
  8993. Scene.prototype.getLastMeshByID = function (id) {
  8994. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8995. if (this.meshes[index].id === id) {
  8996. return this.meshes[index];
  8997. }
  8998. }
  8999. return null;
  9000. };
  9001. /**
  9002. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  9003. * @param {string} id - the id to search for
  9004. * @return {BABYLON.Node|null} the node found or null if not found at all.
  9005. */
  9006. Scene.prototype.getLastEntryByID = function (id) {
  9007. for (var index = this.meshes.length - 1; index >= 0; index--) {
  9008. if (this.meshes[index].id === id) {
  9009. return this.meshes[index];
  9010. }
  9011. }
  9012. for (index = this.cameras.length - 1; index >= 0; index--) {
  9013. if (this.cameras[index].id === id) {
  9014. return this.cameras[index];
  9015. }
  9016. }
  9017. for (index = this.lights.length - 1; index >= 0; index--) {
  9018. if (this.lights[index].id === id) {
  9019. return this.lights[index];
  9020. }
  9021. }
  9022. return null;
  9023. };
  9024. Scene.prototype.getNodeByName = function (name) {
  9025. var mesh = this.getMeshByName(name);
  9026. if (mesh) {
  9027. return mesh;
  9028. }
  9029. var light = this.getLightByName(name);
  9030. if (light) {
  9031. return light;
  9032. }
  9033. return this.getCameraByName(name);
  9034. };
  9035. Scene.prototype.getMeshByName = function (name) {
  9036. for (var index = 0; index < this.meshes.length; index++) {
  9037. if (this.meshes[index].name === name) {
  9038. return this.meshes[index];
  9039. }
  9040. }
  9041. return null;
  9042. };
  9043. Scene.prototype.getSoundByName = function (name) {
  9044. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  9045. if (this.mainSoundTrack.soundCollection[index].name === name) {
  9046. return this.mainSoundTrack.soundCollection[index];
  9047. }
  9048. }
  9049. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  9050. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  9051. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  9052. return this.soundTracks[sdIndex].soundCollection[index];
  9053. }
  9054. }
  9055. }
  9056. return null;
  9057. };
  9058. Scene.prototype.getLastSkeletonByID = function (id) {
  9059. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  9060. if (this.skeletons[index].id === id) {
  9061. return this.skeletons[index];
  9062. }
  9063. }
  9064. return null;
  9065. };
  9066. Scene.prototype.getSkeletonById = function (id) {
  9067. for (var index = 0; index < this.skeletons.length; index++) {
  9068. if (this.skeletons[index].id === id) {
  9069. return this.skeletons[index];
  9070. }
  9071. }
  9072. return null;
  9073. };
  9074. Scene.prototype.getSkeletonByName = function (name) {
  9075. for (var index = 0; index < this.skeletons.length; index++) {
  9076. if (this.skeletons[index].name === name) {
  9077. return this.skeletons[index];
  9078. }
  9079. }
  9080. return null;
  9081. };
  9082. Scene.prototype.isActiveMesh = function (mesh) {
  9083. return (this._activeMeshes.indexOf(mesh) !== -1);
  9084. };
  9085. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9086. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9087. var material = subMesh.getMaterial();
  9088. if (mesh.showSubMeshesBoundingBox) {
  9089. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9090. }
  9091. if (material) {
  9092. // Render targets
  9093. if (material.getRenderTargetTextures) {
  9094. if (this._processedMaterials.indexOf(material) === -1) {
  9095. this._processedMaterials.push(material);
  9096. this._renderTargets.concat(material.getRenderTargetTextures());
  9097. }
  9098. }
  9099. // Dispatch
  9100. this._activeIndices += subMesh.indexCount;
  9101. this._renderingManager.dispatch(subMesh);
  9102. }
  9103. }
  9104. };
  9105. Scene.prototype._evaluateActiveMeshes = function () {
  9106. this.activeCamera._activeMeshes.reset();
  9107. this._activeMeshes.reset();
  9108. this._renderingManager.reset();
  9109. this._processedMaterials.reset();
  9110. this._activeParticleSystems.reset();
  9111. this._activeSkeletons.reset();
  9112. this._boundingBoxRenderer.reset();
  9113. if (!this._frustumPlanes) {
  9114. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9115. }
  9116. else {
  9117. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9118. }
  9119. // Meshes
  9120. var meshes;
  9121. var len;
  9122. if (this._selectionOctree) {
  9123. var selection = this._selectionOctree.select(this._frustumPlanes);
  9124. meshes = selection.data;
  9125. len = selection.length;
  9126. }
  9127. else {
  9128. len = this.meshes.length;
  9129. meshes = this.meshes;
  9130. }
  9131. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9132. var mesh = meshes[meshIndex];
  9133. if (mesh.isBlocked) {
  9134. continue;
  9135. }
  9136. this._totalVertices += mesh.getTotalVertices();
  9137. if (!mesh.isReady()) {
  9138. continue;
  9139. }
  9140. mesh.computeWorldMatrix();
  9141. // Intersections
  9142. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9143. this._meshesForIntersections.pushNoDuplicate(mesh);
  9144. }
  9145. // Switch to current LOD
  9146. var meshLOD = mesh.getLOD(this.activeCamera);
  9147. if (!meshLOD) {
  9148. continue;
  9149. }
  9150. mesh._preActivate();
  9151. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9152. this._activeMeshes.push(mesh);
  9153. this.activeCamera._activeMeshes.push(mesh);
  9154. mesh._activate(this._renderId);
  9155. this._activeMesh(meshLOD);
  9156. }
  9157. }
  9158. // Particle systems
  9159. var beforeParticlesDate = BABYLON.Tools.Now;
  9160. if (this.particlesEnabled) {
  9161. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9162. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9163. var particleSystem = this.particleSystems[particleIndex];
  9164. if (!particleSystem.isStarted()) {
  9165. continue;
  9166. }
  9167. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9168. this._activeParticleSystems.push(particleSystem);
  9169. particleSystem.animate();
  9170. }
  9171. }
  9172. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9173. }
  9174. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9175. };
  9176. Scene.prototype._activeMesh = function (mesh) {
  9177. if (mesh.skeleton && this.skeletonsEnabled) {
  9178. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9179. }
  9180. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9181. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9182. }
  9183. if (mesh && mesh.subMeshes) {
  9184. // Submeshes Octrees
  9185. var len;
  9186. var subMeshes;
  9187. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9188. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9189. len = intersections.length;
  9190. subMeshes = intersections.data;
  9191. }
  9192. else {
  9193. subMeshes = mesh.subMeshes;
  9194. len = subMeshes.length;
  9195. }
  9196. for (var subIndex = 0; subIndex < len; subIndex++) {
  9197. var subMesh = subMeshes[subIndex];
  9198. this._evaluateSubMesh(subMesh, mesh);
  9199. }
  9200. }
  9201. };
  9202. Scene.prototype.updateTransformMatrix = function (force) {
  9203. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9204. };
  9205. Scene.prototype._renderForCamera = function (camera) {
  9206. var engine = this._engine;
  9207. this.activeCamera = camera;
  9208. if (!this.activeCamera)
  9209. throw new Error("Active camera not set");
  9210. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9211. // Viewport
  9212. engine.setViewport(this.activeCamera.viewport);
  9213. // Camera
  9214. this._renderId++;
  9215. this.updateTransformMatrix();
  9216. if (this.beforeCameraRender) {
  9217. this.beforeCameraRender(this.activeCamera);
  9218. }
  9219. // Meshes
  9220. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9221. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9222. this._evaluateActiveMeshes();
  9223. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9224. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9225. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9226. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9227. skeleton.prepare();
  9228. }
  9229. // Render targets
  9230. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9231. if (this.renderTargetsEnabled) {
  9232. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9233. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9234. var renderTarget = this._renderTargets.data[renderIndex];
  9235. if (renderTarget._shouldRender()) {
  9236. this._renderId++;
  9237. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9238. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9239. }
  9240. }
  9241. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9242. this._renderId++;
  9243. }
  9244. if (this._renderTargets.length > 0) {
  9245. engine.restoreDefaultFramebuffer();
  9246. }
  9247. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9248. // Prepare Frame
  9249. this.postProcessManager._prepareFrame();
  9250. var beforeRenderDate = BABYLON.Tools.Now;
  9251. // Backgrounds
  9252. if (this.layers.length) {
  9253. engine.setDepthBuffer(false);
  9254. var layerIndex;
  9255. var layer;
  9256. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9257. layer = this.layers[layerIndex];
  9258. if (layer.isBackground) {
  9259. layer.render();
  9260. }
  9261. }
  9262. engine.setDepthBuffer(true);
  9263. }
  9264. // Render
  9265. BABYLON.Tools.StartPerformanceCounter("Main render");
  9266. this._renderingManager.render(null, null, true, true);
  9267. BABYLON.Tools.EndPerformanceCounter("Main render");
  9268. // Bounding boxes
  9269. this._boundingBoxRenderer.render();
  9270. // Lens flares
  9271. if (this.lensFlaresEnabled) {
  9272. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9273. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9274. this.lensFlareSystems[lensFlareSystemIndex].render();
  9275. }
  9276. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9277. }
  9278. // Foregrounds
  9279. if (this.layers.length) {
  9280. engine.setDepthBuffer(false);
  9281. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9282. layer = this.layers[layerIndex];
  9283. if (!layer.isBackground) {
  9284. layer.render();
  9285. }
  9286. }
  9287. engine.setDepthBuffer(true);
  9288. }
  9289. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9290. // Finalize frame
  9291. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9292. // Update camera
  9293. this.activeCamera._updateFromScene();
  9294. // Reset some special arrays
  9295. this._renderTargets.reset();
  9296. if (this.afterCameraRender) {
  9297. this.afterCameraRender(this.activeCamera);
  9298. }
  9299. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9300. };
  9301. Scene.prototype._processSubCameras = function (camera) {
  9302. if (camera.subCameras.length === 0) {
  9303. this._renderForCamera(camera);
  9304. return;
  9305. }
  9306. for (var index = 0; index < camera.subCameras.length; index++) {
  9307. this._renderForCamera(camera.subCameras[index]);
  9308. }
  9309. this.activeCamera = camera;
  9310. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9311. // Update camera
  9312. this.activeCamera._updateFromScene();
  9313. };
  9314. Scene.prototype._checkIntersections = function () {
  9315. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9316. var sourceMesh = this._meshesForIntersections.data[index];
  9317. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9318. var action = sourceMesh.actionManager.actions[actionIndex];
  9319. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9320. var parameters = action.getTriggerParameter();
  9321. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9322. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9323. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9324. if (areIntersecting && currentIntersectionInProgress === -1) {
  9325. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9326. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9327. sourceMesh._intersectionsInProgress.push(otherMesh);
  9328. }
  9329. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9330. sourceMesh._intersectionsInProgress.push(otherMesh);
  9331. }
  9332. }
  9333. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9334. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9335. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9336. if (indexOfOther > -1) {
  9337. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9338. }
  9339. }
  9340. }
  9341. }
  9342. }
  9343. };
  9344. Scene.prototype.render = function () {
  9345. var startDate = BABYLON.Tools.Now;
  9346. this._particlesDuration = 0;
  9347. this._spritesDuration = 0;
  9348. this._activeParticles = 0;
  9349. this._renderDuration = 0;
  9350. this._renderTargetsDuration = 0;
  9351. this._evaluateActiveMeshesDuration = 0;
  9352. this._totalVertices = 0;
  9353. this._activeIndices = 0;
  9354. this._activeBones = 0;
  9355. this.getEngine().resetDrawCalls();
  9356. this._meshesForIntersections.reset();
  9357. this.resetCachedMaterial();
  9358. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9359. // Actions
  9360. if (this.actionManager) {
  9361. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9362. }
  9363. //Simplification Queue
  9364. if (!this.simplificationQueue.running) {
  9365. this.simplificationQueue.executeNext();
  9366. }
  9367. // Before render
  9368. if (this.beforeRender) {
  9369. this.beforeRender();
  9370. }
  9371. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9372. this._onBeforeRenderCallbacks[callbackIndex]();
  9373. }
  9374. // Animations
  9375. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9376. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9377. this._animate();
  9378. // Physics
  9379. if (this._physicsEngine) {
  9380. BABYLON.Tools.StartPerformanceCounter("Physics");
  9381. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9382. BABYLON.Tools.EndPerformanceCounter("Physics");
  9383. }
  9384. // Customs render targets
  9385. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9386. var engine = this.getEngine();
  9387. var currentActiveCamera = this.activeCamera;
  9388. if (this.renderTargetsEnabled) {
  9389. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9390. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9391. var renderTarget = this.customRenderTargets[customIndex];
  9392. if (renderTarget._shouldRender()) {
  9393. this._renderId++;
  9394. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9395. if (!this.activeCamera)
  9396. throw new Error("Active camera not set");
  9397. // Viewport
  9398. engine.setViewport(this.activeCamera.viewport);
  9399. // Camera
  9400. this.updateTransformMatrix();
  9401. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9402. }
  9403. }
  9404. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9405. this._renderId++;
  9406. }
  9407. if (this.customRenderTargets.length > 0) {
  9408. engine.restoreDefaultFramebuffer();
  9409. }
  9410. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9411. this.activeCamera = currentActiveCamera;
  9412. // Procedural textures
  9413. if (this.proceduralTexturesEnabled) {
  9414. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9415. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9416. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9417. if (proceduralTexture._shouldRender()) {
  9418. proceduralTexture.render();
  9419. }
  9420. }
  9421. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9422. }
  9423. // Clear
  9424. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9425. // Shadows
  9426. if (this.shadowsEnabled) {
  9427. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9428. var light = this.lights[lightIndex];
  9429. var shadowGenerator = light.getShadowGenerator();
  9430. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9431. this._renderTargets.push(shadowGenerator.getShadowMap());
  9432. }
  9433. }
  9434. }
  9435. // Depth renderer
  9436. if (this._depthRenderer) {
  9437. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9438. }
  9439. // RenderPipeline
  9440. this.postProcessRenderPipelineManager.update();
  9441. // Multi-cameras?
  9442. if (this.activeCameras.length > 0) {
  9443. var currentRenderId = this._renderId;
  9444. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9445. this._renderId = currentRenderId;
  9446. this._processSubCameras(this.activeCameras[cameraIndex]);
  9447. }
  9448. }
  9449. else {
  9450. if (!this.activeCamera) {
  9451. throw new Error("No camera defined");
  9452. }
  9453. this._processSubCameras(this.activeCamera);
  9454. }
  9455. // Intersection checks
  9456. this._checkIntersections();
  9457. // Update the audio listener attached to the camera
  9458. this._updateAudioParameters();
  9459. // After render
  9460. if (this.afterRender) {
  9461. this.afterRender();
  9462. }
  9463. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9464. this._onAfterRenderCallbacks[callbackIndex]();
  9465. }
  9466. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9467. this._toBeDisposed.data[index].dispose();
  9468. this._toBeDisposed[index] = null;
  9469. }
  9470. this._toBeDisposed.reset();
  9471. if (this.dumpNextRenderTargets) {
  9472. this.dumpNextRenderTargets = false;
  9473. }
  9474. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9475. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9476. };
  9477. Scene.prototype._updateAudioParameters = function () {
  9478. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9479. return;
  9480. }
  9481. var listeningCamera;
  9482. var audioEngine = BABYLON.Engine.audioEngine;
  9483. if (this.activeCameras.length > 0) {
  9484. listeningCamera = this.activeCameras[0];
  9485. }
  9486. else {
  9487. listeningCamera = this.activeCamera;
  9488. }
  9489. if (listeningCamera && audioEngine.canUseWebAudio) {
  9490. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9491. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9492. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9493. cameraDirection.normalize();
  9494. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9495. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9496. var sound = this.mainSoundTrack.soundCollection[i];
  9497. if (sound.useCustomAttenuation) {
  9498. sound.updateDistanceFromListener();
  9499. }
  9500. }
  9501. for (i = 0; i < this.soundTracks.length; i++) {
  9502. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9503. sound = this.soundTracks[i].soundCollection[j];
  9504. if (sound.useCustomAttenuation) {
  9505. sound.updateDistanceFromListener();
  9506. }
  9507. }
  9508. }
  9509. }
  9510. };
  9511. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9512. // Audio
  9513. get: function () {
  9514. return this._audioEnabled;
  9515. },
  9516. set: function (value) {
  9517. this._audioEnabled = value;
  9518. if (this._audioEnabled) {
  9519. this._enableAudio();
  9520. }
  9521. else {
  9522. this._disableAudio();
  9523. }
  9524. },
  9525. enumerable: true,
  9526. configurable: true
  9527. });
  9528. Scene.prototype._disableAudio = function () {
  9529. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9530. this.mainSoundTrack.soundCollection[i].pause();
  9531. }
  9532. for (i = 0; i < this.soundTracks.length; i++) {
  9533. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9534. this.soundTracks[i].soundCollection[j].pause();
  9535. }
  9536. }
  9537. };
  9538. Scene.prototype._enableAudio = function () {
  9539. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9540. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9541. this.mainSoundTrack.soundCollection[i].play();
  9542. }
  9543. }
  9544. for (i = 0; i < this.soundTracks.length; i++) {
  9545. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9546. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9547. this.soundTracks[i].soundCollection[j].play();
  9548. }
  9549. }
  9550. }
  9551. };
  9552. Object.defineProperty(Scene.prototype, "headphone", {
  9553. get: function () {
  9554. return this._headphone;
  9555. },
  9556. set: function (value) {
  9557. this._headphone = value;
  9558. if (this._headphone) {
  9559. this._switchAudioModeForHeadphones();
  9560. }
  9561. else {
  9562. this._switchAudioModeForNormalSpeakers();
  9563. }
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Scene.prototype._switchAudioModeForHeadphones = function () {
  9569. this.mainSoundTrack.switchPanningModelToHRTF();
  9570. for (var i = 0; i < this.soundTracks.length; i++) {
  9571. this.soundTracks[i].switchPanningModelToHRTF();
  9572. }
  9573. };
  9574. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9575. this.mainSoundTrack.switchPanningModelToEqualPower();
  9576. for (var i = 0; i < this.soundTracks.length; i++) {
  9577. this.soundTracks[i].switchPanningModelToEqualPower();
  9578. }
  9579. };
  9580. Scene.prototype.enableDepthRenderer = function () {
  9581. if (this._depthRenderer) {
  9582. return this._depthRenderer;
  9583. }
  9584. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9585. return this._depthRenderer;
  9586. };
  9587. Scene.prototype.disableDepthRenderer = function () {
  9588. if (!this._depthRenderer) {
  9589. return;
  9590. }
  9591. this._depthRenderer.dispose();
  9592. this._depthRenderer = null;
  9593. };
  9594. Scene.prototype.dispose = function () {
  9595. this.beforeRender = null;
  9596. this.afterRender = null;
  9597. this.skeletons = [];
  9598. this._boundingBoxRenderer.dispose();
  9599. if (this._depthRenderer) {
  9600. this._depthRenderer.dispose();
  9601. }
  9602. // Debug layer
  9603. this.debugLayer.hide();
  9604. // Events
  9605. if (this.onDispose) {
  9606. this.onDispose();
  9607. }
  9608. this._onBeforeRenderCallbacks = [];
  9609. this._onAfterRenderCallbacks = [];
  9610. this.detachControl();
  9611. // Release sounds & sounds tracks
  9612. this.disposeSounds();
  9613. // Detach cameras
  9614. var canvas = this._engine.getRenderingCanvas();
  9615. var index;
  9616. for (index = 0; index < this.cameras.length; index++) {
  9617. this.cameras[index].detachControl(canvas);
  9618. }
  9619. while (this.lights.length) {
  9620. this.lights[0].dispose();
  9621. }
  9622. while (this.meshes.length) {
  9623. this.meshes[0].dispose(true);
  9624. }
  9625. while (this.cameras.length) {
  9626. this.cameras[0].dispose();
  9627. }
  9628. while (this.materials.length) {
  9629. this.materials[0].dispose();
  9630. }
  9631. while (this.particleSystems.length) {
  9632. this.particleSystems[0].dispose();
  9633. }
  9634. while (this.spriteManagers.length) {
  9635. this.spriteManagers[0].dispose();
  9636. }
  9637. while (this.layers.length) {
  9638. this.layers[0].dispose();
  9639. }
  9640. while (this.textures.length) {
  9641. this.textures[0].dispose();
  9642. }
  9643. // Post-processes
  9644. this.postProcessManager.dispose();
  9645. // Physics
  9646. if (this._physicsEngine) {
  9647. this.disablePhysicsEngine();
  9648. }
  9649. // Remove from engine
  9650. index = this._engine.scenes.indexOf(this);
  9651. if (index > -1) {
  9652. this._engine.scenes.splice(index, 1);
  9653. }
  9654. this._engine.wipeCaches();
  9655. };
  9656. // Release sounds & sounds tracks
  9657. Scene.prototype.disposeSounds = function () {
  9658. this.mainSoundTrack.dispose();
  9659. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9660. this.soundTracks[scIndex].dispose();
  9661. }
  9662. };
  9663. // Collisions
  9664. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9665. if (excludedMesh === void 0) { excludedMesh = null; }
  9666. position.divideToRef(collider.radius, this._scaledPosition);
  9667. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9668. collider.retry = 0;
  9669. collider.initialVelocity = this._scaledVelocity;
  9670. collider.initialPosition = this._scaledPosition;
  9671. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9672. finalPosition.multiplyInPlace(collider.radius);
  9673. };
  9674. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9675. if (excludedMesh === void 0) { excludedMesh = null; }
  9676. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9677. if (collider.retry >= maximumRetry) {
  9678. finalPosition.copyFrom(position);
  9679. return;
  9680. }
  9681. collider._initialize(position, velocity, closeDistance);
  9682. for (var index = 0; index < this.meshes.length; index++) {
  9683. var mesh = this.meshes[index];
  9684. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9685. mesh._checkCollision(collider);
  9686. }
  9687. }
  9688. if (!collider.collisionFound) {
  9689. position.addToRef(velocity, finalPosition);
  9690. return;
  9691. }
  9692. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9693. collider._getResponse(position, velocity);
  9694. }
  9695. if (velocity.length() <= closeDistance) {
  9696. finalPosition.copyFrom(position);
  9697. return;
  9698. }
  9699. collider.retry++;
  9700. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9701. };
  9702. // Octrees
  9703. Scene.prototype.getWorldExtends = function () {
  9704. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9705. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9706. for (var index = 0; index < this.meshes.length; index++) {
  9707. var mesh = this.meshes[index];
  9708. mesh.computeWorldMatrix(true);
  9709. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9710. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9711. BABYLON.Tools.CheckExtends(minBox, min, max);
  9712. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9713. }
  9714. return {
  9715. min: min,
  9716. max: max
  9717. };
  9718. };
  9719. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9720. if (maxCapacity === void 0) { maxCapacity = 64; }
  9721. if (maxDepth === void 0) { maxDepth = 2; }
  9722. if (!this._selectionOctree) {
  9723. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9724. }
  9725. var worldExtends = this.getWorldExtends();
  9726. // Update octree
  9727. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9728. return this._selectionOctree;
  9729. };
  9730. // Picking
  9731. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9732. var engine = this._engine;
  9733. if (!camera) {
  9734. if (!this.activeCamera)
  9735. throw new Error("Active camera not set");
  9736. camera = this.activeCamera;
  9737. }
  9738. var cameraViewport = camera.viewport;
  9739. var viewport = cameraViewport.toGlobal(engine);
  9740. // Moving coordinates to local viewport world
  9741. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9742. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9743. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9744. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9745. };
  9746. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9747. var pickingInfo = null;
  9748. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9749. var mesh = this.meshes[meshIndex];
  9750. if (predicate) {
  9751. if (!predicate(mesh)) {
  9752. continue;
  9753. }
  9754. }
  9755. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9756. continue;
  9757. }
  9758. var world = mesh.getWorldMatrix();
  9759. var ray = rayFunction(world);
  9760. var result = mesh.intersects(ray, fastCheck);
  9761. if (!result || !result.hit)
  9762. continue;
  9763. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9764. continue;
  9765. pickingInfo = result;
  9766. if (fastCheck) {
  9767. break;
  9768. }
  9769. }
  9770. return pickingInfo || new BABYLON.PickingInfo();
  9771. };
  9772. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9773. var _this = this;
  9774. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9775. /// <param name="x">X position on screen</param>
  9776. /// <param name="y">Y position on screen</param>
  9777. /// <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>
  9778. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9779. /// <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>
  9780. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9781. };
  9782. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9783. var _this = this;
  9784. return this._internalPick(function (world) {
  9785. if (!_this._pickWithRayInverseMatrix) {
  9786. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9787. }
  9788. world.invertToRef(_this._pickWithRayInverseMatrix);
  9789. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9790. }, predicate, fastCheck);
  9791. };
  9792. Scene.prototype.setPointerOverMesh = function (mesh) {
  9793. if (this._pointerOverMesh === mesh) {
  9794. return;
  9795. }
  9796. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9797. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9798. }
  9799. this._pointerOverMesh = mesh;
  9800. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9801. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9802. }
  9803. };
  9804. Scene.prototype.getPointerOverMesh = function () {
  9805. return this._pointerOverMesh;
  9806. };
  9807. // Physics
  9808. Scene.prototype.getPhysicsEngine = function () {
  9809. return this._physicsEngine;
  9810. };
  9811. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9812. if (this._physicsEngine) {
  9813. return true;
  9814. }
  9815. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9816. if (!this._physicsEngine.isSupported()) {
  9817. this._physicsEngine = null;
  9818. return false;
  9819. }
  9820. this._physicsEngine._initialize(gravity);
  9821. return true;
  9822. };
  9823. Scene.prototype.disablePhysicsEngine = function () {
  9824. if (!this._physicsEngine) {
  9825. return;
  9826. }
  9827. this._physicsEngine.dispose();
  9828. this._physicsEngine = undefined;
  9829. };
  9830. Scene.prototype.isPhysicsEnabled = function () {
  9831. return this._physicsEngine !== undefined;
  9832. };
  9833. Scene.prototype.setGravity = function (gravity) {
  9834. if (!this._physicsEngine) {
  9835. return;
  9836. }
  9837. this._physicsEngine._setGravity(gravity);
  9838. };
  9839. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9840. if (parts.parts) {
  9841. options = parts;
  9842. parts = parts.parts;
  9843. }
  9844. if (!this._physicsEngine) {
  9845. return null;
  9846. }
  9847. for (var index = 0; index < parts.length; index++) {
  9848. var mesh = parts[index].mesh;
  9849. mesh._physicImpostor = parts[index].impostor;
  9850. mesh._physicsMass = options.mass / parts.length;
  9851. mesh._physicsFriction = options.friction;
  9852. mesh._physicRestitution = options.restitution;
  9853. }
  9854. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9855. };
  9856. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9857. for (var index = 0; index < compound.parts.length; index++) {
  9858. var mesh = compound.parts[index].mesh;
  9859. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9860. this._physicsEngine._unregisterMesh(mesh);
  9861. }
  9862. };
  9863. // Misc.
  9864. Scene.prototype.createDefaultCameraOrLight = function () {
  9865. // Light
  9866. if (this.lights.length === 0) {
  9867. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9868. }
  9869. // Camera
  9870. if (!this.activeCamera) {
  9871. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9872. // Compute position
  9873. var worldExtends = this.getWorldExtends();
  9874. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9875. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9876. camera.setTarget(worldCenter);
  9877. this.activeCamera = camera;
  9878. }
  9879. };
  9880. // Tags
  9881. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9882. if (tagsQuery === undefined) {
  9883. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9884. return list;
  9885. }
  9886. var listByTags = [];
  9887. forEach = forEach || (function (item) {
  9888. return;
  9889. });
  9890. for (var i in list) {
  9891. var item = list[i];
  9892. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9893. listByTags.push(item);
  9894. forEach(item);
  9895. }
  9896. }
  9897. return listByTags;
  9898. };
  9899. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9900. return this._getByTags(this.meshes, tagsQuery, forEach);
  9901. };
  9902. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9903. return this._getByTags(this.cameras, tagsQuery, forEach);
  9904. };
  9905. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9906. return this._getByTags(this.lights, tagsQuery, forEach);
  9907. };
  9908. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9909. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9910. };
  9911. // Statics
  9912. Scene._FOGMODE_NONE = 0;
  9913. Scene._FOGMODE_EXP = 1;
  9914. Scene._FOGMODE_EXP2 = 2;
  9915. Scene._FOGMODE_LINEAR = 3;
  9916. Scene.MinDeltaTime = 1.0;
  9917. Scene.MaxDeltaTime = 1000.0;
  9918. return Scene;
  9919. })();
  9920. BABYLON.Scene = Scene;
  9921. })(BABYLON || (BABYLON = {}));
  9922. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9923. (function (BABYLON) {
  9924. var VertexBuffer = (function () {
  9925. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9926. if (engine instanceof BABYLON.Mesh) {
  9927. this._engine = engine.getScene().getEngine();
  9928. }
  9929. else {
  9930. this._engine = engine;
  9931. }
  9932. this._updatable = updatable;
  9933. this._data = data;
  9934. if (!postponeInternalCreation) {
  9935. this.create();
  9936. }
  9937. this._kind = kind;
  9938. if (stride) {
  9939. this._strideSize = stride;
  9940. return;
  9941. }
  9942. switch (kind) {
  9943. case VertexBuffer.PositionKind:
  9944. this._strideSize = 3;
  9945. break;
  9946. case VertexBuffer.NormalKind:
  9947. this._strideSize = 3;
  9948. break;
  9949. case VertexBuffer.UVKind:
  9950. this._strideSize = 2;
  9951. break;
  9952. case VertexBuffer.UV2Kind:
  9953. this._strideSize = 2;
  9954. break;
  9955. case VertexBuffer.ColorKind:
  9956. this._strideSize = 4;
  9957. break;
  9958. case VertexBuffer.MatricesIndicesKind:
  9959. this._strideSize = 4;
  9960. break;
  9961. case VertexBuffer.MatricesWeightsKind:
  9962. this._strideSize = 4;
  9963. break;
  9964. }
  9965. }
  9966. // Properties
  9967. VertexBuffer.prototype.isUpdatable = function () {
  9968. return this._updatable;
  9969. };
  9970. VertexBuffer.prototype.getData = function () {
  9971. return this._data;
  9972. };
  9973. VertexBuffer.prototype.getBuffer = function () {
  9974. return this._buffer;
  9975. };
  9976. VertexBuffer.prototype.getStrideSize = function () {
  9977. return this._strideSize;
  9978. };
  9979. // Methods
  9980. VertexBuffer.prototype.create = function (data) {
  9981. if (!data && this._buffer) {
  9982. return; // nothing to do
  9983. }
  9984. data = data || this._data;
  9985. if (!this._buffer) {
  9986. if (this._updatable) {
  9987. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9988. }
  9989. else {
  9990. this._buffer = this._engine.createVertexBuffer(data);
  9991. }
  9992. }
  9993. if (this._updatable) {
  9994. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9995. this._data = data;
  9996. }
  9997. };
  9998. VertexBuffer.prototype.update = function (data) {
  9999. this.create(data);
  10000. };
  10001. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  10002. if (!this._buffer) {
  10003. return;
  10004. }
  10005. if (this._updatable) {
  10006. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  10007. this._data = null;
  10008. }
  10009. };
  10010. VertexBuffer.prototype.dispose = function () {
  10011. if (!this._buffer) {
  10012. return;
  10013. }
  10014. if (this._engine._releaseBuffer(this._buffer)) {
  10015. this._buffer = null;
  10016. }
  10017. };
  10018. Object.defineProperty(VertexBuffer, "PositionKind", {
  10019. get: function () {
  10020. return VertexBuffer._PositionKind;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. Object.defineProperty(VertexBuffer, "NormalKind", {
  10026. get: function () {
  10027. return VertexBuffer._NormalKind;
  10028. },
  10029. enumerable: true,
  10030. configurable: true
  10031. });
  10032. Object.defineProperty(VertexBuffer, "UVKind", {
  10033. get: function () {
  10034. return VertexBuffer._UVKind;
  10035. },
  10036. enumerable: true,
  10037. configurable: true
  10038. });
  10039. Object.defineProperty(VertexBuffer, "UV2Kind", {
  10040. get: function () {
  10041. return VertexBuffer._UV2Kind;
  10042. },
  10043. enumerable: true,
  10044. configurable: true
  10045. });
  10046. Object.defineProperty(VertexBuffer, "ColorKind", {
  10047. get: function () {
  10048. return VertexBuffer._ColorKind;
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  10054. get: function () {
  10055. return VertexBuffer._MatricesIndicesKind;
  10056. },
  10057. enumerable: true,
  10058. configurable: true
  10059. });
  10060. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  10061. get: function () {
  10062. return VertexBuffer._MatricesWeightsKind;
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. // Enums
  10068. VertexBuffer._PositionKind = "position";
  10069. VertexBuffer._NormalKind = "normal";
  10070. VertexBuffer._UVKind = "uv";
  10071. VertexBuffer._UV2Kind = "uv2";
  10072. VertexBuffer._ColorKind = "color";
  10073. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  10074. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  10075. return VertexBuffer;
  10076. })();
  10077. BABYLON.VertexBuffer = VertexBuffer;
  10078. })(BABYLON || (BABYLON = {}));
  10079. //# sourceMappingURL=babylon.vertexBuffer.js.map
  10080. var BABYLON;
  10081. (function (BABYLON) {
  10082. var AbstractMesh = (function (_super) {
  10083. __extends(AbstractMesh, _super);
  10084. function AbstractMesh(name, scene) {
  10085. _super.call(this, name, scene);
  10086. // Properties
  10087. this.definedFacingForward = true; // orientation for POV movement & rotation
  10088. this.position = new BABYLON.Vector3(0, 0, 0);
  10089. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10090. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10091. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10092. this.visibility = 1.0;
  10093. this.alphaIndex = Number.MAX_VALUE;
  10094. this.infiniteDistance = false;
  10095. this.isVisible = true;
  10096. this.isPickable = true;
  10097. this.showBoundingBox = false;
  10098. this.showSubMeshesBoundingBox = false;
  10099. this.onDispose = null;
  10100. this.checkCollisions = false;
  10101. this.isBlocker = false;
  10102. this.renderingGroupId = 0;
  10103. this.receiveShadows = false;
  10104. this.renderOutline = false;
  10105. this.outlineColor = BABYLON.Color3.Red();
  10106. this.outlineWidth = 0.02;
  10107. this.renderOverlay = false;
  10108. this.overlayColor = BABYLON.Color3.Red();
  10109. this.overlayAlpha = 0.5;
  10110. this.hasVertexAlpha = false;
  10111. this.useVertexColors = true;
  10112. this.applyFog = true;
  10113. this.useOctreeForRenderingSelection = true;
  10114. this.useOctreeForPicking = true;
  10115. this.useOctreeForCollisions = true;
  10116. this.layerMask = 0x0FFFFFFF;
  10117. // Physics
  10118. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10119. // Collisions
  10120. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10121. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10122. this._collider = new BABYLON.Collider();
  10123. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10124. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10125. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10126. // Cache
  10127. this._localScaling = BABYLON.Matrix.Zero();
  10128. this._localRotation = BABYLON.Matrix.Zero();
  10129. this._localTranslation = BABYLON.Matrix.Zero();
  10130. this._localBillboard = BABYLON.Matrix.Zero();
  10131. this._localPivotScaling = BABYLON.Matrix.Zero();
  10132. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10133. this._localWorld = BABYLON.Matrix.Zero();
  10134. this._worldMatrix = BABYLON.Matrix.Zero();
  10135. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10136. this._absolutePosition = BABYLON.Vector3.Zero();
  10137. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10138. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10139. this._isDirty = false;
  10140. this._pivotMatrix = BABYLON.Matrix.Identity();
  10141. this._isDisposed = false;
  10142. this._renderId = 0;
  10143. this._intersectionsInProgress = new Array();
  10144. this._onAfterWorldMatrixUpdate = new Array();
  10145. scene.addMesh(this);
  10146. }
  10147. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10148. get: function () {
  10149. return AbstractMesh._BILLBOARDMODE_NONE;
  10150. },
  10151. enumerable: true,
  10152. configurable: true
  10153. });
  10154. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10155. get: function () {
  10156. return AbstractMesh._BILLBOARDMODE_X;
  10157. },
  10158. enumerable: true,
  10159. configurable: true
  10160. });
  10161. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10162. get: function () {
  10163. return AbstractMesh._BILLBOARDMODE_Y;
  10164. },
  10165. enumerable: true,
  10166. configurable: true
  10167. });
  10168. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10169. get: function () {
  10170. return AbstractMesh._BILLBOARDMODE_Z;
  10171. },
  10172. enumerable: true,
  10173. configurable: true
  10174. });
  10175. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10176. get: function () {
  10177. return AbstractMesh._BILLBOARDMODE_ALL;
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10183. // Methods
  10184. get: function () {
  10185. return false;
  10186. },
  10187. enumerable: true,
  10188. configurable: true
  10189. });
  10190. AbstractMesh.prototype.getLOD = function (camera) {
  10191. return this;
  10192. };
  10193. AbstractMesh.prototype.getTotalVertices = function () {
  10194. return 0;
  10195. };
  10196. AbstractMesh.prototype.getIndices = function () {
  10197. return null;
  10198. };
  10199. AbstractMesh.prototype.getVerticesData = function (kind) {
  10200. return null;
  10201. };
  10202. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10203. return false;
  10204. };
  10205. AbstractMesh.prototype.getBoundingInfo = function () {
  10206. if (this._masterMesh) {
  10207. return this._masterMesh.getBoundingInfo();
  10208. }
  10209. if (!this._boundingInfo) {
  10210. this._updateBoundingInfo();
  10211. }
  10212. return this._boundingInfo;
  10213. };
  10214. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10215. get: function () {
  10216. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10217. },
  10218. enumerable: true,
  10219. configurable: true
  10220. });
  10221. AbstractMesh.prototype._preActivate = function () {
  10222. };
  10223. AbstractMesh.prototype._activate = function (renderId) {
  10224. this._renderId = renderId;
  10225. };
  10226. AbstractMesh.prototype.getWorldMatrix = function () {
  10227. if (this._masterMesh) {
  10228. return this._masterMesh.getWorldMatrix();
  10229. }
  10230. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10231. this.computeWorldMatrix();
  10232. }
  10233. return this._worldMatrix;
  10234. };
  10235. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10236. get: function () {
  10237. return this._worldMatrix;
  10238. },
  10239. enumerable: true,
  10240. configurable: true
  10241. });
  10242. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10243. get: function () {
  10244. return this._absolutePosition;
  10245. },
  10246. enumerable: true,
  10247. configurable: true
  10248. });
  10249. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10250. if (!this.rotationQuaternion) {
  10251. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10252. this.rotation = BABYLON.Vector3.Zero();
  10253. }
  10254. if (!space || space === 0 /* LOCAL */) {
  10255. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10256. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10257. }
  10258. else {
  10259. if (this.parent) {
  10260. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10261. invertParentWorldMatrix.invert();
  10262. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10263. }
  10264. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10265. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10266. }
  10267. };
  10268. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10269. var displacementVector = axis.scale(distance);
  10270. if (!space || space === 0 /* LOCAL */) {
  10271. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10272. this.setPositionWithLocalVector(tempV3);
  10273. }
  10274. else {
  10275. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10276. }
  10277. };
  10278. AbstractMesh.prototype.getAbsolutePosition = function () {
  10279. this.computeWorldMatrix();
  10280. return this._absolutePosition;
  10281. };
  10282. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10283. if (!absolutePosition) {
  10284. return;
  10285. }
  10286. var absolutePositionX;
  10287. var absolutePositionY;
  10288. var absolutePositionZ;
  10289. if (absolutePosition.x === undefined) {
  10290. if (arguments.length < 3) {
  10291. return;
  10292. }
  10293. absolutePositionX = arguments[0];
  10294. absolutePositionY = arguments[1];
  10295. absolutePositionZ = arguments[2];
  10296. }
  10297. else {
  10298. absolutePositionX = absolutePosition.x;
  10299. absolutePositionY = absolutePosition.y;
  10300. absolutePositionZ = absolutePosition.z;
  10301. }
  10302. if (this.parent) {
  10303. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10304. invertParentWorldMatrix.invert();
  10305. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10306. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10307. }
  10308. else {
  10309. this.position.x = absolutePositionX;
  10310. this.position.y = absolutePositionY;
  10311. this.position.z = absolutePositionZ;
  10312. }
  10313. };
  10314. // ================================== Point of View Movement =================================
  10315. /**
  10316. * Perform relative position change from the point of view of behind the front of the mesh.
  10317. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10318. * Supports definition of mesh facing forward or backward.
  10319. * @param {number} amountRight
  10320. * @param {number} amountUp
  10321. * @param {number} amountForward
  10322. */
  10323. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10324. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10325. };
  10326. /**
  10327. * Calculate relative position change from the point of view of behind the front of the mesh.
  10328. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10329. * Supports definition of mesh facing forward or backward.
  10330. * @param {number} amountRight
  10331. * @param {number} amountUp
  10332. * @param {number} amountForward
  10333. */
  10334. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10335. var rotMatrix = new BABYLON.Matrix();
  10336. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10337. rotQuaternion.toRotationMatrix(rotMatrix);
  10338. var translationDelta = BABYLON.Vector3.Zero();
  10339. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10340. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10341. return translationDelta;
  10342. };
  10343. // ================================== Point of View Rotation =================================
  10344. /**
  10345. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10346. * Supports definition of mesh facing forward or backward.
  10347. * @param {number} flipBack
  10348. * @param {number} twirlClockwise
  10349. * @param {number} tiltRight
  10350. */
  10351. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10352. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10353. };
  10354. /**
  10355. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10356. * Supports definition of mesh facing forward or backward.
  10357. * @param {number} flipBack
  10358. * @param {number} twirlClockwise
  10359. * @param {number} tiltRight
  10360. */
  10361. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10362. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10363. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10364. };
  10365. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10366. this._pivotMatrix = matrix;
  10367. this._cache.pivotMatrixUpdated = true;
  10368. };
  10369. AbstractMesh.prototype.getPivotMatrix = function () {
  10370. return this._pivotMatrix;
  10371. };
  10372. AbstractMesh.prototype._isSynchronized = function () {
  10373. if (this._isDirty) {
  10374. return false;
  10375. }
  10376. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10377. return false;
  10378. if (this._cache.pivotMatrixUpdated) {
  10379. return false;
  10380. }
  10381. if (this.infiniteDistance) {
  10382. return false;
  10383. }
  10384. if (!this._cache.position.equals(this.position))
  10385. return false;
  10386. if (this.rotationQuaternion) {
  10387. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10388. return false;
  10389. }
  10390. else {
  10391. if (!this._cache.rotation.equals(this.rotation))
  10392. return false;
  10393. }
  10394. if (!this._cache.scaling.equals(this.scaling))
  10395. return false;
  10396. return true;
  10397. };
  10398. AbstractMesh.prototype._initCache = function () {
  10399. _super.prototype._initCache.call(this);
  10400. this._cache.localMatrixUpdated = false;
  10401. this._cache.position = BABYLON.Vector3.Zero();
  10402. this._cache.scaling = BABYLON.Vector3.Zero();
  10403. this._cache.rotation = BABYLON.Vector3.Zero();
  10404. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10405. };
  10406. AbstractMesh.prototype.markAsDirty = function (property) {
  10407. if (property === "rotation") {
  10408. this.rotationQuaternion = null;
  10409. }
  10410. this._currentRenderId = Number.MAX_VALUE;
  10411. this._isDirty = true;
  10412. };
  10413. AbstractMesh.prototype._updateBoundingInfo = function () {
  10414. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10415. this._boundingInfo._update(this.worldMatrixFromCache);
  10416. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10417. };
  10418. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10419. if (!this.subMeshes) {
  10420. return;
  10421. }
  10422. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10423. var subMesh = this.subMeshes[subIndex];
  10424. subMesh.updateBoundingInfo(matrix);
  10425. }
  10426. };
  10427. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10428. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10429. return this._worldMatrix;
  10430. }
  10431. this._cache.position.copyFrom(this.position);
  10432. this._cache.scaling.copyFrom(this.scaling);
  10433. this._cache.pivotMatrixUpdated = false;
  10434. this._currentRenderId = this.getScene().getRenderId();
  10435. this._isDirty = false;
  10436. // Scaling
  10437. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10438. // Rotation
  10439. if (this.rotationQuaternion) {
  10440. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10441. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10442. }
  10443. else {
  10444. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10445. this._cache.rotation.copyFrom(this.rotation);
  10446. }
  10447. // Translation
  10448. if (this.infiniteDistance && !this.parent) {
  10449. var camera = this.getScene().activeCamera;
  10450. var cameraWorldMatrix = camera.getWorldMatrix();
  10451. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10452. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10453. }
  10454. else {
  10455. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10456. }
  10457. // Composing transformations
  10458. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10459. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10460. // Billboarding
  10461. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10462. var localPosition = this.position.clone();
  10463. var zero = this.getScene().activeCamera.globalPosition.clone();
  10464. if (this.parent && this.parent.position) {
  10465. localPosition.addInPlace(this.parent.position);
  10466. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10467. }
  10468. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  10469. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10470. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10471. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10472. zero.y = localPosition.y + 0.001;
  10473. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10474. zero.z = localPosition.z + 0.001;
  10475. }
  10476. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10477. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10478. this._localBillboard.invert();
  10479. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10480. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10481. }
  10482. // Local world
  10483. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10484. // Parent
  10485. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10486. this._markSyncedWithParent();
  10487. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10488. }
  10489. else {
  10490. this._worldMatrix.copyFrom(this._localWorld);
  10491. }
  10492. // Bounding info
  10493. this._updateBoundingInfo();
  10494. // Absolute position
  10495. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10496. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10497. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10498. }
  10499. return this._worldMatrix;
  10500. };
  10501. /**
  10502. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10503. * @param func: callback function to add
  10504. */
  10505. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10506. this._onAfterWorldMatrixUpdate.push(func);
  10507. };
  10508. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10509. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10510. if (index > -1) {
  10511. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10512. }
  10513. };
  10514. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10515. this.computeWorldMatrix();
  10516. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10517. };
  10518. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10519. this.computeWorldMatrix();
  10520. var invLocalWorldMatrix = this._localWorld.clone();
  10521. invLocalWorldMatrix.invert();
  10522. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10523. };
  10524. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10525. this.computeWorldMatrix();
  10526. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10527. };
  10528. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10529. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10530. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10531. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10532. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10533. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10534. /// <returns>Mesh oriented towards targetMesh</returns>
  10535. yawCor = yawCor || 0; // default to zero if undefined
  10536. pitchCor = pitchCor || 0;
  10537. rollCor = rollCor || 0;
  10538. var dv = targetPoint.subtract(this.position);
  10539. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10540. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10541. var pitch = Math.atan2(dv.y, len);
  10542. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10543. };
  10544. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10545. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10546. return false;
  10547. }
  10548. return true;
  10549. };
  10550. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10551. if (!camera) {
  10552. camera = this.getScene().activeCamera;
  10553. }
  10554. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10555. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10556. return false;
  10557. }
  10558. return true;
  10559. };
  10560. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10561. if (!this._boundingInfo || !mesh._boundingInfo) {
  10562. return false;
  10563. }
  10564. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10565. };
  10566. AbstractMesh.prototype.intersectsPoint = function (point) {
  10567. if (!this._boundingInfo) {
  10568. return false;
  10569. }
  10570. return this._boundingInfo.intersectsPoint(point);
  10571. };
  10572. // Physics
  10573. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10574. var physicsEngine = this.getScene().getPhysicsEngine();
  10575. if (!physicsEngine) {
  10576. return;
  10577. }
  10578. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10579. if (impostor.impostor) {
  10580. // Old API
  10581. options = impostor;
  10582. impostor = impostor.impostor;
  10583. }
  10584. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10585. physicsEngine._unregisterMesh(this);
  10586. return;
  10587. }
  10588. if (!options) {
  10589. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10590. }
  10591. else {
  10592. if (!options.mass && options.mass !== 0)
  10593. options.mass = 0;
  10594. if (!options.friction && options.friction !== 0)
  10595. options.friction = 0.2;
  10596. if (!options.restitution && options.restitution !== 0)
  10597. options.restitution = 0.2;
  10598. }
  10599. this._physicImpostor = impostor;
  10600. this._physicsMass = options.mass;
  10601. this._physicsFriction = options.friction;
  10602. this._physicRestitution = options.restitution;
  10603. return physicsEngine._registerMesh(this, impostor, options);
  10604. };
  10605. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10606. if (!this._physicImpostor) {
  10607. return BABYLON.PhysicsEngine.NoImpostor;
  10608. }
  10609. return this._physicImpostor;
  10610. };
  10611. AbstractMesh.prototype.getPhysicsMass = function () {
  10612. if (!this._physicsMass) {
  10613. return 0;
  10614. }
  10615. return this._physicsMass;
  10616. };
  10617. AbstractMesh.prototype.getPhysicsFriction = function () {
  10618. if (!this._physicsFriction) {
  10619. return 0;
  10620. }
  10621. return this._physicsFriction;
  10622. };
  10623. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10624. if (!this._physicRestitution) {
  10625. return 0;
  10626. }
  10627. return this._physicRestitution;
  10628. };
  10629. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10630. if (!camera) {
  10631. camera = this.getScene().activeCamera;
  10632. }
  10633. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10634. };
  10635. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10636. if (!camera) {
  10637. camera = this.getScene().activeCamera;
  10638. }
  10639. return this.absolutePosition.subtract(camera.position).length();
  10640. };
  10641. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10642. if (!this._physicImpostor) {
  10643. return;
  10644. }
  10645. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10646. };
  10647. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10648. if (!this._physicImpostor) {
  10649. return;
  10650. }
  10651. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10652. };
  10653. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10654. if (!this._physicImpostor) {
  10655. return;
  10656. }
  10657. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10658. };
  10659. // Collisions
  10660. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10661. var globalPosition = this.getAbsolutePosition();
  10662. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10663. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10664. this._collider.radius = this.ellipsoid;
  10665. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10666. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10667. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10668. this.position.addInPlace(this._diffPositionForCollisions);
  10669. }
  10670. };
  10671. // Submeshes octree
  10672. /**
  10673. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10674. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10675. */
  10676. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10677. if (maxCapacity === void 0) { maxCapacity = 64; }
  10678. if (maxDepth === void 0) { maxDepth = 2; }
  10679. if (!this._submeshesOctree) {
  10680. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10681. }
  10682. this.computeWorldMatrix(true);
  10683. // Update octree
  10684. var bbox = this.getBoundingInfo().boundingBox;
  10685. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10686. return this._submeshesOctree;
  10687. };
  10688. // Collisions
  10689. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10690. this._generatePointsArray();
  10691. // Transformation
  10692. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10693. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10694. subMesh._lastColliderWorldVertices = [];
  10695. subMesh._trianglePlanes = [];
  10696. var start = subMesh.verticesStart;
  10697. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10698. for (var i = start; i < end; i++) {
  10699. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10700. }
  10701. }
  10702. // Collide
  10703. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10704. };
  10705. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10706. var subMeshes;
  10707. var len;
  10708. // Octrees
  10709. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10710. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10711. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10712. len = intersections.length;
  10713. subMeshes = intersections.data;
  10714. }
  10715. else {
  10716. subMeshes = this.subMeshes;
  10717. len = subMeshes.length;
  10718. }
  10719. for (var index = 0; index < len; index++) {
  10720. var subMesh = subMeshes[index];
  10721. // Bounding test
  10722. if (len > 1 && !subMesh._checkCollision(collider))
  10723. continue;
  10724. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10725. }
  10726. };
  10727. AbstractMesh.prototype._checkCollision = function (collider) {
  10728. // Bounding box test
  10729. if (!this._boundingInfo._checkCollision(collider))
  10730. return;
  10731. // Transformation matrix
  10732. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10733. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10734. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10735. };
  10736. // Picking
  10737. AbstractMesh.prototype._generatePointsArray = function () {
  10738. return false;
  10739. };
  10740. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10741. var pickingInfo = new BABYLON.PickingInfo();
  10742. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10743. return pickingInfo;
  10744. }
  10745. if (!this._generatePointsArray()) {
  10746. return pickingInfo;
  10747. }
  10748. var intersectInfo = null;
  10749. // Octrees
  10750. var subMeshes;
  10751. var len;
  10752. if (this._submeshesOctree && this.useOctreeForPicking) {
  10753. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10754. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10755. len = intersections.length;
  10756. subMeshes = intersections.data;
  10757. }
  10758. else {
  10759. subMeshes = this.subMeshes;
  10760. len = subMeshes.length;
  10761. }
  10762. for (var index = 0; index < len; index++) {
  10763. var subMesh = subMeshes[index];
  10764. // Bounding test
  10765. if (len > 1 && !subMesh.canIntersects(ray))
  10766. continue;
  10767. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10768. if (currentIntersectInfo) {
  10769. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10770. intersectInfo = currentIntersectInfo;
  10771. intersectInfo.subMeshId = index;
  10772. if (fastCheck) {
  10773. break;
  10774. }
  10775. }
  10776. }
  10777. }
  10778. if (intersectInfo) {
  10779. // Get picked point
  10780. var world = this.getWorldMatrix();
  10781. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10782. var direction = ray.direction.clone();
  10783. direction = direction.scale(intersectInfo.distance);
  10784. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10785. var pickedPoint = worldOrigin.add(worldDirection);
  10786. // Return result
  10787. pickingInfo.hit = true;
  10788. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10789. pickingInfo.pickedPoint = pickedPoint;
  10790. pickingInfo.pickedMesh = this;
  10791. pickingInfo.bu = intersectInfo.bu;
  10792. pickingInfo.bv = intersectInfo.bv;
  10793. pickingInfo.faceId = intersectInfo.faceId;
  10794. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10795. return pickingInfo;
  10796. }
  10797. return pickingInfo;
  10798. };
  10799. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10800. return null;
  10801. };
  10802. AbstractMesh.prototype.releaseSubMeshes = function () {
  10803. if (this.subMeshes) {
  10804. while (this.subMeshes.length) {
  10805. this.subMeshes[0].dispose();
  10806. }
  10807. }
  10808. else {
  10809. this.subMeshes = new Array();
  10810. }
  10811. };
  10812. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10813. var index;
  10814. // Physics
  10815. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10816. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10817. }
  10818. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10819. var other = this._intersectionsInProgress[index];
  10820. var pos = other._intersectionsInProgress.indexOf(this);
  10821. other._intersectionsInProgress.splice(pos, 1);
  10822. }
  10823. this._intersectionsInProgress = [];
  10824. // SubMeshes
  10825. this.releaseSubMeshes();
  10826. // Remove from scene
  10827. this.getScene().removeMesh(this);
  10828. if (!doNotRecurse) {
  10829. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10830. if (this.getScene().particleSystems[index].emitter === this) {
  10831. this.getScene().particleSystems[index].dispose();
  10832. index--;
  10833. }
  10834. }
  10835. // Children
  10836. var objects = this.getScene().meshes.slice(0);
  10837. for (index = 0; index < objects.length; index++) {
  10838. if (objects[index].parent === this) {
  10839. objects[index].dispose();
  10840. }
  10841. }
  10842. }
  10843. else {
  10844. for (index = 0; index < this.getScene().meshes.length; index++) {
  10845. var obj = this.getScene().meshes[index];
  10846. if (obj.parent === this) {
  10847. obj.parent = null;
  10848. obj.computeWorldMatrix(true);
  10849. }
  10850. }
  10851. }
  10852. this._onAfterWorldMatrixUpdate = [];
  10853. this._isDisposed = true;
  10854. // Callback
  10855. if (this.onDispose) {
  10856. this.onDispose();
  10857. }
  10858. };
  10859. // Statics
  10860. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10861. AbstractMesh._BILLBOARDMODE_X = 1;
  10862. AbstractMesh._BILLBOARDMODE_Y = 2;
  10863. AbstractMesh._BILLBOARDMODE_Z = 4;
  10864. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10865. return AbstractMesh;
  10866. })(BABYLON.Node);
  10867. BABYLON.AbstractMesh = AbstractMesh;
  10868. })(BABYLON || (BABYLON = {}));
  10869. //# sourceMappingURL=babylon.abstractMesh.js.map
  10870. var BABYLON;
  10871. (function (BABYLON) {
  10872. var _InstancesBatch = (function () {
  10873. function _InstancesBatch() {
  10874. this.mustReturn = false;
  10875. this.visibleInstances = new Array();
  10876. this.renderSelf = new Array();
  10877. }
  10878. return _InstancesBatch;
  10879. })();
  10880. BABYLON._InstancesBatch = _InstancesBatch;
  10881. var Mesh = (function (_super) {
  10882. __extends(Mesh, _super);
  10883. /**
  10884. * @constructor
  10885. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10886. * @param {Scene} scene - The scene to add this mesh to.
  10887. * @param {Node} parent - The parent of this mesh, if it has one
  10888. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10889. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10890. * When false, achieved by calling a clone(), also passing False.
  10891. * This will make creation of children, recursive.
  10892. */
  10893. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10894. if (parent === void 0) { parent = null; }
  10895. _super.call(this, name, scene);
  10896. // Members
  10897. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10898. this.instances = new Array();
  10899. this._LODLevels = new Array();
  10900. this._onBeforeRenderCallbacks = new Array();
  10901. this._onAfterRenderCallbacks = new Array();
  10902. this._visibleInstances = {};
  10903. this._renderIdForInstances = new Array();
  10904. this._batchCache = new _InstancesBatch();
  10905. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10906. this._sideOrientation = Mesh._DEFAULTSIDE;
  10907. if (source) {
  10908. // Geometry
  10909. if (source._geometry) {
  10910. source._geometry.applyToMesh(this);
  10911. }
  10912. // Deep copy
  10913. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10914. // Material
  10915. this.material = source.material;
  10916. if (!doNotCloneChildren) {
  10917. for (var index = 0; index < scene.meshes.length; index++) {
  10918. var mesh = scene.meshes[index];
  10919. if (mesh.parent === source) {
  10920. // doNotCloneChildren is always going to be False
  10921. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10922. }
  10923. }
  10924. }
  10925. for (index = 0; index < scene.particleSystems.length; index++) {
  10926. var system = scene.particleSystems[index];
  10927. if (system.emitter === source) {
  10928. system.clone(system.name, this);
  10929. }
  10930. }
  10931. this.computeWorldMatrix(true);
  10932. }
  10933. // Parent
  10934. if (parent !== null) {
  10935. this.parent = parent;
  10936. }
  10937. }
  10938. Object.defineProperty(Mesh, "FRONTSIDE", {
  10939. get: function () {
  10940. return Mesh._FRONTSIDE;
  10941. },
  10942. enumerable: true,
  10943. configurable: true
  10944. });
  10945. Object.defineProperty(Mesh, "BACKSIDE", {
  10946. get: function () {
  10947. return Mesh._BACKSIDE;
  10948. },
  10949. enumerable: true,
  10950. configurable: true
  10951. });
  10952. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10953. get: function () {
  10954. return Mesh._DOUBLESIDE;
  10955. },
  10956. enumerable: true,
  10957. configurable: true
  10958. });
  10959. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10960. get: function () {
  10961. return Mesh._DEFAULTSIDE;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10967. // Methods
  10968. get: function () {
  10969. return this._LODLevels.length > 0;
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Mesh.prototype._sortLODLevels = function () {
  10975. this._LODLevels.sort(function (a, b) {
  10976. if (a.distance < b.distance) {
  10977. return 1;
  10978. }
  10979. if (a.distance > b.distance) {
  10980. return -1;
  10981. }
  10982. return 0;
  10983. });
  10984. };
  10985. /**
  10986. * Add a mesh as LOD level triggered at the given distance.
  10987. * @param {number} distance - the distance from the center of the object to show this level
  10988. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10989. * @return {BABYLON.Mesh} this mesh (for chaining)
  10990. */
  10991. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10992. if (mesh && mesh._masterMesh) {
  10993. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10994. return this;
  10995. }
  10996. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10997. this._LODLevels.push(level);
  10998. if (mesh) {
  10999. mesh._masterMesh = this;
  11000. }
  11001. this._sortLODLevels();
  11002. return this;
  11003. };
  11004. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  11005. for (var index = 0; index < this._LODLevels.length; index++) {
  11006. var level = this._LODLevels[index];
  11007. if (level.distance === distance) {
  11008. return level.mesh;
  11009. }
  11010. }
  11011. return null;
  11012. };
  11013. /**
  11014. * Remove a mesh from the LOD array
  11015. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  11016. * @return {BABYLON.Mesh} this mesh (for chaining)
  11017. */
  11018. Mesh.prototype.removeLODLevel = function (mesh) {
  11019. for (var index = 0; index < this._LODLevels.length; index++) {
  11020. if (this._LODLevels[index].mesh === mesh) {
  11021. this._LODLevels.splice(index, 1);
  11022. if (mesh) {
  11023. mesh._masterMesh = null;
  11024. }
  11025. }
  11026. }
  11027. this._sortLODLevels();
  11028. return this;
  11029. };
  11030. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  11031. if (!this._LODLevels || this._LODLevels.length === 0) {
  11032. return this;
  11033. }
  11034. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  11035. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  11036. if (this.onLODLevelSelection) {
  11037. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  11038. }
  11039. return this;
  11040. }
  11041. for (var index = 0; index < this._LODLevels.length; index++) {
  11042. var level = this._LODLevels[index];
  11043. if (level.distance < distanceToCamera) {
  11044. if (level.mesh) {
  11045. level.mesh._preActivate();
  11046. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11047. }
  11048. if (this.onLODLevelSelection) {
  11049. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  11050. }
  11051. return level.mesh;
  11052. }
  11053. }
  11054. if (this.onLODLevelSelection) {
  11055. this.onLODLevelSelection(distanceToCamera, this, this);
  11056. }
  11057. return this;
  11058. };
  11059. Object.defineProperty(Mesh.prototype, "geometry", {
  11060. get: function () {
  11061. return this._geometry;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Mesh.prototype.getTotalVertices = function () {
  11067. if (!this._geometry) {
  11068. return 0;
  11069. }
  11070. return this._geometry.getTotalVertices();
  11071. };
  11072. Mesh.prototype.getVerticesData = function (kind) {
  11073. if (!this._geometry) {
  11074. return null;
  11075. }
  11076. return this._geometry.getVerticesData(kind);
  11077. };
  11078. Mesh.prototype.getVertexBuffer = function (kind) {
  11079. if (!this._geometry) {
  11080. return undefined;
  11081. }
  11082. return this._geometry.getVertexBuffer(kind);
  11083. };
  11084. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11085. if (!this._geometry) {
  11086. if (this._delayInfo) {
  11087. return this._delayInfo.indexOf(kind) !== -1;
  11088. }
  11089. return false;
  11090. }
  11091. return this._geometry.isVerticesDataPresent(kind);
  11092. };
  11093. Mesh.prototype.getVerticesDataKinds = function () {
  11094. if (!this._geometry) {
  11095. var result = [];
  11096. if (this._delayInfo) {
  11097. for (var kind in this._delayInfo) {
  11098. result.push(kind);
  11099. }
  11100. }
  11101. return result;
  11102. }
  11103. return this._geometry.getVerticesDataKinds();
  11104. };
  11105. Mesh.prototype.getTotalIndices = function () {
  11106. if (!this._geometry) {
  11107. return 0;
  11108. }
  11109. return this._geometry.getTotalIndices();
  11110. };
  11111. Mesh.prototype.getIndices = function () {
  11112. if (!this._geometry) {
  11113. return [];
  11114. }
  11115. return this._geometry.getIndices();
  11116. };
  11117. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11118. get: function () {
  11119. return this._masterMesh !== null && this._masterMesh !== undefined;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Mesh.prototype.isReady = function () {
  11125. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11126. return false;
  11127. }
  11128. return _super.prototype.isReady.call(this);
  11129. };
  11130. Mesh.prototype.isDisposed = function () {
  11131. return this._isDisposed;
  11132. };
  11133. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  11134. get: function () {
  11135. return this._sideOrientation;
  11136. },
  11137. set: function (sideO) {
  11138. this._sideOrientation = sideO;
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. // Methods
  11144. Mesh.prototype._preActivate = function () {
  11145. var sceneRenderId = this.getScene().getRenderId();
  11146. if (this._preActivateId === sceneRenderId) {
  11147. return;
  11148. }
  11149. this._preActivateId = sceneRenderId;
  11150. this._visibleInstances = null;
  11151. };
  11152. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11153. if (!this._visibleInstances) {
  11154. this._visibleInstances = {};
  11155. this._visibleInstances.defaultRenderId = renderId;
  11156. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11157. }
  11158. if (!this._visibleInstances[renderId]) {
  11159. this._visibleInstances[renderId] = new Array();
  11160. }
  11161. this._visibleInstances[renderId].push(instance);
  11162. };
  11163. Mesh.prototype.refreshBoundingInfo = function () {
  11164. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11165. if (data) {
  11166. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11167. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11168. }
  11169. if (this.subMeshes) {
  11170. for (var index = 0; index < this.subMeshes.length; index++) {
  11171. this.subMeshes[index].refreshBoundingInfo();
  11172. }
  11173. }
  11174. this._updateBoundingInfo();
  11175. };
  11176. Mesh.prototype._createGlobalSubMesh = function () {
  11177. var totalVertices = this.getTotalVertices();
  11178. if (!totalVertices || !this.getIndices()) {
  11179. return null;
  11180. }
  11181. this.releaseSubMeshes();
  11182. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11183. };
  11184. Mesh.prototype.subdivide = function (count) {
  11185. if (count < 1) {
  11186. return;
  11187. }
  11188. var totalIndices = this.getTotalIndices();
  11189. var subdivisionSize = (totalIndices / count) | 0;
  11190. var offset = 0;
  11191. while (subdivisionSize % 3 !== 0) {
  11192. subdivisionSize++;
  11193. }
  11194. this.releaseSubMeshes();
  11195. for (var index = 0; index < count; index++) {
  11196. if (offset >= totalIndices) {
  11197. break;
  11198. }
  11199. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11200. offset += subdivisionSize;
  11201. }
  11202. this.synchronizeInstances();
  11203. };
  11204. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11205. if (kind instanceof Array) {
  11206. var temp = data;
  11207. data = kind;
  11208. kind = temp;
  11209. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11210. }
  11211. if (!this._geometry) {
  11212. var vertexData = new BABYLON.VertexData();
  11213. vertexData.set(data, kind);
  11214. var scene = this.getScene();
  11215. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11216. }
  11217. else {
  11218. this._geometry.setVerticesData(kind, data, updatable, stride);
  11219. }
  11220. };
  11221. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11222. if (!this._geometry) {
  11223. return;
  11224. }
  11225. if (!makeItUnique) {
  11226. this._geometry.updateVerticesData(kind, data, updateExtends);
  11227. }
  11228. else {
  11229. this.makeGeometryUnique();
  11230. this.updateVerticesData(kind, data, updateExtends, false);
  11231. }
  11232. };
  11233. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11234. if (!this._geometry) {
  11235. return;
  11236. }
  11237. if (!makeItUnique) {
  11238. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11239. }
  11240. else {
  11241. this.makeGeometryUnique();
  11242. this.updateVerticesDataDirectly(kind, data, offset, false);
  11243. }
  11244. };
  11245. // Mesh positions update function :
  11246. // updates the mesh positions according to the positionFunction returned values.
  11247. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  11248. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  11249. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  11250. if (computeNormals === void 0) { computeNormals = true; }
  11251. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11252. positionFunction(positions);
  11253. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  11254. if (computeNormals) {
  11255. var indices = this.getIndices();
  11256. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11257. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  11258. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  11259. }
  11260. };
  11261. Mesh.prototype.makeGeometryUnique = function () {
  11262. if (!this._geometry) {
  11263. return;
  11264. }
  11265. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11266. geometry.applyToMesh(this);
  11267. };
  11268. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11269. if (!this._geometry) {
  11270. var vertexData = new BABYLON.VertexData();
  11271. vertexData.indices = indices;
  11272. var scene = this.getScene();
  11273. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11274. }
  11275. else {
  11276. this._geometry.setIndices(indices, totalVertices);
  11277. }
  11278. };
  11279. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11280. var engine = this.getScene().getEngine();
  11281. // Wireframe
  11282. var indexToBind;
  11283. switch (fillMode) {
  11284. case BABYLON.Material.PointFillMode:
  11285. indexToBind = null;
  11286. break;
  11287. case BABYLON.Material.WireFrameFillMode:
  11288. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11289. break;
  11290. default:
  11291. case BABYLON.Material.TriangleFillMode:
  11292. indexToBind = this._geometry.getIndexBuffer();
  11293. break;
  11294. }
  11295. // VBOs
  11296. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11297. };
  11298. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11299. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11300. return;
  11301. }
  11302. var engine = this.getScene().getEngine();
  11303. switch (fillMode) {
  11304. case BABYLON.Material.PointFillMode:
  11305. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11306. break;
  11307. case BABYLON.Material.WireFrameFillMode:
  11308. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11309. break;
  11310. default:
  11311. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11312. }
  11313. };
  11314. Mesh.prototype.registerBeforeRender = function (func) {
  11315. this._onBeforeRenderCallbacks.push(func);
  11316. };
  11317. Mesh.prototype.unregisterBeforeRender = function (func) {
  11318. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11319. if (index > -1) {
  11320. this._onBeforeRenderCallbacks.splice(index, 1);
  11321. }
  11322. };
  11323. Mesh.prototype.registerAfterRender = function (func) {
  11324. this._onAfterRenderCallbacks.push(func);
  11325. };
  11326. Mesh.prototype.unregisterAfterRender = function (func) {
  11327. var index = this._onAfterRenderCallbacks.indexOf(func);
  11328. if (index > -1) {
  11329. this._onAfterRenderCallbacks.splice(index, 1);
  11330. }
  11331. };
  11332. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11333. var scene = this.getScene();
  11334. this._batchCache.mustReturn = false;
  11335. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11336. this._batchCache.visibleInstances[subMeshId] = null;
  11337. if (this._visibleInstances) {
  11338. var currentRenderId = scene.getRenderId();
  11339. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11340. var selfRenderId = this._renderId;
  11341. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11342. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11343. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11344. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11345. }
  11346. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11347. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11348. this._batchCache.mustReturn = true;
  11349. return this._batchCache;
  11350. }
  11351. if (currentRenderId !== selfRenderId) {
  11352. this._batchCache.renderSelf[subMeshId] = false;
  11353. }
  11354. }
  11355. this._renderIdForInstances[subMeshId] = currentRenderId;
  11356. }
  11357. return this._batchCache;
  11358. };
  11359. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11360. var visibleInstances = batch.visibleInstances[subMesh._id];
  11361. var matricesCount = visibleInstances.length + 1;
  11362. var bufferSize = matricesCount * 16 * 4;
  11363. while (this._instancesBufferSize < bufferSize) {
  11364. this._instancesBufferSize *= 2;
  11365. }
  11366. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11367. if (this._worldMatricesInstancesBuffer) {
  11368. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11369. }
  11370. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11371. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11372. }
  11373. var offset = 0;
  11374. var instancesCount = 0;
  11375. var world = this.getWorldMatrix();
  11376. if (batch.renderSelf[subMesh._id]) {
  11377. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11378. offset += 16;
  11379. instancesCount++;
  11380. }
  11381. if (visibleInstances) {
  11382. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11383. var instance = visibleInstances[instanceIndex];
  11384. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11385. offset += 16;
  11386. instancesCount++;
  11387. }
  11388. }
  11389. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11390. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11391. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11392. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11393. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11394. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11395. this._draw(subMesh, fillMode, instancesCount);
  11396. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11397. };
  11398. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11399. var scene = this.getScene();
  11400. var engine = scene.getEngine();
  11401. if (hardwareInstancedRendering) {
  11402. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11403. }
  11404. else {
  11405. if (batch.renderSelf[subMesh._id]) {
  11406. // Draw
  11407. if (onBeforeDraw) {
  11408. onBeforeDraw(false, this.getWorldMatrix());
  11409. }
  11410. this._draw(subMesh, fillMode);
  11411. }
  11412. if (batch.visibleInstances[subMesh._id]) {
  11413. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11414. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11415. // World
  11416. var world = instance.getWorldMatrix();
  11417. if (onBeforeDraw) {
  11418. onBeforeDraw(true, world);
  11419. }
  11420. // Draw
  11421. this._draw(subMesh, fillMode);
  11422. }
  11423. }
  11424. }
  11425. };
  11426. Mesh.prototype.render = function (subMesh) {
  11427. var scene = this.getScene();
  11428. // Managing instances
  11429. var batch = this._getInstancesRenderList(subMesh._id);
  11430. if (batch.mustReturn) {
  11431. return;
  11432. }
  11433. // Checking geometry state
  11434. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11435. return;
  11436. }
  11437. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11438. this._onBeforeRenderCallbacks[callbackIndex](this);
  11439. }
  11440. var engine = scene.getEngine();
  11441. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11442. // Material
  11443. var effectiveMaterial = subMesh.getMaterial();
  11444. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11445. return;
  11446. }
  11447. // Outline - step 1
  11448. var savedDepthWrite = engine.getDepthWrite();
  11449. if (this.renderOutline) {
  11450. engine.setDepthWrite(false);
  11451. scene.getOutlineRenderer().render(subMesh, batch);
  11452. engine.setDepthWrite(savedDepthWrite);
  11453. }
  11454. effectiveMaterial._preBind();
  11455. var effect = effectiveMaterial.getEffect();
  11456. // Bind
  11457. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11458. this._bind(subMesh, effect, fillMode);
  11459. var world = this.getWorldMatrix();
  11460. effectiveMaterial.bind(world, this);
  11461. // Draw
  11462. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11463. if (isInstance) {
  11464. effectiveMaterial.bindOnlyWorldMatrix(world);
  11465. }
  11466. });
  11467. // Unbind
  11468. effectiveMaterial.unbind();
  11469. // Outline - step 2
  11470. if (this.renderOutline && savedDepthWrite) {
  11471. engine.setDepthWrite(true);
  11472. engine.setColorWrite(false);
  11473. scene.getOutlineRenderer().render(subMesh, batch);
  11474. engine.setColorWrite(true);
  11475. }
  11476. // Overlay
  11477. if (this.renderOverlay) {
  11478. var currentMode = engine.getAlphaMode();
  11479. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11480. scene.getOutlineRenderer().render(subMesh, batch, true);
  11481. engine.setAlphaMode(currentMode);
  11482. }
  11483. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11484. this._onAfterRenderCallbacks[callbackIndex](this);
  11485. }
  11486. };
  11487. Mesh.prototype.getEmittedParticleSystems = function () {
  11488. var results = new Array();
  11489. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11490. var particleSystem = this.getScene().particleSystems[index];
  11491. if (particleSystem.emitter === this) {
  11492. results.push(particleSystem);
  11493. }
  11494. }
  11495. return results;
  11496. };
  11497. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11498. var results = new Array();
  11499. var descendants = this.getDescendants();
  11500. descendants.push(this);
  11501. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11502. var particleSystem = this.getScene().particleSystems[index];
  11503. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11504. results.push(particleSystem);
  11505. }
  11506. }
  11507. return results;
  11508. };
  11509. Mesh.prototype.getChildren = function () {
  11510. var results = [];
  11511. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11512. var mesh = this.getScene().meshes[index];
  11513. if (mesh.parent === this) {
  11514. results.push(mesh);
  11515. }
  11516. }
  11517. return results;
  11518. };
  11519. Mesh.prototype._checkDelayState = function () {
  11520. var _this = this;
  11521. var that = this;
  11522. var scene = this.getScene();
  11523. if (this._geometry) {
  11524. this._geometry.load(scene);
  11525. }
  11526. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11527. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11528. scene._addPendingData(that);
  11529. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11530. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11531. if (data instanceof ArrayBuffer) {
  11532. _this._delayLoadingFunction(data, _this);
  11533. }
  11534. else {
  11535. _this._delayLoadingFunction(JSON.parse(data), _this);
  11536. }
  11537. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11538. scene._removePendingData(_this);
  11539. }, function () {
  11540. }, scene.database, getBinaryData);
  11541. }
  11542. };
  11543. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11544. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11545. return false;
  11546. }
  11547. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11548. return false;
  11549. }
  11550. this._checkDelayState();
  11551. return true;
  11552. };
  11553. Mesh.prototype.setMaterialByID = function (id) {
  11554. var materials = this.getScene().materials;
  11555. for (var index = 0; index < materials.length; index++) {
  11556. if (materials[index].id === id) {
  11557. this.material = materials[index];
  11558. return;
  11559. }
  11560. }
  11561. // Multi
  11562. var multiMaterials = this.getScene().multiMaterials;
  11563. for (index = 0; index < multiMaterials.length; index++) {
  11564. if (multiMaterials[index].id === id) {
  11565. this.material = multiMaterials[index];
  11566. return;
  11567. }
  11568. }
  11569. };
  11570. Mesh.prototype.getAnimatables = function () {
  11571. var results = [];
  11572. if (this.material) {
  11573. results.push(this.material);
  11574. }
  11575. if (this.skeleton) {
  11576. results.push(this.skeleton);
  11577. }
  11578. return results;
  11579. };
  11580. // Geometry
  11581. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11582. // Position
  11583. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11584. return;
  11585. }
  11586. this._resetPointsArrayCache();
  11587. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11588. var temp = [];
  11589. for (var index = 0; index < data.length; index += 3) {
  11590. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11591. }
  11592. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11593. // Normals
  11594. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11595. return;
  11596. }
  11597. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11598. for (index = 0; index < data.length; index += 3) {
  11599. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11600. }
  11601. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11602. };
  11603. // Cache
  11604. Mesh.prototype._resetPointsArrayCache = function () {
  11605. this._positions = null;
  11606. };
  11607. Mesh.prototype._generatePointsArray = function () {
  11608. if (this._positions)
  11609. return true;
  11610. this._positions = [];
  11611. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11612. if (!data) {
  11613. return false;
  11614. }
  11615. for (var index = 0; index < data.length; index += 3) {
  11616. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11617. }
  11618. return true;
  11619. };
  11620. // Clone
  11621. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11622. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11623. };
  11624. // Dispose
  11625. Mesh.prototype.dispose = function (doNotRecurse) {
  11626. if (this._geometry) {
  11627. this._geometry.releaseForMesh(this, true);
  11628. }
  11629. // Instances
  11630. if (this._worldMatricesInstancesBuffer) {
  11631. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11632. this._worldMatricesInstancesBuffer = null;
  11633. }
  11634. while (this.instances.length) {
  11635. this.instances[0].dispose();
  11636. }
  11637. _super.prototype.dispose.call(this, doNotRecurse);
  11638. };
  11639. // Geometric tools
  11640. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11641. var _this = this;
  11642. var scene = this.getScene();
  11643. var onload = function (img) {
  11644. // Getting height map data
  11645. var canvas = document.createElement("canvas");
  11646. var context = canvas.getContext("2d");
  11647. var heightMapWidth = img.width;
  11648. var heightMapHeight = img.height;
  11649. canvas.width = heightMapWidth;
  11650. canvas.height = heightMapHeight;
  11651. context.drawImage(img, 0, 0);
  11652. // Create VertexData from map data
  11653. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11654. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11655. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11656. //execute success callback, if set
  11657. if (onSuccess) {
  11658. onSuccess(_this);
  11659. }
  11660. };
  11661. BABYLON.Tools.LoadImage(url, onload, function () {
  11662. }, scene.database);
  11663. };
  11664. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11665. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11666. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11667. return;
  11668. }
  11669. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11670. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11671. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11672. var position = BABYLON.Vector3.Zero();
  11673. var normal = BABYLON.Vector3.Zero();
  11674. var uv = BABYLON.Vector2.Zero();
  11675. for (var index = 0; index < positions.length; index += 3) {
  11676. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11677. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11678. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11679. // Compute height
  11680. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11681. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11682. var pos = (u + v * heightMapWidth) * 4;
  11683. var r = buffer[pos] / 255.0;
  11684. var g = buffer[pos + 1] / 255.0;
  11685. var b = buffer[pos + 2] / 255.0;
  11686. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11687. normal.normalize();
  11688. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11689. position = position.add(normal);
  11690. position.toArray(positions, index);
  11691. }
  11692. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11693. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11694. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11695. };
  11696. Mesh.prototype.convertToFlatShadedMesh = function () {
  11697. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11698. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11699. var kinds = this.getVerticesDataKinds();
  11700. var vbs = [];
  11701. var data = [];
  11702. var newdata = [];
  11703. var updatableNormals = false;
  11704. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11705. var kind = kinds[kindIndex];
  11706. var vertexBuffer = this.getVertexBuffer(kind);
  11707. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11708. updatableNormals = vertexBuffer.isUpdatable();
  11709. kinds.splice(kindIndex, 1);
  11710. kindIndex--;
  11711. continue;
  11712. }
  11713. vbs[kind] = vertexBuffer;
  11714. data[kind] = vbs[kind].getData();
  11715. newdata[kind] = [];
  11716. }
  11717. // Save previous submeshes
  11718. var previousSubmeshes = this.subMeshes.slice(0);
  11719. var indices = this.getIndices();
  11720. var totalIndices = this.getTotalIndices();
  11721. for (var index = 0; index < totalIndices; index++) {
  11722. var vertexIndex = indices[index];
  11723. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11724. kind = kinds[kindIndex];
  11725. var stride = vbs[kind].getStrideSize();
  11726. for (var offset = 0; offset < stride; offset++) {
  11727. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11728. }
  11729. }
  11730. }
  11731. // Updating faces & normal
  11732. var normals = [];
  11733. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11734. for (index = 0; index < totalIndices; index += 3) {
  11735. indices[index] = index;
  11736. indices[index + 1] = index + 1;
  11737. indices[index + 2] = index + 2;
  11738. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11739. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11740. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11741. var p1p2 = p1.subtract(p2);
  11742. var p3p2 = p3.subtract(p2);
  11743. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11744. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11745. normals.push(normal.x);
  11746. normals.push(normal.y);
  11747. normals.push(normal.z);
  11748. }
  11749. }
  11750. this.setIndices(indices);
  11751. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11752. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11753. kind = kinds[kindIndex];
  11754. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11755. }
  11756. // Updating submeshes
  11757. this.releaseSubMeshes();
  11758. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11759. var previousOne = previousSubmeshes[submeshIndex];
  11760. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11761. }
  11762. this.synchronizeInstances();
  11763. };
  11764. // Instances
  11765. Mesh.prototype.createInstance = function (name) {
  11766. return new BABYLON.InstancedMesh(name, this);
  11767. };
  11768. Mesh.prototype.synchronizeInstances = function () {
  11769. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11770. var instance = this.instances[instanceIndex];
  11771. instance._syncSubMeshes();
  11772. }
  11773. };
  11774. /**
  11775. * Simplify the mesh according to the given array of settings.
  11776. * Function will return immediately and will simplify async.
  11777. * @param settings a collection of simplification settings.
  11778. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11779. * @param type the type of simplification to run.
  11780. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11781. */
  11782. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11783. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11784. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11785. this.getScene().simplificationQueue.addTask({
  11786. settings: settings,
  11787. parallelProcessing: parallelProcessing,
  11788. mesh: this,
  11789. simplificationType: simplificationType,
  11790. successCallback: successCallback
  11791. });
  11792. };
  11793. /**
  11794. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11795. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11796. * This should be used together with the simplification to avoid disappearing triangles.
  11797. * @param successCallback an optional success callback to be called after the optimization finished.
  11798. */
  11799. Mesh.prototype.optimizeIndices = function (successCallback) {
  11800. var _this = this;
  11801. var indices = this.getIndices();
  11802. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11803. var vectorPositions = [];
  11804. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11805. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11806. }
  11807. var dupes = [];
  11808. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11809. var realPos = vectorPositions.length - 1 - iteration;
  11810. var testedPosition = vectorPositions[realPos];
  11811. for (var j = 0; j < realPos; ++j) {
  11812. var againstPosition = vectorPositions[j];
  11813. if (testedPosition.equals(againstPosition)) {
  11814. dupes[realPos] = j;
  11815. break;
  11816. }
  11817. }
  11818. }, function () {
  11819. for (var i = 0; i < indices.length; ++i) {
  11820. indices[i] = dupes[indices[i]] || indices[i];
  11821. }
  11822. //indices are now reordered
  11823. var originalSubMeshes = _this.subMeshes.slice(0);
  11824. _this.setIndices(indices);
  11825. _this.subMeshes = originalSubMeshes;
  11826. if (successCallback) {
  11827. successCallback(_this);
  11828. }
  11829. });
  11830. };
  11831. // Statics
  11832. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  11833. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11834. if (ribbonInstance === void 0) { ribbonInstance = null; }
  11835. if (ribbonInstance) {
  11836. // positionFunction : ribbon case
  11837. // only pathArray and sideOrientation parameters are taken into account for positions update
  11838. var positionsOfRibbon = function (pathArray, sideOrientation) {
  11839. var positionFunction = function (positions) {
  11840. var minlg = pathArray[0].length;
  11841. var i = 0;
  11842. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  11843. for (var si = 1; si <= ns; si++) {
  11844. for (var p = 0; p < pathArray.length; p++) {
  11845. var path = pathArray[p];
  11846. var l = path.length;
  11847. minlg = (minlg < l) ? minlg : l;
  11848. var j = 0;
  11849. while (j < minlg) {
  11850. positions[i] = path[j].x;
  11851. positions[i + 1] = path[j].y;
  11852. positions[i + 2] = path[j].z;
  11853. j++;
  11854. i += 3;
  11855. }
  11856. }
  11857. }
  11858. };
  11859. return positionFunction;
  11860. };
  11861. var sideOrientation = ribbonInstance.sideOrientation;
  11862. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  11863. ribbonInstance.updateMeshPositions(positionFunction, true);
  11864. return ribbonInstance;
  11865. }
  11866. else {
  11867. var ribbon = new Mesh(name, scene);
  11868. ribbon.sideOrientation = sideOrientation;
  11869. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11870. vertexData.applyToMesh(ribbon, updatable);
  11871. return ribbon;
  11872. }
  11873. };
  11874. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  11875. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11876. var disc = new Mesh(name, scene);
  11877. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  11878. vertexData.applyToMesh(disc, updatable);
  11879. return disc;
  11880. };
  11881. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11882. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11883. var box = new Mesh(name, scene);
  11884. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11885. vertexData.applyToMesh(box, updatable);
  11886. return box;
  11887. };
  11888. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11889. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11890. var sphere = new Mesh(name, scene);
  11891. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11892. vertexData.applyToMesh(sphere, updatable);
  11893. return sphere;
  11894. };
  11895. // Cylinder and cone (Code inspired by SharpDX.org)
  11896. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11897. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11898. // subdivisions is a new parameter, we need to support old signature
  11899. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11900. if (scene !== undefined) {
  11901. updatable = scene;
  11902. }
  11903. scene = subdivisions;
  11904. subdivisions = 1;
  11905. }
  11906. var cylinder = new Mesh(name, scene);
  11907. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11908. vertexData.applyToMesh(cylinder, updatable);
  11909. return cylinder;
  11910. };
  11911. // Torus (Code from SharpDX.org)
  11912. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11913. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11914. var torus = new Mesh(name, scene);
  11915. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11916. vertexData.applyToMesh(torus, updatable);
  11917. return torus;
  11918. };
  11919. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11920. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11921. var torusKnot = new Mesh(name, scene);
  11922. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11923. vertexData.applyToMesh(torusKnot, updatable);
  11924. return torusKnot;
  11925. };
  11926. // Lines
  11927. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  11928. if (linesInstance === void 0) { linesInstance = null; }
  11929. if (linesInstance) {
  11930. var positionsOfLines = function (points) {
  11931. var positionFunction = function (positions) {
  11932. var i = 0;
  11933. for (var p = 0; p < points.length; p++) {
  11934. positions[i] = points[p].x;
  11935. positions[i + 1] = points[p].y;
  11936. positions[i + 2] = points[p].z;
  11937. i += 3;
  11938. }
  11939. };
  11940. return positionFunction;
  11941. };
  11942. var positionFunction = positionsOfLines(points);
  11943. linesInstance.updateMeshPositions(positionFunction, false);
  11944. return linesInstance;
  11945. }
  11946. // lines creation
  11947. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11948. var vertexData = BABYLON.VertexData.CreateLines(points);
  11949. vertexData.applyToMesh(lines, updatable);
  11950. return lines;
  11951. };
  11952. // Extrusion
  11953. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation, extrudedInstance) {
  11954. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11955. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11956. scale = scale || 1;
  11957. rotation = rotation || 0;
  11958. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation, extrudedInstance);
  11959. return extruded;
  11960. };
  11961. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation, extrudedInstance) {
  11962. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11963. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11964. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation, extrudedInstance);
  11965. return extrudedCustom;
  11966. };
  11967. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side, instance) {
  11968. // extrusion geometry
  11969. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, custom) {
  11970. var tangents = path3D.getTangents();
  11971. var normals = path3D.getNormals();
  11972. var binormals = path3D.getBinormals();
  11973. var distances = path3D.getDistances();
  11974. var angle = 0;
  11975. var returnScale = function (i, distance) {
  11976. return scale;
  11977. };
  11978. var returnRotation = function (i, distance) {
  11979. return rotation;
  11980. };
  11981. var rotate = custom ? rotateFunction : returnRotation;
  11982. var scl = custom ? scaleFunction : returnScale;
  11983. var index = 0;
  11984. for (var i = 0; i < curve.length; i++) {
  11985. var shapePath = new Array();
  11986. var angleStep = rotate(i, distances[i]);
  11987. var scaleRatio = scl(i, distances[i]);
  11988. for (var p = 0; p < shape.length; p++) {
  11989. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11990. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11991. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11992. shapePath.push(rotated);
  11993. }
  11994. shapePaths[index] = shapePath;
  11995. angle += angleStep;
  11996. index++;
  11997. }
  11998. return shapePaths;
  11999. };
  12000. if (instance) {
  12001. var path3D = (instance.path3D).update(curve);
  12002. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, custom);
  12003. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  12004. return instance;
  12005. }
  12006. // extruded shape creation
  12007. var path3D = new BABYLON.Path3D(curve);
  12008. var newShapePaths = new Array();
  12009. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, custom);
  12010. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  12011. extrudedGeneric.pathArray = pathArray;
  12012. extrudedGeneric.path3D = path3D;
  12013. return extrudedGeneric;
  12014. };
  12015. // Plane & ground
  12016. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  12017. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12018. var plane = new Mesh(name, scene);
  12019. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  12020. vertexData.applyToMesh(plane, updatable);
  12021. return plane;
  12022. };
  12023. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  12024. var ground = new BABYLON.GroundMesh(name, scene);
  12025. ground._setReady(false);
  12026. ground._subdivisions = subdivisions;
  12027. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  12028. vertexData.applyToMesh(ground, updatable);
  12029. ground._setReady(true);
  12030. return ground;
  12031. };
  12032. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  12033. var tiledGround = new Mesh(name, scene);
  12034. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  12035. vertexData.applyToMesh(tiledGround, updatable);
  12036. return tiledGround;
  12037. };
  12038. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  12039. var ground = new BABYLON.GroundMesh(name, scene);
  12040. ground._subdivisions = subdivisions;
  12041. ground._setReady(false);
  12042. var onload = function (img) {
  12043. // Getting height map data
  12044. var canvas = document.createElement("canvas");
  12045. var context = canvas.getContext("2d");
  12046. var heightMapWidth = img.width;
  12047. var heightMapHeight = img.height;
  12048. canvas.width = heightMapWidth;
  12049. canvas.height = heightMapHeight;
  12050. context.drawImage(img, 0, 0);
  12051. // Create VertexData from map data
  12052. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  12053. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  12054. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  12055. vertexData.applyToMesh(ground, updatable);
  12056. ground._setReady(true);
  12057. //execute ready callback, if set
  12058. if (onReady) {
  12059. onReady(ground);
  12060. }
  12061. };
  12062. BABYLON.Tools.LoadImage(url, onload, function () {
  12063. }, scene.database);
  12064. return ground;
  12065. };
  12066. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, scene, updatable, sideOrientation, tubeInstance) {
  12067. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12068. if (tubeInstance === void 0) { tubeInstance = null; }
  12069. // tube geometry
  12070. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction) {
  12071. var tangents = path3D.getTangents();
  12072. var normals = path3D.getNormals();
  12073. var distances = path3D.getDistances();
  12074. var pi2 = Math.PI * 2;
  12075. var step = pi2 / tessellation;
  12076. var returnRadius = function (i, distance) { return radius; };
  12077. var radiusFunctionFinal = radiusFunction || returnRadius;
  12078. var circlePath;
  12079. var rad;
  12080. var normal;
  12081. var rotated;
  12082. var rotationMatrix;
  12083. var index = 0;
  12084. for (var i = 0; i < path.length; i++) {
  12085. rad = radiusFunctionFinal(i, distances[i]); // current radius
  12086. circlePath = Array(); // current circle array
  12087. normal = normals[i]; // current normal
  12088. for (var ang = 0; ang < pi2; ang += step) {
  12089. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  12090. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  12091. circlePath.push(rotated);
  12092. }
  12093. circlePaths[index] = circlePath;
  12094. index++;
  12095. }
  12096. return circlePaths;
  12097. };
  12098. if (tubeInstance) {
  12099. var path3D = (tubeInstance.path3D).update(path);
  12100. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction);
  12101. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  12102. return tubeInstance;
  12103. }
  12104. // tube creation
  12105. var path3D = new BABYLON.Path3D(path);
  12106. var newPathArray = new Array();
  12107. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction);
  12108. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  12109. tube.pathArray = pathArray;
  12110. tube.path3D = path3D;
  12111. tube.tessellation = tessellation;
  12112. return tube;
  12113. };
  12114. // Decals
  12115. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  12116. if (angle === void 0) { angle = 0; }
  12117. var indices = sourceMesh.getIndices();
  12118. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12119. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12120. // Getting correct rotation
  12121. if (!normal) {
  12122. var target = new BABYLON.Vector3(0, 0, 1);
  12123. var camera = sourceMesh.getScene().activeCamera;
  12124. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  12125. normal = camera.globalPosition.subtract(cameraWorldTarget);
  12126. }
  12127. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  12128. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  12129. var pitch = Math.atan2(normal.y, len);
  12130. // Matrix
  12131. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  12132. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  12133. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  12134. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  12135. var vertexData = new BABYLON.VertexData();
  12136. vertexData.indices = [];
  12137. vertexData.positions = [];
  12138. vertexData.normals = [];
  12139. vertexData.uvs = [];
  12140. var currentVertexDataIndex = 0;
  12141. var extractDecalVector3 = function (indexId) {
  12142. var vertexId = indices[indexId];
  12143. var result = new BABYLON.PositionNormalVertex();
  12144. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  12145. // Send vector to decal local world
  12146. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  12147. // Get normal
  12148. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  12149. return result;
  12150. };
  12151. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  12152. var clip = function (vertices, axis) {
  12153. if (vertices.length === 0) {
  12154. return vertices;
  12155. }
  12156. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  12157. var clipVertices = function (v0, v1) {
  12158. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  12159. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  12160. };
  12161. var result = new Array();
  12162. for (var index = 0; index < vertices.length; index += 3) {
  12163. var v1Out;
  12164. var v2Out;
  12165. var v3Out;
  12166. var total = 0;
  12167. var nV1, nV2, nV3, nV4;
  12168. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  12169. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  12170. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  12171. v1Out = d1 > 0;
  12172. v2Out = d2 > 0;
  12173. v3Out = d3 > 0;
  12174. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  12175. switch (total) {
  12176. case 0:
  12177. result.push(vertices[index]);
  12178. result.push(vertices[index + 1]);
  12179. result.push(vertices[index + 2]);
  12180. break;
  12181. case 1:
  12182. if (v1Out) {
  12183. nV1 = vertices[index + 1];
  12184. nV2 = vertices[index + 2];
  12185. nV3 = clipVertices(vertices[index], nV1);
  12186. nV4 = clipVertices(vertices[index], nV2);
  12187. }
  12188. if (v2Out) {
  12189. nV1 = vertices[index];
  12190. nV2 = vertices[index + 2];
  12191. nV3 = clipVertices(vertices[index + 1], nV1);
  12192. nV4 = clipVertices(vertices[index + 1], nV2);
  12193. result.push(nV3);
  12194. result.push(nV2.clone());
  12195. result.push(nV1.clone());
  12196. result.push(nV2.clone());
  12197. result.push(nV3.clone());
  12198. result.push(nV4);
  12199. break;
  12200. }
  12201. if (v3Out) {
  12202. nV1 = vertices[index];
  12203. nV2 = vertices[index + 1];
  12204. nV3 = clipVertices(vertices[index + 2], nV1);
  12205. nV4 = clipVertices(vertices[index + 2], nV2);
  12206. }
  12207. result.push(nV1.clone());
  12208. result.push(nV2.clone());
  12209. result.push(nV3);
  12210. result.push(nV4);
  12211. result.push(nV3.clone());
  12212. result.push(nV2.clone());
  12213. break;
  12214. case 2:
  12215. if (!v1Out) {
  12216. nV1 = vertices[index].clone();
  12217. nV2 = clipVertices(nV1, vertices[index + 1]);
  12218. nV3 = clipVertices(nV1, vertices[index + 2]);
  12219. result.push(nV1);
  12220. result.push(nV2);
  12221. result.push(nV3);
  12222. }
  12223. if (!v2Out) {
  12224. nV1 = vertices[index + 1].clone();
  12225. nV2 = clipVertices(nV1, vertices[index + 2]);
  12226. nV3 = clipVertices(nV1, vertices[index]);
  12227. result.push(nV1);
  12228. result.push(nV2);
  12229. result.push(nV3);
  12230. }
  12231. if (!v3Out) {
  12232. nV1 = vertices[index + 2].clone();
  12233. nV2 = clipVertices(nV1, vertices[index]);
  12234. nV3 = clipVertices(nV1, vertices[index + 1]);
  12235. result.push(nV1);
  12236. result.push(nV2);
  12237. result.push(nV3);
  12238. }
  12239. break;
  12240. case 3:
  12241. break;
  12242. }
  12243. }
  12244. return result;
  12245. };
  12246. for (var index = 0; index < indices.length; index += 3) {
  12247. var faceVertices = new Array();
  12248. faceVertices.push(extractDecalVector3(index));
  12249. faceVertices.push(extractDecalVector3(index + 1));
  12250. faceVertices.push(extractDecalVector3(index + 2));
  12251. // Clip
  12252. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12253. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12254. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12255. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12256. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12257. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12258. if (faceVertices.length === 0) {
  12259. continue;
  12260. }
  12261. // Add UVs and get back to world
  12262. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  12263. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12264. var vertex = faceVertices[vIndex];
  12265. vertexData.indices.push(currentVertexDataIndex);
  12266. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  12267. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12268. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12269. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12270. currentVertexDataIndex++;
  12271. }
  12272. }
  12273. // Return mesh
  12274. var decal = new Mesh(name, sourceMesh.getScene());
  12275. vertexData.applyToMesh(decal);
  12276. decal.position = position.clone();
  12277. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  12278. return decal;
  12279. };
  12280. // Tools
  12281. Mesh.MinMax = function (meshes) {
  12282. var minVector = null;
  12283. var maxVector = null;
  12284. for (var i in meshes) {
  12285. var mesh = meshes[i];
  12286. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12287. if (!minVector) {
  12288. minVector = boundingBox.minimumWorld;
  12289. maxVector = boundingBox.maximumWorld;
  12290. continue;
  12291. }
  12292. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12293. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12294. }
  12295. return {
  12296. min: minVector,
  12297. max: maxVector
  12298. };
  12299. };
  12300. Mesh.Center = function (meshesOrMinMaxVector) {
  12301. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12302. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12303. };
  12304. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  12305. if (disposeSource === void 0) { disposeSource = true; }
  12306. var source = meshes[0];
  12307. var material = source.material;
  12308. var scene = source.getScene();
  12309. if (!allow32BitsIndices) {
  12310. var totalVertices = 0;
  12311. for (var index = 0; index < meshes.length; index++) {
  12312. totalVertices += meshes[index].getTotalVertices();
  12313. if (totalVertices > 65536) {
  12314. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12315. return null;
  12316. }
  12317. }
  12318. }
  12319. // Merge
  12320. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  12321. vertexData.transform(source.getWorldMatrix());
  12322. for (index = 1; index < meshes.length; index++) {
  12323. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  12324. otherVertexData.transform(meshes[index].getWorldMatrix());
  12325. vertexData.merge(otherVertexData);
  12326. }
  12327. var newMesh = new Mesh(source.name + "_merged", scene);
  12328. vertexData.applyToMesh(newMesh);
  12329. // Setting properties
  12330. newMesh.material = material;
  12331. newMesh.checkCollisions = source.checkCollisions;
  12332. // Cleaning
  12333. if (disposeSource) {
  12334. for (index = 0; index < meshes.length; index++) {
  12335. meshes[index].dispose();
  12336. }
  12337. }
  12338. return newMesh;
  12339. };
  12340. // Consts
  12341. Mesh._FRONTSIDE = 0;
  12342. Mesh._BACKSIDE = 1;
  12343. Mesh._DOUBLESIDE = 2;
  12344. Mesh._DEFAULTSIDE = 0;
  12345. return Mesh;
  12346. })(BABYLON.AbstractMesh);
  12347. BABYLON.Mesh = Mesh;
  12348. })(BABYLON || (BABYLON = {}));
  12349. //# sourceMappingURL=babylon.mesh.js.map
  12350. var BABYLON;
  12351. (function (BABYLON) {
  12352. var GroundMesh = (function (_super) {
  12353. __extends(GroundMesh, _super);
  12354. function GroundMesh(name, scene) {
  12355. _super.call(this, name, scene);
  12356. this.generateOctree = false;
  12357. this._worldInverse = new BABYLON.Matrix();
  12358. }
  12359. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12360. get: function () {
  12361. return this._subdivisions;
  12362. },
  12363. enumerable: true,
  12364. configurable: true
  12365. });
  12366. GroundMesh.prototype.optimize = function (chunksCount) {
  12367. this.subdivide(this._subdivisions);
  12368. this.createOrUpdateSubmeshesOctree(32);
  12369. };
  12370. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12371. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12372. this.getWorldMatrix().invertToRef(this._worldInverse);
  12373. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12374. var pickInfo = this.intersects(ray);
  12375. if (pickInfo.hit) {
  12376. return pickInfo.pickedPoint.y;
  12377. }
  12378. return 0;
  12379. };
  12380. return GroundMesh;
  12381. })(BABYLON.Mesh);
  12382. BABYLON.GroundMesh = GroundMesh;
  12383. })(BABYLON || (BABYLON = {}));
  12384. //# sourceMappingURL=babylon.groundMesh.js.map
  12385. var BABYLON;
  12386. (function (BABYLON) {
  12387. /**
  12388. * Creates an instance based on a source mesh.
  12389. */
  12390. var InstancedMesh = (function (_super) {
  12391. __extends(InstancedMesh, _super);
  12392. function InstancedMesh(name, source) {
  12393. _super.call(this, name, source.getScene());
  12394. source.instances.push(this);
  12395. this._sourceMesh = source;
  12396. this.position.copyFrom(source.position);
  12397. this.rotation.copyFrom(source.rotation);
  12398. this.scaling.copyFrom(source.scaling);
  12399. if (source.rotationQuaternion) {
  12400. this.rotationQuaternion = source.rotationQuaternion.clone();
  12401. }
  12402. this.infiniteDistance = source.infiniteDistance;
  12403. this.setPivotMatrix(source.getPivotMatrix());
  12404. this.refreshBoundingInfo();
  12405. this._syncSubMeshes();
  12406. }
  12407. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12408. // Methods
  12409. get: function () {
  12410. return this._sourceMesh.receiveShadows;
  12411. },
  12412. enumerable: true,
  12413. configurable: true
  12414. });
  12415. Object.defineProperty(InstancedMesh.prototype, "material", {
  12416. get: function () {
  12417. return this._sourceMesh.material;
  12418. },
  12419. enumerable: true,
  12420. configurable: true
  12421. });
  12422. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12423. get: function () {
  12424. return this._sourceMesh.visibility;
  12425. },
  12426. enumerable: true,
  12427. configurable: true
  12428. });
  12429. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12430. get: function () {
  12431. return this._sourceMesh.skeleton;
  12432. },
  12433. enumerable: true,
  12434. configurable: true
  12435. });
  12436. InstancedMesh.prototype.getTotalVertices = function () {
  12437. return this._sourceMesh.getTotalVertices();
  12438. };
  12439. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12440. get: function () {
  12441. return this._sourceMesh;
  12442. },
  12443. enumerable: true,
  12444. configurable: true
  12445. });
  12446. InstancedMesh.prototype.getVerticesData = function (kind) {
  12447. return this._sourceMesh.getVerticesData(kind);
  12448. };
  12449. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12450. return this._sourceMesh.isVerticesDataPresent(kind);
  12451. };
  12452. InstancedMesh.prototype.getIndices = function () {
  12453. return this._sourceMesh.getIndices();
  12454. };
  12455. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12456. get: function () {
  12457. return this._sourceMesh._positions;
  12458. },
  12459. enumerable: true,
  12460. configurable: true
  12461. });
  12462. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12463. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12464. if (data) {
  12465. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12466. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12467. }
  12468. this._updateBoundingInfo();
  12469. };
  12470. InstancedMesh.prototype._preActivate = function () {
  12471. if (this._currentLOD) {
  12472. this._currentLOD._preActivate();
  12473. }
  12474. };
  12475. InstancedMesh.prototype._activate = function (renderId) {
  12476. if (this._currentLOD) {
  12477. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12478. }
  12479. };
  12480. InstancedMesh.prototype.getLOD = function (camera) {
  12481. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12482. if (this._currentLOD === this.sourceMesh) {
  12483. return this;
  12484. }
  12485. return this._currentLOD;
  12486. };
  12487. InstancedMesh.prototype._syncSubMeshes = function () {
  12488. this.releaseSubMeshes();
  12489. if (this._sourceMesh.subMeshes) {
  12490. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12491. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12492. }
  12493. }
  12494. };
  12495. InstancedMesh.prototype._generatePointsArray = function () {
  12496. return this._sourceMesh._generatePointsArray();
  12497. };
  12498. // Clone
  12499. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12500. var result = this._sourceMesh.createInstance(name);
  12501. // Deep copy
  12502. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12503. // Bounding info
  12504. this.refreshBoundingInfo();
  12505. // Parent
  12506. if (newParent) {
  12507. result.parent = newParent;
  12508. }
  12509. if (!doNotCloneChildren) {
  12510. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12511. var mesh = this.getScene().meshes[index];
  12512. if (mesh.parent === this) {
  12513. mesh.clone(mesh.name, result);
  12514. }
  12515. }
  12516. }
  12517. result.computeWorldMatrix(true);
  12518. return result;
  12519. };
  12520. // Dispoe
  12521. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12522. // Remove from mesh
  12523. var index = this._sourceMesh.instances.indexOf(this);
  12524. this._sourceMesh.instances.splice(index, 1);
  12525. _super.prototype.dispose.call(this, doNotRecurse);
  12526. };
  12527. return InstancedMesh;
  12528. })(BABYLON.AbstractMesh);
  12529. BABYLON.InstancedMesh = InstancedMesh;
  12530. })(BABYLON || (BABYLON = {}));
  12531. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12532. (function (BABYLON) {
  12533. var SubMesh = (function () {
  12534. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12535. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12536. this.materialIndex = materialIndex;
  12537. this.verticesStart = verticesStart;
  12538. this.verticesCount = verticesCount;
  12539. this.indexStart = indexStart;
  12540. this.indexCount = indexCount;
  12541. this._renderId = 0;
  12542. this._mesh = mesh;
  12543. this._renderingMesh = renderingMesh || mesh;
  12544. mesh.subMeshes.push(this);
  12545. this._id = mesh.subMeshes.length - 1;
  12546. if (createBoundingBox) {
  12547. this.refreshBoundingInfo();
  12548. mesh.computeWorldMatrix(true);
  12549. }
  12550. }
  12551. SubMesh.prototype.getBoundingInfo = function () {
  12552. return this._boundingInfo;
  12553. };
  12554. SubMesh.prototype.getMesh = function () {
  12555. return this._mesh;
  12556. };
  12557. SubMesh.prototype.getRenderingMesh = function () {
  12558. return this._renderingMesh;
  12559. };
  12560. SubMesh.prototype.getMaterial = function () {
  12561. var rootMaterial = this._renderingMesh.material;
  12562. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12563. var multiMaterial = rootMaterial;
  12564. return multiMaterial.getSubMaterial(this.materialIndex);
  12565. }
  12566. if (!rootMaterial) {
  12567. return this._mesh.getScene().defaultMaterial;
  12568. }
  12569. return rootMaterial;
  12570. };
  12571. // Methods
  12572. SubMesh.prototype.refreshBoundingInfo = function () {
  12573. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12574. if (!data) {
  12575. this._boundingInfo = this._mesh._boundingInfo;
  12576. return;
  12577. }
  12578. var indices = this._renderingMesh.getIndices();
  12579. var extend;
  12580. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12581. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12582. }
  12583. else {
  12584. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12585. }
  12586. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12587. };
  12588. SubMesh.prototype._checkCollision = function (collider) {
  12589. return this._boundingInfo._checkCollision(collider);
  12590. };
  12591. SubMesh.prototype.updateBoundingInfo = function (world) {
  12592. if (!this._boundingInfo) {
  12593. this.refreshBoundingInfo();
  12594. }
  12595. this._boundingInfo._update(world);
  12596. };
  12597. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12598. return this._boundingInfo.isInFrustum(frustumPlanes);
  12599. };
  12600. SubMesh.prototype.render = function () {
  12601. this._renderingMesh.render(this);
  12602. };
  12603. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12604. if (!this._linesIndexBuffer) {
  12605. var linesIndices = [];
  12606. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12607. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12608. }
  12609. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12610. this.linesIndexCount = linesIndices.length;
  12611. }
  12612. return this._linesIndexBuffer;
  12613. };
  12614. SubMesh.prototype.canIntersects = function (ray) {
  12615. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12616. };
  12617. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12618. var intersectInfo = null;
  12619. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12620. var p0 = positions[indices[index]];
  12621. var p1 = positions[indices[index + 1]];
  12622. var p2 = positions[indices[index + 2]];
  12623. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12624. if (currentIntersectInfo) {
  12625. if (currentIntersectInfo.distance < 0) {
  12626. continue;
  12627. }
  12628. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12629. intersectInfo = currentIntersectInfo;
  12630. intersectInfo.faceId = index / 3;
  12631. if (fastCheck) {
  12632. break;
  12633. }
  12634. }
  12635. }
  12636. }
  12637. return intersectInfo;
  12638. };
  12639. // Clone
  12640. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12641. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12642. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12643. return result;
  12644. };
  12645. // Dispose
  12646. SubMesh.prototype.dispose = function () {
  12647. if (this._linesIndexBuffer) {
  12648. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12649. this._linesIndexBuffer = null;
  12650. }
  12651. // Remove from mesh
  12652. var index = this._mesh.subMeshes.indexOf(this);
  12653. this._mesh.subMeshes.splice(index, 1);
  12654. };
  12655. // Statics
  12656. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12657. var minVertexIndex = Number.MAX_VALUE;
  12658. var maxVertexIndex = -Number.MAX_VALUE;
  12659. renderingMesh = renderingMesh || mesh;
  12660. var indices = renderingMesh.getIndices();
  12661. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12662. var vertexIndex = indices[index];
  12663. if (vertexIndex < minVertexIndex)
  12664. minVertexIndex = vertexIndex;
  12665. if (vertexIndex > maxVertexIndex)
  12666. maxVertexIndex = vertexIndex;
  12667. }
  12668. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12669. };
  12670. return SubMesh;
  12671. })();
  12672. BABYLON.SubMesh = SubMesh;
  12673. })(BABYLON || (BABYLON = {}));
  12674. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12675. (function (BABYLON) {
  12676. var BaseTexture = (function () {
  12677. function BaseTexture(scene) {
  12678. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12679. this.hasAlpha = false;
  12680. this.getAlphaFromRGB = false;
  12681. this.level = 1;
  12682. this.isCube = false;
  12683. this.isRenderTarget = false;
  12684. this.animations = new Array();
  12685. this.coordinatesIndex = 0;
  12686. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12687. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12688. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12689. this.anisotropicFilteringLevel = 4;
  12690. this._scene = scene;
  12691. this._scene.textures.push(this);
  12692. }
  12693. BaseTexture.prototype.getScene = function () {
  12694. return this._scene;
  12695. };
  12696. BaseTexture.prototype.getTextureMatrix = function () {
  12697. return null;
  12698. };
  12699. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12700. return null;
  12701. };
  12702. BaseTexture.prototype.getInternalTexture = function () {
  12703. return this._texture;
  12704. };
  12705. BaseTexture.prototype.isReady = function () {
  12706. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12707. return true;
  12708. }
  12709. if (this._texture) {
  12710. return this._texture.isReady;
  12711. }
  12712. return false;
  12713. };
  12714. BaseTexture.prototype.getSize = function () {
  12715. if (this._texture._width) {
  12716. return { width: this._texture._width, height: this._texture._height };
  12717. }
  12718. if (this._texture._size) {
  12719. return { width: this._texture._size, height: this._texture._size };
  12720. }
  12721. return { width: 0, height: 0 };
  12722. };
  12723. BaseTexture.prototype.getBaseSize = function () {
  12724. if (!this.isReady())
  12725. return { width: 0, height: 0 };
  12726. if (this._texture._size) {
  12727. return { width: this._texture._size, height: this._texture._size };
  12728. }
  12729. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12730. };
  12731. BaseTexture.prototype.scale = function (ratio) {
  12732. };
  12733. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12734. get: function () {
  12735. return false;
  12736. },
  12737. enumerable: true,
  12738. configurable: true
  12739. });
  12740. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12741. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12742. for (var index = 0; index < texturesCache.length; index++) {
  12743. var texturesCacheEntry = texturesCache[index];
  12744. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12745. texturesCache.splice(index, 1);
  12746. return;
  12747. }
  12748. }
  12749. };
  12750. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12751. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12752. for (var index = 0; index < texturesCache.length; index++) {
  12753. var texturesCacheEntry = texturesCache[index];
  12754. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12755. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12756. texturesCacheEntry.references++;
  12757. return texturesCacheEntry;
  12758. }
  12759. }
  12760. }
  12761. return null;
  12762. };
  12763. BaseTexture.prototype.delayLoad = function () {
  12764. };
  12765. BaseTexture.prototype.releaseInternalTexture = function () {
  12766. if (!this._texture) {
  12767. return;
  12768. }
  12769. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12770. this._texture.references--;
  12771. // Final reference ?
  12772. if (this._texture.references === 0) {
  12773. var index = texturesCache.indexOf(this._texture);
  12774. texturesCache.splice(index, 1);
  12775. this._scene.getEngine()._releaseTexture(this._texture);
  12776. delete this._texture;
  12777. }
  12778. };
  12779. BaseTexture.prototype.clone = function () {
  12780. return null;
  12781. };
  12782. BaseTexture.prototype.dispose = function () {
  12783. // Remove from scene
  12784. var index = this._scene.textures.indexOf(this);
  12785. if (index >= 0) {
  12786. this._scene.textures.splice(index, 1);
  12787. }
  12788. if (this._texture === undefined) {
  12789. return;
  12790. }
  12791. this.releaseInternalTexture();
  12792. // Callback
  12793. if (this.onDispose) {
  12794. this.onDispose();
  12795. }
  12796. };
  12797. return BaseTexture;
  12798. })();
  12799. BABYLON.BaseTexture = BaseTexture;
  12800. })(BABYLON || (BABYLON = {}));
  12801. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12802. (function (BABYLON) {
  12803. var RenderingGroup = (function () {
  12804. function RenderingGroup(index, scene) {
  12805. this.index = index;
  12806. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12807. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12808. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12809. this._scene = scene;
  12810. }
  12811. RenderingGroup.prototype.render = function (customRenderFunction) {
  12812. if (customRenderFunction) {
  12813. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12814. return true;
  12815. }
  12816. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12817. return false;
  12818. }
  12819. var engine = this._scene.getEngine();
  12820. // Opaque
  12821. var subIndex;
  12822. var submesh;
  12823. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12824. submesh = this._opaqueSubMeshes.data[subIndex];
  12825. submesh.render();
  12826. }
  12827. // Alpha test
  12828. engine.setAlphaTesting(true);
  12829. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12830. submesh = this._alphaTestSubMeshes.data[subIndex];
  12831. submesh.render();
  12832. }
  12833. engine.setAlphaTesting(false);
  12834. // Transparent
  12835. if (this._transparentSubMeshes.length) {
  12836. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12837. submesh = this._transparentSubMeshes.data[subIndex];
  12838. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12839. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12840. }
  12841. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12842. sortedArray.sort(function (a, b) {
  12843. // Alpha index first
  12844. if (a._alphaIndex > b._alphaIndex) {
  12845. return 1;
  12846. }
  12847. if (a._alphaIndex < b._alphaIndex) {
  12848. return -1;
  12849. }
  12850. // Then distance to camera
  12851. if (a._distanceToCamera < b._distanceToCamera) {
  12852. return 1;
  12853. }
  12854. if (a._distanceToCamera > b._distanceToCamera) {
  12855. return -1;
  12856. }
  12857. return 0;
  12858. });
  12859. // Rendering
  12860. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12861. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12862. submesh = sortedArray[subIndex];
  12863. submesh.render();
  12864. }
  12865. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12866. }
  12867. return true;
  12868. };
  12869. RenderingGroup.prototype.prepare = function () {
  12870. this._opaqueSubMeshes.reset();
  12871. this._transparentSubMeshes.reset();
  12872. this._alphaTestSubMeshes.reset();
  12873. };
  12874. RenderingGroup.prototype.dispatch = function (subMesh) {
  12875. var material = subMesh.getMaterial();
  12876. var mesh = subMesh.getMesh();
  12877. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12878. this._transparentSubMeshes.push(subMesh);
  12879. }
  12880. else if (material.needAlphaTesting()) {
  12881. this._alphaTestSubMeshes.push(subMesh);
  12882. }
  12883. else {
  12884. this._opaqueSubMeshes.push(subMesh); // Opaque
  12885. }
  12886. };
  12887. return RenderingGroup;
  12888. })();
  12889. BABYLON.RenderingGroup = RenderingGroup;
  12890. })(BABYLON || (BABYLON = {}));
  12891. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12892. (function (BABYLON) {
  12893. var RenderingManager = (function () {
  12894. function RenderingManager(scene) {
  12895. this._renderingGroups = new Array();
  12896. this._scene = scene;
  12897. }
  12898. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12899. if (this._scene._activeParticleSystems.length === 0) {
  12900. return;
  12901. }
  12902. // Particles
  12903. var beforeParticlesDate = BABYLON.Tools.Now;
  12904. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12905. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12906. if (particleSystem.renderingGroupId !== index) {
  12907. continue;
  12908. }
  12909. this._clearDepthBuffer();
  12910. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12911. this._scene._activeParticles += particleSystem.render();
  12912. }
  12913. }
  12914. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12915. };
  12916. RenderingManager.prototype._renderSprites = function (index) {
  12917. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12918. return;
  12919. }
  12920. // Sprites
  12921. var beforeSpritessDate = BABYLON.Tools.Now;
  12922. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12923. var spriteManager = this._scene.spriteManagers[id];
  12924. if (spriteManager.renderingGroupId === index) {
  12925. this._clearDepthBuffer();
  12926. spriteManager.render();
  12927. }
  12928. }
  12929. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12930. };
  12931. RenderingManager.prototype._clearDepthBuffer = function () {
  12932. if (this._depthBufferAlreadyCleaned) {
  12933. return;
  12934. }
  12935. this._scene.getEngine().clear(0, false, true);
  12936. this._depthBufferAlreadyCleaned = true;
  12937. };
  12938. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12939. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12940. this._depthBufferAlreadyCleaned = false;
  12941. var renderingGroup = this._renderingGroups[index];
  12942. var needToStepBack = false;
  12943. if (renderingGroup) {
  12944. this._clearDepthBuffer();
  12945. if (!renderingGroup.render(customRenderFunction)) {
  12946. this._renderingGroups.splice(index, 1);
  12947. needToStepBack = true;
  12948. }
  12949. }
  12950. if (renderSprites) {
  12951. this._renderSprites(index);
  12952. }
  12953. if (renderParticles) {
  12954. this._renderParticles(index, activeMeshes);
  12955. }
  12956. if (needToStepBack) {
  12957. index--;
  12958. }
  12959. }
  12960. };
  12961. RenderingManager.prototype.reset = function () {
  12962. for (var index in this._renderingGroups) {
  12963. var renderingGroup = this._renderingGroups[index];
  12964. renderingGroup.prepare();
  12965. }
  12966. };
  12967. RenderingManager.prototype.dispatch = function (subMesh) {
  12968. var mesh = subMesh.getMesh();
  12969. var renderingGroupId = mesh.renderingGroupId || 0;
  12970. if (!this._renderingGroups[renderingGroupId]) {
  12971. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12972. }
  12973. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12974. };
  12975. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12976. return RenderingManager;
  12977. })();
  12978. BABYLON.RenderingManager = RenderingManager;
  12979. })(BABYLON || (BABYLON = {}));
  12980. //# sourceMappingURL=babylon.renderingManager.js.map
  12981. var BABYLON;
  12982. (function (BABYLON) {
  12983. var Texture = (function (_super) {
  12984. __extends(Texture, _super);
  12985. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12986. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12987. if (onLoad === void 0) { onLoad = null; }
  12988. if (onError === void 0) { onError = null; }
  12989. if (buffer === void 0) { buffer = null; }
  12990. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12991. _super.call(this, scene);
  12992. this.uOffset = 0;
  12993. this.vOffset = 0;
  12994. this.uScale = 1.0;
  12995. this.vScale = 1.0;
  12996. this.uAng = 0;
  12997. this.vAng = 0;
  12998. this.wAng = 0;
  12999. this.name = url;
  13000. this.url = url;
  13001. this._noMipmap = noMipmap;
  13002. this._invertY = invertY;
  13003. this._samplingMode = samplingMode;
  13004. this._buffer = buffer;
  13005. this._deleteBuffer = deleteBuffer;
  13006. if (!url) {
  13007. return;
  13008. }
  13009. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  13010. if (!this._texture) {
  13011. if (!scene.useDelayedTextureLoading) {
  13012. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  13013. if (deleteBuffer) {
  13014. delete this._buffer;
  13015. }
  13016. }
  13017. else {
  13018. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13019. }
  13020. }
  13021. }
  13022. Texture.prototype.delayLoad = function () {
  13023. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13024. return;
  13025. }
  13026. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13027. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  13028. if (!this._texture) {
  13029. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  13030. if (this._deleteBuffer) {
  13031. delete this._buffer;
  13032. }
  13033. }
  13034. };
  13035. Texture.prototype.updateSamplingMode = function (samplingMode) {
  13036. if (!this._texture) {
  13037. return;
  13038. }
  13039. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  13040. };
  13041. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  13042. x -= this.uOffset + 0.5;
  13043. y -= this.vOffset + 0.5;
  13044. z -= 0.5;
  13045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  13046. t.x *= this.uScale;
  13047. t.y *= this.vScale;
  13048. t.x += 0.5;
  13049. t.y += 0.5;
  13050. t.z += 0.5;
  13051. };
  13052. Texture.prototype.getTextureMatrix = function () {
  13053. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  13054. return this._cachedTextureMatrix;
  13055. }
  13056. this._cachedUOffset = this.uOffset;
  13057. this._cachedVOffset = this.vOffset;
  13058. this._cachedUScale = this.uScale;
  13059. this._cachedVScale = this.vScale;
  13060. this._cachedUAng = this.uAng;
  13061. this._cachedVAng = this.vAng;
  13062. this._cachedWAng = this.wAng;
  13063. if (!this._cachedTextureMatrix) {
  13064. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13065. this._rowGenerationMatrix = new BABYLON.Matrix();
  13066. this._t0 = BABYLON.Vector3.Zero();
  13067. this._t1 = BABYLON.Vector3.Zero();
  13068. this._t2 = BABYLON.Vector3.Zero();
  13069. }
  13070. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  13071. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  13072. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  13073. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  13074. this._t1.subtractInPlace(this._t0);
  13075. this._t2.subtractInPlace(this._t0);
  13076. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13077. this._cachedTextureMatrix.m[0] = this._t1.x;
  13078. this._cachedTextureMatrix.m[1] = this._t1.y;
  13079. this._cachedTextureMatrix.m[2] = this._t1.z;
  13080. this._cachedTextureMatrix.m[4] = this._t2.x;
  13081. this._cachedTextureMatrix.m[5] = this._t2.y;
  13082. this._cachedTextureMatrix.m[6] = this._t2.z;
  13083. this._cachedTextureMatrix.m[8] = this._t0.x;
  13084. this._cachedTextureMatrix.m[9] = this._t0.y;
  13085. this._cachedTextureMatrix.m[10] = this._t0.z;
  13086. return this._cachedTextureMatrix;
  13087. };
  13088. Texture.prototype.getReflectionTextureMatrix = function () {
  13089. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  13090. return this._cachedTextureMatrix;
  13091. }
  13092. if (!this._cachedTextureMatrix) {
  13093. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13094. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  13095. }
  13096. this._cachedCoordinatesMode = this.coordinatesMode;
  13097. switch (this.coordinatesMode) {
  13098. case Texture.SPHERICAL_MODE:
  13099. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13100. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  13101. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  13102. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  13103. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  13104. break;
  13105. case Texture.PLANAR_MODE:
  13106. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13107. this._cachedTextureMatrix[0] = this.uScale;
  13108. this._cachedTextureMatrix[5] = this.vScale;
  13109. this._cachedTextureMatrix[12] = this.uOffset;
  13110. this._cachedTextureMatrix[13] = this.vOffset;
  13111. break;
  13112. case Texture.PROJECTION_MODE:
  13113. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  13114. this._projectionModeMatrix.m[0] = 0.5;
  13115. this._projectionModeMatrix.m[5] = -0.5;
  13116. this._projectionModeMatrix.m[10] = 0.0;
  13117. this._projectionModeMatrix.m[12] = 0.5;
  13118. this._projectionModeMatrix.m[13] = 0.5;
  13119. this._projectionModeMatrix.m[14] = 1.0;
  13120. this._projectionModeMatrix.m[15] = 1.0;
  13121. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  13122. break;
  13123. default:
  13124. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13125. break;
  13126. }
  13127. return this._cachedTextureMatrix;
  13128. };
  13129. Texture.prototype.clone = function () {
  13130. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  13131. // Base texture
  13132. newTexture.hasAlpha = this.hasAlpha;
  13133. newTexture.level = this.level;
  13134. newTexture.wrapU = this.wrapU;
  13135. newTexture.wrapV = this.wrapV;
  13136. newTexture.coordinatesIndex = this.coordinatesIndex;
  13137. newTexture.coordinatesMode = this.coordinatesMode;
  13138. // Texture
  13139. newTexture.uOffset = this.uOffset;
  13140. newTexture.vOffset = this.vOffset;
  13141. newTexture.uScale = this.uScale;
  13142. newTexture.vScale = this.vScale;
  13143. newTexture.uAng = this.uAng;
  13144. newTexture.vAng = this.vAng;
  13145. newTexture.wAng = this.wAng;
  13146. return newTexture;
  13147. };
  13148. // Statics
  13149. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  13150. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13151. if (onLoad === void 0) { onLoad = null; }
  13152. if (onError === void 0) { onError = null; }
  13153. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  13154. };
  13155. // Constants
  13156. Texture.NEAREST_SAMPLINGMODE = 1;
  13157. Texture.BILINEAR_SAMPLINGMODE = 2;
  13158. Texture.TRILINEAR_SAMPLINGMODE = 3;
  13159. Texture.EXPLICIT_MODE = 0;
  13160. Texture.SPHERICAL_MODE = 1;
  13161. Texture.PLANAR_MODE = 2;
  13162. Texture.CUBIC_MODE = 3;
  13163. Texture.PROJECTION_MODE = 4;
  13164. Texture.SKYBOX_MODE = 5;
  13165. Texture.CLAMP_ADDRESSMODE = 0;
  13166. Texture.WRAP_ADDRESSMODE = 1;
  13167. Texture.MIRROR_ADDRESSMODE = 2;
  13168. return Texture;
  13169. })(BABYLON.BaseTexture);
  13170. BABYLON.Texture = Texture;
  13171. })(BABYLON || (BABYLON = {}));
  13172. //# sourceMappingURL=babylon.texture.js.map
  13173. var BABYLON;
  13174. (function (BABYLON) {
  13175. var CubeTexture = (function (_super) {
  13176. __extends(CubeTexture, _super);
  13177. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  13178. _super.call(this, scene);
  13179. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  13180. this.name = rootUrl;
  13181. this.url = rootUrl;
  13182. this._noMipmap = noMipmap;
  13183. this.hasAlpha = false;
  13184. this._texture = this._getFromCache(rootUrl, noMipmap);
  13185. if (!extensions) {
  13186. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  13187. }
  13188. this._extensions = extensions;
  13189. if (!this._texture) {
  13190. if (!scene.useDelayedTextureLoading) {
  13191. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  13192. }
  13193. else {
  13194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13195. }
  13196. }
  13197. this.isCube = true;
  13198. this._textureMatrix = BABYLON.Matrix.Identity();
  13199. }
  13200. CubeTexture.prototype.clone = function () {
  13201. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  13202. // Base texture
  13203. newTexture.level = this.level;
  13204. newTexture.wrapU = this.wrapU;
  13205. newTexture.wrapV = this.wrapV;
  13206. newTexture.coordinatesIndex = this.coordinatesIndex;
  13207. newTexture.coordinatesMode = this.coordinatesMode;
  13208. return newTexture;
  13209. };
  13210. // Methods
  13211. CubeTexture.prototype.delayLoad = function () {
  13212. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13213. return;
  13214. }
  13215. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13216. this._texture = this._getFromCache(this.url, this._noMipmap);
  13217. if (!this._texture) {
  13218. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13219. }
  13220. };
  13221. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13222. return this._textureMatrix;
  13223. };
  13224. return CubeTexture;
  13225. })(BABYLON.BaseTexture);
  13226. BABYLON.CubeTexture = CubeTexture;
  13227. })(BABYLON || (BABYLON = {}));
  13228. //# sourceMappingURL=babylon.cubeTexture.js.map
  13229. var BABYLON;
  13230. (function (BABYLON) {
  13231. var RenderTargetTexture = (function (_super) {
  13232. __extends(RenderTargetTexture, _super);
  13233. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13234. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13235. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13236. _super.call(this, null, scene, !generateMipMaps);
  13237. this.renderList = new Array();
  13238. this.renderParticles = true;
  13239. this.renderSprites = false;
  13240. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13241. this._currentRefreshId = -1;
  13242. this._refreshRate = 1;
  13243. this.name = name;
  13244. this.isRenderTarget = true;
  13245. this._size = size;
  13246. this._generateMipMaps = generateMipMaps;
  13247. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13248. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13249. // Rendering groups
  13250. this._renderingManager = new BABYLON.RenderingManager(scene);
  13251. }
  13252. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13253. this._currentRefreshId = -1;
  13254. };
  13255. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13256. get: function () {
  13257. return this._refreshRate;
  13258. },
  13259. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13260. set: function (value) {
  13261. this._refreshRate = value;
  13262. this.resetRefreshCounter();
  13263. },
  13264. enumerable: true,
  13265. configurable: true
  13266. });
  13267. RenderTargetTexture.prototype._shouldRender = function () {
  13268. if (this._currentRefreshId === -1) {
  13269. this._currentRefreshId = 1;
  13270. return true;
  13271. }
  13272. if (this.refreshRate === this._currentRefreshId) {
  13273. this._currentRefreshId = 1;
  13274. return true;
  13275. }
  13276. this._currentRefreshId++;
  13277. return false;
  13278. };
  13279. RenderTargetTexture.prototype.isReady = function () {
  13280. if (!this.getScene().renderTargetsEnabled) {
  13281. return false;
  13282. }
  13283. return _super.prototype.isReady.call(this);
  13284. };
  13285. RenderTargetTexture.prototype.getRenderSize = function () {
  13286. return this._size;
  13287. };
  13288. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13289. get: function () {
  13290. return true;
  13291. },
  13292. enumerable: true,
  13293. configurable: true
  13294. });
  13295. RenderTargetTexture.prototype.scale = function (ratio) {
  13296. var newSize = this._size * ratio;
  13297. this.resize(newSize, this._generateMipMaps);
  13298. };
  13299. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13300. this.releaseInternalTexture();
  13301. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13302. };
  13303. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13304. var scene = this.getScene();
  13305. var engine = scene.getEngine();
  13306. if (this._waitingRenderList) {
  13307. this.renderList = [];
  13308. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13309. var id = this._waitingRenderList[index];
  13310. this.renderList.push(scene.getMeshByID(id));
  13311. }
  13312. delete this._waitingRenderList;
  13313. }
  13314. if (this.renderList && this.renderList.length === 0) {
  13315. return;
  13316. }
  13317. // Bind
  13318. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13319. engine.bindFramebuffer(this._texture);
  13320. }
  13321. this._renderingManager.reset();
  13322. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13323. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13324. var mesh = currentRenderList[meshIndex];
  13325. if (mesh) {
  13326. if (!mesh.isReady()) {
  13327. // Reset _currentRefreshId
  13328. this.resetRefreshCounter();
  13329. continue;
  13330. }
  13331. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13332. mesh._activate(scene.getRenderId());
  13333. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13334. var subMesh = mesh.subMeshes[subIndex];
  13335. scene._activeIndices += subMesh.indexCount;
  13336. this._renderingManager.dispatch(subMesh);
  13337. }
  13338. }
  13339. }
  13340. }
  13341. if (this.onBeforeRender) {
  13342. this.onBeforeRender();
  13343. }
  13344. // Clear
  13345. if (this.onClear) {
  13346. this.onClear(engine);
  13347. }
  13348. else {
  13349. engine.clear(scene.clearColor, true, true);
  13350. }
  13351. if (!this._doNotChangeAspectRatio) {
  13352. scene.updateTransformMatrix(true);
  13353. }
  13354. // Render
  13355. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13356. if (useCameraPostProcess) {
  13357. scene.postProcessManager._finalizeFrame(false, this._texture);
  13358. }
  13359. if (!this._doNotChangeAspectRatio) {
  13360. scene.updateTransformMatrix(true);
  13361. }
  13362. if (this.onAfterRender) {
  13363. this.onAfterRender();
  13364. }
  13365. // Dump ?
  13366. if (dumpForDebug) {
  13367. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13368. }
  13369. // Unbind
  13370. engine.unBindFramebuffer(this._texture);
  13371. if (this.onAfterUnbind) {
  13372. this.onAfterUnbind();
  13373. }
  13374. };
  13375. RenderTargetTexture.prototype.clone = function () {
  13376. var textureSize = this.getSize();
  13377. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13378. // Base texture
  13379. newTexture.hasAlpha = this.hasAlpha;
  13380. newTexture.level = this.level;
  13381. // RenderTarget Texture
  13382. newTexture.coordinatesMode = this.coordinatesMode;
  13383. newTexture.renderList = this.renderList.slice(0);
  13384. return newTexture;
  13385. };
  13386. return RenderTargetTexture;
  13387. })(BABYLON.Texture);
  13388. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13389. })(BABYLON || (BABYLON = {}));
  13390. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13391. var BABYLON;
  13392. (function (BABYLON) {
  13393. var ProceduralTexture = (function (_super) {
  13394. __extends(ProceduralTexture, _super);
  13395. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13396. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13397. _super.call(this, null, scene, !generateMipMaps);
  13398. this._currentRefreshId = -1;
  13399. this._refreshRate = 1;
  13400. this._vertexDeclaration = [2];
  13401. this._vertexStrideSize = 2 * 4;
  13402. this._uniforms = new Array();
  13403. this._samplers = new Array();
  13404. this._textures = new Array();
  13405. this._floats = new Array();
  13406. this._floatsArrays = {};
  13407. this._colors3 = new Array();
  13408. this._colors4 = new Array();
  13409. this._vectors2 = new Array();
  13410. this._vectors3 = new Array();
  13411. this._matrices = new Array();
  13412. this._fallbackTextureUsed = false;
  13413. scene._proceduralTextures.push(this);
  13414. this.name = name;
  13415. this.isRenderTarget = true;
  13416. this._size = size;
  13417. this._generateMipMaps = generateMipMaps;
  13418. this.setFragment(fragment);
  13419. this._fallbackTexture = fallbackTexture;
  13420. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13421. // VBO
  13422. var vertices = [];
  13423. vertices.push(1, 1);
  13424. vertices.push(-1, 1);
  13425. vertices.push(-1, -1);
  13426. vertices.push(1, -1);
  13427. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13428. // Indices
  13429. var indices = [];
  13430. indices.push(0);
  13431. indices.push(1);
  13432. indices.push(2);
  13433. indices.push(0);
  13434. indices.push(2);
  13435. indices.push(3);
  13436. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13437. }
  13438. ProceduralTexture.prototype.reset = function () {
  13439. if (this._effect === undefined) {
  13440. return;
  13441. }
  13442. var engine = this.getScene().getEngine();
  13443. engine._releaseEffect(this._effect);
  13444. };
  13445. ProceduralTexture.prototype.isReady = function () {
  13446. var _this = this;
  13447. var engine = this.getScene().getEngine();
  13448. var shaders;
  13449. if (!this._fragment) {
  13450. return false;
  13451. }
  13452. if (this._fallbackTextureUsed) {
  13453. return true;
  13454. }
  13455. if (this._fragment.fragmentElement !== undefined) {
  13456. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13457. }
  13458. else {
  13459. shaders = { vertex: "procedural", fragment: this._fragment };
  13460. }
  13461. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13462. _this.releaseInternalTexture();
  13463. if (_this._fallbackTexture) {
  13464. _this._texture = _this._fallbackTexture._texture;
  13465. _this._texture.references++;
  13466. }
  13467. _this._fallbackTextureUsed = true;
  13468. });
  13469. return this._effect.isReady();
  13470. };
  13471. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13472. this._currentRefreshId = -1;
  13473. };
  13474. ProceduralTexture.prototype.setFragment = function (fragment) {
  13475. this._fragment = fragment;
  13476. };
  13477. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13478. get: function () {
  13479. return this._refreshRate;
  13480. },
  13481. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13482. set: function (value) {
  13483. this._refreshRate = value;
  13484. this.resetRefreshCounter();
  13485. },
  13486. enumerable: true,
  13487. configurable: true
  13488. });
  13489. ProceduralTexture.prototype._shouldRender = function () {
  13490. if (!this.isReady() || !this._texture) {
  13491. return false;
  13492. }
  13493. if (this._fallbackTextureUsed) {
  13494. return false;
  13495. }
  13496. if (this._currentRefreshId === -1) {
  13497. this._currentRefreshId = 1;
  13498. return true;
  13499. }
  13500. if (this.refreshRate === this._currentRefreshId) {
  13501. this._currentRefreshId = 1;
  13502. return true;
  13503. }
  13504. this._currentRefreshId++;
  13505. return false;
  13506. };
  13507. ProceduralTexture.prototype.getRenderSize = function () {
  13508. return this._size;
  13509. };
  13510. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13511. if (this._fallbackTextureUsed) {
  13512. return;
  13513. }
  13514. this.releaseInternalTexture();
  13515. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13516. };
  13517. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13518. if (this._uniforms.indexOf(uniformName) === -1) {
  13519. this._uniforms.push(uniformName);
  13520. }
  13521. };
  13522. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13523. if (this._samplers.indexOf(name) === -1) {
  13524. this._samplers.push(name);
  13525. }
  13526. this._textures[name] = texture;
  13527. return this;
  13528. };
  13529. ProceduralTexture.prototype.setFloat = function (name, value) {
  13530. this._checkUniform(name);
  13531. this._floats[name] = value;
  13532. return this;
  13533. };
  13534. ProceduralTexture.prototype.setFloats = function (name, value) {
  13535. this._checkUniform(name);
  13536. this._floatsArrays[name] = value;
  13537. return this;
  13538. };
  13539. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13540. this._checkUniform(name);
  13541. this._colors3[name] = value;
  13542. return this;
  13543. };
  13544. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13545. this._checkUniform(name);
  13546. this._colors4[name] = value;
  13547. return this;
  13548. };
  13549. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13550. this._checkUniform(name);
  13551. this._vectors2[name] = value;
  13552. return this;
  13553. };
  13554. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13555. this._checkUniform(name);
  13556. this._vectors3[name] = value;
  13557. return this;
  13558. };
  13559. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13560. this._checkUniform(name);
  13561. this._matrices[name] = value;
  13562. return this;
  13563. };
  13564. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13565. var scene = this.getScene();
  13566. var engine = scene.getEngine();
  13567. engine.bindFramebuffer(this._texture);
  13568. // Clear
  13569. engine.clear(scene.clearColor, true, true);
  13570. // Render
  13571. engine.enableEffect(this._effect);
  13572. engine.setState(false);
  13573. for (var name in this._textures) {
  13574. this._effect.setTexture(name, this._textures[name]);
  13575. }
  13576. for (name in this._floats) {
  13577. this._effect.setFloat(name, this._floats[name]);
  13578. }
  13579. for (name in this._floatsArrays) {
  13580. this._effect.setArray(name, this._floatsArrays[name]);
  13581. }
  13582. for (name in this._colors3) {
  13583. this._effect.setColor3(name, this._colors3[name]);
  13584. }
  13585. for (name in this._colors4) {
  13586. var color = this._colors4[name];
  13587. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13588. }
  13589. for (name in this._vectors2) {
  13590. this._effect.setVector2(name, this._vectors2[name]);
  13591. }
  13592. for (name in this._vectors3) {
  13593. this._effect.setVector3(name, this._vectors3[name]);
  13594. }
  13595. for (name in this._matrices) {
  13596. this._effect.setMatrix(name, this._matrices[name]);
  13597. }
  13598. // VBOs
  13599. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13600. // Draw order
  13601. engine.draw(true, 0, 6);
  13602. // Unbind
  13603. engine.unBindFramebuffer(this._texture);
  13604. };
  13605. ProceduralTexture.prototype.clone = function () {
  13606. var textureSize = this.getSize();
  13607. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13608. // Base texture
  13609. newTexture.hasAlpha = this.hasAlpha;
  13610. newTexture.level = this.level;
  13611. // RenderTarget Texture
  13612. newTexture.coordinatesMode = this.coordinatesMode;
  13613. return newTexture;
  13614. };
  13615. ProceduralTexture.prototype.dispose = function () {
  13616. var index = this.getScene()._proceduralTextures.indexOf(this);
  13617. if (index >= 0) {
  13618. this.getScene()._proceduralTextures.splice(index, 1);
  13619. }
  13620. _super.prototype.dispose.call(this);
  13621. };
  13622. return ProceduralTexture;
  13623. })(BABYLON.Texture);
  13624. BABYLON.ProceduralTexture = ProceduralTexture;
  13625. })(BABYLON || (BABYLON = {}));
  13626. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13627. var BABYLON;
  13628. (function (BABYLON) {
  13629. var WoodProceduralTexture = (function (_super) {
  13630. __extends(WoodProceduralTexture, _super);
  13631. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13632. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13633. this._ampScale = 100.0;
  13634. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13635. this.updateShaderUniforms();
  13636. this.refreshRate = 0;
  13637. }
  13638. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13639. this.setFloat("ampScale", this._ampScale);
  13640. this.setColor3("woodColor", this._woodColor);
  13641. };
  13642. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13643. get: function () {
  13644. return this._ampScale;
  13645. },
  13646. set: function (value) {
  13647. this._ampScale = value;
  13648. this.updateShaderUniforms();
  13649. },
  13650. enumerable: true,
  13651. configurable: true
  13652. });
  13653. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13654. get: function () {
  13655. return this._woodColor;
  13656. },
  13657. set: function (value) {
  13658. this._woodColor = value;
  13659. this.updateShaderUniforms();
  13660. },
  13661. enumerable: true,
  13662. configurable: true
  13663. });
  13664. return WoodProceduralTexture;
  13665. })(BABYLON.ProceduralTexture);
  13666. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13667. var FireProceduralTexture = (function (_super) {
  13668. __extends(FireProceduralTexture, _super);
  13669. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13670. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13671. this._time = 0.0;
  13672. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13673. this._autoGenerateTime = true;
  13674. this._alphaThreshold = 0.5;
  13675. this._fireColors = FireProceduralTexture.RedFireColors;
  13676. this.updateShaderUniforms();
  13677. this.refreshRate = 1;
  13678. }
  13679. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13680. this.setFloat("time", this._time);
  13681. this.setVector2("speed", this._speed);
  13682. this.setColor3("c1", this._fireColors[0]);
  13683. this.setColor3("c2", this._fireColors[1]);
  13684. this.setColor3("c3", this._fireColors[2]);
  13685. this.setColor3("c4", this._fireColors[3]);
  13686. this.setColor3("c5", this._fireColors[4]);
  13687. this.setColor3("c6", this._fireColors[5]);
  13688. this.setFloat("alphaThreshold", this._alphaThreshold);
  13689. };
  13690. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13691. if (this._autoGenerateTime) {
  13692. this._time += this.getScene().getAnimationRatio() * 0.03;
  13693. this.updateShaderUniforms();
  13694. }
  13695. _super.prototype.render.call(this, useCameraPostProcess);
  13696. };
  13697. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13698. get: function () {
  13699. return [
  13700. new BABYLON.Color3(0.5, 0.0, 1.0),
  13701. new BABYLON.Color3(0.9, 0.0, 1.0),
  13702. new BABYLON.Color3(0.2, 0.0, 1.0),
  13703. new BABYLON.Color3(1.0, 0.9, 1.0),
  13704. new BABYLON.Color3(0.1, 0.1, 1.0),
  13705. new BABYLON.Color3(0.9, 0.9, 1.0)
  13706. ];
  13707. },
  13708. enumerable: true,
  13709. configurable: true
  13710. });
  13711. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13712. get: function () {
  13713. return [
  13714. new BABYLON.Color3(0.5, 1.0, 0.0),
  13715. new BABYLON.Color3(0.5, 1.0, 0.0),
  13716. new BABYLON.Color3(0.3, 0.4, 0.0),
  13717. new BABYLON.Color3(0.5, 1.0, 0.0),
  13718. new BABYLON.Color3(0.2, 0.0, 0.0),
  13719. new BABYLON.Color3(0.5, 1.0, 0.0)
  13720. ];
  13721. },
  13722. enumerable: true,
  13723. configurable: true
  13724. });
  13725. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13726. get: function () {
  13727. return [
  13728. new BABYLON.Color3(0.5, 0.0, 0.1),
  13729. new BABYLON.Color3(0.9, 0.0, 0.0),
  13730. new BABYLON.Color3(0.2, 0.0, 0.0),
  13731. new BABYLON.Color3(1.0, 0.9, 0.0),
  13732. new BABYLON.Color3(0.1, 0.1, 0.1),
  13733. new BABYLON.Color3(0.9, 0.9, 0.9)
  13734. ];
  13735. },
  13736. enumerable: true,
  13737. configurable: true
  13738. });
  13739. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13740. get: function () {
  13741. return [
  13742. new BABYLON.Color3(0.1, 0.0, 0.5),
  13743. new BABYLON.Color3(0.0, 0.0, 0.5),
  13744. new BABYLON.Color3(0.1, 0.0, 0.2),
  13745. new BABYLON.Color3(0.0, 0.0, 1.0),
  13746. new BABYLON.Color3(0.1, 0.2, 0.3),
  13747. new BABYLON.Color3(0.0, 0.2, 0.9)
  13748. ];
  13749. },
  13750. enumerable: true,
  13751. configurable: true
  13752. });
  13753. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13754. get: function () {
  13755. return this._fireColors;
  13756. },
  13757. set: function (value) {
  13758. this._fireColors = value;
  13759. this.updateShaderUniforms();
  13760. },
  13761. enumerable: true,
  13762. configurable: true
  13763. });
  13764. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13765. get: function () {
  13766. return this._time;
  13767. },
  13768. set: function (value) {
  13769. this._time = value;
  13770. this.updateShaderUniforms();
  13771. },
  13772. enumerable: true,
  13773. configurable: true
  13774. });
  13775. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13776. get: function () {
  13777. return this._speed;
  13778. },
  13779. set: function (value) {
  13780. this._speed = value;
  13781. this.updateShaderUniforms();
  13782. },
  13783. enumerable: true,
  13784. configurable: true
  13785. });
  13786. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13787. get: function () {
  13788. return this._alphaThreshold;
  13789. },
  13790. set: function (value) {
  13791. this._alphaThreshold = value;
  13792. this.updateShaderUniforms();
  13793. },
  13794. enumerable: true,
  13795. configurable: true
  13796. });
  13797. return FireProceduralTexture;
  13798. })(BABYLON.ProceduralTexture);
  13799. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13800. var CloudProceduralTexture = (function (_super) {
  13801. __extends(CloudProceduralTexture, _super);
  13802. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13803. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13804. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13805. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13806. this.updateShaderUniforms();
  13807. this.refreshRate = 0;
  13808. }
  13809. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13810. this.setColor3("skyColor", this._skyColor);
  13811. this.setColor3("cloudColor", this._cloudColor);
  13812. };
  13813. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13814. get: function () {
  13815. return this._skyColor;
  13816. },
  13817. set: function (value) {
  13818. this._skyColor = value;
  13819. this.updateShaderUniforms();
  13820. },
  13821. enumerable: true,
  13822. configurable: true
  13823. });
  13824. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13825. get: function () {
  13826. return this._cloudColor;
  13827. },
  13828. set: function (value) {
  13829. this._cloudColor = value;
  13830. this.updateShaderUniforms();
  13831. },
  13832. enumerable: true,
  13833. configurable: true
  13834. });
  13835. return CloudProceduralTexture;
  13836. })(BABYLON.ProceduralTexture);
  13837. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13838. var GrassProceduralTexture = (function (_super) {
  13839. __extends(GrassProceduralTexture, _super);
  13840. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13841. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13842. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13843. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13844. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13845. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13846. this._grassColors = [
  13847. new BABYLON.Color3(0.29, 0.38, 0.02),
  13848. new BABYLON.Color3(0.36, 0.49, 0.09),
  13849. new BABYLON.Color3(0.51, 0.6, 0.28)
  13850. ];
  13851. this.updateShaderUniforms();
  13852. this.refreshRate = 0;
  13853. }
  13854. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13855. this.setColor3("herb1Color", this._grassColors[0]);
  13856. this.setColor3("herb2Color", this._grassColors[1]);
  13857. this.setColor3("herb3Color", this._grassColors[2]);
  13858. this.setColor3("groundColor", this._groundColor);
  13859. };
  13860. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13861. get: function () {
  13862. return this._grassColors;
  13863. },
  13864. set: function (value) {
  13865. this._grassColors = value;
  13866. this.updateShaderUniforms();
  13867. },
  13868. enumerable: true,
  13869. configurable: true
  13870. });
  13871. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13872. get: function () {
  13873. return this._groundColor;
  13874. },
  13875. set: function (value) {
  13876. this.groundColor = value;
  13877. this.updateShaderUniforms();
  13878. },
  13879. enumerable: true,
  13880. configurable: true
  13881. });
  13882. return GrassProceduralTexture;
  13883. })(BABYLON.ProceduralTexture);
  13884. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13885. var RoadProceduralTexture = (function (_super) {
  13886. __extends(RoadProceduralTexture, _super);
  13887. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13888. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13889. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13890. this.updateShaderUniforms();
  13891. this.refreshRate = 0;
  13892. }
  13893. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13894. this.setColor3("roadColor", this._roadColor);
  13895. };
  13896. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13897. get: function () {
  13898. return this._roadColor;
  13899. },
  13900. set: function (value) {
  13901. this._roadColor = value;
  13902. this.updateShaderUniforms();
  13903. },
  13904. enumerable: true,
  13905. configurable: true
  13906. });
  13907. return RoadProceduralTexture;
  13908. })(BABYLON.ProceduralTexture);
  13909. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13910. var BrickProceduralTexture = (function (_super) {
  13911. __extends(BrickProceduralTexture, _super);
  13912. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13913. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13914. this._numberOfBricksHeight = 15;
  13915. this._numberOfBricksWidth = 5;
  13916. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13917. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13918. this.updateShaderUniforms();
  13919. this.refreshRate = 0;
  13920. }
  13921. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13922. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13923. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13924. this.setColor3("brickColor", this._brickColor);
  13925. this.setColor3("jointColor", this._jointColor);
  13926. };
  13927. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13928. get: function () {
  13929. return this._numberOfBricksHeight;
  13930. },
  13931. set: function (value) {
  13932. this._numberOfBricksHeight = value;
  13933. this.updateShaderUniforms();
  13934. },
  13935. enumerable: true,
  13936. configurable: true
  13937. });
  13938. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13939. get: function () {
  13940. return this._numberOfBricksWidth;
  13941. },
  13942. set: function (value) {
  13943. this._numberOfBricksHeight = value;
  13944. this.updateShaderUniforms();
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13950. get: function () {
  13951. return this._jointColor;
  13952. },
  13953. set: function (value) {
  13954. this._jointColor = value;
  13955. this.updateShaderUniforms();
  13956. },
  13957. enumerable: true,
  13958. configurable: true
  13959. });
  13960. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13961. get: function () {
  13962. return this._brickColor;
  13963. },
  13964. set: function (value) {
  13965. this._brickColor = value;
  13966. this.updateShaderUniforms();
  13967. },
  13968. enumerable: true,
  13969. configurable: true
  13970. });
  13971. return BrickProceduralTexture;
  13972. })(BABYLON.ProceduralTexture);
  13973. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13974. var MarbleProceduralTexture = (function (_super) {
  13975. __extends(MarbleProceduralTexture, _super);
  13976. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13977. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13978. this._numberOfTilesHeight = 3;
  13979. this._numberOfTilesWidth = 3;
  13980. this._amplitude = 9.0;
  13981. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13982. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13983. this.updateShaderUniforms();
  13984. this.refreshRate = 0;
  13985. }
  13986. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13987. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13988. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13989. this.setFloat("amplitude", this._amplitude);
  13990. this.setColor3("marbleColor", this._marbleColor);
  13991. this.setColor3("jointColor", this._jointColor);
  13992. };
  13993. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13994. get: function () {
  13995. return this._numberOfTilesHeight;
  13996. },
  13997. set: function (value) {
  13998. this._numberOfTilesHeight = value;
  13999. this.updateShaderUniforms();
  14000. },
  14001. enumerable: true,
  14002. configurable: true
  14003. });
  14004. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  14005. get: function () {
  14006. return this._numberOfTilesWidth;
  14007. },
  14008. set: function (value) {
  14009. this._numberOfTilesWidth = value;
  14010. this.updateShaderUniforms();
  14011. },
  14012. enumerable: true,
  14013. configurable: true
  14014. });
  14015. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  14016. get: function () {
  14017. return this._jointColor;
  14018. },
  14019. set: function (value) {
  14020. this._jointColor = value;
  14021. this.updateShaderUniforms();
  14022. },
  14023. enumerable: true,
  14024. configurable: true
  14025. });
  14026. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  14027. get: function () {
  14028. return this._marbleColor;
  14029. },
  14030. set: function (value) {
  14031. this._marbleColor = value;
  14032. this.updateShaderUniforms();
  14033. },
  14034. enumerable: true,
  14035. configurable: true
  14036. });
  14037. return MarbleProceduralTexture;
  14038. })(BABYLON.ProceduralTexture);
  14039. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  14040. })(BABYLON || (BABYLON = {}));
  14041. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  14042. var BABYLON;
  14043. (function (BABYLON) {
  14044. var CustomProceduralTexture = (function (_super) {
  14045. __extends(CustomProceduralTexture, _super);
  14046. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  14047. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  14048. this._animate = true;
  14049. this._time = 0;
  14050. this._texturePath = texturePath;
  14051. //Try to load json
  14052. this.loadJson(texturePath);
  14053. this.refreshRate = 1;
  14054. }
  14055. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  14056. var _this = this;
  14057. var that = this;
  14058. function noConfigFile() {
  14059. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  14060. try {
  14061. that.setFragment(that._texturePath);
  14062. }
  14063. catch (ex) {
  14064. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  14065. }
  14066. }
  14067. var configFileUrl = jsonUrl + "/config.json";
  14068. var xhr = new XMLHttpRequest();
  14069. xhr.open("GET", configFileUrl, true);
  14070. xhr.addEventListener("load", function () {
  14071. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14072. try {
  14073. _this._config = JSON.parse(xhr.response);
  14074. _this.updateShaderUniforms();
  14075. _this.updateTextures();
  14076. _this.setFragment(_this._texturePath + "/custom");
  14077. _this._animate = _this._config.animate;
  14078. _this.refreshRate = _this._config.refreshrate;
  14079. }
  14080. catch (ex) {
  14081. noConfigFile();
  14082. }
  14083. }
  14084. else {
  14085. noConfigFile();
  14086. }
  14087. }, false);
  14088. xhr.addEventListener("error", function () {
  14089. noConfigFile();
  14090. }, false);
  14091. try {
  14092. xhr.send();
  14093. }
  14094. catch (ex) {
  14095. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  14096. }
  14097. };
  14098. CustomProceduralTexture.prototype.isReady = function () {
  14099. if (!_super.prototype.isReady.call(this)) {
  14100. return false;
  14101. }
  14102. for (var name in this._textures) {
  14103. var texture = this._textures[name];
  14104. if (!texture.isReady()) {
  14105. return false;
  14106. }
  14107. }
  14108. return true;
  14109. };
  14110. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  14111. if (this._animate) {
  14112. this._time += this.getScene().getAnimationRatio() * 0.03;
  14113. this.updateShaderUniforms();
  14114. }
  14115. _super.prototype.render.call(this, useCameraPostProcess);
  14116. };
  14117. CustomProceduralTexture.prototype.updateTextures = function () {
  14118. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  14119. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  14120. }
  14121. };
  14122. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  14123. if (this._config) {
  14124. for (var j = 0; j < this._config.uniforms.length; j++) {
  14125. var uniform = this._config.uniforms[j];
  14126. switch (uniform.type) {
  14127. case "float":
  14128. this.setFloat(uniform.name, uniform.value);
  14129. break;
  14130. case "color3":
  14131. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  14132. break;
  14133. case "color4":
  14134. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  14135. break;
  14136. case "vector2":
  14137. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  14138. break;
  14139. case "vector3":
  14140. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  14141. break;
  14142. }
  14143. }
  14144. }
  14145. this.setFloat("time", this._time);
  14146. };
  14147. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  14148. get: function () {
  14149. return this._animate;
  14150. },
  14151. set: function (value) {
  14152. this._animate = value;
  14153. },
  14154. enumerable: true,
  14155. configurable: true
  14156. });
  14157. return CustomProceduralTexture;
  14158. })(BABYLON.ProceduralTexture);
  14159. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  14160. })(BABYLON || (BABYLON = {}));
  14161. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  14162. var BABYLON;
  14163. (function (BABYLON) {
  14164. var MirrorTexture = (function (_super) {
  14165. __extends(MirrorTexture, _super);
  14166. function MirrorTexture(name, size, scene, generateMipMaps) {
  14167. var _this = this;
  14168. _super.call(this, name, size, scene, generateMipMaps, true);
  14169. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  14170. this._transformMatrix = BABYLON.Matrix.Zero();
  14171. this._mirrorMatrix = BABYLON.Matrix.Zero();
  14172. this.onBeforeRender = function () {
  14173. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  14174. _this._savedViewMatrix = scene.getViewMatrix();
  14175. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  14176. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  14177. scene.clipPlane = _this.mirrorPlane;
  14178. scene.getEngine().cullBackFaces = false;
  14179. };
  14180. this.onAfterRender = function () {
  14181. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  14182. scene.getEngine().cullBackFaces = true;
  14183. delete scene.clipPlane;
  14184. };
  14185. }
  14186. MirrorTexture.prototype.clone = function () {
  14187. var textureSize = this.getSize();
  14188. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14189. // Base texture
  14190. newTexture.hasAlpha = this.hasAlpha;
  14191. newTexture.level = this.level;
  14192. // Mirror Texture
  14193. newTexture.mirrorPlane = this.mirrorPlane.clone();
  14194. newTexture.renderList = this.renderList.slice(0);
  14195. return newTexture;
  14196. };
  14197. return MirrorTexture;
  14198. })(BABYLON.RenderTargetTexture);
  14199. BABYLON.MirrorTexture = MirrorTexture;
  14200. })(BABYLON || (BABYLON = {}));
  14201. //# sourceMappingURL=babylon.mirrorTexture.js.map
  14202. var BABYLON;
  14203. (function (BABYLON) {
  14204. var DynamicTexture = (function (_super) {
  14205. __extends(DynamicTexture, _super);
  14206. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  14207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14208. _super.call(this, null, scene, !generateMipMaps);
  14209. this.name = name;
  14210. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14211. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14212. this._generateMipMaps = generateMipMaps;
  14213. if (options.getContext) {
  14214. this._canvas = options;
  14215. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14216. }
  14217. else {
  14218. this._canvas = document.createElement("canvas");
  14219. if (options.width) {
  14220. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14221. }
  14222. else {
  14223. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14224. }
  14225. }
  14226. var textureSize = this.getSize();
  14227. this._canvas.width = textureSize.width;
  14228. this._canvas.height = textureSize.height;
  14229. this._context = this._canvas.getContext("2d");
  14230. }
  14231. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14232. get: function () {
  14233. return true;
  14234. },
  14235. enumerable: true,
  14236. configurable: true
  14237. });
  14238. DynamicTexture.prototype.scale = function (ratio) {
  14239. var textureSize = this.getSize();
  14240. textureSize.width *= ratio;
  14241. textureSize.height *= ratio;
  14242. this._canvas.width = textureSize.width;
  14243. this._canvas.height = textureSize.height;
  14244. this.releaseInternalTexture();
  14245. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14246. };
  14247. DynamicTexture.prototype.getContext = function () {
  14248. return this._context;
  14249. };
  14250. DynamicTexture.prototype.clear = function () {
  14251. var size = this.getSize();
  14252. this._context.fillRect(0, 0, size.width, size.height);
  14253. };
  14254. DynamicTexture.prototype.update = function (invertY) {
  14255. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14256. };
  14257. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14258. if (update === void 0) { update = true; }
  14259. var size = this.getSize();
  14260. if (clearColor) {
  14261. this._context.fillStyle = clearColor;
  14262. this._context.fillRect(0, 0, size.width, size.height);
  14263. }
  14264. this._context.font = font;
  14265. if (x === null) {
  14266. var textSize = this._context.measureText(text);
  14267. x = (size.width - textSize.width) / 2;
  14268. }
  14269. this._context.fillStyle = color;
  14270. this._context.fillText(text, x, y);
  14271. if (update) {
  14272. this.update(invertY);
  14273. }
  14274. };
  14275. DynamicTexture.prototype.clone = function () {
  14276. var textureSize = this.getSize();
  14277. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14278. // Base texture
  14279. newTexture.hasAlpha = this.hasAlpha;
  14280. newTexture.level = this.level;
  14281. // Dynamic Texture
  14282. newTexture.wrapU = this.wrapU;
  14283. newTexture.wrapV = this.wrapV;
  14284. return newTexture;
  14285. };
  14286. return DynamicTexture;
  14287. })(BABYLON.Texture);
  14288. BABYLON.DynamicTexture = DynamicTexture;
  14289. })(BABYLON || (BABYLON = {}));
  14290. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14291. var BABYLON;
  14292. (function (BABYLON) {
  14293. var VideoTexture = (function (_super) {
  14294. __extends(VideoTexture, _super);
  14295. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14296. var _this = this;
  14297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14298. _super.call(this, null, scene, !generateMipMaps, invertY);
  14299. this._autoLaunch = true;
  14300. this.name = name;
  14301. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14302. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14303. var requiredWidth = size.width || size;
  14304. var requiredHeight = size.height || size;
  14305. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14306. var textureSize = this.getSize();
  14307. this.video = document.createElement("video");
  14308. this.video.width = textureSize.width;
  14309. this.video.height = textureSize.height;
  14310. this.video.autoplay = false;
  14311. this.video.loop = true;
  14312. this.video.addEventListener("canplaythrough", function () {
  14313. if (_this._texture) {
  14314. _this._texture.isReady = true;
  14315. }
  14316. });
  14317. urls.forEach(function (url) {
  14318. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14319. var source = document.createElement("source");
  14320. source.src = url;
  14321. _this.video.appendChild(source);
  14322. });
  14323. this._lastUpdate = BABYLON.Tools.Now;
  14324. }
  14325. VideoTexture.prototype.update = function () {
  14326. if (this._autoLaunch) {
  14327. this._autoLaunch = false;
  14328. this.video.play();
  14329. }
  14330. var now = BABYLON.Tools.Now;
  14331. if (now - this._lastUpdate < 15) {
  14332. return false;
  14333. }
  14334. this._lastUpdate = now;
  14335. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14336. return true;
  14337. };
  14338. return VideoTexture;
  14339. })(BABYLON.Texture);
  14340. BABYLON.VideoTexture = VideoTexture;
  14341. })(BABYLON || (BABYLON = {}));
  14342. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14343. (function (BABYLON) {
  14344. var EffectFallbacks = (function () {
  14345. function EffectFallbacks() {
  14346. this._defines = {};
  14347. this._currentRank = 32;
  14348. this._maxRank = -1;
  14349. }
  14350. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14351. if (!this._defines[rank]) {
  14352. if (rank < this._currentRank) {
  14353. this._currentRank = rank;
  14354. }
  14355. if (rank > this._maxRank) {
  14356. this._maxRank = rank;
  14357. }
  14358. this._defines[rank] = new Array();
  14359. }
  14360. this._defines[rank].push(define);
  14361. };
  14362. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14363. get: function () {
  14364. return this._currentRank <= this._maxRank;
  14365. },
  14366. enumerable: true,
  14367. configurable: true
  14368. });
  14369. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14370. var currentFallbacks = this._defines[this._currentRank];
  14371. for (var index = 0; index < currentFallbacks.length; index++) {
  14372. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14373. }
  14374. this._currentRank++;
  14375. return currentDefines;
  14376. };
  14377. return EffectFallbacks;
  14378. })();
  14379. BABYLON.EffectFallbacks = EffectFallbacks;
  14380. var Effect = (function () {
  14381. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14382. var _this = this;
  14383. this._isReady = false;
  14384. this._compilationError = "";
  14385. this._valueCache = [];
  14386. this._engine = engine;
  14387. this.name = baseName;
  14388. this.defines = defines;
  14389. this._uniformsNames = uniformsNames.concat(samplers);
  14390. this._samplers = samplers;
  14391. this._attributesNames = attributesNames;
  14392. this.onError = onError;
  14393. this.onCompiled = onCompiled;
  14394. var vertexSource;
  14395. var fragmentSource;
  14396. if (baseName.vertexElement) {
  14397. vertexSource = document.getElementById(baseName.vertexElement);
  14398. if (!vertexSource) {
  14399. vertexSource = baseName.vertexElement;
  14400. }
  14401. }
  14402. else {
  14403. vertexSource = baseName.vertex || baseName;
  14404. }
  14405. if (baseName.fragmentElement) {
  14406. fragmentSource = document.getElementById(baseName.fragmentElement);
  14407. if (!fragmentSource) {
  14408. fragmentSource = baseName.fragmentElement;
  14409. }
  14410. }
  14411. else {
  14412. fragmentSource = baseName.fragment || baseName;
  14413. }
  14414. this._loadVertexShader(vertexSource, function (vertexCode) {
  14415. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14416. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14417. });
  14418. });
  14419. }
  14420. // Properties
  14421. Effect.prototype.isReady = function () {
  14422. return this._isReady;
  14423. };
  14424. Effect.prototype.getProgram = function () {
  14425. return this._program;
  14426. };
  14427. Effect.prototype.getAttributesNames = function () {
  14428. return this._attributesNames;
  14429. };
  14430. Effect.prototype.getAttributeLocation = function (index) {
  14431. return this._attributes[index];
  14432. };
  14433. Effect.prototype.getAttributeLocationByName = function (name) {
  14434. var index = this._attributesNames.indexOf(name);
  14435. return this._attributes[index];
  14436. };
  14437. Effect.prototype.getAttributesCount = function () {
  14438. return this._attributes.length;
  14439. };
  14440. Effect.prototype.getUniformIndex = function (uniformName) {
  14441. return this._uniformsNames.indexOf(uniformName);
  14442. };
  14443. Effect.prototype.getUniform = function (uniformName) {
  14444. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14445. };
  14446. Effect.prototype.getSamplers = function () {
  14447. return this._samplers;
  14448. };
  14449. Effect.prototype.getCompilationError = function () {
  14450. return this._compilationError;
  14451. };
  14452. // Methods
  14453. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14454. // DOM element ?
  14455. if (vertex instanceof HTMLElement) {
  14456. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14457. callback(vertexCode);
  14458. return;
  14459. }
  14460. // Is in local store ?
  14461. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14462. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14463. return;
  14464. }
  14465. var vertexShaderUrl;
  14466. if (vertex[0] === ".") {
  14467. vertexShaderUrl = vertex;
  14468. }
  14469. else {
  14470. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14471. }
  14472. // Vertex shader
  14473. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14474. };
  14475. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14476. // DOM element ?
  14477. if (fragment instanceof HTMLElement) {
  14478. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14479. callback(fragmentCode);
  14480. return;
  14481. }
  14482. // Is in local store ?
  14483. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14484. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14485. return;
  14486. }
  14487. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14488. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14489. return;
  14490. }
  14491. var fragmentShaderUrl;
  14492. if (fragment[0] === ".") {
  14493. fragmentShaderUrl = fragment;
  14494. }
  14495. else {
  14496. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14497. }
  14498. // Fragment shader
  14499. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14500. };
  14501. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14502. try {
  14503. var engine = this._engine;
  14504. if (!engine.getCaps().highPrecisionShaderSupported) {
  14505. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14506. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14507. }
  14508. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14509. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14510. this._attributes = engine.getAttributes(this._program, attributesNames);
  14511. for (var index = 0; index < this._samplers.length; index++) {
  14512. var sampler = this.getUniform(this._samplers[index]);
  14513. if (sampler == null) {
  14514. this._samplers.splice(index, 1);
  14515. index--;
  14516. }
  14517. }
  14518. engine.bindSamplers(this);
  14519. this._isReady = true;
  14520. if (this.onCompiled) {
  14521. this.onCompiled(this);
  14522. }
  14523. }
  14524. catch (e) {
  14525. // Is it a problem with precision?
  14526. if (e.message.indexOf("highp") !== -1) {
  14527. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14528. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14529. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14530. return;
  14531. }
  14532. // Let's go through fallbacks then
  14533. if (fallbacks && fallbacks.isMoreFallbacks) {
  14534. defines = fallbacks.reduce(defines);
  14535. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14536. }
  14537. else {
  14538. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14539. BABYLON.Tools.Error("Defines: " + defines);
  14540. BABYLON.Tools.Error("Error: " + e.message);
  14541. this._compilationError = e.message;
  14542. if (this.onError) {
  14543. this.onError(this, this._compilationError);
  14544. }
  14545. }
  14546. }
  14547. };
  14548. Effect.prototype._bindTexture = function (channel, texture) {
  14549. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14550. };
  14551. Effect.prototype.setTexture = function (channel, texture) {
  14552. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14553. };
  14554. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14555. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14556. };
  14557. //public _cacheMatrix(uniformName, matrix) {
  14558. // if (!this._valueCache[uniformName]) {
  14559. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14560. // }
  14561. // for (var index = 0; index < 16; index++) {
  14562. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14563. // }
  14564. //};
  14565. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14566. if (!this._valueCache[uniformName]) {
  14567. this._valueCache[uniformName] = [x, y];
  14568. return;
  14569. }
  14570. this._valueCache[uniformName][0] = x;
  14571. this._valueCache[uniformName][1] = y;
  14572. };
  14573. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14574. if (!this._valueCache[uniformName]) {
  14575. this._valueCache[uniformName] = [x, y, z];
  14576. return;
  14577. }
  14578. this._valueCache[uniformName][0] = x;
  14579. this._valueCache[uniformName][1] = y;
  14580. this._valueCache[uniformName][2] = z;
  14581. };
  14582. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14583. if (!this._valueCache[uniformName]) {
  14584. this._valueCache[uniformName] = [x, y, z, w];
  14585. return;
  14586. }
  14587. this._valueCache[uniformName][0] = x;
  14588. this._valueCache[uniformName][1] = y;
  14589. this._valueCache[uniformName][2] = z;
  14590. this._valueCache[uniformName][3] = w;
  14591. };
  14592. Effect.prototype.setArray = function (uniformName, array) {
  14593. this._engine.setArray(this.getUniform(uniformName), array);
  14594. return this;
  14595. };
  14596. Effect.prototype.setArray2 = function (uniformName, array) {
  14597. this._engine.setArray2(this.getUniform(uniformName), array);
  14598. return this;
  14599. };
  14600. Effect.prototype.setArray3 = function (uniformName, array) {
  14601. this._engine.setArray3(this.getUniform(uniformName), array);
  14602. return this;
  14603. };
  14604. Effect.prototype.setArray4 = function (uniformName, array) {
  14605. this._engine.setArray4(this.getUniform(uniformName), array);
  14606. return this;
  14607. };
  14608. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14609. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14610. return this;
  14611. };
  14612. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14613. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14614. // return;
  14615. //this._cacheMatrix(uniformName, matrix);
  14616. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14617. return this;
  14618. };
  14619. Effect.prototype.setFloat = function (uniformName, value) {
  14620. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14621. return this;
  14622. this._valueCache[uniformName] = value;
  14623. this._engine.setFloat(this.getUniform(uniformName), value);
  14624. return this;
  14625. };
  14626. Effect.prototype.setBool = function (uniformName, bool) {
  14627. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14628. return this;
  14629. this._valueCache[uniformName] = bool;
  14630. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14631. return this;
  14632. };
  14633. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14634. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14635. return this;
  14636. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14637. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14638. return this;
  14639. };
  14640. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14641. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14642. return this;
  14643. this._cacheFloat2(uniformName, x, y);
  14644. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14645. return this;
  14646. };
  14647. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14648. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14649. return this;
  14650. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14651. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14652. return this;
  14653. };
  14654. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14655. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14656. return this;
  14657. this._cacheFloat3(uniformName, x, y, z);
  14658. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14659. return this;
  14660. };
  14661. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14662. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14663. return this;
  14664. this._cacheFloat4(uniformName, x, y, z, w);
  14665. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14666. return this;
  14667. };
  14668. Effect.prototype.setColor3 = function (uniformName, color3) {
  14669. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14670. return this;
  14671. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14672. this._engine.setColor3(this.getUniform(uniformName), color3);
  14673. return this;
  14674. };
  14675. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14676. 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)
  14677. return this;
  14678. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14679. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14680. return this;
  14681. };
  14682. // Statics
  14683. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\nvec4 leftFrag = texture2D(leftSampler, vUV);\nleftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\nvec4 rightFrag = texture2D(textureSampler, vUV);\nrightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\ngl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  14684. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\nfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\ngl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  14685. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\nfloat weights[7];\nweights[0] = 0.05;\nweights[1] = 0.1;\nweights[2] = 0.2;\nweights[3] = 0.3;\nweights[4] = 0.2;\nweights[5] = 0.1;\nweights[6] = 0.05;\n\nvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\nvec2 texelStep = texelSize * direction * blurWidth;\nvec2 start = vUV - 3.0 * texelStep;\n\nvec4 baseColor = vec4(0., 0., 0., 0.);\nvec2 texelOffset = vec2(0., 0.);\n\nfor (int i = 0; i < 7; i++)\n{\nbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\ntexelOffset += texelStep;\n}\n\ngl_FragColor = baseColor;\n}",
  14686. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\nfloat brickW = 1.0 / numberOfBricksWidth;\nfloat brickH = 1.0 / numberOfBricksHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.05;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\nif (brickColorSwitch == 0.0)\ncolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\nelse if (brickColorSwitch == 2.0)\ncolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n}\n\ngl_FragColor = vec4(color, 1.0);\n}",
  14687. chromaticAberrationPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvoid main(void)\n{\nvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;\nfloat radius = sqrt(radius2);\n\nvec4 original = texture2D(textureSampler, vUV);\n\nif (chromatic_aberration > 0.0) {\nvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\nfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\nfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\n\nvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\noriginal.r = texture2D(textureSampler, ref_coords_r).r;\noriginal.g = texture2D(textureSampler, ref_coords_g).g;\noriginal.b = texture2D(textureSampler, ref_coords_b).b;\n}\n\ngl_FragColor = original;\n}",
  14688. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\n\nvec2 p = vUV * 12.0;\nvec3 c = mix(skyColor, cloudColor, fbm(p));\ngl_FragColor = vec4(c, 1);\n\n}",
  14689. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14690. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14691. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\nfloat sliceSize = 1.0 / width; // space of 1 slice\nfloat slicePixelSize = sliceSize / width; // space of 1 pixel\nfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\nfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\nfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\nfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\nfloat s0 = xOffset + (zSlice0 * sliceSize);\nfloat s1 = xOffset + (zSlice1 * sliceSize);\nvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\nvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\nfloat zOffset = mod(uv.z * width, 1.0);\nvec4 result = mix(slice0Color, slice1Color, zOffset);\nreturn result;\n}\n\nvoid main(void)\n{\nvec4 screen_color = texture2D(textureSampler, vUV);\ngl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  14692. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\nvec2 onePixel = vec2(1.0, 1.0) / screenSize;\nvec4 colorSum =\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\n\nif (kernelWeight <= 0.0) {\nkernelWeight = 1.0;\n}\n\ngl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  14693. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform vec3 shadowsInfo0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform vec3 shadowsInfo1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform vec3 shadowsInfo2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn vPositionUVW;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\nreturn dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\nif (depth.z > shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat visibility = 1.;\n\nvec2 poissonDisk[4];\npoissonDisk[0] = vec2(-0.94201624, -0.39906216);\npoissonDisk[1] = vec2(0.94558609, -0.76890725);\npoissonDisk[2] = vec2(-0.094184101, -0.92938870);\npoissonDisk[3] = vec2(0.34495938, 0.29387760);\n\nfloat biasedDepth = depth.z - bias;\n\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\n\nreturn visibility;\n}\n\nfloat linstep(float low, float high, float v) {\nreturn clamp((v - low) / (high - low), 0.0, 1.0);\n}\n\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\n{\nfloat p = smoothstep(compare - bias, compare, moments.x);\nfloat variance = max(moments.y - moments.x * moments.x, 0.02);\nfloat d = compare - moments.x;\nfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n\nreturn clamp(max(p, p_max), 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\nvec3 dp1 = dFdx(p);\nvec3 dp2 = dFdy(p);\nvec2 duv1 = dFdx(uv);\nvec2 duv2 = dFdy(uv);\n\nvec3 dp2perp = cross(dp2, normal);\nvec3 dp1perp = cross(normal, dp1);\nvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\nvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\nfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\nreturn mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\nvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\nmap = map * 255. / 127. - 128. / 127.;\nmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\nreturn normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nstruct lightingInfo\n{\nvec3 diffuse;\nvec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 lightVectorW;\nfloat attenuation = 1.0;\nif (lightData.w == 0.)\n{\nvec3 direction = lightData.xyz - vPositionW;\n\nattenuation = max(0., 1.0 - length(direction) / range);\nlightVectorW = normalize(direction);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, max(1., vSpecularColor.a));\n\nresult.diffuse = ndl * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * attenuation;\n\nreturn result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 direction = lightData.xyz - vPositionW;\nvec3 lightVectorW = normalize(direction);\nfloat attenuation = max(0., 1.0 - length(direction) / range);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * spotAtten * attenuation;\n\nreturn result;\n}\n\nresult.diffuse = vec3(0.);\nresult.specular = vec3(0.);\n\nreturn result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\nlightingInfo result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = mix(groundColor, diffuseColor, ndl);\nresult.specular = specComp * specularColor;\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\nalpha *= baseColor.a;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n#ifdef NORMAL\nvec3 normalW = normalize(vNormalW);\n#else\nvec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\nnormalW = perturbNormal(viewDirectionW);\n#endif\n\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\nlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n#ifdef SHADOWPCF0\nshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n#ifdef SHADOWPCF1\nshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n#ifdef SHADOWPCF2\nshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n#ifdef SHADOWPCF3\nshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\nalpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14694. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\nmat4 finalWorld;\n\n#ifdef REFLECTION\nvPositionUVW = position;\n#endif\n\n#ifdef INSTANCES\nfinalWorld = mat4(world0, world1, world2, world3);\n#else\nfinalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = finalWorld * (m0 + m1 + m2);\n#endif\n\n#endif\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\n\n#ifdef NORMAL\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize = pointSize;\n#endif\n}",
  14695. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\nfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\ngl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  14696. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14697. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\n\nvoid main(void)\n{\nvec4 colorDepth = vec4(0.0);\n\nfor (int x = -OFFSET; x <= OFFSET; x++)\nfor (int y = -OFFSET; y <= OFFSET; y++)\ncolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\ngl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  14698. depthOfFieldPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform float maxZ;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform float focus_depth;\nuniform float aperture;\nuniform float edge_blur;\nuniform bool highlights;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\nvec2 getDistortedCoords(vec2 coords) {\n\nif (distortion == 0.0) { return coords; }\n\nvec2 direction = 1.0 * normalize(centered_screen_pos);\nvec2 dist_coords = vec2(0.5, 0.5);\ndist_coords.x = 0.5 + direction.x * radius2 * 1.0;\ndist_coords.y = 0.5 + direction.y * radius2 * 1.0;\nfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\ndist_coords = mix(coords, dist_coords, dist_amount);\n\nreturn dist_coords;\n}\n\nvec4 getBlurColor(vec2 coords, float size) {\n\nvec4 col = texture2D(textureSampler, coords);\nif (size == 0.0) { return col; }\n\nfloat blur_level = min(3.0, ceil(size / 1.0));\n\nfloat w = (size / screen_width);\nfloat h = (size / screen_height);\nfloat total_weight = 1.0;\n\ncol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\ncol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\ncol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\ncol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\ncol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\ncol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\ncol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\ncol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\ncol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\ncol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\ntotal_weight += 8.18;\n\nif (blur_level > 1.0) {\ncol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\ncol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\ncol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\ncol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\ncol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\ncol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\ncol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\ncol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\ncol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\ncol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\ntotal_weight += 5.96;\n}\n\nif (blur_level > 2.0) {\ncol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\ncol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\ncol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\ncol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\ncol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\ncol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\ncol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\ncol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\ncol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\ntotal_weight += 2.97;\n}\n\ncol /= total_weight; // scales color according to weights\ncol.a = 1.0;\n\n\nreturn col;\n}\n\nvec2 rand(vec2 co)\n{\nfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\nfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\nreturn clamp(vec2(noise1, noise2), 0.0, 1.0);\n}\n\nvoid main(void)\n{\n\ncentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\nradius = sqrt(radius2);\n\nvec4 final_color;\nvec2 distorted_coords = getDistortedCoords(vUV);\nvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\nfloat dof_blur_amount = 0.0;\nfloat depth_bias = 0.0; // positive if the pixel is further than focus depth; negative if closer\nif (focus_depth != -1.0) {\nvec4 depth_sample = texture2D(depthSampler, distorted_coords);\nfloat depth = depth_sample.r;\ndepth_bias = depth - focus_depth;\n\nif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\nelse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\n\nif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n}\n\nfloat edge_blur_amount = 0.0;\nif (edge_blur > 0.0) {\nedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\n}\n\nfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\n\nif (blur_amount == 0.0) {\ngl_FragColor = texture2D(textureSampler, distorted_coords);\n}\nelse {\n\ngl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\n\nif (depth_bias > 0.0 && highlights) {\ngl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\n}\n\nif (blur_noise) {\nvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\nvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\ngl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\n}\n}\n\nif (grain_amount > 0.0) {\nvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\ngl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\n}\n}",
  14699. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(passSampler, vUV);\n}",
  14700. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\nvec3 baseColor = texture2D(textureSampler, vUV).rgb;\nvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\ngl_FragColor = vec4(updatedColor, 1.0);\n}",
  14701. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\nvec2 p = vUV * 8.0;\nfloat q = fbm(p - time * 0.1);\nvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\nvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\nvec3 color = c * cos(shift * vUV.y);\nfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\ngl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  14702. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\nvec2 localTexelSize = texelSize;\nvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\nvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\nvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\nvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\nvec4 rgbM = texture2D(textureSampler, vUV);\nvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM = dot(rgbM, luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\nvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\nfloat dirReduce = max(\n(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\n\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\ndir * rcpDirMin)) * localTexelSize;\n\nvec4 rgbA = 0.5 * (\ntexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\ntexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\nvec4 rgbB = rgbA * 0.5 + 0.25 * (\ntexture2D(textureSampler, vUV + dir * -0.5) +\ntexture2D(textureSampler, vUV + dir * 0.5));\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\ngl_FragColor = rgbA;\n}\nelse {\ngl_FragColor = rgbB;\n}\n}",
  14703. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\ncolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\ncolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\ncolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\ngl_FragColor = vec4(color, 1.0);\n}",
  14704. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14705. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14706. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\nreturn dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv));\n\nif (depth.z > shadow)\n{\nreturn 0.;\n}\nreturn 1.;\n}\n\nfloat ChebychevInequality(vec2 moments, float t)\n{\nif (t <= moments.x)\n{\nreturn 1.0;\n}\n\nfloat variance = moments.y - (moments.x * moments.x);\nvariance = max(variance, 0.);\n\nfloat d = t - moments.x;\nreturn variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW;\nif (lightData.w == 0.)\n{\nlightVectorW = normalize(lightData.xyz - vPositionW);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\nresult[0] = ndl * diffuseColor.rgb;\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = ndl * spotAtten * diffuseColor.rgb;\nresult[1] = specComp * specularColor * spotAtten;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nresult[0] = vec3(0.);\nresult[1] = vec3(0.);\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\nmat3 result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\nvec3 normalW = normalize(vNormalW);\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\nmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14707. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn position;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\nmat4 finalWorld;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = world * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = world * (m0 + m1 + m2);\n#endif\n\n#else\nfinalWorld = world;\n#endif\n\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef REFLECTION\nvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n}",
  14708. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14709. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  14710. lensHighlightsPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float gain;\nuniform float threshold;\nuniform bool pentagon;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight = color;\nfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\nfloat lum_threshold;\nif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\nelse { lum_threshold = 0.5 + 0.44 * threshold; }\n\nluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\n\nhighlight *= luminance * gain;\nhighlight.a = 1.0;\n\nreturn highlight;\n}\n\nvoid main(void)\n{\nvec4 original = texture2D(textureSampler, vUV);\n\nif (gain == -1.0) {\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nreturn;\n}\n\nfloat w = 2.0 / screen_width;\nfloat h = 2.0 / screen_height;\n\nfloat weight = 1.0;\n\nvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\n\nif (pentagon) {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\n}\nelse {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\n}\n\nblurred /= 39.0;\n\ngl_FragColor = blurred;\n\n}",
  14711. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\nfloat val = 0.0;\nfloat freq = 1.0;\nfor (int i = 0; i < 4; i++)\n{\nval += abs(noise(P*freq) / freq);\nfreq *= 2.07;\n}\nreturn val;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\nvec3 col;\nx = 0.5*(x + 1.);\nx = sqrt(x);\nx = sqrt(x);\nx = sqrt(x);\ncol = vec3(.2 + .75*x);\ncol.b *= 0.95;\nreturn col;\n}\n\nvoid main()\n{\nfloat brickW = 1.0 / numberOfTilesWidth;\nfloat brickH = 1.0 / numberOfTilesHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.01;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\nt += amplitude * turbulence(brickvUV.xy);\nt = sin(t);\ncolor = marble_color(t);\n}\n\ngl_FragColor = vec4(color, 0.0);\n}",
  14712. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\nvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\nfloat rSq = theta.x * theta.x + theta.y * theta.y;\nvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\nreturn LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\nvec2 tc = HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nelse{\ngl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n}\n}",
  14713. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\ngl_FragColor = color;\n}",
  14714. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\nvec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14715. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\ngl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  14716. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\nvec3 viewPos = (view * vec4(position, 1.0)).xyz;\nvec3 cornerPos;\nfloat size = options.y;\nfloat angle = options.x;\nvec2 offset = options.zw;\n\ncornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\nvUV = offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos = invView * vec4(viewPos, 1.0);\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  14717. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(textureSampler, vUV);\n}",
  14718. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14719. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\nvPosition = position;\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14720. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\nfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\nvec2 uv = vUV - vec2(0.5);\nvec2 offset = uv * depth * ref;\nvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\ngl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  14721. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\nvec3 color = roadColor * ratioy;\ngl_FragColor = vec4(color, 1.0);\n}",
  14722. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\nconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\nconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\nvec4 res = fract(depth * bit_shift);\nres -= res.xxyz * bit_mask;\n\nreturn res;\n}\n\nvec2 packHalf(float depth)\n{\nconst vec2 bitOffset = vec2(1.0 / 255., 0.);\nvec2 color = vec2(depth, fract(depth * 255.));\n\nreturn color - (color.yy * bitOffset);\n}\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\nfloat depth = vPosition.z / vPosition.w;\ndepth = depth * 0.5 + 0.5;\n\n#ifdef VSM\nfloat moment1 = depth;\nfloat moment2 = moment1 * moment1;\n\ngl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\ngl_FragColor = pack(depth);\n#endif\n}",
  14723. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\nvPosition = viewProjection * finalWorld * vec4(position, 1.0);\ngl_Position = vPosition;\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14724. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\nif (alphaTest)\n{\nif (baseColor.a < 0.95)\ndiscard;\n}\n\nbaseColor *= vColor;\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\nbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = baseColor;\n}",
  14725. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) {\nvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz;\nvec2 cornerPos;\n\nfloat angle = position.w;\nvec2 size = vec2(options.x, options.y);\nvec2 offset = options.zw;\nvec2 uvScale = textureInfos.xy;\n\ncornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\n\nvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\nvUV = (uvOffset + cellInfo.zw) * uvScale;\n\n#ifdef FOG\nfFogDistance = viewPos.z;\n#endif\n}",
  14726. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.001);\nconst vec2 offset2 = vec2(0.001, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\nfloat depth1 = texture2D(textureSampler, coords + offset1).r;\nfloat depth2 = texture2D(textureSampler, coords + offset2).r;\n\nvec3 p1 = vec3(offset1, depth1 - depth);\nvec3 p2 = vec3(offset2, depth2 - depth);\n\nvec3 normal = cross(p1, p2);\nnormal.z = -normal.z;\n\nreturn normalize(normal);\n}\n\nvoid main(void)\n{\nconst float base = 0.2;\n\nvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\nfloat depth = texture2D(textureSampler, vUV).r;\nvec3 position = vec3(vUV, depth);\nvec3 normal = normalFromDepth(depth, vUV);\nfloat radiusDepth = radius / depth;\nfloat occlusion = 0.0;\n\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\n\nfor (int i = 0; i < SAMPLES; i++)\n{\nray = radiusDepth * reflect(sampleSphere[i], random);\nhemiRay = position + sign(dot(ray, normal)) * ray;\n\nocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\ndifference = depth - occlusionDepth;\n\nocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n}\n\nfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\nfloat result = clamp(ao + base, 0.0, 1.0);\ngl_FragColor.r = result;\ngl_FragColor.g = result;\ngl_FragColor.b = result;\ngl_FragColor.a = 1.0;\n}",
  14727. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\ngl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  14728. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\nvec2 tc = vUV;\nvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\ndeltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\nfloat illuminationDecay = 1.0;\n\nvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\nfor(int i=0; i < NUM_SAMPLES; i++) {\ntc -= deltaTexCoord;\nvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\nsample *= illuminationDecay * weight;\ncolor += sample;\nilluminationDecay *= decay;\n}\n\nvec4 realColor = texture2D(textureSampler, vUV);\ngl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  14729. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\nif (diffuseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef OPACITY\nvec4 opacityColor = texture2D(opacitySampler, vUV);\nfloat alpha = 1.0;\n\n#ifdef OPACITYRGB\nopacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n#else\nalpha *= opacityColor.a * opacityLevel;\n#endif\n\n#if defined(BASIC_RENDER)\ngl_FragColor = vec4(diffuseColor.rgb, alpha);\n#else\ngl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n#endif\n\ngl_FragColor.a = alpha;\n#else\n#ifndef BASIC_RENDER\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#else\ngl_FragColor = diffuseColor;\n#endif\n#endif\n\n}",
  14730. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\nvec3 wood = woodColor * ratioy;\ngl_FragColor = vec4(wood, 1.0);\n}",
  14731. };
  14732. return Effect;
  14733. })();
  14734. BABYLON.Effect = Effect;
  14735. })(BABYLON || (BABYLON = {}));
  14736. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14737. (function (BABYLON) {
  14738. var Material = (function () {
  14739. function Material(name, scene, doNotAdd) {
  14740. this.name = name;
  14741. this.checkReadyOnEveryCall = true;
  14742. this.checkReadyOnlyOnce = false;
  14743. this.state = "";
  14744. this.alpha = 1.0;
  14745. this.backFaceCulling = true;
  14746. this._wasPreviouslyReady = false;
  14747. this._fillMode = Material.TriangleFillMode;
  14748. this.pointSize = 1.0;
  14749. this.zOffset = 0;
  14750. this.id = name;
  14751. this._scene = scene;
  14752. if (!doNotAdd) {
  14753. scene.materials.push(this);
  14754. }
  14755. }
  14756. Object.defineProperty(Material, "TriangleFillMode", {
  14757. get: function () {
  14758. return Material._TriangleFillMode;
  14759. },
  14760. enumerable: true,
  14761. configurable: true
  14762. });
  14763. Object.defineProperty(Material, "WireFrameFillMode", {
  14764. get: function () {
  14765. return Material._WireFrameFillMode;
  14766. },
  14767. enumerable: true,
  14768. configurable: true
  14769. });
  14770. Object.defineProperty(Material, "PointFillMode", {
  14771. get: function () {
  14772. return Material._PointFillMode;
  14773. },
  14774. enumerable: true,
  14775. configurable: true
  14776. });
  14777. Object.defineProperty(Material.prototype, "wireframe", {
  14778. get: function () {
  14779. return this._fillMode === Material.WireFrameFillMode;
  14780. },
  14781. set: function (value) {
  14782. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14783. },
  14784. enumerable: true,
  14785. configurable: true
  14786. });
  14787. Object.defineProperty(Material.prototype, "pointsCloud", {
  14788. get: function () {
  14789. return this._fillMode === Material.PointFillMode;
  14790. },
  14791. set: function (value) {
  14792. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14793. },
  14794. enumerable: true,
  14795. configurable: true
  14796. });
  14797. Object.defineProperty(Material.prototype, "fillMode", {
  14798. get: function () {
  14799. return this._fillMode;
  14800. },
  14801. set: function (value) {
  14802. this._fillMode = value;
  14803. },
  14804. enumerable: true,
  14805. configurable: true
  14806. });
  14807. Material.prototype.isReady = function (mesh, useInstances) {
  14808. return true;
  14809. };
  14810. Material.prototype.getEffect = function () {
  14811. return this._effect;
  14812. };
  14813. Material.prototype.getScene = function () {
  14814. return this._scene;
  14815. };
  14816. Material.prototype.needAlphaBlending = function () {
  14817. return (this.alpha < 1.0);
  14818. };
  14819. Material.prototype.needAlphaTesting = function () {
  14820. return false;
  14821. };
  14822. Material.prototype.getAlphaTestTexture = function () {
  14823. return null;
  14824. };
  14825. Material.prototype.trackCreation = function (onCompiled, onError) {
  14826. };
  14827. Material.prototype._preBind = function () {
  14828. var engine = this._scene.getEngine();
  14829. engine.enableEffect(this._effect);
  14830. engine.setState(this.backFaceCulling, this.zOffset);
  14831. };
  14832. Material.prototype.bind = function (world, mesh) {
  14833. this._scene._cachedMaterial = this;
  14834. if (this.onBind) {
  14835. this.onBind(this, mesh);
  14836. }
  14837. };
  14838. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14839. };
  14840. Material.prototype.unbind = function () {
  14841. };
  14842. Material.prototype.dispose = function (forceDisposeEffect) {
  14843. // Remove from scene
  14844. var index = this._scene.materials.indexOf(this);
  14845. this._scene.materials.splice(index, 1);
  14846. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14847. if (forceDisposeEffect && this._effect) {
  14848. this._scene.getEngine()._releaseEffect(this._effect);
  14849. this._effect = null;
  14850. }
  14851. // Callback
  14852. if (this.onDispose) {
  14853. this.onDispose();
  14854. }
  14855. };
  14856. Material._TriangleFillMode = 0;
  14857. Material._WireFrameFillMode = 1;
  14858. Material._PointFillMode = 2;
  14859. return Material;
  14860. })();
  14861. BABYLON.Material = Material;
  14862. })(BABYLON || (BABYLON = {}));
  14863. //# sourceMappingURL=babylon.material.js.map
  14864. var BABYLON;
  14865. (function (BABYLON) {
  14866. var maxSimultaneousLights = 4;
  14867. var FresnelParameters = (function () {
  14868. function FresnelParameters() {
  14869. this.isEnabled = true;
  14870. this.leftColor = BABYLON.Color3.White();
  14871. this.rightColor = BABYLON.Color3.Black();
  14872. this.bias = 0;
  14873. this.power = 1;
  14874. }
  14875. return FresnelParameters;
  14876. })();
  14877. BABYLON.FresnelParameters = FresnelParameters;
  14878. var StandardMaterial = (function (_super) {
  14879. __extends(StandardMaterial, _super);
  14880. function StandardMaterial(name, scene) {
  14881. var _this = this;
  14882. _super.call(this, name, scene);
  14883. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14884. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14885. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14886. this.specularPower = 64;
  14887. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14888. this.useAlphaFromDiffuseTexture = false;
  14889. this.useSpecularOverAlpha = true;
  14890. this.fogEnabled = true;
  14891. this._cachedDefines = null;
  14892. this._renderTargets = new BABYLON.SmartArray(16);
  14893. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14894. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14895. this._scaledDiffuse = new BABYLON.Color3();
  14896. this._scaledSpecular = new BABYLON.Color3();
  14897. this.getRenderTargetTextures = function () {
  14898. _this._renderTargets.reset();
  14899. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14900. _this._renderTargets.push(_this.reflectionTexture);
  14901. }
  14902. return _this._renderTargets;
  14903. };
  14904. }
  14905. StandardMaterial.prototype.needAlphaBlending = function () {
  14906. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14907. };
  14908. StandardMaterial.prototype.needAlphaTesting = function () {
  14909. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  14910. };
  14911. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14912. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14913. };
  14914. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14915. return this.diffuseTexture;
  14916. };
  14917. // Methods
  14918. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14919. if (this.checkReadyOnlyOnce) {
  14920. if (this._wasPreviouslyReady) {
  14921. }
  14922. }
  14923. var scene = this.getScene();
  14924. if (!this.checkReadyOnEveryCall) {
  14925. if (this._renderId === scene.getRenderId()) {
  14926. }
  14927. }
  14928. var engine = scene.getEngine();
  14929. var defines = [];
  14930. var fallbacks = new BABYLON.EffectFallbacks();
  14931. var needNormals = false;
  14932. var needUVs = false;
  14933. // Textures
  14934. if (scene.texturesEnabled) {
  14935. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14936. if (!this.diffuseTexture.isReady()) {
  14937. return false;
  14938. }
  14939. else {
  14940. needUVs = true;
  14941. defines.push("#define DIFFUSE");
  14942. }
  14943. }
  14944. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14945. if (!this.ambientTexture.isReady()) {
  14946. return false;
  14947. }
  14948. else {
  14949. needUVs = true;
  14950. defines.push("#define AMBIENT");
  14951. }
  14952. }
  14953. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14954. if (!this.opacityTexture.isReady()) {
  14955. return false;
  14956. }
  14957. else {
  14958. needUVs = true;
  14959. defines.push("#define OPACITY");
  14960. if (this.opacityTexture.getAlphaFromRGB) {
  14961. defines.push("#define OPACITYRGB");
  14962. }
  14963. }
  14964. }
  14965. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14966. if (!this.reflectionTexture.isReady()) {
  14967. return false;
  14968. }
  14969. else {
  14970. needNormals = true;
  14971. needUVs = true;
  14972. defines.push("#define REFLECTION");
  14973. fallbacks.addFallback(0, "REFLECTION");
  14974. }
  14975. }
  14976. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14977. if (!this.emissiveTexture.isReady()) {
  14978. return false;
  14979. }
  14980. else {
  14981. needUVs = true;
  14982. defines.push("#define EMISSIVE");
  14983. }
  14984. }
  14985. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14986. if (!this.specularTexture.isReady()) {
  14987. return false;
  14988. }
  14989. else {
  14990. needUVs = true;
  14991. defines.push("#define SPECULAR");
  14992. fallbacks.addFallback(0, "SPECULAR");
  14993. }
  14994. }
  14995. }
  14996. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14997. if (!this.bumpTexture.isReady()) {
  14998. return false;
  14999. }
  15000. else {
  15001. needUVs = true;
  15002. defines.push("#define BUMP");
  15003. fallbacks.addFallback(0, "BUMP");
  15004. }
  15005. }
  15006. // Effect
  15007. if (this.useSpecularOverAlpha) {
  15008. defines.push("#define SPECULAROVERALPHA");
  15009. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  15010. }
  15011. if (scene.clipPlane) {
  15012. defines.push("#define CLIPPLANE");
  15013. }
  15014. if (engine.getAlphaTesting()) {
  15015. defines.push("#define ALPHATEST");
  15016. }
  15017. if (this._shouldUseAlphaFromDiffuseTexture()) {
  15018. defines.push("#define ALPHAFROMDIFFUSE");
  15019. }
  15020. // Point size
  15021. if (this.pointsCloud || scene.forcePointsCloud) {
  15022. defines.push("#define POINTSIZE");
  15023. }
  15024. // Fog
  15025. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15026. defines.push("#define FOG");
  15027. fallbacks.addFallback(1, "FOG");
  15028. }
  15029. var shadowsActivated = false;
  15030. var lightIndex = 0;
  15031. if (scene.lightsEnabled) {
  15032. for (var index = 0; index < scene.lights.length; index++) {
  15033. var light = scene.lights[index];
  15034. if (!light.isEnabled()) {
  15035. continue;
  15036. }
  15037. // Excluded check
  15038. if (light._excludedMeshesIds.length > 0) {
  15039. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  15040. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  15041. if (excludedMesh) {
  15042. light.excludedMeshes.push(excludedMesh);
  15043. }
  15044. }
  15045. light._excludedMeshesIds = [];
  15046. }
  15047. // Included check
  15048. if (light._includedOnlyMeshesIds.length > 0) {
  15049. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  15050. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  15051. if (includedOnlyMesh) {
  15052. light.includedOnlyMeshes.push(includedOnlyMesh);
  15053. }
  15054. }
  15055. light._includedOnlyMeshesIds = [];
  15056. }
  15057. if (!light.canAffectMesh(mesh)) {
  15058. continue;
  15059. }
  15060. needNormals = true;
  15061. defines.push("#define LIGHT" + lightIndex);
  15062. if (lightIndex > 0) {
  15063. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  15064. }
  15065. var type;
  15066. if (light instanceof BABYLON.SpotLight) {
  15067. type = "#define SPOTLIGHT" + lightIndex;
  15068. }
  15069. else if (light instanceof BABYLON.HemisphericLight) {
  15070. type = "#define HEMILIGHT" + lightIndex;
  15071. }
  15072. else {
  15073. type = "#define POINTDIRLIGHT" + lightIndex;
  15074. }
  15075. defines.push(type);
  15076. if (lightIndex > 0) {
  15077. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  15078. }
  15079. // Shadows
  15080. if (scene.shadowsEnabled) {
  15081. var shadowGenerator = light.getShadowGenerator();
  15082. if (mesh && mesh.receiveShadows && shadowGenerator) {
  15083. defines.push("#define SHADOW" + lightIndex);
  15084. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  15085. if (!shadowsActivated) {
  15086. defines.push("#define SHADOWS");
  15087. shadowsActivated = true;
  15088. }
  15089. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  15090. defines.push("#define SHADOWVSM" + lightIndex);
  15091. if (lightIndex > 0) {
  15092. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  15093. }
  15094. }
  15095. if (shadowGenerator.usePoissonSampling) {
  15096. defines.push("#define SHADOWPCF" + lightIndex);
  15097. if (lightIndex > 0) {
  15098. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  15099. }
  15100. }
  15101. }
  15102. }
  15103. lightIndex++;
  15104. if (lightIndex === maxSimultaneousLights)
  15105. break;
  15106. }
  15107. }
  15108. if (StandardMaterial.FresnelEnabled) {
  15109. // Fresnel
  15110. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15111. var fresnelRank = 1;
  15112. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15113. defines.push("#define DIFFUSEFRESNEL");
  15114. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  15115. fresnelRank++;
  15116. }
  15117. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15118. defines.push("#define OPACITYFRESNEL");
  15119. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  15120. fresnelRank++;
  15121. }
  15122. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15123. defines.push("#define REFLECTIONFRESNEL");
  15124. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  15125. fresnelRank++;
  15126. }
  15127. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15128. defines.push("#define EMISSIVEFRESNEL");
  15129. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  15130. fresnelRank++;
  15131. }
  15132. needNormals = true;
  15133. defines.push("#define FRESNEL");
  15134. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  15135. }
  15136. }
  15137. // Attribs
  15138. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15139. if (mesh) {
  15140. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15141. attribs.push(BABYLON.VertexBuffer.NormalKind);
  15142. defines.push("#define NORMAL");
  15143. }
  15144. if (needUVs) {
  15145. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15146. attribs.push(BABYLON.VertexBuffer.UVKind);
  15147. defines.push("#define UV1");
  15148. }
  15149. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15150. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15151. defines.push("#define UV2");
  15152. }
  15153. }
  15154. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15155. attribs.push(BABYLON.VertexBuffer.ColorKind);
  15156. defines.push("#define VERTEXCOLOR");
  15157. if (mesh.hasVertexAlpha) {
  15158. defines.push("#define VERTEXALPHA");
  15159. }
  15160. }
  15161. if (mesh.useBones) {
  15162. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15163. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15164. defines.push("#define BONES");
  15165. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15166. defines.push("#define BONES4");
  15167. fallbacks.addFallback(0, "BONES4");
  15168. }
  15169. // Instances
  15170. if (useInstances) {
  15171. defines.push("#define INSTANCES");
  15172. attribs.push("world0");
  15173. attribs.push("world1");
  15174. attribs.push("world2");
  15175. attribs.push("world3");
  15176. }
  15177. }
  15178. // Get correct effect
  15179. var join = defines.join("\n");
  15180. if (this._cachedDefines !== join) {
  15181. this._cachedDefines = join;
  15182. scene.resetCachedMaterial();
  15183. // Legacy browser patch
  15184. var shaderName = "default";
  15185. if (!scene.getEngine().getCaps().standardDerivatives) {
  15186. shaderName = "legacydefault";
  15187. }
  15188. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  15189. }
  15190. if (!this._effect.isReady()) {
  15191. return false;
  15192. }
  15193. this._renderId = scene.getRenderId();
  15194. this._wasPreviouslyReady = true;
  15195. return true;
  15196. };
  15197. StandardMaterial.prototype.unbind = function () {
  15198. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  15199. this._effect.setTexture("reflection2DSampler", null);
  15200. }
  15201. };
  15202. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  15203. this._effect.setMatrix("world", world);
  15204. };
  15205. StandardMaterial.prototype.bind = function (world, mesh) {
  15206. var scene = this.getScene();
  15207. // Matrices
  15208. this.bindOnlyWorldMatrix(world);
  15209. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  15210. // Bones
  15211. if (mesh && mesh.useBones) {
  15212. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15213. }
  15214. if (scene.getCachedMaterial() !== this) {
  15215. if (StandardMaterial.FresnelEnabled) {
  15216. // Fresnel
  15217. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15218. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15219. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15220. }
  15221. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15222. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15223. }
  15224. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15225. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15226. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15227. }
  15228. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15229. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15230. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15231. }
  15232. }
  15233. // Textures
  15234. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15235. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15236. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15237. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15238. }
  15239. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15240. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15241. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15242. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15243. }
  15244. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15245. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15246. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15247. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15248. }
  15249. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15250. if (this.reflectionTexture.isCube) {
  15251. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15252. }
  15253. else {
  15254. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15255. }
  15256. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15257. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15258. }
  15259. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15260. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15261. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15262. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15263. }
  15264. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15265. this._effect.setTexture("specularSampler", this.specularTexture);
  15266. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15267. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15268. }
  15269. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15270. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15271. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15272. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15273. }
  15274. // Clip plane
  15275. if (scene.clipPlane) {
  15276. var clipPlane = scene.clipPlane;
  15277. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15278. }
  15279. // Point size
  15280. if (this.pointsCloud) {
  15281. this._effect.setFloat("pointSize", this.pointSize);
  15282. }
  15283. // Colors
  15284. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15285. // Scaling down color according to emissive
  15286. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15287. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15288. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15289. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15290. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15291. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15292. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15293. }
  15294. // Scaling down color according to emissive
  15295. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15296. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15297. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15298. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15299. if (scene.lightsEnabled) {
  15300. var lightIndex = 0;
  15301. for (var index = 0; index < scene.lights.length; index++) {
  15302. var light = scene.lights[index];
  15303. if (!light.isEnabled()) {
  15304. continue;
  15305. }
  15306. if (!light.canAffectMesh(mesh)) {
  15307. continue;
  15308. }
  15309. if (light instanceof BABYLON.PointLight) {
  15310. // Point Light
  15311. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15312. }
  15313. else if (light instanceof BABYLON.DirectionalLight) {
  15314. // Directional Light
  15315. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15316. }
  15317. else if (light instanceof BABYLON.SpotLight) {
  15318. // Spot Light
  15319. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15320. }
  15321. else if (light instanceof BABYLON.HemisphericLight) {
  15322. // Hemispheric Light
  15323. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15324. }
  15325. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15326. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15327. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15328. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15329. // Shadows
  15330. if (scene.shadowsEnabled) {
  15331. var shadowGenerator = light.getShadowGenerator();
  15332. if (mesh.receiveShadows && shadowGenerator) {
  15333. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15334. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15335. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15336. }
  15337. }
  15338. lightIndex++;
  15339. if (lightIndex === maxSimultaneousLights)
  15340. break;
  15341. }
  15342. }
  15343. // View
  15344. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15345. this._effect.setMatrix("view", scene.getViewMatrix());
  15346. }
  15347. // Fog
  15348. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15349. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15350. this._effect.setColor3("vFogColor", scene.fogColor);
  15351. }
  15352. _super.prototype.bind.call(this, world, mesh);
  15353. };
  15354. StandardMaterial.prototype.getAnimatables = function () {
  15355. var results = [];
  15356. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15357. results.push(this.diffuseTexture);
  15358. }
  15359. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15360. results.push(this.ambientTexture);
  15361. }
  15362. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15363. results.push(this.opacityTexture);
  15364. }
  15365. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15366. results.push(this.reflectionTexture);
  15367. }
  15368. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15369. results.push(this.emissiveTexture);
  15370. }
  15371. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15372. results.push(this.specularTexture);
  15373. }
  15374. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15375. results.push(this.bumpTexture);
  15376. }
  15377. return results;
  15378. };
  15379. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15380. if (this.diffuseTexture) {
  15381. this.diffuseTexture.dispose();
  15382. }
  15383. if (this.ambientTexture) {
  15384. this.ambientTexture.dispose();
  15385. }
  15386. if (this.opacityTexture) {
  15387. this.opacityTexture.dispose();
  15388. }
  15389. if (this.reflectionTexture) {
  15390. this.reflectionTexture.dispose();
  15391. }
  15392. if (this.emissiveTexture) {
  15393. this.emissiveTexture.dispose();
  15394. }
  15395. if (this.specularTexture) {
  15396. this.specularTexture.dispose();
  15397. }
  15398. if (this.bumpTexture) {
  15399. this.bumpTexture.dispose();
  15400. }
  15401. _super.prototype.dispose.call(this, forceDisposeEffect);
  15402. };
  15403. StandardMaterial.prototype.clone = function (name) {
  15404. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15405. // Base material
  15406. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15407. newStandardMaterial.alpha = this.alpha;
  15408. newStandardMaterial.fillMode = this.fillMode;
  15409. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15410. // Standard material
  15411. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15412. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15413. }
  15414. if (this.ambientTexture && this.ambientTexture.clone) {
  15415. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15416. }
  15417. if (this.opacityTexture && this.opacityTexture.clone) {
  15418. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15419. }
  15420. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15421. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15422. }
  15423. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15424. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15425. }
  15426. if (this.specularTexture && this.specularTexture.clone) {
  15427. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15428. }
  15429. if (this.bumpTexture && this.bumpTexture.clone) {
  15430. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15431. }
  15432. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15433. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15434. newStandardMaterial.specularColor = this.specularColor.clone();
  15435. newStandardMaterial.specularPower = this.specularPower;
  15436. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15437. return newStandardMaterial;
  15438. };
  15439. // Statics
  15440. // Flags used to enable or disable a type of texture for all Standard Materials
  15441. StandardMaterial.DiffuseTextureEnabled = true;
  15442. StandardMaterial.AmbientTextureEnabled = true;
  15443. StandardMaterial.OpacityTextureEnabled = true;
  15444. StandardMaterial.ReflectionTextureEnabled = true;
  15445. StandardMaterial.EmissiveTextureEnabled = true;
  15446. StandardMaterial.SpecularTextureEnabled = true;
  15447. StandardMaterial.BumpTextureEnabled = true;
  15448. StandardMaterial.FresnelEnabled = true;
  15449. return StandardMaterial;
  15450. })(BABYLON.Material);
  15451. BABYLON.StandardMaterial = StandardMaterial;
  15452. })(BABYLON || (BABYLON = {}));
  15453. //# sourceMappingURL=babylon.standardMaterial.js.map
  15454. var BABYLON;
  15455. (function (BABYLON) {
  15456. var MultiMaterial = (function (_super) {
  15457. __extends(MultiMaterial, _super);
  15458. function MultiMaterial(name, scene) {
  15459. _super.call(this, name, scene, true);
  15460. this.subMaterials = new Array();
  15461. scene.multiMaterials.push(this);
  15462. }
  15463. // Properties
  15464. MultiMaterial.prototype.getSubMaterial = function (index) {
  15465. if (index < 0 || index >= this.subMaterials.length) {
  15466. return this.getScene().defaultMaterial;
  15467. }
  15468. return this.subMaterials[index];
  15469. };
  15470. // Methods
  15471. MultiMaterial.prototype.isReady = function (mesh) {
  15472. for (var index = 0; index < this.subMaterials.length; index++) {
  15473. var subMaterial = this.subMaterials[index];
  15474. if (subMaterial) {
  15475. if (!this.subMaterials[index].isReady(mesh)) {
  15476. return false;
  15477. }
  15478. }
  15479. }
  15480. return true;
  15481. };
  15482. return MultiMaterial;
  15483. })(BABYLON.Material);
  15484. BABYLON.MultiMaterial = MultiMaterial;
  15485. })(BABYLON || (BABYLON = {}));
  15486. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15487. (function (BABYLON) {
  15488. var Database = (function () {
  15489. function Database(urlToScene, callbackManifestChecked) {
  15490. // Handling various flavors of prefixed version of IndexedDB
  15491. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15492. this.callbackManifestChecked = callbackManifestChecked;
  15493. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15494. this.db = null;
  15495. this.enableSceneOffline = false;
  15496. this.enableTexturesOffline = false;
  15497. this.manifestVersionFound = 0;
  15498. this.mustUpdateRessources = false;
  15499. this.hasReachedQuota = false;
  15500. this.checkManifestFile();
  15501. }
  15502. Database.prototype.checkManifestFile = function () {
  15503. var _this = this;
  15504. function noManifestFile() {
  15505. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15506. that.enableSceneOffline = false;
  15507. that.enableTexturesOffline = false;
  15508. that.callbackManifestChecked(false);
  15509. }
  15510. var that = this;
  15511. var manifestURL = this.currentSceneUrl + ".manifest";
  15512. var xhr = new XMLHttpRequest();
  15513. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15514. xhr.open("GET", manifestURLTimeStamped, true);
  15515. xhr.addEventListener("load", function () {
  15516. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15517. try {
  15518. var manifestFile = JSON.parse(xhr.response);
  15519. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15520. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15521. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15522. _this.manifestVersionFound = manifestFile.version;
  15523. }
  15524. if (_this.callbackManifestChecked) {
  15525. _this.callbackManifestChecked(true);
  15526. }
  15527. }
  15528. catch (ex) {
  15529. noManifestFile();
  15530. }
  15531. }
  15532. else {
  15533. noManifestFile();
  15534. }
  15535. }, false);
  15536. xhr.addEventListener("error", function (event) {
  15537. noManifestFile();
  15538. }, false);
  15539. try {
  15540. xhr.send();
  15541. }
  15542. catch (ex) {
  15543. BABYLON.Tools.Error("Error on XHR send request.");
  15544. that.callbackManifestChecked(false);
  15545. }
  15546. };
  15547. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15548. var _this = this;
  15549. function handleError() {
  15550. that.isSupported = false;
  15551. if (errorCallback)
  15552. errorCallback();
  15553. }
  15554. var that = this;
  15555. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15556. // Your browser doesn't support IndexedDB
  15557. this.isSupported = false;
  15558. if (errorCallback)
  15559. errorCallback();
  15560. }
  15561. else {
  15562. // If the DB hasn't been opened or created yet
  15563. if (!this.db) {
  15564. this.hasReachedQuota = false;
  15565. this.isSupported = true;
  15566. var request = this.idbFactory.open("babylonjs", 1);
  15567. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15568. request.onerror = function (event) {
  15569. handleError();
  15570. };
  15571. // executes when a version change transaction cannot complete due to other active transactions
  15572. request.onblocked = function (event) {
  15573. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15574. handleError();
  15575. };
  15576. // DB has been opened successfully
  15577. request.onsuccess = function (event) {
  15578. _this.db = request.result;
  15579. successCallback();
  15580. };
  15581. // Initialization of the DB. Creating Scenes & Textures stores
  15582. request.onupgradeneeded = function (event) {
  15583. _this.db = (event.target).result;
  15584. try {
  15585. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15586. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15587. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15588. }
  15589. catch (ex) {
  15590. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15591. handleError();
  15592. }
  15593. };
  15594. }
  15595. else {
  15596. if (successCallback)
  15597. successCallback();
  15598. }
  15599. }
  15600. };
  15601. Database.prototype.loadImageFromDB = function (url, image) {
  15602. var _this = this;
  15603. var completeURL = Database.ReturnFullUrlLocation(url);
  15604. var saveAndLoadImage = function () {
  15605. if (!_this.hasReachedQuota && _this.db !== null) {
  15606. // the texture is not yet in the DB, let's try to save it
  15607. _this._saveImageIntoDBAsync(completeURL, image);
  15608. }
  15609. else {
  15610. image.src = url;
  15611. }
  15612. };
  15613. if (!this.mustUpdateRessources) {
  15614. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15615. }
  15616. else {
  15617. saveAndLoadImage();
  15618. }
  15619. };
  15620. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15621. if (this.isSupported && this.db !== null) {
  15622. var texture;
  15623. var transaction = this.db.transaction(["textures"]);
  15624. transaction.onabort = function (event) {
  15625. image.src = url;
  15626. };
  15627. transaction.oncomplete = function (event) {
  15628. var blobTextureURL;
  15629. if (texture) {
  15630. var URL = window.URL || window.webkitURL;
  15631. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15632. image.onerror = function () {
  15633. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15634. image.src = url;
  15635. };
  15636. image.src = blobTextureURL;
  15637. }
  15638. else {
  15639. notInDBCallback();
  15640. }
  15641. };
  15642. var getRequest = transaction.objectStore("textures").get(url);
  15643. getRequest.onsuccess = function (event) {
  15644. texture = (event.target).result;
  15645. };
  15646. getRequest.onerror = function (event) {
  15647. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15648. image.src = url;
  15649. };
  15650. }
  15651. else {
  15652. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15653. image.src = url;
  15654. }
  15655. };
  15656. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15657. var _this = this;
  15658. if (this.isSupported) {
  15659. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15660. var generateBlobUrl = function () {
  15661. var blobTextureURL;
  15662. if (blob) {
  15663. var URL = window.URL || window.webkitURL;
  15664. try {
  15665. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15666. }
  15667. catch (ex) {
  15668. blobTextureURL = URL.createObjectURL(blob);
  15669. }
  15670. }
  15671. image.src = blobTextureURL;
  15672. };
  15673. if (Database.isUASupportingBlobStorage) {
  15674. var xhr = new XMLHttpRequest(), blob;
  15675. xhr.open("GET", url, true);
  15676. xhr.responseType = "blob";
  15677. xhr.addEventListener("load", function () {
  15678. if (xhr.status === 200) {
  15679. // Blob as response (XHR2)
  15680. blob = xhr.response;
  15681. var transaction = _this.db.transaction(["textures"], "readwrite");
  15682. // the transaction could abort because of a QuotaExceededError error
  15683. transaction.onabort = function (event) {
  15684. try {
  15685. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15686. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15687. this.hasReachedQuota = true;
  15688. }
  15689. }
  15690. catch (ex) {
  15691. }
  15692. generateBlobUrl();
  15693. };
  15694. transaction.oncomplete = function (event) {
  15695. generateBlobUrl();
  15696. };
  15697. var newTexture = { textureUrl: url, data: blob };
  15698. try {
  15699. // Put the blob into the dabase
  15700. var addRequest = transaction.objectStore("textures").put(newTexture);
  15701. addRequest.onsuccess = function (event) {
  15702. };
  15703. addRequest.onerror = function (event) {
  15704. generateBlobUrl();
  15705. };
  15706. }
  15707. catch (ex) {
  15708. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15709. if (ex.code === 25) {
  15710. Database.isUASupportingBlobStorage = false;
  15711. }
  15712. image.src = url;
  15713. }
  15714. }
  15715. else {
  15716. image.src = url;
  15717. }
  15718. }, false);
  15719. xhr.addEventListener("error", function (event) {
  15720. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15721. image.src = url;
  15722. }, false);
  15723. xhr.send();
  15724. }
  15725. else {
  15726. image.src = url;
  15727. }
  15728. }
  15729. else {
  15730. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15731. image.src = url;
  15732. }
  15733. };
  15734. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15735. var _this = this;
  15736. var updateVersion = function (event) {
  15737. // the version is not yet in the DB or we need to update it
  15738. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15739. };
  15740. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15741. };
  15742. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15743. var _this = this;
  15744. if (this.isSupported) {
  15745. var version;
  15746. try {
  15747. var transaction = this.db.transaction(["versions"]);
  15748. transaction.oncomplete = function (event) {
  15749. if (version) {
  15750. // If the version in the JSON file is > than the version in DB
  15751. if (_this.manifestVersionFound > version.data) {
  15752. _this.mustUpdateRessources = true;
  15753. updateInDBCallback();
  15754. }
  15755. else {
  15756. callback(version.data);
  15757. }
  15758. }
  15759. else {
  15760. _this.mustUpdateRessources = true;
  15761. updateInDBCallback();
  15762. }
  15763. };
  15764. transaction.onabort = function (event) {
  15765. callback(-1);
  15766. };
  15767. var getRequest = transaction.objectStore("versions").get(url);
  15768. getRequest.onsuccess = function (event) {
  15769. version = (event.target).result;
  15770. };
  15771. getRequest.onerror = function (event) {
  15772. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15773. callback(-1);
  15774. };
  15775. }
  15776. catch (ex) {
  15777. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15778. callback(-1);
  15779. }
  15780. }
  15781. else {
  15782. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15783. callback(-1);
  15784. }
  15785. };
  15786. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15787. var _this = this;
  15788. if (this.isSupported && !this.hasReachedQuota) {
  15789. try {
  15790. // Open a transaction to the database
  15791. var transaction = this.db.transaction(["versions"], "readwrite");
  15792. // the transaction could abort because of a QuotaExceededError error
  15793. transaction.onabort = function (event) {
  15794. try {
  15795. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15796. _this.hasReachedQuota = true;
  15797. }
  15798. }
  15799. catch (ex) {
  15800. }
  15801. callback(-1);
  15802. };
  15803. transaction.oncomplete = function (event) {
  15804. callback(_this.manifestVersionFound);
  15805. };
  15806. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15807. // Put the scene into the database
  15808. var addRequest = transaction.objectStore("versions").put(newVersion);
  15809. addRequest.onsuccess = function (event) {
  15810. };
  15811. addRequest.onerror = function (event) {
  15812. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15813. };
  15814. }
  15815. catch (ex) {
  15816. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15817. callback(-1);
  15818. }
  15819. }
  15820. else {
  15821. callback(-1);
  15822. }
  15823. };
  15824. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15825. var _this = this;
  15826. var completeUrl = Database.ReturnFullUrlLocation(url);
  15827. var saveAndLoadFile = function (event) {
  15828. // the scene is not yet in the DB, let's try to save it
  15829. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15830. };
  15831. this._checkVersionFromDB(completeUrl, function (version) {
  15832. if (version !== -1) {
  15833. if (!_this.mustUpdateRessources) {
  15834. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15835. }
  15836. else {
  15837. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15838. }
  15839. }
  15840. else {
  15841. errorCallback();
  15842. }
  15843. });
  15844. };
  15845. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15846. if (this.isSupported) {
  15847. var targetStore;
  15848. if (url.indexOf(".babylon") !== -1) {
  15849. targetStore = "scenes";
  15850. }
  15851. else {
  15852. targetStore = "textures";
  15853. }
  15854. var file;
  15855. var transaction = this.db.transaction([targetStore]);
  15856. transaction.oncomplete = function (event) {
  15857. if (file) {
  15858. callback(file.data);
  15859. }
  15860. else {
  15861. notInDBCallback();
  15862. }
  15863. };
  15864. transaction.onabort = function (event) {
  15865. notInDBCallback();
  15866. };
  15867. var getRequest = transaction.objectStore(targetStore).get(url);
  15868. getRequest.onsuccess = function (event) {
  15869. file = (event.target).result;
  15870. };
  15871. getRequest.onerror = function (event) {
  15872. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15873. notInDBCallback();
  15874. };
  15875. }
  15876. else {
  15877. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15878. callback();
  15879. }
  15880. };
  15881. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15882. var _this = this;
  15883. if (this.isSupported) {
  15884. var targetStore;
  15885. if (url.indexOf(".babylon") !== -1) {
  15886. targetStore = "scenes";
  15887. }
  15888. else {
  15889. targetStore = "textures";
  15890. }
  15891. // Create XHR
  15892. var xhr = new XMLHttpRequest(), fileData;
  15893. xhr.open("GET", url, true);
  15894. if (useArrayBuffer) {
  15895. xhr.responseType = "arraybuffer";
  15896. }
  15897. xhr.onprogress = progressCallback;
  15898. xhr.addEventListener("load", function () {
  15899. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15900. // Blob as response (XHR2)
  15901. //fileData = xhr.responseText;
  15902. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15903. if (!_this.hasReachedQuota) {
  15904. // Open a transaction to the database
  15905. var transaction = _this.db.transaction([targetStore], "readwrite");
  15906. // the transaction could abort because of a QuotaExceededError error
  15907. transaction.onabort = function (event) {
  15908. try {
  15909. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15910. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15911. this.hasReachedQuota = true;
  15912. }
  15913. }
  15914. catch (ex) {
  15915. }
  15916. callback(fileData);
  15917. };
  15918. transaction.oncomplete = function (event) {
  15919. callback(fileData);
  15920. };
  15921. var newFile;
  15922. if (targetStore === "scenes") {
  15923. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15924. }
  15925. else {
  15926. newFile = { textureUrl: url, data: fileData };
  15927. }
  15928. try {
  15929. // Put the scene into the database
  15930. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15931. addRequest.onsuccess = function (event) {
  15932. };
  15933. addRequest.onerror = function (event) {
  15934. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15935. };
  15936. }
  15937. catch (ex) {
  15938. callback(fileData);
  15939. }
  15940. }
  15941. else {
  15942. callback(fileData);
  15943. }
  15944. }
  15945. else {
  15946. callback();
  15947. }
  15948. }, false);
  15949. xhr.addEventListener("error", function (event) {
  15950. BABYLON.Tools.Error("error on XHR request.");
  15951. callback();
  15952. }, false);
  15953. xhr.send();
  15954. }
  15955. else {
  15956. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15957. callback();
  15958. }
  15959. };
  15960. Database.isUASupportingBlobStorage = true;
  15961. Database.parseURL = function (url) {
  15962. var a = document.createElement('a');
  15963. a.href = url;
  15964. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15965. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15966. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15967. return absLocation;
  15968. };
  15969. Database.ReturnFullUrlLocation = function (url) {
  15970. if (url.indexOf("http:/") === -1) {
  15971. return (BABYLON.Database.parseURL(window.location.href) + url);
  15972. }
  15973. else {
  15974. return url;
  15975. }
  15976. };
  15977. return Database;
  15978. })();
  15979. BABYLON.Database = Database;
  15980. })(BABYLON || (BABYLON = {}));
  15981. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15982. (function (BABYLON) {
  15983. var SpriteManager = (function () {
  15984. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15986. this.name = name;
  15987. this.cellSize = cellSize;
  15988. this.sprites = new Array();
  15989. this.renderingGroupId = 0;
  15990. this.fogEnabled = true;
  15991. this._vertexDeclaration = [4, 4, 4, 4];
  15992. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15993. this._capacity = capacity;
  15994. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15995. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15996. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15997. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15998. this._scene = scene;
  15999. this._scene.spriteManagers.push(this);
  16000. // VBO
  16001. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16002. var indices = [];
  16003. var index = 0;
  16004. for (var count = 0; count < capacity; count++) {
  16005. indices.push(index);
  16006. indices.push(index + 1);
  16007. indices.push(index + 2);
  16008. indices.push(index);
  16009. indices.push(index + 2);
  16010. indices.push(index + 3);
  16011. index += 4;
  16012. }
  16013. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16014. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16015. // Effects
  16016. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  16017. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  16018. }
  16019. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  16020. var arrayOffset = index * 16;
  16021. if (offsetX === 0)
  16022. offsetX = this._epsilon;
  16023. else if (offsetX === 1)
  16024. offsetX = 1 - this._epsilon;
  16025. if (offsetY === 0)
  16026. offsetY = this._epsilon;
  16027. else if (offsetY === 1)
  16028. offsetY = 1 - this._epsilon;
  16029. this._vertices[arrayOffset] = sprite.position.x;
  16030. this._vertices[arrayOffset + 1] = sprite.position.y;
  16031. this._vertices[arrayOffset + 2] = sprite.position.z;
  16032. this._vertices[arrayOffset + 3] = sprite.angle;
  16033. this._vertices[arrayOffset + 4] = sprite.width;
  16034. this._vertices[arrayOffset + 5] = sprite.height;
  16035. this._vertices[arrayOffset + 6] = offsetX;
  16036. this._vertices[arrayOffset + 7] = offsetY;
  16037. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  16038. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  16039. var offset = (sprite.cellIndex / rowSize) >> 0;
  16040. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  16041. this._vertices[arrayOffset + 11] = offset;
  16042. // Color
  16043. this._vertices[arrayOffset + 12] = sprite.color.r;
  16044. this._vertices[arrayOffset + 13] = sprite.color.g;
  16045. this._vertices[arrayOffset + 14] = sprite.color.b;
  16046. this._vertices[arrayOffset + 15] = sprite.color.a;
  16047. };
  16048. SpriteManager.prototype.render = function () {
  16049. // Check
  16050. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  16051. return;
  16052. var engine = this._scene.getEngine();
  16053. var baseSize = this._spriteTexture.getBaseSize();
  16054. // Sprites
  16055. var deltaTime = engine.getDeltaTime();
  16056. var max = Math.min(this._capacity, this.sprites.length);
  16057. var rowSize = baseSize.width / this.cellSize;
  16058. var offset = 0;
  16059. for (var index = 0; index < max; index++) {
  16060. var sprite = this.sprites[index];
  16061. if (!sprite) {
  16062. continue;
  16063. }
  16064. sprite._animate(deltaTime);
  16065. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  16066. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  16067. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  16068. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  16069. }
  16070. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16071. // Render
  16072. var effect = this._effectBase;
  16073. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16074. effect = this._effectFog;
  16075. }
  16076. engine.enableEffect(effect);
  16077. var viewMatrix = this._scene.getViewMatrix();
  16078. effect.setTexture("diffuseSampler", this._spriteTexture);
  16079. effect.setMatrix("view", viewMatrix);
  16080. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16081. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  16082. // Fog
  16083. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16084. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  16085. effect.setColor3("vFogColor", this._scene.fogColor);
  16086. }
  16087. // VBOs
  16088. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16089. // Draw order
  16090. engine.setDepthFunctionToLessOrEqual();
  16091. effect.setBool("alphaTest", true);
  16092. engine.setColorWrite(false);
  16093. engine.draw(true, 0, max * 6);
  16094. engine.setColorWrite(true);
  16095. effect.setBool("alphaTest", false);
  16096. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16097. engine.draw(true, 0, max * 6);
  16098. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16099. };
  16100. SpriteManager.prototype.dispose = function () {
  16101. if (this._vertexBuffer) {
  16102. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16103. this._vertexBuffer = null;
  16104. }
  16105. if (this._indexBuffer) {
  16106. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16107. this._indexBuffer = null;
  16108. }
  16109. if (this._spriteTexture) {
  16110. this._spriteTexture.dispose();
  16111. this._spriteTexture = null;
  16112. }
  16113. // Remove from scene
  16114. var index = this._scene.spriteManagers.indexOf(this);
  16115. this._scene.spriteManagers.splice(index, 1);
  16116. // Callback
  16117. if (this.onDispose) {
  16118. this.onDispose();
  16119. }
  16120. };
  16121. return SpriteManager;
  16122. })();
  16123. BABYLON.SpriteManager = SpriteManager;
  16124. })(BABYLON || (BABYLON = {}));
  16125. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  16126. (function (BABYLON) {
  16127. var Sprite = (function () {
  16128. function Sprite(name, manager) {
  16129. this.name = name;
  16130. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16131. this.width = 1.0;
  16132. this.height = 1.0;
  16133. this.angle = 0;
  16134. this.cellIndex = 0;
  16135. this.invertU = 0;
  16136. this.invertV = 0;
  16137. this.animations = new Array();
  16138. this._animationStarted = false;
  16139. this._loopAnimation = false;
  16140. this._fromIndex = 0;
  16141. this._toIndex = 0;
  16142. this._delay = 0;
  16143. this._direction = 1;
  16144. this._frameCount = 0;
  16145. this._time = 0;
  16146. this._manager = manager;
  16147. this._manager.sprites.push(this);
  16148. this.position = BABYLON.Vector3.Zero();
  16149. }
  16150. Object.defineProperty(Sprite.prototype, "size", {
  16151. get: function () {
  16152. return this.width;
  16153. },
  16154. set: function (value) {
  16155. this.width = value;
  16156. this.height = value;
  16157. },
  16158. enumerable: true,
  16159. configurable: true
  16160. });
  16161. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  16162. this._fromIndex = from;
  16163. this._toIndex = to;
  16164. this._loopAnimation = loop;
  16165. this._delay = delay;
  16166. this._animationStarted = true;
  16167. this._direction = from < to ? 1 : -1;
  16168. this.cellIndex = from;
  16169. this._time = 0;
  16170. };
  16171. Sprite.prototype.stopAnimation = function () {
  16172. this._animationStarted = false;
  16173. };
  16174. Sprite.prototype._animate = function (deltaTime) {
  16175. if (!this._animationStarted)
  16176. return;
  16177. this._time += deltaTime;
  16178. if (this._time > this._delay) {
  16179. this._time = this._time % this._delay;
  16180. this.cellIndex += this._direction;
  16181. if (this.cellIndex == this._toIndex) {
  16182. if (this._loopAnimation) {
  16183. this.cellIndex = this._fromIndex;
  16184. }
  16185. else {
  16186. this._animationStarted = false;
  16187. if (this.disposeWhenFinishedAnimating) {
  16188. this.dispose();
  16189. }
  16190. }
  16191. }
  16192. }
  16193. };
  16194. Sprite.prototype.dispose = function () {
  16195. for (var i = 0; i < this._manager.sprites.length; i++) {
  16196. if (this._manager.sprites[i] == this) {
  16197. this._manager.sprites.splice(i, 1);
  16198. }
  16199. }
  16200. };
  16201. return Sprite;
  16202. })();
  16203. BABYLON.Sprite = Sprite;
  16204. })(BABYLON || (BABYLON = {}));
  16205. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  16206. (function (BABYLON) {
  16207. var Layer = (function () {
  16208. function Layer(name, imgUrl, scene, isBackground, color) {
  16209. this.name = name;
  16210. this._vertexDeclaration = [2];
  16211. this._vertexStrideSize = 2 * 4;
  16212. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16213. this.isBackground = isBackground === undefined ? true : isBackground;
  16214. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16215. this._scene = scene;
  16216. this._scene.layers.push(this);
  16217. // VBO
  16218. var vertices = [];
  16219. vertices.push(1, 1);
  16220. vertices.push(-1, 1);
  16221. vertices.push(-1, -1);
  16222. vertices.push(1, -1);
  16223. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16224. // Indices
  16225. var indices = [];
  16226. indices.push(0);
  16227. indices.push(1);
  16228. indices.push(2);
  16229. indices.push(0);
  16230. indices.push(2);
  16231. indices.push(3);
  16232. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16233. // Effects
  16234. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16235. }
  16236. Layer.prototype.render = function () {
  16237. // Check
  16238. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16239. return;
  16240. var engine = this._scene.getEngine();
  16241. // Render
  16242. engine.enableEffect(this._effect);
  16243. engine.setState(false);
  16244. // Texture
  16245. this._effect.setTexture("textureSampler", this.texture);
  16246. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16247. // Color
  16248. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16249. // VBOs
  16250. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16251. // Draw order
  16252. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16253. engine.draw(true, 0, 6);
  16254. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16255. };
  16256. Layer.prototype.dispose = function () {
  16257. if (this._vertexBuffer) {
  16258. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16259. this._vertexBuffer = null;
  16260. }
  16261. if (this._indexBuffer) {
  16262. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16263. this._indexBuffer = null;
  16264. }
  16265. if (this.texture) {
  16266. this.texture.dispose();
  16267. this.texture = null;
  16268. }
  16269. // Remove from scene
  16270. var index = this._scene.layers.indexOf(this);
  16271. this._scene.layers.splice(index, 1);
  16272. // Callback
  16273. if (this.onDispose) {
  16274. this.onDispose();
  16275. }
  16276. };
  16277. return Layer;
  16278. })();
  16279. BABYLON.Layer = Layer;
  16280. })(BABYLON || (BABYLON = {}));
  16281. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16282. (function (BABYLON) {
  16283. var Particle = (function () {
  16284. function Particle() {
  16285. this.position = BABYLON.Vector3.Zero();
  16286. this.direction = BABYLON.Vector3.Zero();
  16287. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16288. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16289. this.lifeTime = 1.0;
  16290. this.age = 0;
  16291. this.size = 0;
  16292. this.angle = 0;
  16293. this.angularSpeed = 0;
  16294. }
  16295. Particle.prototype.copyTo = function (other) {
  16296. other.position.copyFrom(this.position);
  16297. other.direction.copyFrom(this.direction);
  16298. other.color.copyFrom(this.color);
  16299. other.colorStep.copyFrom(this.colorStep);
  16300. other.lifeTime = this.lifeTime;
  16301. other.age = this.age;
  16302. other.size = this.size;
  16303. other.angle = this.angle;
  16304. other.angularSpeed = this.angularSpeed;
  16305. };
  16306. return Particle;
  16307. })();
  16308. BABYLON.Particle = Particle;
  16309. })(BABYLON || (BABYLON = {}));
  16310. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16311. (function (BABYLON) {
  16312. var randomNumber = function (min, max) {
  16313. if (min === max) {
  16314. return (min);
  16315. }
  16316. var random = Math.random();
  16317. return ((random * (max - min)) + min);
  16318. };
  16319. var ParticleSystem = (function () {
  16320. function ParticleSystem(name, capacity, scene, customEffect) {
  16321. var _this = this;
  16322. this.name = name;
  16323. this.renderingGroupId = 0;
  16324. this.emitter = null;
  16325. this.emitRate = 10;
  16326. this.manualEmitCount = -1;
  16327. this.updateSpeed = 0.01;
  16328. this.targetStopDuration = 0;
  16329. this.disposeOnStop = false;
  16330. this.minEmitPower = 1;
  16331. this.maxEmitPower = 1;
  16332. this.minLifeTime = 1;
  16333. this.maxLifeTime = 1;
  16334. this.minSize = 1;
  16335. this.maxSize = 1;
  16336. this.minAngularSpeed = 0;
  16337. this.maxAngularSpeed = 0;
  16338. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16339. this.forceDepthWrite = false;
  16340. this.gravity = BABYLON.Vector3.Zero();
  16341. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16342. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16343. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16344. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16345. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16346. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16347. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16348. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16349. this.particles = new Array();
  16350. this._vertexDeclaration = [3, 4, 4];
  16351. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16352. this._stockParticles = new Array();
  16353. this._newPartsExcess = 0;
  16354. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16355. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16356. this._scaledDirection = BABYLON.Vector3.Zero();
  16357. this._scaledGravity = BABYLON.Vector3.Zero();
  16358. this._currentRenderId = -1;
  16359. this._started = false;
  16360. this._stopped = false;
  16361. this._actualFrame = 0;
  16362. this.id = name;
  16363. this._capacity = capacity;
  16364. this._scene = scene;
  16365. this._customEffect = customEffect;
  16366. scene.particleSystems.push(this);
  16367. // VBO
  16368. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16369. var indices = [];
  16370. var index = 0;
  16371. for (var count = 0; count < capacity; count++) {
  16372. indices.push(index);
  16373. indices.push(index + 1);
  16374. indices.push(index + 2);
  16375. indices.push(index);
  16376. indices.push(index + 2);
  16377. indices.push(index + 3);
  16378. index += 4;
  16379. }
  16380. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16381. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16382. // Default behaviors
  16383. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16384. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16385. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16386. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16387. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16388. };
  16389. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16390. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16391. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16392. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16393. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16394. };
  16395. this.updateFunction = function (particles) {
  16396. for (var index = 0; index < particles.length; index++) {
  16397. var particle = particles[index];
  16398. particle.age += _this._scaledUpdateSpeed;
  16399. if (particle.age >= particle.lifeTime) {
  16400. _this.recycleParticle(particle);
  16401. index--;
  16402. continue;
  16403. }
  16404. else {
  16405. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16406. particle.color.addInPlace(_this._scaledColorStep);
  16407. if (particle.color.a < 0)
  16408. particle.color.a = 0;
  16409. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16410. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16411. particle.position.addInPlace(_this._scaledDirection);
  16412. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16413. particle.direction.addInPlace(_this._scaledGravity);
  16414. }
  16415. }
  16416. };
  16417. }
  16418. ParticleSystem.prototype.recycleParticle = function (particle) {
  16419. var lastParticle = this.particles.pop();
  16420. if (lastParticle !== particle) {
  16421. lastParticle.copyTo(particle);
  16422. this._stockParticles.push(lastParticle);
  16423. }
  16424. };
  16425. ParticleSystem.prototype.getCapacity = function () {
  16426. return this._capacity;
  16427. };
  16428. ParticleSystem.prototype.isAlive = function () {
  16429. return this._alive;
  16430. };
  16431. ParticleSystem.prototype.isStarted = function () {
  16432. return this._started;
  16433. };
  16434. ParticleSystem.prototype.start = function () {
  16435. this._started = true;
  16436. this._stopped = false;
  16437. this._actualFrame = 0;
  16438. };
  16439. ParticleSystem.prototype.stop = function () {
  16440. this._stopped = true;
  16441. };
  16442. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16443. var offset = index * 11;
  16444. this._vertices[offset] = particle.position.x;
  16445. this._vertices[offset + 1] = particle.position.y;
  16446. this._vertices[offset + 2] = particle.position.z;
  16447. this._vertices[offset + 3] = particle.color.r;
  16448. this._vertices[offset + 4] = particle.color.g;
  16449. this._vertices[offset + 5] = particle.color.b;
  16450. this._vertices[offset + 6] = particle.color.a;
  16451. this._vertices[offset + 7] = particle.angle;
  16452. this._vertices[offset + 8] = particle.size;
  16453. this._vertices[offset + 9] = offsetX;
  16454. this._vertices[offset + 10] = offsetY;
  16455. };
  16456. ParticleSystem.prototype._update = function (newParticles) {
  16457. // Update current
  16458. this._alive = this.particles.length > 0;
  16459. this.updateFunction(this.particles);
  16460. // Add new ones
  16461. var worldMatrix;
  16462. if (this.emitter.position) {
  16463. worldMatrix = this.emitter.getWorldMatrix();
  16464. }
  16465. else {
  16466. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16467. }
  16468. for (var index = 0; index < newParticles; index++) {
  16469. if (this.particles.length === this._capacity) {
  16470. break;
  16471. }
  16472. if (this._stockParticles.length !== 0) {
  16473. var particle = this._stockParticles.pop();
  16474. particle.age = 0;
  16475. }
  16476. else {
  16477. particle = new BABYLON.Particle();
  16478. }
  16479. this.particles.push(particle);
  16480. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16481. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16482. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16483. particle.size = randomNumber(this.minSize, this.maxSize);
  16484. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16485. this.startPositionFunction(worldMatrix, particle.position);
  16486. var step = randomNumber(0, 1.0);
  16487. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16488. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16489. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16490. }
  16491. };
  16492. ParticleSystem.prototype._getEffect = function () {
  16493. if (this._customEffect) {
  16494. return this._customEffect;
  16495. }
  16496. ;
  16497. var defines = [];
  16498. if (this._scene.clipPlane) {
  16499. defines.push("#define CLIPPLANE");
  16500. }
  16501. // Effect
  16502. var join = defines.join("\n");
  16503. if (this._cachedDefines !== join) {
  16504. this._cachedDefines = join;
  16505. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16506. }
  16507. return this._effect;
  16508. };
  16509. ParticleSystem.prototype.animate = function () {
  16510. if (!this._started)
  16511. return;
  16512. var effect = this._getEffect();
  16513. // Check
  16514. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16515. return;
  16516. if (this._currentRenderId === this._scene.getRenderId()) {
  16517. return;
  16518. }
  16519. this._currentRenderId = this._scene.getRenderId();
  16520. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16521. // determine the number of particles we need to create
  16522. var emitCout;
  16523. if (this.manualEmitCount > -1) {
  16524. emitCout = this.manualEmitCount;
  16525. this.manualEmitCount = 0;
  16526. }
  16527. else {
  16528. emitCout = this.emitRate;
  16529. }
  16530. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16531. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16532. if (this._newPartsExcess > 1.0) {
  16533. newParticles += this._newPartsExcess >> 0;
  16534. this._newPartsExcess -= this._newPartsExcess >> 0;
  16535. }
  16536. this._alive = false;
  16537. if (!this._stopped) {
  16538. this._actualFrame += this._scaledUpdateSpeed;
  16539. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16540. this.stop();
  16541. }
  16542. else {
  16543. newParticles = 0;
  16544. }
  16545. this._update(newParticles);
  16546. // Stopped?
  16547. if (this._stopped) {
  16548. if (!this._alive) {
  16549. this._started = false;
  16550. if (this.disposeOnStop) {
  16551. this._scene._toBeDisposed.push(this);
  16552. }
  16553. }
  16554. }
  16555. // Update VBO
  16556. var offset = 0;
  16557. for (var index = 0; index < this.particles.length; index++) {
  16558. var particle = this.particles[index];
  16559. this._appendParticleVertex(offset++, particle, 0, 0);
  16560. this._appendParticleVertex(offset++, particle, 1, 0);
  16561. this._appendParticleVertex(offset++, particle, 1, 1);
  16562. this._appendParticleVertex(offset++, particle, 0, 1);
  16563. }
  16564. var engine = this._scene.getEngine();
  16565. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16566. };
  16567. ParticleSystem.prototype.render = function () {
  16568. var effect = this._getEffect();
  16569. // Check
  16570. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16571. return 0;
  16572. var engine = this._scene.getEngine();
  16573. // Render
  16574. engine.enableEffect(effect);
  16575. engine.setState(false);
  16576. var viewMatrix = this._scene.getViewMatrix();
  16577. effect.setTexture("diffuseSampler", this.particleTexture);
  16578. effect.setMatrix("view", viewMatrix);
  16579. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16580. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16581. if (this._scene.clipPlane) {
  16582. var clipPlane = this._scene.clipPlane;
  16583. var invView = viewMatrix.clone();
  16584. invView.invert();
  16585. effect.setMatrix("invView", invView);
  16586. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16587. }
  16588. // VBOs
  16589. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16590. // Draw order
  16591. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16592. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16593. }
  16594. else {
  16595. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16596. }
  16597. if (this.forceDepthWrite) {
  16598. engine.setDepthWrite(true);
  16599. }
  16600. engine.draw(true, 0, this.particles.length * 6);
  16601. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16602. return this.particles.length;
  16603. };
  16604. ParticleSystem.prototype.dispose = function () {
  16605. if (this._vertexBuffer) {
  16606. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16607. this._vertexBuffer = null;
  16608. }
  16609. if (this._indexBuffer) {
  16610. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16611. this._indexBuffer = null;
  16612. }
  16613. if (this.particleTexture) {
  16614. this.particleTexture.dispose();
  16615. this.particleTexture = null;
  16616. }
  16617. // Remove from scene
  16618. var index = this._scene.particleSystems.indexOf(this);
  16619. this._scene.particleSystems.splice(index, 1);
  16620. // Callback
  16621. if (this.onDispose) {
  16622. this.onDispose();
  16623. }
  16624. };
  16625. // Clone
  16626. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16627. var result = new ParticleSystem(name, this._capacity, this._scene);
  16628. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16629. if (newEmitter === undefined) {
  16630. newEmitter = this.emitter;
  16631. }
  16632. result.emitter = newEmitter;
  16633. if (this.particleTexture) {
  16634. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16635. }
  16636. result.start();
  16637. return result;
  16638. };
  16639. // Statics
  16640. ParticleSystem.BLENDMODE_ONEONE = 0;
  16641. ParticleSystem.BLENDMODE_STANDARD = 1;
  16642. return ParticleSystem;
  16643. })();
  16644. BABYLON.ParticleSystem = ParticleSystem;
  16645. })(BABYLON || (BABYLON = {}));
  16646. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16647. (function (BABYLON) {
  16648. var Animation = (function () {
  16649. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16650. this.name = name;
  16651. this.targetProperty = targetProperty;
  16652. this.framePerSecond = framePerSecond;
  16653. this.dataType = dataType;
  16654. this.loopMode = loopMode;
  16655. this._offsetsCache = {};
  16656. this._highLimitsCache = {};
  16657. this._stopped = false;
  16658. this.targetPropertyPath = targetProperty.split(".");
  16659. this.dataType = dataType;
  16660. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16661. }
  16662. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16663. var dataType = undefined;
  16664. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16665. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16666. }
  16667. else if (from instanceof BABYLON.Quaternion) {
  16668. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16669. }
  16670. else if (from instanceof BABYLON.Vector3) {
  16671. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16672. }
  16673. else if (from instanceof BABYLON.Vector2) {
  16674. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16675. }
  16676. else if (from instanceof BABYLON.Color3) {
  16677. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16678. }
  16679. if (dataType == undefined) {
  16680. return null;
  16681. }
  16682. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16683. var keys = [];
  16684. keys.push({ frame: 0, value: from });
  16685. keys.push({ frame: totalFrame, value: to });
  16686. animation.setKeys(keys);
  16687. mesh.animations.push(animation);
  16688. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16689. };
  16690. // Methods
  16691. Animation.prototype.isStopped = function () {
  16692. return this._stopped;
  16693. };
  16694. Animation.prototype.getKeys = function () {
  16695. return this._keys;
  16696. };
  16697. Animation.prototype.getEasingFunction = function () {
  16698. return this._easingFunction;
  16699. };
  16700. Animation.prototype.setEasingFunction = function (easingFunction) {
  16701. this._easingFunction = easingFunction;
  16702. };
  16703. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16704. return startValue + (endValue - startValue) * gradient;
  16705. };
  16706. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16707. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16708. };
  16709. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16710. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16711. };
  16712. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16713. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16714. };
  16715. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16716. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16717. };
  16718. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16719. var startScale = new BABYLON.Vector3(0, 0, 0);
  16720. var startRotation = new BABYLON.Quaternion();
  16721. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16722. startValue.decompose(startScale, startRotation, startTranslation);
  16723. var endScale = new BABYLON.Vector3(0, 0, 0);
  16724. var endRotation = new BABYLON.Quaternion();
  16725. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16726. endValue.decompose(endScale, endRotation, endTranslation);
  16727. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16728. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16729. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16730. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16731. return result;
  16732. };
  16733. Animation.prototype.clone = function () {
  16734. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16735. clone.setKeys(this._keys);
  16736. return clone;
  16737. };
  16738. Animation.prototype.setKeys = function (values) {
  16739. this._keys = values.slice(0);
  16740. this._offsetsCache = {};
  16741. this._highLimitsCache = {};
  16742. };
  16743. Animation.prototype._getKeyValue = function (value) {
  16744. if (typeof value === "function") {
  16745. return value();
  16746. }
  16747. return value;
  16748. };
  16749. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16750. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16751. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16752. }
  16753. this.currentFrame = currentFrame;
  16754. // Try to get a hash to find the right key
  16755. 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));
  16756. if (this._keys[startKey].frame >= currentFrame) {
  16757. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16758. startKey--;
  16759. }
  16760. }
  16761. for (var key = startKey; key < this._keys.length; key++) {
  16762. if (this._keys[key + 1].frame >= currentFrame) {
  16763. var startValue = this._getKeyValue(this._keys[key].value);
  16764. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16765. // gradient : percent of currentFrame between the frame inf and the frame sup
  16766. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16767. // check for easingFunction and correction of gradient
  16768. if (this._easingFunction != null) {
  16769. gradient = this._easingFunction.ease(gradient);
  16770. }
  16771. switch (this.dataType) {
  16772. case Animation.ANIMATIONTYPE_FLOAT:
  16773. switch (loopMode) {
  16774. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16775. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16776. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16777. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16778. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16779. }
  16780. break;
  16781. case Animation.ANIMATIONTYPE_QUATERNION:
  16782. var quaternion = null;
  16783. switch (loopMode) {
  16784. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16785. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16786. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16787. break;
  16788. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16789. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16790. break;
  16791. }
  16792. return quaternion;
  16793. case Animation.ANIMATIONTYPE_VECTOR3:
  16794. switch (loopMode) {
  16795. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16796. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16797. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16798. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16799. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16800. }
  16801. case Animation.ANIMATIONTYPE_VECTOR2:
  16802. switch (loopMode) {
  16803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16805. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16807. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16808. }
  16809. case Animation.ANIMATIONTYPE_COLOR3:
  16810. switch (loopMode) {
  16811. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16812. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16813. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16814. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16815. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16816. }
  16817. case Animation.ANIMATIONTYPE_MATRIX:
  16818. switch (loopMode) {
  16819. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16820. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16821. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16822. return startValue;
  16823. }
  16824. default:
  16825. break;
  16826. }
  16827. break;
  16828. }
  16829. }
  16830. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16831. };
  16832. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16833. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16834. this._stopped = true;
  16835. return false;
  16836. }
  16837. var returnValue = true;
  16838. // Adding a start key at frame 0 if missing
  16839. if (this._keys[0].frame !== 0) {
  16840. var newKey = { frame: 0, value: this._keys[0].value };
  16841. this._keys.splice(0, 0, newKey);
  16842. }
  16843. // Check limits
  16844. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16845. from = this._keys[0].frame;
  16846. }
  16847. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16848. to = this._keys[this._keys.length - 1].frame;
  16849. }
  16850. // Compute ratio
  16851. var range = to - from;
  16852. var offsetValue;
  16853. // ratio represents the frame delta between from and to
  16854. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16855. var highLimitValue = 0;
  16856. if (ratio > range && !loop) {
  16857. returnValue = false;
  16858. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16859. }
  16860. else {
  16861. // Get max value if required
  16862. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16863. var keyOffset = to.toString() + from.toString();
  16864. if (!this._offsetsCache[keyOffset]) {
  16865. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16866. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16867. switch (this.dataType) {
  16868. case Animation.ANIMATIONTYPE_FLOAT:
  16869. this._offsetsCache[keyOffset] = toValue - fromValue;
  16870. break;
  16871. case Animation.ANIMATIONTYPE_QUATERNION:
  16872. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16873. break;
  16874. case Animation.ANIMATIONTYPE_VECTOR3:
  16875. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16876. case Animation.ANIMATIONTYPE_VECTOR2:
  16877. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16878. case Animation.ANIMATIONTYPE_COLOR3:
  16879. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16880. default:
  16881. break;
  16882. }
  16883. this._highLimitsCache[keyOffset] = toValue;
  16884. }
  16885. highLimitValue = this._highLimitsCache[keyOffset];
  16886. offsetValue = this._offsetsCache[keyOffset];
  16887. }
  16888. }
  16889. if (offsetValue === undefined) {
  16890. switch (this.dataType) {
  16891. case Animation.ANIMATIONTYPE_FLOAT:
  16892. offsetValue = 0;
  16893. break;
  16894. case Animation.ANIMATIONTYPE_QUATERNION:
  16895. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16896. break;
  16897. case Animation.ANIMATIONTYPE_VECTOR3:
  16898. offsetValue = BABYLON.Vector3.Zero();
  16899. break;
  16900. case Animation.ANIMATIONTYPE_VECTOR2:
  16901. offsetValue = BABYLON.Vector2.Zero();
  16902. break;
  16903. case Animation.ANIMATIONTYPE_COLOR3:
  16904. offsetValue = BABYLON.Color3.Black();
  16905. }
  16906. }
  16907. // Compute value
  16908. var repeatCount = (ratio / range) >> 0;
  16909. var currentFrame = returnValue ? from + ratio % range : to;
  16910. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16911. // Set value
  16912. if (this.targetPropertyPath.length > 1) {
  16913. var property = this._target[this.targetPropertyPath[0]];
  16914. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16915. property = property[this.targetPropertyPath[index]];
  16916. }
  16917. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16918. }
  16919. else {
  16920. this._target[this.targetPropertyPath[0]] = currentValue;
  16921. }
  16922. if (this._target.markAsDirty) {
  16923. this._target.markAsDirty(this.targetProperty);
  16924. }
  16925. if (!returnValue) {
  16926. this._stopped = true;
  16927. }
  16928. return returnValue;
  16929. };
  16930. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16931. get: function () {
  16932. return Animation._ANIMATIONTYPE_FLOAT;
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16938. get: function () {
  16939. return Animation._ANIMATIONTYPE_VECTOR3;
  16940. },
  16941. enumerable: true,
  16942. configurable: true
  16943. });
  16944. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16945. get: function () {
  16946. return Animation._ANIMATIONTYPE_VECTOR2;
  16947. },
  16948. enumerable: true,
  16949. configurable: true
  16950. });
  16951. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16952. get: function () {
  16953. return Animation._ANIMATIONTYPE_QUATERNION;
  16954. },
  16955. enumerable: true,
  16956. configurable: true
  16957. });
  16958. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16959. get: function () {
  16960. return Animation._ANIMATIONTYPE_MATRIX;
  16961. },
  16962. enumerable: true,
  16963. configurable: true
  16964. });
  16965. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16966. get: function () {
  16967. return Animation._ANIMATIONTYPE_COLOR3;
  16968. },
  16969. enumerable: true,
  16970. configurable: true
  16971. });
  16972. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16973. get: function () {
  16974. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16980. get: function () {
  16981. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16987. get: function () {
  16988. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16989. },
  16990. enumerable: true,
  16991. configurable: true
  16992. });
  16993. // Statics
  16994. Animation._ANIMATIONTYPE_FLOAT = 0;
  16995. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16996. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16997. Animation._ANIMATIONTYPE_MATRIX = 3;
  16998. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16999. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  17000. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  17001. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  17002. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  17003. return Animation;
  17004. })();
  17005. BABYLON.Animation = Animation;
  17006. })(BABYLON || (BABYLON = {}));
  17007. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  17008. (function (BABYLON) {
  17009. var Animatable = (function () {
  17010. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  17011. if (fromFrame === void 0) { fromFrame = 0; }
  17012. if (toFrame === void 0) { toFrame = 100; }
  17013. if (loopAnimation === void 0) { loopAnimation = false; }
  17014. if (speedRatio === void 0) { speedRatio = 1.0; }
  17015. this.target = target;
  17016. this.fromFrame = fromFrame;
  17017. this.toFrame = toFrame;
  17018. this.loopAnimation = loopAnimation;
  17019. this.speedRatio = speedRatio;
  17020. this.onAnimationEnd = onAnimationEnd;
  17021. this._animations = new Array();
  17022. this._paused = false;
  17023. this.animationStarted = false;
  17024. if (animations) {
  17025. this.appendAnimations(target, animations);
  17026. }
  17027. this._scene = scene;
  17028. scene._activeAnimatables.push(this);
  17029. }
  17030. // Methods
  17031. Animatable.prototype.appendAnimations = function (target, animations) {
  17032. for (var index = 0; index < animations.length; index++) {
  17033. var animation = animations[index];
  17034. animation._target = target;
  17035. this._animations.push(animation);
  17036. }
  17037. };
  17038. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  17039. var animations = this._animations;
  17040. for (var index = 0; index < animations.length; index++) {
  17041. if (animations[index].targetProperty === property) {
  17042. return animations[index];
  17043. }
  17044. }
  17045. return null;
  17046. };
  17047. Animatable.prototype.pause = function () {
  17048. if (this._paused) {
  17049. return;
  17050. }
  17051. this._paused = true;
  17052. };
  17053. Animatable.prototype.restart = function () {
  17054. this._paused = false;
  17055. };
  17056. Animatable.prototype.stop = function () {
  17057. var index = this._scene._activeAnimatables.indexOf(this);
  17058. if (index > -1) {
  17059. this._scene._activeAnimatables.splice(index, 1);
  17060. }
  17061. if (this.onAnimationEnd) {
  17062. this.onAnimationEnd();
  17063. }
  17064. };
  17065. Animatable.prototype._animate = function (delay) {
  17066. if (this._paused) {
  17067. if (!this._pausedDelay) {
  17068. this._pausedDelay = delay;
  17069. }
  17070. return true;
  17071. }
  17072. if (!this._localDelayOffset) {
  17073. this._localDelayOffset = delay;
  17074. }
  17075. else if (this._pausedDelay) {
  17076. this._localDelayOffset += delay - this._pausedDelay;
  17077. this._pausedDelay = null;
  17078. }
  17079. // Animating
  17080. var running = false;
  17081. var animations = this._animations;
  17082. for (var index = 0; index < animations.length; index++) {
  17083. var animation = animations[index];
  17084. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  17085. running = running || isRunning;
  17086. }
  17087. if (!running) {
  17088. // Remove from active animatables
  17089. index = this._scene._activeAnimatables.indexOf(this);
  17090. this._scene._activeAnimatables.splice(index, 1);
  17091. }
  17092. if (!running && this.onAnimationEnd) {
  17093. this.onAnimationEnd();
  17094. }
  17095. return running;
  17096. };
  17097. return Animatable;
  17098. })();
  17099. BABYLON.Animatable = Animatable;
  17100. })(BABYLON || (BABYLON = {}));
  17101. //# sourceMappingURL=babylon.animatable.js.map
  17102. var BABYLON;
  17103. (function (BABYLON) {
  17104. var EasingFunction = (function () {
  17105. function EasingFunction() {
  17106. // Properties
  17107. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  17108. }
  17109. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  17110. get: function () {
  17111. return EasingFunction._EASINGMODE_EASEIN;
  17112. },
  17113. enumerable: true,
  17114. configurable: true
  17115. });
  17116. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  17117. get: function () {
  17118. return EasingFunction._EASINGMODE_EASEOUT;
  17119. },
  17120. enumerable: true,
  17121. configurable: true
  17122. });
  17123. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  17124. get: function () {
  17125. return EasingFunction._EASINGMODE_EASEINOUT;
  17126. },
  17127. enumerable: true,
  17128. configurable: true
  17129. });
  17130. EasingFunction.prototype.setEasingMode = function (easingMode) {
  17131. var n = Math.min(Math.max(easingMode, 0), 2);
  17132. this._easingMode = n;
  17133. };
  17134. EasingFunction.prototype.getEasingMode = function () {
  17135. return this._easingMode;
  17136. };
  17137. EasingFunction.prototype.easeInCore = function (gradient) {
  17138. throw new Error('You must implement this method');
  17139. };
  17140. EasingFunction.prototype.ease = function (gradient) {
  17141. switch (this._easingMode) {
  17142. case EasingFunction.EASINGMODE_EASEIN:
  17143. return this.easeInCore(gradient);
  17144. case EasingFunction.EASINGMODE_EASEOUT:
  17145. return (1 - this.easeInCore(1 - gradient));
  17146. }
  17147. if (gradient >= 0.5) {
  17148. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  17149. }
  17150. return (this.easeInCore(gradient * 2) * 0.5);
  17151. };
  17152. //Statics
  17153. EasingFunction._EASINGMODE_EASEIN = 0;
  17154. EasingFunction._EASINGMODE_EASEOUT = 1;
  17155. EasingFunction._EASINGMODE_EASEINOUT = 2;
  17156. return EasingFunction;
  17157. })();
  17158. BABYLON.EasingFunction = EasingFunction;
  17159. var CircleEase = (function (_super) {
  17160. __extends(CircleEase, _super);
  17161. function CircleEase() {
  17162. _super.apply(this, arguments);
  17163. }
  17164. CircleEase.prototype.easeInCore = function (gradient) {
  17165. gradient = Math.max(0, Math.min(1, gradient));
  17166. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  17167. };
  17168. return CircleEase;
  17169. })(EasingFunction);
  17170. BABYLON.CircleEase = CircleEase;
  17171. var BackEase = (function (_super) {
  17172. __extends(BackEase, _super);
  17173. function BackEase(amplitude) {
  17174. if (amplitude === void 0) { amplitude = 1; }
  17175. _super.call(this);
  17176. this.amplitude = amplitude;
  17177. }
  17178. BackEase.prototype.easeInCore = function (gradient) {
  17179. var num = Math.max(0, this.amplitude);
  17180. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  17181. };
  17182. return BackEase;
  17183. })(EasingFunction);
  17184. BABYLON.BackEase = BackEase;
  17185. var BounceEase = (function (_super) {
  17186. __extends(BounceEase, _super);
  17187. function BounceEase(bounces, bounciness) {
  17188. if (bounces === void 0) { bounces = 3; }
  17189. if (bounciness === void 0) { bounciness = 2; }
  17190. _super.call(this);
  17191. this.bounces = bounces;
  17192. this.bounciness = bounciness;
  17193. }
  17194. BounceEase.prototype.easeInCore = function (gradient) {
  17195. var y = Math.max(0.0, this.bounces);
  17196. var bounciness = this.bounciness;
  17197. if (bounciness <= 1.0) {
  17198. bounciness = 1.001;
  17199. }
  17200. var num9 = Math.pow(bounciness, y);
  17201. var num5 = 1.0 - bounciness;
  17202. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  17203. var num15 = gradient * num4;
  17204. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  17205. var num3 = Math.floor(num65);
  17206. var num13 = num3 + 1.0;
  17207. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  17208. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  17209. var num7 = (num8 + num12) * 0.5;
  17210. var num6 = gradient - num7;
  17211. var num2 = num7 - num8;
  17212. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17213. };
  17214. return BounceEase;
  17215. })(EasingFunction);
  17216. BABYLON.BounceEase = BounceEase;
  17217. var CubicEase = (function (_super) {
  17218. __extends(CubicEase, _super);
  17219. function CubicEase() {
  17220. _super.apply(this, arguments);
  17221. }
  17222. CubicEase.prototype.easeInCore = function (gradient) {
  17223. return (gradient * gradient * gradient);
  17224. };
  17225. return CubicEase;
  17226. })(EasingFunction);
  17227. BABYLON.CubicEase = CubicEase;
  17228. var ElasticEase = (function (_super) {
  17229. __extends(ElasticEase, _super);
  17230. function ElasticEase(oscillations, springiness) {
  17231. if (oscillations === void 0) { oscillations = 3; }
  17232. if (springiness === void 0) { springiness = 3; }
  17233. _super.call(this);
  17234. this.oscillations = oscillations;
  17235. this.springiness = springiness;
  17236. }
  17237. ElasticEase.prototype.easeInCore = function (gradient) {
  17238. var num2;
  17239. var num3 = Math.max(0.0, this.oscillations);
  17240. var num = Math.max(0.0, this.springiness);
  17241. if (num == 0) {
  17242. num2 = gradient;
  17243. }
  17244. else {
  17245. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17246. }
  17247. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17248. };
  17249. return ElasticEase;
  17250. })(EasingFunction);
  17251. BABYLON.ElasticEase = ElasticEase;
  17252. var ExponentialEase = (function (_super) {
  17253. __extends(ExponentialEase, _super);
  17254. function ExponentialEase(exponent) {
  17255. if (exponent === void 0) { exponent = 2; }
  17256. _super.call(this);
  17257. this.exponent = exponent;
  17258. }
  17259. ExponentialEase.prototype.easeInCore = function (gradient) {
  17260. if (this.exponent <= 0) {
  17261. return gradient;
  17262. }
  17263. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17264. };
  17265. return ExponentialEase;
  17266. })(EasingFunction);
  17267. BABYLON.ExponentialEase = ExponentialEase;
  17268. var PowerEase = (function (_super) {
  17269. __extends(PowerEase, _super);
  17270. function PowerEase(power) {
  17271. if (power === void 0) { power = 2; }
  17272. _super.call(this);
  17273. this.power = power;
  17274. }
  17275. PowerEase.prototype.easeInCore = function (gradient) {
  17276. var y = Math.max(0.0, this.power);
  17277. return Math.pow(gradient, y);
  17278. };
  17279. return PowerEase;
  17280. })(EasingFunction);
  17281. BABYLON.PowerEase = PowerEase;
  17282. var QuadraticEase = (function (_super) {
  17283. __extends(QuadraticEase, _super);
  17284. function QuadraticEase() {
  17285. _super.apply(this, arguments);
  17286. }
  17287. QuadraticEase.prototype.easeInCore = function (gradient) {
  17288. return (gradient * gradient);
  17289. };
  17290. return QuadraticEase;
  17291. })(EasingFunction);
  17292. BABYLON.QuadraticEase = QuadraticEase;
  17293. var QuarticEase = (function (_super) {
  17294. __extends(QuarticEase, _super);
  17295. function QuarticEase() {
  17296. _super.apply(this, arguments);
  17297. }
  17298. QuarticEase.prototype.easeInCore = function (gradient) {
  17299. return (gradient * gradient * gradient * gradient);
  17300. };
  17301. return QuarticEase;
  17302. })(EasingFunction);
  17303. BABYLON.QuarticEase = QuarticEase;
  17304. var QuinticEase = (function (_super) {
  17305. __extends(QuinticEase, _super);
  17306. function QuinticEase() {
  17307. _super.apply(this, arguments);
  17308. }
  17309. QuinticEase.prototype.easeInCore = function (gradient) {
  17310. return (gradient * gradient * gradient * gradient * gradient);
  17311. };
  17312. return QuinticEase;
  17313. })(EasingFunction);
  17314. BABYLON.QuinticEase = QuinticEase;
  17315. var SineEase = (function (_super) {
  17316. __extends(SineEase, _super);
  17317. function SineEase() {
  17318. _super.apply(this, arguments);
  17319. }
  17320. SineEase.prototype.easeInCore = function (gradient) {
  17321. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17322. };
  17323. return SineEase;
  17324. })(EasingFunction);
  17325. BABYLON.SineEase = SineEase;
  17326. var BezierCurveEase = (function (_super) {
  17327. __extends(BezierCurveEase, _super);
  17328. function BezierCurveEase(x1, y1, x2, y2) {
  17329. if (x1 === void 0) { x1 = 0; }
  17330. if (y1 === void 0) { y1 = 0; }
  17331. if (x2 === void 0) { x2 = 1; }
  17332. if (y2 === void 0) { y2 = 1; }
  17333. _super.call(this);
  17334. this.x1 = x1;
  17335. this.y1 = y1;
  17336. this.x2 = x2;
  17337. this.y2 = y2;
  17338. }
  17339. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17340. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17341. };
  17342. return BezierCurveEase;
  17343. })(EasingFunction);
  17344. BABYLON.BezierCurveEase = BezierCurveEase;
  17345. })(BABYLON || (BABYLON = {}));
  17346. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17347. (function (BABYLON) {
  17348. var Octree = (function () {
  17349. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17350. if (maxDepth === void 0) { maxDepth = 2; }
  17351. this.maxDepth = maxDepth;
  17352. this.dynamicContent = new Array();
  17353. this._maxBlockCapacity = maxBlockCapacity || 64;
  17354. this._selectionContent = new BABYLON.SmartArray(1024);
  17355. this._creationFunc = creationFunc;
  17356. }
  17357. // Methods
  17358. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17359. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17360. };
  17361. Octree.prototype.addMesh = function (entry) {
  17362. for (var index = 0; index < this.blocks.length; index++) {
  17363. var block = this.blocks[index];
  17364. block.addEntry(entry);
  17365. }
  17366. };
  17367. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17368. this._selectionContent.reset();
  17369. for (var index = 0; index < this.blocks.length; index++) {
  17370. var block = this.blocks[index];
  17371. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17372. }
  17373. if (allowDuplicate) {
  17374. this._selectionContent.concat(this.dynamicContent);
  17375. }
  17376. else {
  17377. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17378. }
  17379. return this._selectionContent;
  17380. };
  17381. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17382. this._selectionContent.reset();
  17383. for (var index = 0; index < this.blocks.length; index++) {
  17384. var block = this.blocks[index];
  17385. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17386. }
  17387. if (allowDuplicate) {
  17388. this._selectionContent.concat(this.dynamicContent);
  17389. }
  17390. else {
  17391. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17392. }
  17393. return this._selectionContent;
  17394. };
  17395. Octree.prototype.intersectsRay = function (ray) {
  17396. this._selectionContent.reset();
  17397. for (var index = 0; index < this.blocks.length; index++) {
  17398. var block = this.blocks[index];
  17399. block.intersectsRay(ray, this._selectionContent);
  17400. }
  17401. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17402. return this._selectionContent;
  17403. };
  17404. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17405. target.blocks = new Array();
  17406. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17407. for (var x = 0; x < 2; x++) {
  17408. for (var y = 0; y < 2; y++) {
  17409. for (var z = 0; z < 2; z++) {
  17410. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17411. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17412. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17413. block.addEntries(entries);
  17414. target.blocks.push(block);
  17415. }
  17416. }
  17417. }
  17418. };
  17419. Octree.CreationFuncForMeshes = function (entry, block) {
  17420. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17421. block.entries.push(entry);
  17422. }
  17423. };
  17424. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17425. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17426. block.entries.push(entry);
  17427. }
  17428. };
  17429. return Octree;
  17430. })();
  17431. BABYLON.Octree = Octree;
  17432. })(BABYLON || (BABYLON = {}));
  17433. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17434. (function (BABYLON) {
  17435. var OctreeBlock = (function () {
  17436. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17437. this.entries = new Array();
  17438. this._boundingVectors = new Array();
  17439. this._capacity = capacity;
  17440. this._depth = depth;
  17441. this._maxDepth = maxDepth;
  17442. this._creationFunc = creationFunc;
  17443. this._minPoint = minPoint;
  17444. this._maxPoint = maxPoint;
  17445. this._boundingVectors.push(minPoint.clone());
  17446. this._boundingVectors.push(maxPoint.clone());
  17447. this._boundingVectors.push(minPoint.clone());
  17448. this._boundingVectors[2].x = maxPoint.x;
  17449. this._boundingVectors.push(minPoint.clone());
  17450. this._boundingVectors[3].y = maxPoint.y;
  17451. this._boundingVectors.push(minPoint.clone());
  17452. this._boundingVectors[4].z = maxPoint.z;
  17453. this._boundingVectors.push(maxPoint.clone());
  17454. this._boundingVectors[5].z = minPoint.z;
  17455. this._boundingVectors.push(maxPoint.clone());
  17456. this._boundingVectors[6].x = minPoint.x;
  17457. this._boundingVectors.push(maxPoint.clone());
  17458. this._boundingVectors[7].y = minPoint.y;
  17459. }
  17460. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17461. // Property
  17462. get: function () {
  17463. return this._capacity;
  17464. },
  17465. enumerable: true,
  17466. configurable: true
  17467. });
  17468. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17469. get: function () {
  17470. return this._minPoint;
  17471. },
  17472. enumerable: true,
  17473. configurable: true
  17474. });
  17475. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17476. get: function () {
  17477. return this._maxPoint;
  17478. },
  17479. enumerable: true,
  17480. configurable: true
  17481. });
  17482. // Methods
  17483. OctreeBlock.prototype.addEntry = function (entry) {
  17484. if (this.blocks) {
  17485. for (var index = 0; index < this.blocks.length; index++) {
  17486. var block = this.blocks[index];
  17487. block.addEntry(entry);
  17488. }
  17489. return;
  17490. }
  17491. this._creationFunc(entry, this);
  17492. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17493. this.createInnerBlocks();
  17494. }
  17495. };
  17496. OctreeBlock.prototype.addEntries = function (entries) {
  17497. for (var index = 0; index < entries.length; index++) {
  17498. var mesh = entries[index];
  17499. this.addEntry(mesh);
  17500. }
  17501. };
  17502. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17503. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17504. if (this.blocks) {
  17505. for (var index = 0; index < this.blocks.length; index++) {
  17506. var block = this.blocks[index];
  17507. block.select(frustumPlanes, selection, allowDuplicate);
  17508. }
  17509. return;
  17510. }
  17511. if (allowDuplicate) {
  17512. selection.concat(this.entries);
  17513. }
  17514. else {
  17515. selection.concatWithNoDuplicate(this.entries);
  17516. }
  17517. }
  17518. };
  17519. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17520. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17521. if (this.blocks) {
  17522. for (var index = 0; index < this.blocks.length; index++) {
  17523. var block = this.blocks[index];
  17524. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17525. }
  17526. return;
  17527. }
  17528. if (allowDuplicate) {
  17529. selection.concat(this.entries);
  17530. }
  17531. else {
  17532. selection.concatWithNoDuplicate(this.entries);
  17533. }
  17534. }
  17535. };
  17536. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17537. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17538. if (this.blocks) {
  17539. for (var index = 0; index < this.blocks.length; index++) {
  17540. var block = this.blocks[index];
  17541. block.intersectsRay(ray, selection);
  17542. }
  17543. return;
  17544. }
  17545. selection.concatWithNoDuplicate(this.entries);
  17546. }
  17547. };
  17548. OctreeBlock.prototype.createInnerBlocks = function () {
  17549. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17550. };
  17551. return OctreeBlock;
  17552. })();
  17553. BABYLON.OctreeBlock = OctreeBlock;
  17554. })(BABYLON || (BABYLON = {}));
  17555. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17556. (function (BABYLON) {
  17557. var Bone = (function () {
  17558. function Bone(name, skeleton, parentBone, matrix) {
  17559. this.name = name;
  17560. this.children = new Array();
  17561. this.animations = new Array();
  17562. this._worldTransform = new BABYLON.Matrix();
  17563. this._absoluteTransform = new BABYLON.Matrix();
  17564. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17565. this._skeleton = skeleton;
  17566. this._matrix = matrix;
  17567. this._baseMatrix = matrix;
  17568. skeleton.bones.push(this);
  17569. if (parentBone) {
  17570. this._parent = parentBone;
  17571. parentBone.children.push(this);
  17572. }
  17573. else {
  17574. this._parent = null;
  17575. }
  17576. this._updateDifferenceMatrix();
  17577. }
  17578. // Members
  17579. Bone.prototype.getParent = function () {
  17580. return this._parent;
  17581. };
  17582. Bone.prototype.getLocalMatrix = function () {
  17583. return this._matrix;
  17584. };
  17585. Bone.prototype.getBaseMatrix = function () {
  17586. return this._baseMatrix;
  17587. };
  17588. Bone.prototype.getWorldMatrix = function () {
  17589. return this._worldTransform;
  17590. };
  17591. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17592. return this._invertedAbsoluteTransform;
  17593. };
  17594. Bone.prototype.getAbsoluteMatrix = function () {
  17595. var matrix = this._matrix.clone();
  17596. var parent = this._parent;
  17597. while (parent) {
  17598. matrix = matrix.multiply(parent.getLocalMatrix());
  17599. parent = parent.getParent();
  17600. }
  17601. return matrix;
  17602. };
  17603. // Methods
  17604. Bone.prototype.updateMatrix = function (matrix) {
  17605. this._matrix = matrix;
  17606. this._skeleton._markAsDirty();
  17607. this._updateDifferenceMatrix();
  17608. };
  17609. Bone.prototype._updateDifferenceMatrix = function () {
  17610. if (this._parent) {
  17611. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17612. }
  17613. else {
  17614. this._absoluteTransform.copyFrom(this._matrix);
  17615. }
  17616. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17617. for (var index = 0; index < this.children.length; index++) {
  17618. this.children[index]._updateDifferenceMatrix();
  17619. }
  17620. };
  17621. Bone.prototype.markAsDirty = function () {
  17622. this._skeleton._markAsDirty();
  17623. };
  17624. return Bone;
  17625. })();
  17626. BABYLON.Bone = Bone;
  17627. })(BABYLON || (BABYLON = {}));
  17628. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17629. (function (BABYLON) {
  17630. var Skeleton = (function () {
  17631. function Skeleton(name, id, scene) {
  17632. this.name = name;
  17633. this.id = id;
  17634. this.bones = new Array();
  17635. this._isDirty = true;
  17636. this._identity = BABYLON.Matrix.Identity();
  17637. this.bones = [];
  17638. this._scene = scene;
  17639. scene.skeletons.push(this);
  17640. this.prepare();
  17641. //make sure it will recalculate the matrix next time prepare is called.
  17642. this._isDirty = true;
  17643. }
  17644. // Members
  17645. Skeleton.prototype.getTransformMatrices = function () {
  17646. return this._transformMatrices;
  17647. };
  17648. // Methods
  17649. Skeleton.prototype._markAsDirty = function () {
  17650. this._isDirty = true;
  17651. };
  17652. Skeleton.prototype.prepare = function () {
  17653. if (!this._isDirty) {
  17654. return;
  17655. }
  17656. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17657. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17658. }
  17659. for (var index = 0; index < this.bones.length; index++) {
  17660. var bone = this.bones[index];
  17661. var parentBone = bone.getParent();
  17662. if (parentBone) {
  17663. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17664. }
  17665. else {
  17666. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17667. }
  17668. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17669. }
  17670. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17671. this._isDirty = false;
  17672. this._scene._activeBones += this.bones.length;
  17673. };
  17674. Skeleton.prototype.getAnimatables = function () {
  17675. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17676. this._animatables = [];
  17677. for (var index = 0; index < this.bones.length; index++) {
  17678. this._animatables.push(this.bones[index]);
  17679. }
  17680. }
  17681. return this._animatables;
  17682. };
  17683. Skeleton.prototype.clone = function (name, id) {
  17684. var result = new Skeleton(name, id || name, this._scene);
  17685. for (var index = 0; index < this.bones.length; index++) {
  17686. var source = this.bones[index];
  17687. var parentBone = null;
  17688. if (source.getParent()) {
  17689. var parentIndex = this.bones.indexOf(source.getParent());
  17690. parentBone = result.bones[parentIndex];
  17691. }
  17692. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17693. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17694. }
  17695. return result;
  17696. };
  17697. return Skeleton;
  17698. })();
  17699. BABYLON.Skeleton = Skeleton;
  17700. })(BABYLON || (BABYLON = {}));
  17701. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17702. (function (BABYLON) {
  17703. var PostProcess = (function () {
  17704. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17706. this.name = name;
  17707. this.width = -1;
  17708. this.height = -1;
  17709. this._reusable = false;
  17710. this._textures = new BABYLON.SmartArray(2);
  17711. this._currentRenderTextureInd = 0;
  17712. if (camera != null) {
  17713. this._camera = camera;
  17714. this._scene = camera.getScene();
  17715. camera.attachPostProcess(this);
  17716. this._engine = this._scene.getEngine();
  17717. }
  17718. else {
  17719. this._engine = engine;
  17720. }
  17721. this._renderRatio = ratio;
  17722. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17723. this._reusable = reusable || false;
  17724. samplers = samplers || [];
  17725. samplers.push("textureSampler");
  17726. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17727. }
  17728. PostProcess.prototype.isReusable = function () {
  17729. return this._reusable;
  17730. };
  17731. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17732. camera = camera || this._camera;
  17733. var scene = camera.getScene();
  17734. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17735. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17736. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17737. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17738. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17739. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17740. if (this._textures.length > 0) {
  17741. for (var i = 0; i < this._textures.length; i++) {
  17742. this._engine._releaseTexture(this._textures.data[i]);
  17743. }
  17744. this._textures.reset();
  17745. }
  17746. this.width = desiredWidth;
  17747. this.height = desiredHeight;
  17748. 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 }));
  17749. if (this._reusable) {
  17750. 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 }));
  17751. }
  17752. if (this.onSizeChanged) {
  17753. this.onSizeChanged();
  17754. }
  17755. }
  17756. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17757. if (this.onActivate) {
  17758. this.onActivate(camera);
  17759. }
  17760. // Clear
  17761. if (this.clearColor) {
  17762. this._engine.clear(this.clearColor, true, true);
  17763. }
  17764. else {
  17765. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17766. }
  17767. if (this._reusable) {
  17768. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17769. }
  17770. };
  17771. PostProcess.prototype.apply = function () {
  17772. // Check
  17773. if (!this._effect.isReady())
  17774. return null;
  17775. // States
  17776. this._engine.enableEffect(this._effect);
  17777. this._engine.setState(false);
  17778. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17779. this._engine.setDepthBuffer(false);
  17780. this._engine.setDepthWrite(false);
  17781. // Texture
  17782. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17783. // Parameters
  17784. if (this.onApply) {
  17785. this.onApply(this._effect);
  17786. }
  17787. return this._effect;
  17788. };
  17789. PostProcess.prototype.dispose = function (camera) {
  17790. camera = camera || this._camera;
  17791. if (this._textures.length > 0) {
  17792. for (var i = 0; i < this._textures.length; i++) {
  17793. this._engine._releaseTexture(this._textures.data[i]);
  17794. }
  17795. this._textures.reset();
  17796. }
  17797. if (!camera) {
  17798. return;
  17799. }
  17800. camera.detachPostProcess(this);
  17801. var index = camera._postProcesses.indexOf(this);
  17802. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17803. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17804. }
  17805. };
  17806. return PostProcess;
  17807. })();
  17808. BABYLON.PostProcess = PostProcess;
  17809. })(BABYLON || (BABYLON = {}));
  17810. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17811. (function (BABYLON) {
  17812. var PostProcessManager = (function () {
  17813. function PostProcessManager(scene) {
  17814. this._vertexDeclaration = [2];
  17815. this._vertexStrideSize = 2 * 4;
  17816. this._scene = scene;
  17817. }
  17818. PostProcessManager.prototype._prepareBuffers = function () {
  17819. if (this._vertexBuffer) {
  17820. return;
  17821. }
  17822. // VBO
  17823. var vertices = [];
  17824. vertices.push(1, 1);
  17825. vertices.push(-1, 1);
  17826. vertices.push(-1, -1);
  17827. vertices.push(1, -1);
  17828. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17829. // Indices
  17830. var indices = [];
  17831. indices.push(0);
  17832. indices.push(1);
  17833. indices.push(2);
  17834. indices.push(0);
  17835. indices.push(2);
  17836. indices.push(3);
  17837. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17838. };
  17839. // Methods
  17840. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17841. var postProcesses = this._scene.activeCamera._postProcesses;
  17842. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17843. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17844. return false;
  17845. }
  17846. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17847. return true;
  17848. };
  17849. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17850. var engine = this._scene.getEngine();
  17851. for (var index = 0; index < postProcesses.length; index++) {
  17852. if (index < postProcesses.length - 1) {
  17853. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17854. }
  17855. else {
  17856. if (targetTexture) {
  17857. engine.bindFramebuffer(targetTexture);
  17858. }
  17859. else {
  17860. engine.restoreDefaultFramebuffer();
  17861. }
  17862. }
  17863. var pp = postProcesses[index];
  17864. var effect = pp.apply();
  17865. if (effect) {
  17866. if (pp.onBeforeRender) {
  17867. pp.onBeforeRender(effect);
  17868. }
  17869. // VBOs
  17870. this._prepareBuffers();
  17871. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17872. // Draw order
  17873. engine.draw(true, 0, 6);
  17874. }
  17875. }
  17876. // Restore depth buffer
  17877. engine.setDepthBuffer(true);
  17878. engine.setDepthWrite(true);
  17879. };
  17880. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17881. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17882. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17883. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17884. return;
  17885. }
  17886. var engine = this._scene.getEngine();
  17887. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17888. if (index < postProcessesTakenIndices.length - 1) {
  17889. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17890. }
  17891. else {
  17892. if (targetTexture) {
  17893. engine.bindFramebuffer(targetTexture);
  17894. }
  17895. else {
  17896. engine.restoreDefaultFramebuffer();
  17897. }
  17898. }
  17899. if (doNotPresent) {
  17900. break;
  17901. }
  17902. var pp = postProcesses[postProcessesTakenIndices[index]];
  17903. var effect = pp.apply();
  17904. if (effect) {
  17905. if (pp.onBeforeRender) {
  17906. pp.onBeforeRender(effect);
  17907. }
  17908. // VBOs
  17909. this._prepareBuffers();
  17910. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17911. // Draw order
  17912. engine.draw(true, 0, 6);
  17913. }
  17914. }
  17915. // Restore depth buffer
  17916. engine.setDepthBuffer(true);
  17917. engine.setDepthWrite(true);
  17918. };
  17919. PostProcessManager.prototype.dispose = function () {
  17920. if (this._vertexBuffer) {
  17921. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17922. this._vertexBuffer = null;
  17923. }
  17924. if (this._indexBuffer) {
  17925. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17926. this._indexBuffer = null;
  17927. }
  17928. };
  17929. return PostProcessManager;
  17930. })();
  17931. BABYLON.PostProcessManager = PostProcessManager;
  17932. })(BABYLON || (BABYLON = {}));
  17933. //# sourceMappingURL=babylon.postProcessManager.js.map
  17934. var BABYLON;
  17935. (function (BABYLON) {
  17936. var PassPostProcess = (function (_super) {
  17937. __extends(PassPostProcess, _super);
  17938. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17939. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17940. }
  17941. return PassPostProcess;
  17942. })(BABYLON.PostProcess);
  17943. BABYLON.PassPostProcess = PassPostProcess;
  17944. })(BABYLON || (BABYLON = {}));
  17945. //# sourceMappingURL=babylon.passPostProcess.js.map
  17946. var BABYLON;
  17947. (function (BABYLON) {
  17948. var BlurPostProcess = (function (_super) {
  17949. __extends(BlurPostProcess, _super);
  17950. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17951. var _this = this;
  17952. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17953. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17954. this.direction = direction;
  17955. this.blurWidth = blurWidth;
  17956. this.onApply = function (effect) {
  17957. effect.setFloat2("screenSize", _this.width, _this.height);
  17958. effect.setVector2("direction", _this.direction);
  17959. effect.setFloat("blurWidth", _this.blurWidth);
  17960. };
  17961. }
  17962. return BlurPostProcess;
  17963. })(BABYLON.PostProcess);
  17964. BABYLON.BlurPostProcess = BlurPostProcess;
  17965. })(BABYLON || (BABYLON = {}));
  17966. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17967. var BABYLON;
  17968. (function (BABYLON) {
  17969. var FilterPostProcess = (function (_super) {
  17970. __extends(FilterPostProcess, _super);
  17971. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17972. var _this = this;
  17973. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17974. this.kernelMatrix = kernelMatrix;
  17975. this.onApply = function (effect) {
  17976. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17977. };
  17978. }
  17979. return FilterPostProcess;
  17980. })(BABYLON.PostProcess);
  17981. BABYLON.FilterPostProcess = FilterPostProcess;
  17982. })(BABYLON || (BABYLON = {}));
  17983. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17984. var BABYLON;
  17985. (function (BABYLON) {
  17986. var RefractionPostProcess = (function (_super) {
  17987. __extends(RefractionPostProcess, _super);
  17988. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17989. var _this = this;
  17990. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17991. this.color = color;
  17992. this.depth = depth;
  17993. this.colorLevel = colorLevel;
  17994. this.onActivate = function (cam) {
  17995. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17996. };
  17997. this.onApply = function (effect) {
  17998. effect.setColor3("baseColor", _this.color);
  17999. effect.setFloat("depth", _this.depth);
  18000. effect.setFloat("colorLevel", _this.colorLevel);
  18001. effect.setTexture("refractionSampler", _this._refRexture);
  18002. };
  18003. }
  18004. // Methods
  18005. RefractionPostProcess.prototype.dispose = function (camera) {
  18006. if (this._refRexture) {
  18007. this._refRexture.dispose();
  18008. }
  18009. _super.prototype.dispose.call(this, camera);
  18010. };
  18011. return RefractionPostProcess;
  18012. })(BABYLON.PostProcess);
  18013. BABYLON.RefractionPostProcess = RefractionPostProcess;
  18014. })(BABYLON || (BABYLON = {}));
  18015. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  18016. var BABYLON;
  18017. (function (BABYLON) {
  18018. var BlackAndWhitePostProcess = (function (_super) {
  18019. __extends(BlackAndWhitePostProcess, _super);
  18020. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18021. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  18022. }
  18023. return BlackAndWhitePostProcess;
  18024. })(BABYLON.PostProcess);
  18025. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  18026. })(BABYLON || (BABYLON = {}));
  18027. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  18028. var BABYLON;
  18029. (function (BABYLON) {
  18030. var ConvolutionPostProcess = (function (_super) {
  18031. __extends(ConvolutionPostProcess, _super);
  18032. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  18033. var _this = this;
  18034. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  18035. this.kernel = kernel;
  18036. this.onApply = function (effect) {
  18037. effect.setFloat2("screenSize", _this.width, _this.height);
  18038. effect.setArray("kernel", _this.kernel);
  18039. };
  18040. }
  18041. // Statics
  18042. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  18043. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  18044. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  18045. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  18046. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  18047. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  18048. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  18049. return ConvolutionPostProcess;
  18050. })(BABYLON.PostProcess);
  18051. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  18052. })(BABYLON || (BABYLON = {}));
  18053. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  18054. var BABYLON;
  18055. (function (BABYLON) {
  18056. var FxaaPostProcess = (function (_super) {
  18057. __extends(FxaaPostProcess, _super);
  18058. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18059. var _this = this;
  18060. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  18061. this.onSizeChanged = function () {
  18062. _this.texelWidth = 1.0 / _this.width;
  18063. _this.texelHeight = 1.0 / _this.height;
  18064. };
  18065. this.onApply = function (effect) {
  18066. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  18067. };
  18068. }
  18069. return FxaaPostProcess;
  18070. })(BABYLON.PostProcess);
  18071. BABYLON.FxaaPostProcess = FxaaPostProcess;
  18072. })(BABYLON || (BABYLON = {}));
  18073. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  18074. (function (BABYLON) {
  18075. var LensFlare = (function () {
  18076. function LensFlare(size, position, color, imgUrl, system) {
  18077. this.size = size;
  18078. this.position = position;
  18079. this.dispose = function () {
  18080. if (this.texture) {
  18081. this.texture.dispose();
  18082. }
  18083. // Remove from scene
  18084. var index = this._system.lensFlares.indexOf(this);
  18085. this._system.lensFlares.splice(index, 1);
  18086. };
  18087. this.color = color || new BABYLON.Color3(1, 1, 1);
  18088. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  18089. this._system = system;
  18090. system.lensFlares.push(this);
  18091. }
  18092. return LensFlare;
  18093. })();
  18094. BABYLON.LensFlare = LensFlare;
  18095. })(BABYLON || (BABYLON = {}));
  18096. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  18097. (function (BABYLON) {
  18098. var LensFlareSystem = (function () {
  18099. function LensFlareSystem(name, emitter, scene) {
  18100. this.name = name;
  18101. this.lensFlares = new Array();
  18102. this.borderLimit = 300;
  18103. this._vertexDeclaration = [2];
  18104. this._vertexStrideSize = 2 * 4;
  18105. this._isEnabled = true;
  18106. this._scene = scene;
  18107. this._emitter = emitter;
  18108. scene.lensFlareSystems.push(this);
  18109. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  18110. // VBO
  18111. var vertices = [];
  18112. vertices.push(1, 1);
  18113. vertices.push(-1, 1);
  18114. vertices.push(-1, -1);
  18115. vertices.push(1, -1);
  18116. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18117. // Indices
  18118. var indices = [];
  18119. indices.push(0);
  18120. indices.push(1);
  18121. indices.push(2);
  18122. indices.push(0);
  18123. indices.push(2);
  18124. indices.push(3);
  18125. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18126. // Effects
  18127. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  18128. }
  18129. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  18130. get: function () {
  18131. return this._isEnabled;
  18132. },
  18133. set: function (value) {
  18134. this._isEnabled = value;
  18135. },
  18136. enumerable: true,
  18137. configurable: true
  18138. });
  18139. LensFlareSystem.prototype.getScene = function () {
  18140. return this._scene;
  18141. };
  18142. LensFlareSystem.prototype.getEmitter = function () {
  18143. return this._emitter;
  18144. };
  18145. LensFlareSystem.prototype.getEmitterPosition = function () {
  18146. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  18147. };
  18148. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  18149. var position = this.getEmitterPosition();
  18150. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  18151. this._positionX = position.x;
  18152. this._positionY = position.y;
  18153. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  18154. if (position.z > 0) {
  18155. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  18156. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  18157. return true;
  18158. }
  18159. }
  18160. return false;
  18161. };
  18162. LensFlareSystem.prototype._isVisible = function () {
  18163. if (!this._isEnabled) {
  18164. return false;
  18165. }
  18166. var emitterPosition = this.getEmitterPosition();
  18167. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  18168. var distance = direction.length();
  18169. direction.normalize();
  18170. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  18171. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  18172. return !pickInfo.hit || pickInfo.distance > distance;
  18173. };
  18174. LensFlareSystem.prototype.render = function () {
  18175. if (!this._effect.isReady())
  18176. return false;
  18177. var engine = this._scene.getEngine();
  18178. var viewport = this._scene.activeCamera.viewport;
  18179. var globalViewport = viewport.toGlobal(engine);
  18180. // Position
  18181. if (!this.computeEffectivePosition(globalViewport)) {
  18182. return false;
  18183. }
  18184. // Visibility
  18185. if (!this._isVisible()) {
  18186. return false;
  18187. }
  18188. // Intensity
  18189. var awayX;
  18190. var awayY;
  18191. if (this._positionX < this.borderLimit + globalViewport.x) {
  18192. awayX = this.borderLimit + globalViewport.x - this._positionX;
  18193. }
  18194. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  18195. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  18196. }
  18197. else {
  18198. awayX = 0;
  18199. }
  18200. if (this._positionY < this.borderLimit + globalViewport.y) {
  18201. awayY = this.borderLimit + globalViewport.y - this._positionY;
  18202. }
  18203. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  18204. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  18205. }
  18206. else {
  18207. awayY = 0;
  18208. }
  18209. var away = (awayX > awayY) ? awayX : awayY;
  18210. if (away > this.borderLimit) {
  18211. away = this.borderLimit;
  18212. }
  18213. var intensity = 1.0 - (away / this.borderLimit);
  18214. if (intensity < 0) {
  18215. return false;
  18216. }
  18217. if (intensity > 1.0) {
  18218. intensity = 1.0;
  18219. }
  18220. // Position
  18221. var centerX = globalViewport.x + globalViewport.width / 2;
  18222. var centerY = globalViewport.y + globalViewport.height / 2;
  18223. var distX = centerX - this._positionX;
  18224. var distY = centerY - this._positionY;
  18225. // Effects
  18226. engine.enableEffect(this._effect);
  18227. engine.setState(false);
  18228. engine.setDepthBuffer(false);
  18229. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18230. // VBOs
  18231. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18232. for (var index = 0; index < this.lensFlares.length; index++) {
  18233. var flare = this.lensFlares[index];
  18234. var x = centerX - (distX * flare.position);
  18235. var y = centerY - (distY * flare.position);
  18236. var cw = flare.size;
  18237. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18238. var cx = 2 * (x / globalViewport.width) - 1.0;
  18239. var cy = 1.0 - 2 * (y / globalViewport.height);
  18240. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18241. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18242. // Texture
  18243. this._effect.setTexture("textureSampler", flare.texture);
  18244. // Color
  18245. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18246. // Draw order
  18247. engine.draw(true, 0, 6);
  18248. }
  18249. engine.setDepthBuffer(true);
  18250. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18251. return true;
  18252. };
  18253. LensFlareSystem.prototype.dispose = function () {
  18254. if (this._vertexBuffer) {
  18255. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18256. this._vertexBuffer = null;
  18257. }
  18258. if (this._indexBuffer) {
  18259. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18260. this._indexBuffer = null;
  18261. }
  18262. while (this.lensFlares.length) {
  18263. this.lensFlares[0].dispose();
  18264. }
  18265. // Remove from scene
  18266. var index = this._scene.lensFlareSystems.indexOf(this);
  18267. this._scene.lensFlareSystems.splice(index, 1);
  18268. };
  18269. return LensFlareSystem;
  18270. })();
  18271. BABYLON.LensFlareSystem = LensFlareSystem;
  18272. })(BABYLON || (BABYLON = {}));
  18273. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18274. (function (BABYLON) {
  18275. var IntersectionInfo = (function () {
  18276. function IntersectionInfo(bu, bv, distance) {
  18277. this.bu = bu;
  18278. this.bv = bv;
  18279. this.distance = distance;
  18280. this.faceId = 0;
  18281. this.subMeshId = 0;
  18282. }
  18283. return IntersectionInfo;
  18284. })();
  18285. BABYLON.IntersectionInfo = IntersectionInfo;
  18286. var PickingInfo = (function () {
  18287. function PickingInfo() {
  18288. this.hit = false;
  18289. this.distance = 0;
  18290. this.pickedPoint = null;
  18291. this.pickedMesh = null;
  18292. this.bu = 0;
  18293. this.bv = 0;
  18294. this.faceId = -1;
  18295. this.subMeshId = 0;
  18296. }
  18297. // Methods
  18298. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18299. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18300. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18301. return null;
  18302. }
  18303. var indices = this.pickedMesh.getIndices();
  18304. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18305. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18306. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18307. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18308. normal0 = normal0.scale(this.bu);
  18309. normal1 = normal1.scale(this.bv);
  18310. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18311. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18312. if (useWorldCoordinates) {
  18313. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18314. }
  18315. return result;
  18316. };
  18317. PickingInfo.prototype.getTextureCoordinates = function () {
  18318. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18319. return null;
  18320. }
  18321. var indices = this.pickedMesh.getIndices();
  18322. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18323. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18324. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18325. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18326. uv0 = uv0.scale(this.bu);
  18327. uv1 = uv1.scale(this.bv);
  18328. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18329. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18330. };
  18331. return PickingInfo;
  18332. })();
  18333. BABYLON.PickingInfo = PickingInfo;
  18334. })(BABYLON || (BABYLON = {}));
  18335. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18336. (function (BABYLON) {
  18337. var FilesInput = (function () {
  18338. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18339. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18340. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18341. this._engine = p_engine;
  18342. this._canvas = p_canvas;
  18343. this._currentScene = p_scene;
  18344. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18345. this._progressCallback = p_progressCallback;
  18346. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18347. this._textureLoadingCallback = p_textureLoadingCallback;
  18348. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18349. }
  18350. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18351. var _this = this;
  18352. if (p_elementToMonitor) {
  18353. this._elementToMonitor = p_elementToMonitor;
  18354. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18355. _this.drag(e);
  18356. }, false);
  18357. this._elementToMonitor.addEventListener("dragover", function (e) {
  18358. _this.drag(e);
  18359. }, false);
  18360. this._elementToMonitor.addEventListener("drop", function (e) {
  18361. _this.drop(e);
  18362. }, false);
  18363. }
  18364. };
  18365. FilesInput.prototype.renderFunction = function () {
  18366. if (this._additionnalRenderLoopLogicCallback) {
  18367. this._additionnalRenderLoopLogicCallback();
  18368. }
  18369. if (this._currentScene) {
  18370. if (this._textureLoadingCallback) {
  18371. var remaining = this._currentScene.getWaitingItemsCount();
  18372. if (remaining > 0) {
  18373. this._textureLoadingCallback(remaining);
  18374. }
  18375. }
  18376. this._currentScene.render();
  18377. }
  18378. };
  18379. FilesInput.prototype.drag = function (e) {
  18380. e.stopPropagation();
  18381. e.preventDefault();
  18382. };
  18383. FilesInput.prototype.drop = function (eventDrop) {
  18384. eventDrop.stopPropagation();
  18385. eventDrop.preventDefault();
  18386. this.loadFiles(eventDrop);
  18387. };
  18388. FilesInput.prototype.loadFiles = function (event) {
  18389. if (this._startingProcessingFilesCallback)
  18390. this._startingProcessingFilesCallback();
  18391. // Handling data transfer via drag'n'drop
  18392. if (event && event.dataTransfer && event.dataTransfer.files) {
  18393. this._filesToLoad = event.dataTransfer.files;
  18394. }
  18395. // Handling files from input files
  18396. if (event && event.target && event.target.files) {
  18397. this._filesToLoad = event.target.files;
  18398. }
  18399. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18400. for (var i = 0; i < this._filesToLoad.length; i++) {
  18401. switch (this._filesToLoad[i].type) {
  18402. case "image/jpeg":
  18403. case "image/png":
  18404. case "image/bmp":
  18405. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18406. break;
  18407. case "image/targa":
  18408. case "image/vnd.ms-dds":
  18409. case "audio/wav":
  18410. case "audio/x-wav":
  18411. case "audio/mp3":
  18412. case "audio/mpeg":
  18413. case "audio/mpeg3":
  18414. case "audio/x-mpeg-3":
  18415. case "audio/ogg":
  18416. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18417. break;
  18418. default:
  18419. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  18420. this._sceneFileToLoad = this._filesToLoad[i];
  18421. }
  18422. break;
  18423. }
  18424. }
  18425. this.reload();
  18426. }
  18427. };
  18428. FilesInput.prototype.reload = function () {
  18429. var _this = this;
  18430. var that = this;
  18431. // If a ".babylon" file has been provided
  18432. if (this._sceneFileToLoad) {
  18433. if (this._currentScene) {
  18434. this._engine.stopRenderLoop();
  18435. this._currentScene.dispose();
  18436. }
  18437. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18438. that._currentScene = newScene;
  18439. // Wait for textures and shaders to be ready
  18440. that._currentScene.executeWhenReady(function () {
  18441. // Attach camera to canvas inputs
  18442. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18443. that._currentScene.createDefaultCameraOrLight();
  18444. }
  18445. that._currentScene.activeCamera.attachControl(that._canvas);
  18446. if (that._sceneLoadedCallback) {
  18447. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18448. }
  18449. that._engine.runRenderLoop(function () {
  18450. that.renderFunction();
  18451. });
  18452. });
  18453. }, function (progress) {
  18454. if (_this._progressCallback) {
  18455. _this._progressCallback(progress);
  18456. }
  18457. });
  18458. }
  18459. else {
  18460. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18461. }
  18462. };
  18463. FilesInput.FilesTextures = new Array();
  18464. FilesInput.FilesToLoad = new Array();
  18465. return FilesInput;
  18466. })();
  18467. BABYLON.FilesInput = FilesInput;
  18468. })(BABYLON || (BABYLON = {}));
  18469. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18470. (function (BABYLON) {
  18471. var OimoJSPlugin = (function () {
  18472. function OimoJSPlugin() {
  18473. this._registeredMeshes = [];
  18474. /**
  18475. * Update the body position according to the mesh position
  18476. * @param mesh
  18477. */
  18478. this.updateBodyPosition = function (mesh) {
  18479. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18480. var registeredMesh = this._registeredMeshes[index];
  18481. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18482. var body = registeredMesh.body.body;
  18483. mesh.computeWorldMatrix(true);
  18484. var center = mesh.getBoundingInfo().boundingBox.center;
  18485. body.setPosition(center.x, center.y, center.z);
  18486. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18487. return;
  18488. }
  18489. // Case where the parent has been updated
  18490. if (registeredMesh.mesh.parent === mesh) {
  18491. mesh.computeWorldMatrix(true);
  18492. registeredMesh.mesh.computeWorldMatrix(true);
  18493. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18494. var absoluteRotation = mesh.rotation;
  18495. body = registeredMesh.body.body;
  18496. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18497. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18498. return;
  18499. }
  18500. }
  18501. };
  18502. }
  18503. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18504. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18505. };
  18506. OimoJSPlugin.prototype.initialize = function (iterations) {
  18507. this._world = new OIMO.World();
  18508. this._world.clear();
  18509. };
  18510. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18511. this._world.gravity = gravity;
  18512. };
  18513. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18514. var body = null;
  18515. this.unregisterMesh(mesh);
  18516. mesh.computeWorldMatrix(true);
  18517. var initialRotation = null;
  18518. if (mesh.rotationQuaternion) {
  18519. initialRotation = mesh.rotationQuaternion.clone();
  18520. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18521. mesh.computeWorldMatrix(true);
  18522. }
  18523. var bbox = mesh.getBoundingInfo().boundingBox;
  18524. // The delta between the mesh position and the mesh bounding box center
  18525. var deltaPosition = mesh.position.subtract(bbox.center);
  18526. // Transform delta position with the rotation
  18527. if (initialRotation) {
  18528. var m = new BABYLON.Matrix();
  18529. initialRotation.toRotationMatrix(m);
  18530. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18531. }
  18532. switch (impostor) {
  18533. case BABYLON.PhysicsEngine.SphereImpostor:
  18534. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18535. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18536. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18537. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18538. body = new OIMO.Body({
  18539. type: 'sphere',
  18540. size: [size],
  18541. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18542. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18543. move: options.mass != 0,
  18544. config: [options.mass, options.friction, options.restitution],
  18545. world: this._world
  18546. });
  18547. break;
  18548. case BABYLON.PhysicsEngine.PlaneImpostor:
  18549. case BABYLON.PhysicsEngine.CylinderImpostor:
  18550. case BABYLON.PhysicsEngine.BoxImpostor:
  18551. var min = bbox.minimumWorld;
  18552. var max = bbox.maximumWorld;
  18553. var box = max.subtract(min);
  18554. var sizeX = this._checkWithEpsilon(box.x);
  18555. var sizeY = this._checkWithEpsilon(box.y);
  18556. var sizeZ = this._checkWithEpsilon(box.z);
  18557. body = new OIMO.Body({
  18558. type: 'box',
  18559. size: [sizeX, sizeY, sizeZ],
  18560. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18561. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18562. move: options.mass != 0,
  18563. config: [options.mass, options.friction, options.restitution],
  18564. world: this._world
  18565. });
  18566. break;
  18567. }
  18568. //If quaternion was set as the rotation of the object
  18569. if (initialRotation) {
  18570. //We have to access the rigid body's properties to set the quaternion.
  18571. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18572. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18573. //update the internal rotation matrix
  18574. body.body.syncShapes();
  18575. }
  18576. this._registeredMeshes.push({
  18577. mesh: mesh,
  18578. body: body,
  18579. delta: deltaPosition
  18580. });
  18581. return body;
  18582. };
  18583. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18584. var types = [], sizes = [], positions = [], rotations = [];
  18585. var initialMesh = parts[0].mesh;
  18586. for (var index = 0; index < parts.length; index++) {
  18587. var part = parts[index];
  18588. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18589. types.push(bodyParameters.type);
  18590. sizes.push.apply(sizes, bodyParameters.size);
  18591. positions.push.apply(positions, bodyParameters.pos);
  18592. rotations.push.apply(rotations, bodyParameters.rot);
  18593. }
  18594. var body = new OIMO.Body({
  18595. type: types,
  18596. size: sizes,
  18597. pos: positions,
  18598. rot: rotations,
  18599. move: options.mass != 0,
  18600. config: [options.mass, options.friction, options.restitution],
  18601. world: this._world
  18602. });
  18603. this._registeredMeshes.push({
  18604. mesh: initialMesh,
  18605. body: body
  18606. });
  18607. return body;
  18608. };
  18609. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18610. var bodyParameters = null;
  18611. var mesh = part.mesh;
  18612. // We need the bounding box/sphere info to compute the physics body
  18613. mesh.computeWorldMatrix();
  18614. switch (part.impostor) {
  18615. case BABYLON.PhysicsEngine.SphereImpostor:
  18616. var bbox = mesh.getBoundingInfo().boundingBox;
  18617. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18618. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18619. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18620. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18621. bodyParameters = {
  18622. type: 'sphere',
  18623. /* bug with oimo : sphere needs 3 sizes in this case */
  18624. size: [size, -1, -1],
  18625. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18626. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18627. };
  18628. break;
  18629. case BABYLON.PhysicsEngine.PlaneImpostor:
  18630. case BABYLON.PhysicsEngine.BoxImpostor:
  18631. bbox = mesh.getBoundingInfo().boundingBox;
  18632. var min = bbox.minimumWorld;
  18633. var max = bbox.maximumWorld;
  18634. var box = max.subtract(min);
  18635. var sizeX = this._checkWithEpsilon(box.x);
  18636. var sizeY = this._checkWithEpsilon(box.y);
  18637. var sizeZ = this._checkWithEpsilon(box.z);
  18638. var relativePosition = mesh.position;
  18639. bodyParameters = {
  18640. type: 'box',
  18641. size: [sizeX, sizeY, sizeZ],
  18642. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18643. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18644. };
  18645. break;
  18646. }
  18647. return bodyParameters;
  18648. };
  18649. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18650. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18651. var registeredMesh = this._registeredMeshes[index];
  18652. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18653. if (registeredMesh.body) {
  18654. this._world.removeRigidBody(registeredMesh.body.body);
  18655. this._unbindBody(registeredMesh.body);
  18656. }
  18657. this._registeredMeshes.splice(index, 1);
  18658. return;
  18659. }
  18660. }
  18661. };
  18662. OimoJSPlugin.prototype._unbindBody = function (body) {
  18663. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18664. var registeredMesh = this._registeredMeshes[index];
  18665. if (registeredMesh.body === body) {
  18666. registeredMesh.body = null;
  18667. }
  18668. }
  18669. };
  18670. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18671. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18672. var registeredMesh = this._registeredMeshes[index];
  18673. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18674. // Get object mass to have a behaviour similar to cannon.js
  18675. var mass = registeredMesh.body.body.massInfo.mass;
  18676. // The force is scaled with the mass of object
  18677. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18678. return;
  18679. }
  18680. }
  18681. };
  18682. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18683. var body1 = null, body2 = null;
  18684. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18685. var registeredMesh = this._registeredMeshes[index];
  18686. if (registeredMesh.mesh === mesh1) {
  18687. body1 = registeredMesh.body.body;
  18688. }
  18689. else if (registeredMesh.mesh === mesh2) {
  18690. body2 = registeredMesh.body.body;
  18691. }
  18692. }
  18693. if (!body1 || !body2) {
  18694. return false;
  18695. }
  18696. if (!options) {
  18697. options = {};
  18698. }
  18699. new OIMO.Link({
  18700. type: options.type,
  18701. body1: body1,
  18702. body2: body2,
  18703. min: options.min,
  18704. max: options.max,
  18705. axe1: options.axe1,
  18706. axe2: options.axe2,
  18707. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18708. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18709. collision: options.collision,
  18710. spring: options.spring,
  18711. world: this._world
  18712. });
  18713. return true;
  18714. };
  18715. OimoJSPlugin.prototype.dispose = function () {
  18716. this._world.clear();
  18717. while (this._registeredMeshes.length) {
  18718. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18719. }
  18720. };
  18721. OimoJSPlugin.prototype.isSupported = function () {
  18722. return OIMO !== undefined;
  18723. };
  18724. OimoJSPlugin.prototype._getLastShape = function (body) {
  18725. var lastShape = body.shapes;
  18726. while (lastShape.next) {
  18727. lastShape = lastShape.next;
  18728. }
  18729. return lastShape;
  18730. };
  18731. OimoJSPlugin.prototype.runOneStep = function (time) {
  18732. this._world.step();
  18733. // Update the position of all registered meshes
  18734. var i = this._registeredMeshes.length;
  18735. var m;
  18736. while (i--) {
  18737. var body = this._registeredMeshes[i].body.body;
  18738. var mesh = this._registeredMeshes[i].mesh;
  18739. var delta = this._registeredMeshes[i].delta;
  18740. if (!body.sleeping) {
  18741. if (body.shapes.next) {
  18742. var parentShape = this._getLastShape(body);
  18743. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18744. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18745. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18746. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18747. if (!mesh.rotationQuaternion) {
  18748. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18749. }
  18750. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18751. mesh.computeWorldMatrix();
  18752. }
  18753. else {
  18754. m = body.getMatrix();
  18755. mtx = BABYLON.Matrix.FromArray(m);
  18756. // Body position
  18757. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18758. if (!delta) {
  18759. mesh.position.x = bodyX;
  18760. mesh.position.y = bodyY;
  18761. mesh.position.z = bodyZ;
  18762. }
  18763. else {
  18764. mesh.position.x = bodyX + delta.x;
  18765. mesh.position.y = bodyY + delta.y;
  18766. mesh.position.z = bodyZ + delta.z;
  18767. }
  18768. if (!mesh.rotationQuaternion) {
  18769. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18770. }
  18771. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18772. mesh.computeWorldMatrix();
  18773. }
  18774. }
  18775. }
  18776. };
  18777. return OimoJSPlugin;
  18778. })();
  18779. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18780. })(BABYLON || (BABYLON = {}));
  18781. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18782. (function (BABYLON) {
  18783. var PhysicsEngine = (function () {
  18784. function PhysicsEngine(plugin) {
  18785. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18786. }
  18787. PhysicsEngine.prototype._initialize = function (gravity) {
  18788. this._currentPlugin.initialize();
  18789. this._setGravity(gravity);
  18790. };
  18791. PhysicsEngine.prototype._runOneStep = function (delta) {
  18792. if (delta > 0.1) {
  18793. delta = 0.1;
  18794. }
  18795. else if (delta <= 0) {
  18796. delta = 1.0 / 60.0;
  18797. }
  18798. this._currentPlugin.runOneStep(delta);
  18799. };
  18800. PhysicsEngine.prototype._setGravity = function (gravity) {
  18801. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18802. this._currentPlugin.setGravity(this.gravity);
  18803. };
  18804. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18805. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18806. };
  18807. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18808. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18809. };
  18810. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18811. this._currentPlugin.unregisterMesh(mesh);
  18812. };
  18813. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18814. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18815. };
  18816. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18817. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18818. };
  18819. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18820. this._currentPlugin.updateBodyPosition(mesh);
  18821. };
  18822. PhysicsEngine.prototype.dispose = function () {
  18823. this._currentPlugin.dispose();
  18824. };
  18825. PhysicsEngine.prototype.isSupported = function () {
  18826. return this._currentPlugin.isSupported();
  18827. };
  18828. // Statics
  18829. PhysicsEngine.NoImpostor = 0;
  18830. PhysicsEngine.SphereImpostor = 1;
  18831. PhysicsEngine.BoxImpostor = 2;
  18832. PhysicsEngine.PlaneImpostor = 3;
  18833. PhysicsEngine.MeshImpostor = 4;
  18834. PhysicsEngine.CapsuleImpostor = 5;
  18835. PhysicsEngine.ConeImpostor = 6;
  18836. PhysicsEngine.CylinderImpostor = 7;
  18837. PhysicsEngine.ConvexHullImpostor = 8;
  18838. PhysicsEngine.Epsilon = 0.001;
  18839. return PhysicsEngine;
  18840. })();
  18841. BABYLON.PhysicsEngine = PhysicsEngine;
  18842. })(BABYLON || (BABYLON = {}));
  18843. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18844. (function (BABYLON) {
  18845. var serializeLight = function (light) {
  18846. var serializationObject = {};
  18847. serializationObject.name = light.name;
  18848. serializationObject.id = light.id;
  18849. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18850. if (light instanceof BABYLON.PointLight) {
  18851. serializationObject.type = 0;
  18852. serializationObject.position = light.position.asArray();
  18853. }
  18854. else if (light instanceof BABYLON.DirectionalLight) {
  18855. serializationObject.type = 1;
  18856. var directionalLight = light;
  18857. serializationObject.position = directionalLight.position.asArray();
  18858. serializationObject.direction = directionalLight.direction.asArray();
  18859. }
  18860. else if (light instanceof BABYLON.SpotLight) {
  18861. serializationObject.type = 2;
  18862. var spotLight = light;
  18863. serializationObject.position = spotLight.position.asArray();
  18864. serializationObject.direction = spotLight.position.asArray();
  18865. serializationObject.angle = spotLight.angle;
  18866. serializationObject.exponent = spotLight.exponent;
  18867. }
  18868. else if (light instanceof BABYLON.HemisphericLight) {
  18869. serializationObject.type = 3;
  18870. var hemisphericLight = light;
  18871. serializationObject.direction = hemisphericLight.direction.asArray();
  18872. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18873. }
  18874. if (light.intensity) {
  18875. serializationObject.intensity = light.intensity;
  18876. }
  18877. serializationObject.range = light.range;
  18878. serializationObject.diffuse = light.diffuse.asArray();
  18879. serializationObject.specular = light.specular.asArray();
  18880. return serializationObject;
  18881. };
  18882. var serializeFresnelParameter = function (fresnelParameter) {
  18883. var serializationObject = {};
  18884. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18885. serializationObject.leftColor = fresnelParameter.leftColor;
  18886. serializationObject.rightColor = fresnelParameter.rightColor;
  18887. serializationObject.bias = fresnelParameter.bias;
  18888. serializationObject.power = fresnelParameter.power;
  18889. return serializationObject;
  18890. };
  18891. var appendAnimations = function (source, destination) {
  18892. if (source.animations) {
  18893. destination.animations = [];
  18894. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18895. var animation = source.animations[animationIndex];
  18896. destination.animations.push(serializeAnimation(animation));
  18897. }
  18898. }
  18899. };
  18900. var serializeCamera = function (camera) {
  18901. var serializationObject = {};
  18902. serializationObject.name = camera.name;
  18903. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18904. serializationObject.id = camera.id;
  18905. serializationObject.position = camera.position.asArray();
  18906. // Parent
  18907. if (camera.parent) {
  18908. serializationObject.parentId = camera.parent.id;
  18909. }
  18910. serializationObject.fov = camera.fov;
  18911. serializationObject.minZ = camera.minZ;
  18912. serializationObject.maxZ = camera.maxZ;
  18913. serializationObject.inertia = camera.inertia;
  18914. //setting the type
  18915. if (camera instanceof BABYLON.FreeCamera) {
  18916. serializationObject.type = "FreeCamera";
  18917. }
  18918. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18919. serializationObject.type = "ArcRotateCamera";
  18920. }
  18921. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18922. serializationObject.type = "AnaglyphArcRotateCamera";
  18923. }
  18924. else if (camera instanceof BABYLON.GamepadCamera) {
  18925. serializationObject.type = "GamepadCamera";
  18926. }
  18927. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18928. serializationObject.type = "AnaglyphFreeCamera";
  18929. }
  18930. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18931. serializationObject.type = "DeviceOrientationCamera";
  18932. }
  18933. else if (camera instanceof BABYLON.FollowCamera) {
  18934. serializationObject.type = "FollowCamera";
  18935. }
  18936. else if (camera instanceof BABYLON.OculusCamera) {
  18937. serializationObject.type = "OculusCamera";
  18938. }
  18939. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18940. serializationObject.type = "OculusGamepadCamera";
  18941. }
  18942. else if (camera instanceof BABYLON.TouchCamera) {
  18943. serializationObject.type = "TouchCamera";
  18944. }
  18945. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18946. serializationObject.type = "VirtualJoysticksCamera";
  18947. }
  18948. else if (camera instanceof BABYLON.WebVRCamera) {
  18949. serializationObject.type = "WebVRCamera";
  18950. }
  18951. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18952. serializationObject.type = "VRDeviceOrientationCamera";
  18953. }
  18954. //special properties of specific cameras
  18955. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18956. var arcCamera = camera;
  18957. serializationObject.alpha = arcCamera.alpha;
  18958. serializationObject.beta = arcCamera.beta;
  18959. serializationObject.radius = arcCamera.radius;
  18960. if (arcCamera.target && arcCamera.target.id) {
  18961. serializationObject.lockedTargetId = arcCamera.target.id;
  18962. }
  18963. }
  18964. else if (camera instanceof BABYLON.FollowCamera) {
  18965. var followCam = camera;
  18966. serializationObject.radius = followCam.radius;
  18967. serializationObject.heightOffset = followCam.heightOffset;
  18968. serializationObject.rotationOffset = followCam.rotationOffset;
  18969. }
  18970. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18971. //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.
  18972. if (camera['_eyeSpace'] !== undefined) {
  18973. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18974. }
  18975. }
  18976. //general properties that not all cameras have. The [] is due to typescript's type safety
  18977. if (camera['speed'] !== undefined) {
  18978. serializationObject.speed = camera['speed'];
  18979. }
  18980. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18981. serializationObject.target = camera['target'].asArray();
  18982. }
  18983. // Target
  18984. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18985. serializationObject.rotation = camera['rotation'].asArray();
  18986. }
  18987. // Locked target
  18988. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18989. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18990. }
  18991. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18992. serializationObject.applyGravity = camera['applyGravity'] || false;
  18993. if (camera['ellipsoid']) {
  18994. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18995. }
  18996. // Animations
  18997. appendAnimations(camera, serializationObject);
  18998. // Layer mask
  18999. serializationObject.layerMask = camera.layerMask;
  19000. return serializationObject;
  19001. };
  19002. var serializeAnimation = function (animation) {
  19003. var serializationObject = {};
  19004. serializationObject.name = animation.name;
  19005. serializationObject.property = animation.targetProperty;
  19006. serializationObject.framePerSecond = animation.framePerSecond;
  19007. serializationObject.dataType = animation.dataType;
  19008. serializationObject.loopBehavior = animation.loopMode;
  19009. var dataType = animation.dataType;
  19010. serializationObject.keys = [];
  19011. var keys = animation.getKeys();
  19012. for (var index = 0; index < keys.length; index++) {
  19013. var animationKey = keys[index];
  19014. var key = {};
  19015. key.frame = animationKey.frame;
  19016. switch (dataType) {
  19017. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19018. key.values = [animationKey.value];
  19019. break;
  19020. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19021. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19022. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19023. key.values = animationKey.value.asArray();
  19024. break;
  19025. }
  19026. serializationObject.keys.push(key);
  19027. }
  19028. return serializationObject;
  19029. };
  19030. var serializeMultiMaterial = function (material) {
  19031. var serializationObject = {};
  19032. serializationObject.name = material.name;
  19033. serializationObject.id = material.id;
  19034. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19035. serializationObject.materials = [];
  19036. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  19037. var subMat = material.subMaterials[matIndex];
  19038. if (subMat) {
  19039. serializationObject.materials.push(subMat.id);
  19040. }
  19041. else {
  19042. serializationObject.materials.push(null);
  19043. }
  19044. }
  19045. return serializationObject;
  19046. };
  19047. var serializeMaterial = function (material) {
  19048. var serializationObject = {};
  19049. serializationObject.name = material.name;
  19050. serializationObject.ambient = material.ambientColor.asArray();
  19051. serializationObject.diffuse = material.diffuseColor.asArray();
  19052. serializationObject.specular = material.specularColor.asArray();
  19053. serializationObject.specularPower = material.specularPower;
  19054. serializationObject.emissive = material.emissiveColor.asArray();
  19055. serializationObject.alpha = material.alpha;
  19056. serializationObject.id = material.id;
  19057. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19058. serializationObject.backFaceCulling = material.backFaceCulling;
  19059. if (material.diffuseTexture) {
  19060. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  19061. }
  19062. if (material.diffuseFresnelParameters) {
  19063. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  19064. }
  19065. if (material.ambientTexture) {
  19066. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  19067. }
  19068. if (material.opacityTexture) {
  19069. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  19070. }
  19071. if (material.opacityFresnelParameters) {
  19072. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  19073. }
  19074. if (material.reflectionTexture) {
  19075. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  19076. }
  19077. if (material.reflectionFresnelParameters) {
  19078. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  19079. }
  19080. if (material.emissiveTexture) {
  19081. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  19082. }
  19083. if (material.emissiveFresnelParameters) {
  19084. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  19085. }
  19086. if (material.specularTexture) {
  19087. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  19088. }
  19089. if (material.bumpTexture) {
  19090. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  19091. }
  19092. return serializationObject;
  19093. };
  19094. var serializeTexture = function (texture) {
  19095. var serializationObject = {};
  19096. if (!texture.name) {
  19097. return null;
  19098. }
  19099. if (texture instanceof BABYLON.CubeTexture) {
  19100. serializationObject.name = texture.name;
  19101. serializationObject.hasAlpha = texture.hasAlpha;
  19102. serializationObject.level = texture.level;
  19103. serializationObject.coordinatesMode = texture.coordinatesMode;
  19104. return serializationObject;
  19105. }
  19106. if (texture instanceof BABYLON.MirrorTexture) {
  19107. var mirrorTexture = texture;
  19108. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  19109. serializationObject.renderList = [];
  19110. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  19111. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  19112. }
  19113. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  19114. }
  19115. else if (texture instanceof BABYLON.RenderTargetTexture) {
  19116. var renderTargetTexture = texture;
  19117. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  19118. serializationObject.renderList = [];
  19119. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  19120. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  19121. }
  19122. }
  19123. var regularTexture = texture;
  19124. serializationObject.name = texture.name;
  19125. serializationObject.hasAlpha = texture.hasAlpha;
  19126. serializationObject.level = texture.level;
  19127. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  19128. serializationObject.coordinatesMode = texture.coordinatesMode;
  19129. serializationObject.uOffset = regularTexture.uOffset;
  19130. serializationObject.vOffset = regularTexture.vOffset;
  19131. serializationObject.uScale = regularTexture.uScale;
  19132. serializationObject.vScale = regularTexture.vScale;
  19133. serializationObject.uAng = regularTexture.uAng;
  19134. serializationObject.vAng = regularTexture.vAng;
  19135. serializationObject.wAng = regularTexture.wAng;
  19136. serializationObject.wrapU = texture.wrapU;
  19137. serializationObject.wrapV = texture.wrapV;
  19138. // Animations
  19139. appendAnimations(texture, serializationObject);
  19140. return serializationObject;
  19141. };
  19142. var serializeSkeleton = function (skeleton) {
  19143. var serializationObject = {};
  19144. serializationObject.name = skeleton.name;
  19145. serializationObject.id = skeleton.id;
  19146. serializationObject.bones = [];
  19147. for (var index = 0; index < skeleton.bones.length; index++) {
  19148. var bone = skeleton.bones[index];
  19149. var serializedBone = {
  19150. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  19151. name: bone.name,
  19152. matrix: bone.getLocalMatrix().toArray()
  19153. };
  19154. serializationObject.bones.push(serializedBone);
  19155. if (bone.animations && bone.animations.length > 0) {
  19156. serializedBone.animation = serializeAnimation(bone.animations[0]);
  19157. }
  19158. }
  19159. return serializationObject;
  19160. };
  19161. var serializeParticleSystem = function (particleSystem) {
  19162. var serializationObject = {};
  19163. serializationObject.emitterId = particleSystem.emitter.id;
  19164. serializationObject.capacity = particleSystem.getCapacity();
  19165. if (particleSystem.particleTexture) {
  19166. serializationObject.textureName = particleSystem.particleTexture.name;
  19167. }
  19168. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  19169. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  19170. serializationObject.minSize = particleSystem.minSize;
  19171. serializationObject.maxSize = particleSystem.maxSize;
  19172. serializationObject.minLifeTime = particleSystem.minLifeTime;
  19173. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  19174. serializationObject.emitRate = particleSystem.emitRate;
  19175. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  19176. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  19177. serializationObject.gravity = particleSystem.gravity.asArray();
  19178. serializationObject.direction1 = particleSystem.direction1.asArray();
  19179. serializationObject.direction2 = particleSystem.direction2.asArray();
  19180. serializationObject.color1 = particleSystem.color1.asArray();
  19181. serializationObject.color2 = particleSystem.color2.asArray();
  19182. serializationObject.colorDead = particleSystem.colorDead.asArray();
  19183. serializationObject.updateSpeed = particleSystem.updateSpeed;
  19184. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  19185. serializationObject.textureMask = particleSystem.textureMask.asArray();
  19186. serializationObject.blendMode = particleSystem.blendMode;
  19187. return serializationObject;
  19188. };
  19189. var serializeLensFlareSystem = function (lensFlareSystem) {
  19190. var serializationObject = {};
  19191. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  19192. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  19193. serializationObject.flares = [];
  19194. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  19195. var flare = lensFlareSystem.lensFlares[index];
  19196. serializationObject.flares.push({
  19197. size: flare.size,
  19198. position: flare.position,
  19199. color: flare.color.asArray(),
  19200. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  19201. });
  19202. }
  19203. return serializationObject;
  19204. };
  19205. var serializeShadowGenerator = function (light) {
  19206. var serializationObject = {};
  19207. var shadowGenerator = light.getShadowGenerator();
  19208. serializationObject.lightId = light.id;
  19209. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  19210. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  19211. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  19212. serializationObject.renderList = [];
  19213. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19214. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19215. serializationObject.renderList.push(mesh.id);
  19216. }
  19217. return serializationObject;
  19218. };
  19219. var serializedGeometries = [];
  19220. var serializeGeometry = function (geometry, serializationGeometries) {
  19221. if (serializedGeometries[geometry.id]) {
  19222. return;
  19223. }
  19224. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19225. serializationGeometries.boxes.push(serializeBox(geometry));
  19226. }
  19227. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19228. serializationGeometries.spheres.push(serializeSphere(geometry));
  19229. }
  19230. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19231. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19232. }
  19233. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19234. serializationGeometries.toruses.push(serializeTorus(geometry));
  19235. }
  19236. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19237. serializationGeometries.grounds.push(serializeGround(geometry));
  19238. }
  19239. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19240. serializationGeometries.planes.push(serializePlane(geometry));
  19241. }
  19242. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19243. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19244. }
  19245. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19246. throw new Error("Unknow primitive type");
  19247. }
  19248. else {
  19249. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19250. }
  19251. serializedGeometries[geometry.id] = true;
  19252. };
  19253. var serializeGeometryBase = function (geometry) {
  19254. var serializationObject = {};
  19255. serializationObject.id = geometry.id;
  19256. if (BABYLON.Tags.HasTags(geometry)) {
  19257. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19258. }
  19259. return serializationObject;
  19260. };
  19261. var serializeVertexData = function (vertexData) {
  19262. var serializationObject = serializeGeometryBase(vertexData);
  19263. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19264. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19265. }
  19266. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19267. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19268. }
  19269. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19270. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19271. }
  19272. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19273. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19274. }
  19275. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19276. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19277. }
  19278. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19279. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19280. serializationObject.matricesIndices._isExpanded = true;
  19281. }
  19282. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19283. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19284. }
  19285. serializationObject.indices = vertexData.getIndices();
  19286. return serializationObject;
  19287. };
  19288. var serializePrimitive = function (primitive) {
  19289. var serializationObject = serializeGeometryBase(primitive);
  19290. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19291. return serializationObject;
  19292. };
  19293. var serializeBox = function (box) {
  19294. var serializationObject = serializePrimitive(box);
  19295. serializationObject.size = box.size;
  19296. return serializationObject;
  19297. };
  19298. var serializeSphere = function (sphere) {
  19299. var serializationObject = serializePrimitive(sphere);
  19300. serializationObject.segments = sphere.segments;
  19301. serializationObject.diameter = sphere.diameter;
  19302. return serializationObject;
  19303. };
  19304. var serializeCylinder = function (cylinder) {
  19305. var serializationObject = serializePrimitive(cylinder);
  19306. serializationObject.height = cylinder.height;
  19307. serializationObject.diameterTop = cylinder.diameterTop;
  19308. serializationObject.diameterBottom = cylinder.diameterBottom;
  19309. serializationObject.tessellation = cylinder.tessellation;
  19310. return serializationObject;
  19311. };
  19312. var serializeTorus = function (torus) {
  19313. var serializationObject = serializePrimitive(torus);
  19314. serializationObject.diameter = torus.diameter;
  19315. serializationObject.thickness = torus.thickness;
  19316. serializationObject.tessellation = torus.tessellation;
  19317. return serializationObject;
  19318. };
  19319. var serializeGround = function (ground) {
  19320. var serializationObject = serializePrimitive(ground);
  19321. serializationObject.width = ground.width;
  19322. serializationObject.height = ground.height;
  19323. serializationObject.subdivisions = ground.subdivisions;
  19324. return serializationObject;
  19325. };
  19326. var serializePlane = function (plane) {
  19327. var serializationObject = serializePrimitive(plane);
  19328. serializationObject.size = plane.size;
  19329. return serializationObject;
  19330. };
  19331. var serializeTorusKnot = function (torusKnot) {
  19332. var serializationObject = serializePrimitive(torusKnot);
  19333. serializationObject.radius = torusKnot.radius;
  19334. serializationObject.tube = torusKnot.tube;
  19335. serializationObject.radialSegments = torusKnot.radialSegments;
  19336. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19337. serializationObject.p = torusKnot.p;
  19338. serializationObject.q = torusKnot.q;
  19339. return serializationObject;
  19340. };
  19341. var serializeMesh = function (mesh, serializationScene) {
  19342. var serializationObject = {};
  19343. serializationObject.name = mesh.name;
  19344. serializationObject.id = mesh.id;
  19345. if (BABYLON.Tags.HasTags(mesh)) {
  19346. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19347. }
  19348. serializationObject.position = mesh.position.asArray();
  19349. if (mesh.rotationQuaternion) {
  19350. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19351. }
  19352. else if (mesh.rotation) {
  19353. serializationObject.rotation = mesh.rotation.asArray();
  19354. }
  19355. serializationObject.scaling = mesh.scaling.asArray();
  19356. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19357. serializationObject.isEnabled = mesh.isEnabled();
  19358. serializationObject.isVisible = mesh.isVisible;
  19359. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19360. serializationObject.pickable = mesh.isPickable;
  19361. serializationObject.receiveShadows = mesh.receiveShadows;
  19362. serializationObject.billboardMode = mesh.billboardMode;
  19363. serializationObject.visibility = mesh.visibility;
  19364. serializationObject.checkCollisions = mesh.checkCollisions;
  19365. // Parent
  19366. if (mesh.parent) {
  19367. serializationObject.parentId = mesh.parent.id;
  19368. }
  19369. // Geometry
  19370. var geometry = mesh._geometry;
  19371. if (geometry) {
  19372. var geometryId = geometry.id;
  19373. serializationObject.geometryId = geometryId;
  19374. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19375. // 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
  19376. serializeGeometry(geometry, serializationScene.geometries);
  19377. }
  19378. // SubMeshes
  19379. serializationObject.subMeshes = [];
  19380. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19381. var subMesh = mesh.subMeshes[subIndex];
  19382. serializationObject.subMeshes.push({
  19383. materialIndex: subMesh.materialIndex,
  19384. verticesStart: subMesh.verticesStart,
  19385. verticesCount: subMesh.verticesCount,
  19386. indexStart: subMesh.indexStart,
  19387. indexCount: subMesh.indexCount
  19388. });
  19389. }
  19390. }
  19391. // Material
  19392. if (mesh.material) {
  19393. serializationObject.materialId = mesh.material.id;
  19394. }
  19395. else {
  19396. mesh.material = null;
  19397. }
  19398. // Skeleton
  19399. if (mesh.skeleton) {
  19400. serializationObject.skeletonId = mesh.skeleton.id;
  19401. }
  19402. // Physics
  19403. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19404. serializationObject.physicsMass = mesh.getPhysicsMass();
  19405. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19406. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19407. switch (mesh.getPhysicsImpostor()) {
  19408. case BABYLON.PhysicsEngine.BoxImpostor:
  19409. serializationObject.physicsImpostor = 1;
  19410. break;
  19411. case BABYLON.PhysicsEngine.SphereImpostor:
  19412. serializationObject.physicsImpostor = 2;
  19413. break;
  19414. }
  19415. }
  19416. // Instances
  19417. serializationObject.instances = [];
  19418. for (var index = 0; index < mesh.instances.length; index++) {
  19419. var instance = mesh.instances[index];
  19420. var serializationInstance = {
  19421. name: instance.name,
  19422. position: instance.position,
  19423. rotation: instance.rotation,
  19424. rotationQuaternion: instance.rotationQuaternion,
  19425. scaling: instance.scaling
  19426. };
  19427. serializationObject.instances.push(serializationInstance);
  19428. // Animations
  19429. appendAnimations(instance, serializationInstance);
  19430. }
  19431. // Animations
  19432. appendAnimations(mesh, serializationObject);
  19433. // Layer mask
  19434. serializationObject.layerMask = mesh.layerMask;
  19435. return serializationObject;
  19436. };
  19437. var SceneSerializer = (function () {
  19438. function SceneSerializer() {
  19439. }
  19440. SceneSerializer.Serialize = function (scene) {
  19441. var serializationObject = {};
  19442. // Scene
  19443. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19444. serializationObject.autoClear = scene.autoClear;
  19445. serializationObject.clearColor = scene.clearColor.asArray();
  19446. serializationObject.ambientColor = scene.ambientColor.asArray();
  19447. serializationObject.gravity = scene.gravity.asArray();
  19448. // Fog
  19449. if (scene.fogMode && scene.fogMode !== 0) {
  19450. serializationObject.fogMode = scene.fogMode;
  19451. serializationObject.fogColor = scene.fogColor.asArray();
  19452. serializationObject.fogStart = scene.fogStart;
  19453. serializationObject.fogEnd = scene.fogEnd;
  19454. serializationObject.fogDensity = scene.fogDensity;
  19455. }
  19456. // Lights
  19457. serializationObject.lights = [];
  19458. for (var index = 0; index < scene.lights.length; index++) {
  19459. var light = scene.lights[index];
  19460. serializationObject.lights.push(serializeLight(light));
  19461. }
  19462. // Cameras
  19463. serializationObject.cameras = [];
  19464. for (index = 0; index < scene.cameras.length; index++) {
  19465. var camera = scene.cameras[index];
  19466. serializationObject.cameras.push(serializeCamera(camera));
  19467. }
  19468. if (scene.activeCamera) {
  19469. serializationObject.activeCameraID = scene.activeCamera.id;
  19470. }
  19471. // Materials
  19472. serializationObject.materials = [];
  19473. serializationObject.multiMaterials = [];
  19474. for (index = 0; index < scene.materials.length; index++) {
  19475. var material = scene.materials[index];
  19476. if (material instanceof BABYLON.StandardMaterial) {
  19477. serializationObject.materials.push(serializeMaterial(material));
  19478. }
  19479. else if (material instanceof BABYLON.MultiMaterial) {
  19480. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19481. }
  19482. }
  19483. // Skeletons
  19484. serializationObject.skeletons = [];
  19485. for (index = 0; index < scene.skeletons.length; index++) {
  19486. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19487. }
  19488. // Geometries
  19489. serializationObject.geometries = {};
  19490. serializationObject.geometries.boxes = [];
  19491. serializationObject.geometries.spheres = [];
  19492. serializationObject.geometries.cylinders = [];
  19493. serializationObject.geometries.toruses = [];
  19494. serializationObject.geometries.grounds = [];
  19495. serializationObject.geometries.planes = [];
  19496. serializationObject.geometries.torusKnots = [];
  19497. serializationObject.geometries.vertexData = [];
  19498. serializedGeometries = [];
  19499. var geometries = scene.getGeometries();
  19500. for (index = 0; index < geometries.length; index++) {
  19501. var geometry = geometries[index];
  19502. if (geometry.isReady()) {
  19503. serializeGeometry(geometry, serializationObject.geometries);
  19504. }
  19505. }
  19506. // Meshes
  19507. serializationObject.meshes = [];
  19508. for (index = 0; index < scene.meshes.length; index++) {
  19509. var abstractMesh = scene.meshes[index];
  19510. if (abstractMesh instanceof BABYLON.Mesh) {
  19511. var mesh = abstractMesh;
  19512. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19513. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19514. }
  19515. }
  19516. }
  19517. // Particles Systems
  19518. serializationObject.particleSystems = [];
  19519. for (index = 0; index < scene.particleSystems.length; index++) {
  19520. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19521. }
  19522. // Lens flares
  19523. serializationObject.lensFlareSystems = [];
  19524. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19525. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19526. }
  19527. // Shadows
  19528. serializationObject.shadowGenerators = [];
  19529. for (index = 0; index < scene.lights.length; index++) {
  19530. light = scene.lights[index];
  19531. if (light.getShadowGenerator()) {
  19532. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19533. }
  19534. }
  19535. return serializationObject;
  19536. };
  19537. return SceneSerializer;
  19538. })();
  19539. BABYLON.SceneSerializer = SceneSerializer;
  19540. })(BABYLON || (BABYLON = {}));
  19541. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19542. (function (BABYLON) {
  19543. var SceneLoader = (function () {
  19544. function SceneLoader() {
  19545. }
  19546. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19547. get: function () {
  19548. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19549. },
  19550. set: function (value) {
  19551. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19552. },
  19553. enumerable: true,
  19554. configurable: true
  19555. });
  19556. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19557. get: function () {
  19558. return SceneLoader._ShowLoadingScreen;
  19559. },
  19560. set: function (value) {
  19561. SceneLoader._ShowLoadingScreen = value;
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19567. var dotPosition = sceneFilename.lastIndexOf(".");
  19568. var queryStringPosition = sceneFilename.indexOf("?");
  19569. if (queryStringPosition === -1) {
  19570. queryStringPosition = sceneFilename.length;
  19571. }
  19572. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19573. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19574. var plugin = this._registeredPlugins[index];
  19575. if (plugin.extensions.indexOf(extension) !== -1) {
  19576. return plugin;
  19577. }
  19578. }
  19579. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19580. };
  19581. // Public functions
  19582. SceneLoader.RegisterPlugin = function (plugin) {
  19583. plugin.extensions = plugin.extensions.toLowerCase();
  19584. SceneLoader._registeredPlugins.push(plugin);
  19585. };
  19586. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19587. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19588. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19589. return;
  19590. }
  19591. var manifestChecked = function (success) {
  19592. scene.database = database;
  19593. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19594. var importMeshFromData = function (data) {
  19595. var meshes = [];
  19596. var particleSystems = [];
  19597. var skeletons = [];
  19598. try {
  19599. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19600. if (onerror) {
  19601. onerror(scene, 'unable to load the scene');
  19602. }
  19603. return;
  19604. }
  19605. }
  19606. catch (e) {
  19607. if (onerror) {
  19608. onerror(scene, e);
  19609. }
  19610. return;
  19611. }
  19612. if (onsuccess) {
  19613. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19614. onsuccess(meshes, particleSystems, skeletons);
  19615. }
  19616. };
  19617. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19618. // Direct load
  19619. importMeshFromData(sceneFilename.substr(5));
  19620. return;
  19621. }
  19622. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19623. importMeshFromData(data);
  19624. }, progressCallBack, database);
  19625. };
  19626. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19627. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19628. };
  19629. /**
  19630. * Load a scene
  19631. * @param rootUrl a string that defines the root url for scene and resources
  19632. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19633. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19634. */
  19635. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19636. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19637. };
  19638. /**
  19639. * Append a scene
  19640. * @param rootUrl a string that defines the root url for scene and resources
  19641. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19642. * @param scene is the instance of BABYLON.Scene to append to
  19643. */
  19644. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19645. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19646. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19647. return;
  19648. }
  19649. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19650. var database;
  19651. if (SceneLoader.ShowLoadingScreen) {
  19652. scene.getEngine().displayLoadingUI();
  19653. }
  19654. var loadSceneFromData = function (data) {
  19655. scene.database = database;
  19656. if (!plugin.load(scene, data, rootUrl)) {
  19657. if (onerror) {
  19658. onerror(scene);
  19659. }
  19660. scene.getEngine().hideLoadingUI();
  19661. return;
  19662. }
  19663. if (onsuccess) {
  19664. onsuccess(scene);
  19665. }
  19666. if (SceneLoader.ShowLoadingScreen) {
  19667. scene.executeWhenReady(function () {
  19668. scene.getEngine().hideLoadingUI();
  19669. });
  19670. }
  19671. };
  19672. var manifestChecked = function (success) {
  19673. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19674. };
  19675. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19676. // Direct load
  19677. loadSceneFromData(sceneFilename.substr(5));
  19678. return;
  19679. }
  19680. if (rootUrl.indexOf("file:") === -1) {
  19681. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19682. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19683. }
  19684. else {
  19685. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19686. }
  19687. };
  19688. // Flags
  19689. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19690. SceneLoader._ShowLoadingScreen = true;
  19691. // Members
  19692. SceneLoader._registeredPlugins = new Array();
  19693. return SceneLoader;
  19694. })();
  19695. BABYLON.SceneLoader = SceneLoader;
  19696. ;
  19697. })(BABYLON || (BABYLON = {}));
  19698. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19699. (function (BABYLON) {
  19700. var Internals;
  19701. (function (Internals) {
  19702. var checkColors4 = function (colors, count) {
  19703. // Check if color3 was used
  19704. if (colors.length === count * 3) {
  19705. var colors4 = [];
  19706. for (var index = 0; index < colors.length; index += 3) {
  19707. var newIndex = (index / 3) * 4;
  19708. colors4[newIndex] = colors[index];
  19709. colors4[newIndex + 1] = colors[index + 1];
  19710. colors4[newIndex + 2] = colors[index + 2];
  19711. colors4[newIndex + 3] = 1.0;
  19712. }
  19713. return colors4;
  19714. }
  19715. return colors;
  19716. };
  19717. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19718. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19719. texture.name = parsedTexture.name;
  19720. texture.hasAlpha = parsedTexture.hasAlpha;
  19721. texture.level = parsedTexture.level;
  19722. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19723. return texture;
  19724. };
  19725. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19726. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19727. return null;
  19728. }
  19729. if (parsedTexture.isCube) {
  19730. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19731. }
  19732. var texture;
  19733. if (parsedTexture.mirrorPlane) {
  19734. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19735. texture._waitingRenderList = parsedTexture.renderList;
  19736. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19737. }
  19738. else if (parsedTexture.isRenderTarget) {
  19739. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19740. texture._waitingRenderList = parsedTexture.renderList;
  19741. }
  19742. else {
  19743. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19744. }
  19745. texture.name = parsedTexture.name;
  19746. texture.hasAlpha = parsedTexture.hasAlpha;
  19747. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19748. texture.level = parsedTexture.level;
  19749. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19750. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19751. texture.uOffset = parsedTexture.uOffset;
  19752. texture.vOffset = parsedTexture.vOffset;
  19753. texture.uScale = parsedTexture.uScale;
  19754. texture.vScale = parsedTexture.vScale;
  19755. texture.uAng = parsedTexture.uAng;
  19756. texture.vAng = parsedTexture.vAng;
  19757. texture.wAng = parsedTexture.wAng;
  19758. texture.wrapU = parsedTexture.wrapU;
  19759. texture.wrapV = parsedTexture.wrapV;
  19760. // Animations
  19761. if (parsedTexture.animations) {
  19762. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19763. var parsedAnimation = parsedTexture.animations[animationIndex];
  19764. texture.animations.push(parseAnimation(parsedAnimation));
  19765. }
  19766. }
  19767. return texture;
  19768. };
  19769. var parseSkeleton = function (parsedSkeleton, scene) {
  19770. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19771. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19772. var parsedBone = parsedSkeleton.bones[index];
  19773. var parentBone = null;
  19774. if (parsedBone.parentBoneIndex > -1) {
  19775. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19776. }
  19777. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19778. if (parsedBone.animation) {
  19779. bone.animations.push(parseAnimation(parsedBone.animation));
  19780. }
  19781. }
  19782. return skeleton;
  19783. };
  19784. var parseFresnelParameters = function (parsedFresnelParameters) {
  19785. var fresnelParameters = new BABYLON.FresnelParameters();
  19786. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19787. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19788. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19789. fresnelParameters.bias = parsedFresnelParameters.bias;
  19790. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19791. return fresnelParameters;
  19792. };
  19793. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19794. var material;
  19795. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19796. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19797. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19798. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19799. material.specularPower = parsedMaterial.specularPower;
  19800. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19801. material.alpha = parsedMaterial.alpha;
  19802. material.id = parsedMaterial.id;
  19803. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19804. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19805. material.wireframe = parsedMaterial.wireframe;
  19806. if (parsedMaterial.diffuseTexture) {
  19807. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19808. }
  19809. if (parsedMaterial.diffuseFresnelParameters) {
  19810. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19811. }
  19812. if (parsedMaterial.ambientTexture) {
  19813. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19814. }
  19815. if (parsedMaterial.opacityTexture) {
  19816. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19817. }
  19818. if (parsedMaterial.opacityFresnelParameters) {
  19819. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19820. }
  19821. if (parsedMaterial.reflectionTexture) {
  19822. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19823. }
  19824. if (parsedMaterial.reflectionFresnelParameters) {
  19825. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19826. }
  19827. if (parsedMaterial.emissiveTexture) {
  19828. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19829. }
  19830. if (parsedMaterial.emissiveFresnelParameters) {
  19831. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19832. }
  19833. if (parsedMaterial.specularTexture) {
  19834. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19835. }
  19836. if (parsedMaterial.bumpTexture) {
  19837. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19838. }
  19839. return material;
  19840. };
  19841. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19842. for (var index = 0; index < parsedData.materials.length; index++) {
  19843. var parsedMaterial = parsedData.materials[index];
  19844. if (parsedMaterial.id === id) {
  19845. return parseMaterial(parsedMaterial, scene, rootUrl);
  19846. }
  19847. }
  19848. return null;
  19849. };
  19850. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19851. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19852. multiMaterial.id = parsedMultiMaterial.id;
  19853. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19854. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19855. var subMatId = parsedMultiMaterial.materials[matIndex];
  19856. if (subMatId) {
  19857. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19858. }
  19859. else {
  19860. multiMaterial.subMaterials.push(null);
  19861. }
  19862. }
  19863. return multiMaterial;
  19864. };
  19865. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19866. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19867. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19868. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19869. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19870. var parsedFlare = parsedLensFlareSystem.flares[index];
  19871. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19872. }
  19873. return lensFlareSystem;
  19874. };
  19875. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19876. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19877. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19878. if (parsedParticleSystem.textureName) {
  19879. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19880. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19881. }
  19882. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19883. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19884. particleSystem.minSize = parsedParticleSystem.minSize;
  19885. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19886. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19887. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19888. particleSystem.emitter = emitter;
  19889. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19890. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19891. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19892. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19893. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19894. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19895. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19896. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19897. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19898. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19899. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19900. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19901. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19902. particleSystem.start();
  19903. return particleSystem;
  19904. };
  19905. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19906. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19907. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19908. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19909. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19910. shadowGenerator.getShadowMap().renderList.push(mesh);
  19911. }
  19912. if (parsedShadowGenerator.usePoissonSampling) {
  19913. shadowGenerator.usePoissonSampling = true;
  19914. }
  19915. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19916. shadowGenerator.useVarianceShadowMap = true;
  19917. }
  19918. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19919. shadowGenerator.useBlurVarianceShadowMap = true;
  19920. if (parsedShadowGenerator.blurScale) {
  19921. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19922. }
  19923. if (parsedShadowGenerator.blurBoxOffset) {
  19924. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19925. }
  19926. }
  19927. if (parsedShadowGenerator.bias !== undefined) {
  19928. shadowGenerator.bias = parsedShadowGenerator.bias;
  19929. }
  19930. return shadowGenerator;
  19931. };
  19932. var parseAnimation = function (parsedAnimation) {
  19933. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19934. var dataType = parsedAnimation.dataType;
  19935. var keys = [];
  19936. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19937. var key = parsedAnimation.keys[index];
  19938. var data;
  19939. switch (dataType) {
  19940. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19941. data = key.values[0];
  19942. break;
  19943. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19944. data = BABYLON.Quaternion.FromArray(key.values);
  19945. break;
  19946. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19947. data = BABYLON.Matrix.FromArray(key.values);
  19948. break;
  19949. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19950. default:
  19951. data = BABYLON.Vector3.FromArray(key.values);
  19952. break;
  19953. }
  19954. keys.push({
  19955. frame: key.frame,
  19956. value: data
  19957. });
  19958. }
  19959. animation.setKeys(keys);
  19960. return animation;
  19961. };
  19962. var parseLight = function (parsedLight, scene) {
  19963. var light;
  19964. switch (parsedLight.type) {
  19965. case 0:
  19966. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19967. break;
  19968. case 1:
  19969. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19970. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19971. break;
  19972. case 2:
  19973. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19974. break;
  19975. case 3:
  19976. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19977. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19978. break;
  19979. }
  19980. light.id = parsedLight.id;
  19981. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19982. if (parsedLight.intensity !== undefined) {
  19983. light.intensity = parsedLight.intensity;
  19984. }
  19985. if (parsedLight.range) {
  19986. light.range = parsedLight.range;
  19987. }
  19988. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19989. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19990. if (parsedLight.excludedMeshesIds) {
  19991. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19992. }
  19993. // Parent
  19994. if (parsedLight.parentId) {
  19995. light._waitingParentId = parsedLight.parentId;
  19996. }
  19997. if (parsedLight.includedOnlyMeshesIds) {
  19998. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19999. }
  20000. // Animations
  20001. if (parsedLight.animations) {
  20002. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20003. var parsedAnimation = parsedLight.animations[animationIndex];
  20004. light.animations.push(parseAnimation(parsedAnimation));
  20005. }
  20006. }
  20007. if (parsedLight.autoAnimate) {
  20008. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  20009. }
  20010. };
  20011. var parseCamera = function (parsedCamera, scene) {
  20012. var camera;
  20013. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  20014. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  20015. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  20016. var alpha = parsedCamera.alpha;
  20017. var beta = parsedCamera.beta;
  20018. var radius = parsedCamera.radius;
  20019. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  20020. var eye_space = parsedCamera.eye_space;
  20021. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  20022. }
  20023. else {
  20024. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  20025. }
  20026. }
  20027. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20028. eye_space = parsedCamera.eye_space;
  20029. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  20030. }
  20031. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20032. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20033. }
  20034. else if (parsedCamera.type === "FollowCamera") {
  20035. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20036. camera.heightOffset = parsedCamera.heightOffset;
  20037. camera.radius = parsedCamera.radius;
  20038. camera.rotationOffset = parsedCamera.rotationOffset;
  20039. if (lockedTargetMesh)
  20040. camera.target = lockedTargetMesh;
  20041. }
  20042. else if (parsedCamera.type === "GamepadCamera") {
  20043. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20044. }
  20045. else if (parsedCamera.type === "OculusCamera") {
  20046. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  20047. }
  20048. else if (parsedCamera.type === "OculusGamepadCamera") {
  20049. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  20050. }
  20051. else if (parsedCamera.type === "TouchCamera") {
  20052. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20053. }
  20054. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20055. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20056. }
  20057. else if (parsedCamera.type === "WebVRCamera") {
  20058. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  20059. }
  20060. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  20061. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  20062. }
  20063. else {
  20064. // Free Camera is the default value
  20065. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20066. }
  20067. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20068. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20069. camera.lockedTarget = lockedTargetMesh;
  20070. }
  20071. camera.id = parsedCamera.id;
  20072. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20073. // Parent
  20074. if (parsedCamera.parentId) {
  20075. camera._waitingParentId = parsedCamera.parentId;
  20076. }
  20077. // Target
  20078. if (parsedCamera.target) {
  20079. if (camera.setTarget) {
  20080. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20081. }
  20082. else {
  20083. //For ArcRotate
  20084. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20085. }
  20086. }
  20087. else {
  20088. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20089. }
  20090. camera.fov = parsedCamera.fov;
  20091. camera.minZ = parsedCamera.minZ;
  20092. camera.maxZ = parsedCamera.maxZ;
  20093. camera.speed = parsedCamera.speed;
  20094. camera.inertia = parsedCamera.inertia;
  20095. camera.checkCollisions = parsedCamera.checkCollisions;
  20096. camera.applyGravity = parsedCamera.applyGravity;
  20097. if (parsedCamera.ellipsoid) {
  20098. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20099. }
  20100. // Animations
  20101. if (parsedCamera.animations) {
  20102. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20103. var parsedAnimation = parsedCamera.animations[animationIndex];
  20104. camera.animations.push(parseAnimation(parsedAnimation));
  20105. }
  20106. }
  20107. if (parsedCamera.autoAnimate) {
  20108. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20109. }
  20110. // Layer Mask
  20111. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20112. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20113. }
  20114. else {
  20115. camera.layerMask = 0xFFFFFFFF;
  20116. }
  20117. return camera;
  20118. };
  20119. var parseGeometry = function (parsedGeometry, scene) {
  20120. var id = parsedGeometry.id;
  20121. return scene.getGeometryByID(id);
  20122. };
  20123. var parseBox = function (parsedBox, scene) {
  20124. if (parseGeometry(parsedBox, scene)) {
  20125. return null; // null since geometry could be something else than a box...
  20126. }
  20127. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20128. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20129. scene.pushGeometry(box, true);
  20130. return box;
  20131. };
  20132. var parseSphere = function (parsedSphere, scene) {
  20133. if (parseGeometry(parsedSphere, scene)) {
  20134. return null; // null since geometry could be something else than a sphere...
  20135. }
  20136. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20137. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20138. scene.pushGeometry(sphere, true);
  20139. return sphere;
  20140. };
  20141. var parseCylinder = function (parsedCylinder, scene) {
  20142. if (parseGeometry(parsedCylinder, scene)) {
  20143. return null; // null since geometry could be something else than a cylinder...
  20144. }
  20145. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20146. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20147. scene.pushGeometry(cylinder, true);
  20148. return cylinder;
  20149. };
  20150. var parseTorus = function (parsedTorus, scene) {
  20151. if (parseGeometry(parsedTorus, scene)) {
  20152. return null; // null since geometry could be something else than a torus...
  20153. }
  20154. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20155. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20156. scene.pushGeometry(torus, true);
  20157. return torus;
  20158. };
  20159. var parseGround = function (parsedGround, scene) {
  20160. if (parseGeometry(parsedGround, scene)) {
  20161. return null; // null since geometry could be something else than a ground...
  20162. }
  20163. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20164. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20165. scene.pushGeometry(ground, true);
  20166. return ground;
  20167. };
  20168. var parsePlane = function (parsedPlane, scene) {
  20169. if (parseGeometry(parsedPlane, scene)) {
  20170. return null; // null since geometry could be something else than a plane...
  20171. }
  20172. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20173. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20174. scene.pushGeometry(plane, true);
  20175. return plane;
  20176. };
  20177. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20178. if (parseGeometry(parsedTorusKnot, scene)) {
  20179. return null; // null since geometry could be something else than a torusKnot...
  20180. }
  20181. 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);
  20182. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20183. scene.pushGeometry(torusKnot, true);
  20184. return torusKnot;
  20185. };
  20186. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20187. if (parseGeometry(parsedVertexData, scene)) {
  20188. return null; // null since geometry could be a primitive
  20189. }
  20190. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20191. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20192. if (parsedVertexData.delayLoadingFile) {
  20193. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20194. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20195. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20196. geometry._delayInfo = [];
  20197. if (parsedVertexData.hasUVs) {
  20198. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20199. }
  20200. if (parsedVertexData.hasUVs2) {
  20201. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20202. }
  20203. if (parsedVertexData.hasColors) {
  20204. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20205. }
  20206. if (parsedVertexData.hasMatricesIndices) {
  20207. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20208. }
  20209. if (parsedVertexData.hasMatricesWeights) {
  20210. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20211. }
  20212. geometry._delayLoadingFunction = importVertexData;
  20213. }
  20214. else {
  20215. importVertexData(parsedVertexData, geometry);
  20216. }
  20217. scene.pushGeometry(geometry, true);
  20218. return geometry;
  20219. };
  20220. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20221. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20222. mesh.id = parsedMesh.id;
  20223. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20224. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20225. if (parsedMesh.rotationQuaternion) {
  20226. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20227. }
  20228. else if (parsedMesh.rotation) {
  20229. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20230. }
  20231. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20232. if (parsedMesh.localMatrix) {
  20233. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20234. }
  20235. else if (parsedMesh.pivotMatrix) {
  20236. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20237. }
  20238. mesh.setEnabled(parsedMesh.isEnabled);
  20239. mesh.isVisible = parsedMesh.isVisible;
  20240. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20241. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20242. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20243. if (parsedMesh.applyFog !== undefined) {
  20244. mesh.applyFog = parsedMesh.applyFog;
  20245. }
  20246. if (parsedMesh.pickable !== undefined) {
  20247. mesh.isPickable = parsedMesh.pickable;
  20248. }
  20249. if (parsedMesh.alphaIndex !== undefined) {
  20250. mesh.alphaIndex = parsedMesh.alphaIndex;
  20251. }
  20252. mesh.receiveShadows = parsedMesh.receiveShadows;
  20253. mesh.billboardMode = parsedMesh.billboardMode;
  20254. if (parsedMesh.visibility !== undefined) {
  20255. mesh.visibility = parsedMesh.visibility;
  20256. }
  20257. mesh.checkCollisions = parsedMesh.checkCollisions;
  20258. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20259. // Parent
  20260. if (parsedMesh.parentId) {
  20261. mesh._waitingParentId = parsedMesh.parentId;
  20262. }
  20263. // Actions
  20264. if (parsedMesh.actions !== undefined) {
  20265. mesh._waitingActions = parsedMesh.actions;
  20266. }
  20267. // Geometry
  20268. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20269. if (parsedMesh.delayLoadingFile) {
  20270. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20271. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20272. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20273. if (parsedMesh._binaryInfo) {
  20274. mesh._binaryInfo = parsedMesh._binaryInfo;
  20275. }
  20276. mesh._delayInfo = [];
  20277. if (parsedMesh.hasUVs) {
  20278. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20279. }
  20280. if (parsedMesh.hasUVs2) {
  20281. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20282. }
  20283. if (parsedMesh.hasColors) {
  20284. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20285. }
  20286. if (parsedMesh.hasMatricesIndices) {
  20287. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20288. }
  20289. if (parsedMesh.hasMatricesWeights) {
  20290. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20291. }
  20292. mesh._delayLoadingFunction = importGeometry;
  20293. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20294. mesh._checkDelayState();
  20295. }
  20296. }
  20297. else {
  20298. importGeometry(parsedMesh, mesh);
  20299. }
  20300. // Material
  20301. if (parsedMesh.materialId) {
  20302. mesh.setMaterialByID(parsedMesh.materialId);
  20303. }
  20304. else {
  20305. mesh.material = null;
  20306. }
  20307. // Skeleton
  20308. if (parsedMesh.skeletonId > -1) {
  20309. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20310. }
  20311. // Physics
  20312. if (parsedMesh.physicsImpostor) {
  20313. if (!scene.isPhysicsEnabled()) {
  20314. scene.enablePhysics();
  20315. }
  20316. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20317. }
  20318. // Animations
  20319. if (parsedMesh.animations) {
  20320. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20321. var parsedAnimation = parsedMesh.animations[animationIndex];
  20322. mesh.animations.push(parseAnimation(parsedAnimation));
  20323. }
  20324. }
  20325. if (parsedMesh.autoAnimate) {
  20326. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20327. }
  20328. // Layer Mask
  20329. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20330. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20331. }
  20332. else {
  20333. mesh.layerMask = 0xFFFFFFFF;
  20334. }
  20335. // Instances
  20336. if (parsedMesh.instances) {
  20337. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20338. var parsedInstance = parsedMesh.instances[index];
  20339. var instance = mesh.createInstance(parsedInstance.name);
  20340. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20341. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20342. if (parsedInstance.rotationQuaternion) {
  20343. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20344. }
  20345. else if (parsedInstance.rotation) {
  20346. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20347. }
  20348. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20349. instance.checkCollisions = mesh.checkCollisions;
  20350. if (parsedMesh.animations) {
  20351. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20352. parsedAnimation = parsedMesh.animations[animationIndex];
  20353. instance.animations.push(parseAnimation(parsedAnimation));
  20354. }
  20355. }
  20356. }
  20357. }
  20358. return mesh;
  20359. };
  20360. var parseActions = function (parsedActions, object, scene) {
  20361. var actionManager = new BABYLON.ActionManager(scene);
  20362. if (object === null)
  20363. scene.actionManager = actionManager;
  20364. else
  20365. object.actionManager = actionManager;
  20366. // instanciate a new object
  20367. var instanciate = function (name, params) {
  20368. var newInstance = Object.create(BABYLON[name].prototype);
  20369. newInstance.constructor.apply(newInstance, params);
  20370. return newInstance;
  20371. };
  20372. var parseParameter = function (name, value, target, propertyPath) {
  20373. if (propertyPath === null) {
  20374. // String, boolean or float
  20375. var floatValue = parseFloat(value);
  20376. if (value === "true" || value === "false")
  20377. return value === "true";
  20378. else
  20379. return isNaN(floatValue) ? value : floatValue;
  20380. }
  20381. var effectiveTarget = propertyPath.split(".");
  20382. var values = value.split(",");
  20383. for (var i = 0; i < effectiveTarget.length; i++) {
  20384. target = target[effectiveTarget[i]];
  20385. }
  20386. // Return appropriate value with its type
  20387. if (typeof (target) === "boolean")
  20388. return values[0] === "true";
  20389. if (typeof (target) === "string")
  20390. return values[0];
  20391. // Parameters with multiple values such as Vector3 etc.
  20392. var split = new Array();
  20393. for (var i = 0; i < values.length; i++)
  20394. split.push(parseFloat(values[i]));
  20395. if (target instanceof BABYLON.Vector3)
  20396. return BABYLON.Vector3.FromArray(split);
  20397. if (target instanceof BABYLON.Vector4)
  20398. return BABYLON.Vector4.FromArray(split);
  20399. if (target instanceof BABYLON.Color3)
  20400. return BABYLON.Color3.FromArray(split);
  20401. if (target instanceof BABYLON.Color4)
  20402. return BABYLON.Color4.FromArray(split);
  20403. return parseFloat(values[0]);
  20404. };
  20405. // traverse graph per trigger
  20406. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20407. if (combineArray === void 0) { combineArray = null; }
  20408. if (parsedAction.detached)
  20409. return;
  20410. var parameters = new Array();
  20411. var target = null;
  20412. var propertyPath = null;
  20413. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20414. // Parameters
  20415. if (parsedAction.type === 2)
  20416. parameters.push(actionManager);
  20417. else
  20418. parameters.push(trigger);
  20419. if (combine) {
  20420. var actions = new Array();
  20421. for (var j = 0; j < parsedAction.combine.length; j++) {
  20422. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20423. }
  20424. parameters.push(actions);
  20425. }
  20426. else {
  20427. for (var i = 0; i < parsedAction.properties.length; i++) {
  20428. var value = parsedAction.properties[i].value;
  20429. var name = parsedAction.properties[i].name;
  20430. var targetType = parsedAction.properties[i].targetType;
  20431. if (name === "target")
  20432. if (targetType !== null && targetType === "SceneProperties")
  20433. value = target = scene;
  20434. else
  20435. value = target = scene.getNodeByName(value);
  20436. else if (name === "parent")
  20437. value = scene.getNodeByName(value);
  20438. else if (name === "sound")
  20439. value = scene.getSoundByName(value);
  20440. else if (name !== "propertyPath") {
  20441. if (parsedAction.type === 2 && name === "operator")
  20442. value = BABYLON.ValueCondition[value];
  20443. else
  20444. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20445. }
  20446. else {
  20447. propertyPath = value;
  20448. }
  20449. parameters.push(value);
  20450. }
  20451. }
  20452. if (combineArray === null) {
  20453. parameters.push(condition);
  20454. }
  20455. else {
  20456. parameters.push(null);
  20457. }
  20458. // If interpolate value action
  20459. if (parsedAction.name === "InterpolateValueAction") {
  20460. var param = parameters[parameters.length - 2];
  20461. parameters[parameters.length - 1] = param;
  20462. parameters[parameters.length - 2] = condition;
  20463. }
  20464. // Action or condition(s) and not CombineAction
  20465. var newAction = instanciate(parsedAction.name, parameters);
  20466. if (combineArray === null) {
  20467. if (newAction instanceof BABYLON.Condition) {
  20468. condition = newAction;
  20469. newAction = action;
  20470. }
  20471. else {
  20472. condition = null;
  20473. if (action)
  20474. action.then(newAction);
  20475. else
  20476. actionManager.registerAction(newAction);
  20477. }
  20478. }
  20479. else {
  20480. combineArray.push(newAction);
  20481. }
  20482. for (var i = 0; i < parsedAction.children.length; i++)
  20483. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20484. };
  20485. for (var i = 0; i < parsedActions.children.length; i++) {
  20486. var triggerParams;
  20487. var trigger = parsedActions.children[i];
  20488. if (trigger.properties.length > 0) {
  20489. var param = trigger.properties[0].value;
  20490. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20491. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20492. }
  20493. else
  20494. triggerParams = BABYLON.ActionManager[trigger.name];
  20495. for (var j = 0; j < trigger.children.length; j++) {
  20496. if (!trigger.detached)
  20497. traverse(trigger.children[j], triggerParams, null, null);
  20498. }
  20499. }
  20500. };
  20501. var parseSound = function (parsedSound, scene, rootUrl) {
  20502. var soundName = parsedSound.name;
  20503. var soundUrl = rootUrl + soundName;
  20504. var options = {
  20505. autoplay: parsedSound.autoplay,
  20506. loop: parsedSound.loop,
  20507. volume: parsedSound.volume,
  20508. spatialSound: parsedSound.spatialSound,
  20509. maxDistance: parsedSound.maxDistance,
  20510. rolloffFactor: parsedSound.rolloffFactor,
  20511. refDistance: parsedSound.refDistance,
  20512. distanceModel: parsedSound.distanceModel,
  20513. playbackRate: parsedSound.playbackRate
  20514. };
  20515. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20516. scene._removePendingData(newSound);
  20517. }, options);
  20518. scene._addPendingData(newSound);
  20519. if (parsedSound.position) {
  20520. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20521. newSound.setPosition(soundPosition);
  20522. }
  20523. if (parsedSound.isDirectional) {
  20524. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20525. if (parsedSound.localDirectionToMesh) {
  20526. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20527. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20528. }
  20529. }
  20530. if (parsedSound.connectedMeshId) {
  20531. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20532. if (connectedMesh) {
  20533. newSound.attachToMesh(connectedMesh);
  20534. }
  20535. }
  20536. };
  20537. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20538. names = (names instanceof Array) ? names : [names];
  20539. for (var i in names) {
  20540. if (mesh.name === names[i]) {
  20541. hierarchyIds.push(mesh.id);
  20542. return true;
  20543. }
  20544. }
  20545. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20546. hierarchyIds.push(mesh.id);
  20547. return true;
  20548. }
  20549. return false;
  20550. };
  20551. var importVertexData = function (parsedVertexData, geometry) {
  20552. var vertexData = new BABYLON.VertexData();
  20553. // positions
  20554. var positions = parsedVertexData.positions;
  20555. if (positions) {
  20556. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20557. }
  20558. // normals
  20559. var normals = parsedVertexData.normals;
  20560. if (normals) {
  20561. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20562. }
  20563. // uvs
  20564. var uvs = parsedVertexData.uvs;
  20565. if (uvs) {
  20566. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20567. }
  20568. // uv2s
  20569. var uv2s = parsedVertexData.uv2s;
  20570. if (uv2s) {
  20571. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20572. }
  20573. // colors
  20574. var colors = parsedVertexData.colors;
  20575. if (colors) {
  20576. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20577. }
  20578. // matricesIndices
  20579. var matricesIndices = parsedVertexData.matricesIndices;
  20580. if (matricesIndices) {
  20581. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20582. }
  20583. // matricesWeights
  20584. var matricesWeights = parsedVertexData.matricesWeights;
  20585. if (matricesWeights) {
  20586. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20587. }
  20588. // indices
  20589. var indices = parsedVertexData.indices;
  20590. if (indices) {
  20591. vertexData.indices = indices;
  20592. }
  20593. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20594. };
  20595. var importGeometry = function (parsedGeometry, mesh) {
  20596. var scene = mesh.getScene();
  20597. // Geometry
  20598. var geometryId = parsedGeometry.geometryId;
  20599. if (geometryId) {
  20600. var geometry = scene.getGeometryByID(geometryId);
  20601. if (geometry) {
  20602. geometry.applyToMesh(mesh);
  20603. }
  20604. }
  20605. else if (parsedGeometry instanceof ArrayBuffer) {
  20606. var binaryInfo = mesh._binaryInfo;
  20607. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20608. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20609. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20610. }
  20611. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20612. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20613. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20614. }
  20615. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20616. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20617. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20618. }
  20619. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20620. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20621. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20622. }
  20623. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20624. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20625. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20626. }
  20627. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20628. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20629. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20630. }
  20631. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20632. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20634. }
  20635. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20636. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20637. mesh.setIndices(indicesData);
  20638. }
  20639. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20640. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20641. mesh.subMeshes = [];
  20642. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20643. var materialIndex = subMeshesData[(i * 5) + 0];
  20644. var verticesStart = subMeshesData[(i * 5) + 1];
  20645. var verticesCount = subMeshesData[(i * 5) + 2];
  20646. var indexStart = subMeshesData[(i * 5) + 3];
  20647. var indexCount = subMeshesData[(i * 5) + 4];
  20648. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20649. }
  20650. }
  20651. }
  20652. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20653. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20654. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20655. if (parsedGeometry.uvs) {
  20656. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20657. }
  20658. if (parsedGeometry.uvs2) {
  20659. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20660. }
  20661. if (parsedGeometry.colors) {
  20662. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20663. }
  20664. if (parsedGeometry.matricesIndices) {
  20665. if (!parsedGeometry.matricesIndices._isExpanded) {
  20666. var floatIndices = [];
  20667. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20668. var matricesIndex = parsedGeometry.matricesIndices[i];
  20669. floatIndices.push(matricesIndex & 0x000000FF);
  20670. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20671. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20672. floatIndices.push(matricesIndex >> 24);
  20673. }
  20674. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20675. }
  20676. else {
  20677. delete parsedGeometry.matricesIndices._isExpanded;
  20678. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20679. }
  20680. }
  20681. if (parsedGeometry.matricesWeights) {
  20682. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20683. }
  20684. mesh.setIndices(parsedGeometry.indices);
  20685. // SubMeshes
  20686. if (parsedGeometry.subMeshes) {
  20687. mesh.subMeshes = [];
  20688. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20689. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20690. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20691. }
  20692. }
  20693. }
  20694. // Flat shading
  20695. if (mesh._shouldGenerateFlatShading) {
  20696. mesh.convertToFlatShadedMesh();
  20697. delete mesh._shouldGenerateFlatShading;
  20698. }
  20699. // Update
  20700. mesh.computeWorldMatrix(true);
  20701. // Octree
  20702. if (scene._selectionOctree) {
  20703. scene._selectionOctree.addMesh(mesh);
  20704. }
  20705. };
  20706. BABYLON.SceneLoader.RegisterPlugin({
  20707. extensions: ".babylon",
  20708. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20709. var parsedData = JSON.parse(data);
  20710. var loadedSkeletonsIds = [];
  20711. var loadedMaterialsIds = [];
  20712. var hierarchyIds = [];
  20713. for (var index = 0; index < parsedData.meshes.length; index++) {
  20714. var parsedMesh = parsedData.meshes[index];
  20715. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20716. if (meshesNames instanceof Array) {
  20717. // Remove found mesh name from list.
  20718. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20719. }
  20720. // Material ?
  20721. if (parsedMesh.materialId) {
  20722. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20723. if (!materialFound) {
  20724. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20725. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20726. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20727. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20728. var subMatId = parsedMultiMaterial.materials[matIndex];
  20729. loadedMaterialsIds.push(subMatId);
  20730. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20731. }
  20732. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20733. parseMultiMaterial(parsedMultiMaterial, scene);
  20734. materialFound = true;
  20735. break;
  20736. }
  20737. }
  20738. }
  20739. if (!materialFound) {
  20740. loadedMaterialsIds.push(parsedMesh.materialId);
  20741. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20742. }
  20743. }
  20744. // Skeleton ?
  20745. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20746. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20747. if (!skeletonAlreadyLoaded) {
  20748. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20749. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20750. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20751. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20752. loadedSkeletonsIds.push(parsedSkeleton.id);
  20753. }
  20754. }
  20755. }
  20756. }
  20757. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20758. meshes.push(mesh);
  20759. }
  20760. }
  20761. for (index = 0; index < scene.meshes.length; index++) {
  20762. var currentMesh = scene.meshes[index];
  20763. if (currentMesh._waitingParentId) {
  20764. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20765. currentMesh._waitingParentId = undefined;
  20766. }
  20767. }
  20768. // Particles
  20769. if (parsedData.particleSystems) {
  20770. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20771. var parsedParticleSystem = parsedData.particleSystems[index];
  20772. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20773. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20774. }
  20775. }
  20776. }
  20777. return true;
  20778. },
  20779. load: function (scene, data, rootUrl) {
  20780. var parsedData = JSON.parse(data);
  20781. // Scene
  20782. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20783. scene.autoClear = parsedData.autoClear;
  20784. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20785. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20786. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20787. // Fog
  20788. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20789. scene.fogMode = parsedData.fogMode;
  20790. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20791. scene.fogStart = parsedData.fogStart;
  20792. scene.fogEnd = parsedData.fogEnd;
  20793. scene.fogDensity = parsedData.fogDensity;
  20794. }
  20795. for (var index = 0; index < parsedData.lights.length; index++) {
  20796. var parsedLight = parsedData.lights[index];
  20797. parseLight(parsedLight, scene);
  20798. }
  20799. // Materials
  20800. if (parsedData.materials) {
  20801. for (index = 0; index < parsedData.materials.length; index++) {
  20802. var parsedMaterial = parsedData.materials[index];
  20803. parseMaterial(parsedMaterial, scene, rootUrl);
  20804. }
  20805. }
  20806. if (parsedData.multiMaterials) {
  20807. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20808. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20809. parseMultiMaterial(parsedMultiMaterial, scene);
  20810. }
  20811. }
  20812. // Skeletons
  20813. if (parsedData.skeletons) {
  20814. for (index = 0; index < parsedData.skeletons.length; index++) {
  20815. var parsedSkeleton = parsedData.skeletons[index];
  20816. parseSkeleton(parsedSkeleton, scene);
  20817. }
  20818. }
  20819. // Geometries
  20820. var geometries = parsedData.geometries;
  20821. if (geometries) {
  20822. // Boxes
  20823. var boxes = geometries.boxes;
  20824. if (boxes) {
  20825. for (index = 0; index < boxes.length; index++) {
  20826. var parsedBox = boxes[index];
  20827. parseBox(parsedBox, scene);
  20828. }
  20829. }
  20830. // Spheres
  20831. var spheres = geometries.spheres;
  20832. if (spheres) {
  20833. for (index = 0; index < spheres.length; index++) {
  20834. var parsedSphere = spheres[index];
  20835. parseSphere(parsedSphere, scene);
  20836. }
  20837. }
  20838. // Cylinders
  20839. var cylinders = geometries.cylinders;
  20840. if (cylinders) {
  20841. for (index = 0; index < cylinders.length; index++) {
  20842. var parsedCylinder = cylinders[index];
  20843. parseCylinder(parsedCylinder, scene);
  20844. }
  20845. }
  20846. // Toruses
  20847. var toruses = geometries.toruses;
  20848. if (toruses) {
  20849. for (index = 0; index < toruses.length; index++) {
  20850. var parsedTorus = toruses[index];
  20851. parseTorus(parsedTorus, scene);
  20852. }
  20853. }
  20854. // Grounds
  20855. var grounds = geometries.grounds;
  20856. if (grounds) {
  20857. for (index = 0; index < grounds.length; index++) {
  20858. var parsedGround = grounds[index];
  20859. parseGround(parsedGround, scene);
  20860. }
  20861. }
  20862. // Planes
  20863. var planes = geometries.planes;
  20864. if (planes) {
  20865. for (index = 0; index < planes.length; index++) {
  20866. var parsedPlane = planes[index];
  20867. parsePlane(parsedPlane, scene);
  20868. }
  20869. }
  20870. // TorusKnots
  20871. var torusKnots = geometries.torusKnots;
  20872. if (torusKnots) {
  20873. for (index = 0; index < torusKnots.length; index++) {
  20874. var parsedTorusKnot = torusKnots[index];
  20875. parseTorusKnot(parsedTorusKnot, scene);
  20876. }
  20877. }
  20878. // VertexData
  20879. var vertexData = geometries.vertexData;
  20880. if (vertexData) {
  20881. for (index = 0; index < vertexData.length; index++) {
  20882. var parsedVertexData = vertexData[index];
  20883. parseVertexData(parsedVertexData, scene, rootUrl);
  20884. }
  20885. }
  20886. }
  20887. for (index = 0; index < parsedData.meshes.length; index++) {
  20888. var parsedMesh = parsedData.meshes[index];
  20889. parseMesh(parsedMesh, scene, rootUrl);
  20890. }
  20891. for (index = 0; index < parsedData.cameras.length; index++) {
  20892. var parsedCamera = parsedData.cameras[index];
  20893. parseCamera(parsedCamera, scene);
  20894. }
  20895. if (parsedData.activeCameraID) {
  20896. scene.setActiveCameraByID(parsedData.activeCameraID);
  20897. }
  20898. for (index = 0; index < scene.cameras.length; index++) {
  20899. var camera = scene.cameras[index];
  20900. if (camera._waitingParentId) {
  20901. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20902. camera._waitingParentId = undefined;
  20903. }
  20904. }
  20905. for (index = 0; index < scene.lights.length; index++) {
  20906. var light = scene.lights[index];
  20907. if (light._waitingParentId) {
  20908. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20909. light._waitingParentId = undefined;
  20910. }
  20911. }
  20912. // Sounds
  20913. if (parsedData.sounds) {
  20914. for (index = 0; index < parsedData.sounds.length; index++) {
  20915. var parsedSound = parsedData.sounds[index];
  20916. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20917. parseSound(parsedSound, scene, rootUrl);
  20918. }
  20919. else {
  20920. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20921. }
  20922. }
  20923. }
  20924. for (index = 0; index < scene.meshes.length; index++) {
  20925. var mesh = scene.meshes[index];
  20926. if (mesh._waitingParentId) {
  20927. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20928. mesh._waitingParentId = undefined;
  20929. }
  20930. if (mesh._waitingActions) {
  20931. parseActions(mesh._waitingActions, mesh, scene);
  20932. mesh._waitingActions = undefined;
  20933. }
  20934. }
  20935. // Particles Systems
  20936. if (parsedData.particleSystems) {
  20937. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20938. var parsedParticleSystem = parsedData.particleSystems[index];
  20939. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20940. }
  20941. }
  20942. // Lens flares
  20943. if (parsedData.lensFlareSystems) {
  20944. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20945. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20946. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20947. }
  20948. }
  20949. // Shadows
  20950. if (parsedData.shadowGenerators) {
  20951. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20952. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20953. parseShadowGenerator(parsedShadowGenerator, scene);
  20954. }
  20955. }
  20956. // Actions (scene)
  20957. if (parsedData.actions) {
  20958. parseActions(parsedData.actions, null, scene);
  20959. }
  20960. // Finish
  20961. return true;
  20962. }
  20963. });
  20964. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20965. })(BABYLON || (BABYLON = {}));
  20966. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20967. (function (BABYLON) {
  20968. // Unique ID when we import meshes from Babylon to CSG
  20969. var currentCSGMeshId = 0;
  20970. // # class Vertex
  20971. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20972. // one to provide additional features like texture coordinates and vertex
  20973. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20974. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20975. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20976. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20977. // is not used anywhere else.
  20978. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20979. var Vertex = (function () {
  20980. function Vertex(pos, normal, uv) {
  20981. this.pos = pos;
  20982. this.normal = normal;
  20983. this.uv = uv;
  20984. }
  20985. Vertex.prototype.clone = function () {
  20986. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20987. };
  20988. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20989. // orientation of a polygon is flipped.
  20990. Vertex.prototype.flip = function () {
  20991. this.normal = this.normal.scale(-1);
  20992. };
  20993. // Create a new vertex between this vertex and `other` by linearly
  20994. // interpolating all properties using a parameter of `t`. Subclasses should
  20995. // override this to interpolate additional properties.
  20996. Vertex.prototype.interpolate = function (other, t) {
  20997. 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));
  20998. };
  20999. return Vertex;
  21000. })();
  21001. // # class Plane
  21002. // Represents a plane in 3D space.
  21003. var Plane = (function () {
  21004. function Plane(normal, w) {
  21005. this.normal = normal;
  21006. this.w = w;
  21007. }
  21008. Plane.FromPoints = function (a, b, c) {
  21009. var v0 = c.subtract(a);
  21010. var v1 = b.subtract(a);
  21011. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  21012. return null;
  21013. }
  21014. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  21015. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  21016. };
  21017. Plane.prototype.clone = function () {
  21018. return new Plane(this.normal.clone(), this.w);
  21019. };
  21020. Plane.prototype.flip = function () {
  21021. this.normal.scaleInPlace(-1);
  21022. this.w = -this.w;
  21023. };
  21024. // Split `polygon` by this plane if needed, then put the polygon or polygon
  21025. // fragments in the appropriate lists. Coplanar polygons go into either
  21026. // `coplanarFront` or `coplanarBack` depending on their orientation with
  21027. // respect to this plane. Polygons in front or in back of this plane go into
  21028. // either `front` or `back`.
  21029. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  21030. var COPLANAR = 0;
  21031. var FRONT = 1;
  21032. var BACK = 2;
  21033. var SPANNING = 3;
  21034. // Classify each point as well as the entire polygon into one of the above
  21035. // four classes.
  21036. var polygonType = 0;
  21037. var types = [];
  21038. for (var i = 0; i < polygon.vertices.length; i++) {
  21039. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  21040. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  21041. polygonType |= type;
  21042. types.push(type);
  21043. }
  21044. switch (polygonType) {
  21045. case COPLANAR:
  21046. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  21047. break;
  21048. case FRONT:
  21049. front.push(polygon);
  21050. break;
  21051. case BACK:
  21052. back.push(polygon);
  21053. break;
  21054. case SPANNING:
  21055. var f = [], b = [];
  21056. for (i = 0; i < polygon.vertices.length; i++) {
  21057. var j = (i + 1) % polygon.vertices.length;
  21058. var ti = types[i], tj = types[j];
  21059. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  21060. if (ti != BACK)
  21061. f.push(vi);
  21062. if (ti != FRONT)
  21063. b.push(ti != BACK ? vi.clone() : vi);
  21064. if ((ti | tj) == SPANNING) {
  21065. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  21066. var v = vi.interpolate(vj, t);
  21067. f.push(v);
  21068. b.push(v.clone());
  21069. }
  21070. }
  21071. if (f.length >= 3) {
  21072. var poly = new Polygon(f, polygon.shared);
  21073. if (poly.plane)
  21074. front.push(poly);
  21075. }
  21076. if (b.length >= 3) {
  21077. poly = new Polygon(b, polygon.shared);
  21078. if (poly.plane)
  21079. back.push(poly);
  21080. }
  21081. break;
  21082. }
  21083. };
  21084. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  21085. // point is on the plane.
  21086. Plane.EPSILON = 1e-5;
  21087. return Plane;
  21088. })();
  21089. // # class Polygon
  21090. // Represents a convex polygon. The vertices used to initialize a polygon must
  21091. // be coplanar and form a convex loop.
  21092. //
  21093. // Each convex polygon has a `shared` property, which is shared between all
  21094. // polygons that are clones of each other or were split from the same polygon.
  21095. // This can be used to define per-polygon properties (such as surface color).
  21096. var Polygon = (function () {
  21097. function Polygon(vertices, shared) {
  21098. this.vertices = vertices;
  21099. this.shared = shared;
  21100. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  21101. }
  21102. Polygon.prototype.clone = function () {
  21103. var vertices = this.vertices.map(function (v) { return v.clone(); });
  21104. return new Polygon(vertices, this.shared);
  21105. };
  21106. Polygon.prototype.flip = function () {
  21107. this.vertices.reverse().map(function (v) {
  21108. v.flip();
  21109. });
  21110. this.plane.flip();
  21111. };
  21112. return Polygon;
  21113. })();
  21114. // # class Node
  21115. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  21116. // by picking a polygon to split along. That polygon (and all other coplanar
  21117. // polygons) are added directly to that node and the other polygons are added to
  21118. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  21119. // no distinction between internal and leaf nodes.
  21120. var Node = (function () {
  21121. function Node(polygons) {
  21122. this.plane = null;
  21123. this.front = null;
  21124. this.back = null;
  21125. this.polygons = [];
  21126. if (polygons) {
  21127. this.build(polygons);
  21128. }
  21129. }
  21130. Node.prototype.clone = function () {
  21131. var node = new Node();
  21132. node.plane = this.plane && this.plane.clone();
  21133. node.front = this.front && this.front.clone();
  21134. node.back = this.back && this.back.clone();
  21135. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  21136. return node;
  21137. };
  21138. // Convert solid space to empty space and empty space to solid space.
  21139. Node.prototype.invert = function () {
  21140. for (var i = 0; i < this.polygons.length; i++) {
  21141. this.polygons[i].flip();
  21142. }
  21143. if (this.plane) {
  21144. this.plane.flip();
  21145. }
  21146. if (this.front) {
  21147. this.front.invert();
  21148. }
  21149. if (this.back) {
  21150. this.back.invert();
  21151. }
  21152. var temp = this.front;
  21153. this.front = this.back;
  21154. this.back = temp;
  21155. };
  21156. // Recursively remove all polygons in `polygons` that are inside this BSP
  21157. // tree.
  21158. Node.prototype.clipPolygons = function (polygons) {
  21159. if (!this.plane)
  21160. return polygons.slice();
  21161. var front = [], back = [];
  21162. for (var i = 0; i < polygons.length; i++) {
  21163. this.plane.splitPolygon(polygons[i], front, back, front, back);
  21164. }
  21165. if (this.front) {
  21166. front = this.front.clipPolygons(front);
  21167. }
  21168. if (this.back) {
  21169. back = this.back.clipPolygons(back);
  21170. }
  21171. else {
  21172. back = [];
  21173. }
  21174. return front.concat(back);
  21175. };
  21176. // Remove all polygons in this BSP tree that are inside the other BSP tree
  21177. // `bsp`.
  21178. Node.prototype.clipTo = function (bsp) {
  21179. this.polygons = bsp.clipPolygons(this.polygons);
  21180. if (this.front)
  21181. this.front.clipTo(bsp);
  21182. if (this.back)
  21183. this.back.clipTo(bsp);
  21184. };
  21185. // Return a list of all polygons in this BSP tree.
  21186. Node.prototype.allPolygons = function () {
  21187. var polygons = this.polygons.slice();
  21188. if (this.front)
  21189. polygons = polygons.concat(this.front.allPolygons());
  21190. if (this.back)
  21191. polygons = polygons.concat(this.back.allPolygons());
  21192. return polygons;
  21193. };
  21194. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  21195. // new polygons are filtered down to the bottom of the tree and become new
  21196. // nodes there. Each set of polygons is partitioned using the first polygon
  21197. // (no heuristic is used to pick a good split).
  21198. Node.prototype.build = function (polygons) {
  21199. if (!polygons.length)
  21200. return;
  21201. if (!this.plane)
  21202. this.plane = polygons[0].plane.clone();
  21203. var front = [], back = [];
  21204. for (var i = 0; i < polygons.length; i++) {
  21205. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  21206. }
  21207. if (front.length) {
  21208. if (!this.front)
  21209. this.front = new Node();
  21210. this.front.build(front);
  21211. }
  21212. if (back.length) {
  21213. if (!this.back)
  21214. this.back = new Node();
  21215. this.back.build(back);
  21216. }
  21217. };
  21218. return Node;
  21219. })();
  21220. var CSG = (function () {
  21221. function CSG() {
  21222. this.polygons = new Array();
  21223. }
  21224. // Convert BABYLON.Mesh to BABYLON.CSG
  21225. CSG.FromMesh = function (mesh) {
  21226. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21227. if (mesh instanceof BABYLON.Mesh) {
  21228. mesh.computeWorldMatrix(true);
  21229. var matrix = mesh.getWorldMatrix();
  21230. var meshPosition = mesh.position.clone();
  21231. var meshRotation = mesh.rotation.clone();
  21232. var meshScaling = mesh.scaling.clone();
  21233. }
  21234. else {
  21235. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21236. }
  21237. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21238. var subMeshes = mesh.subMeshes;
  21239. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21240. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21241. vertices = [];
  21242. for (var j = 0; j < 3; j++) {
  21243. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21244. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21245. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21246. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21247. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21248. vertex = new Vertex(position, normal, uv);
  21249. vertices.push(vertex);
  21250. }
  21251. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21252. // To handle the case of degenerated triangle
  21253. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21254. if (polygon.plane)
  21255. polygons.push(polygon);
  21256. }
  21257. }
  21258. var csg = CSG.FromPolygons(polygons);
  21259. csg.matrix = matrix;
  21260. csg.position = meshPosition;
  21261. csg.rotation = meshRotation;
  21262. csg.scaling = meshScaling;
  21263. currentCSGMeshId++;
  21264. return csg;
  21265. };
  21266. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21267. CSG.FromPolygons = function (polygons) {
  21268. var csg = new BABYLON.CSG();
  21269. csg.polygons = polygons;
  21270. return csg;
  21271. };
  21272. CSG.prototype.clone = function () {
  21273. var csg = new BABYLON.CSG();
  21274. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21275. csg.copyTransformAttributes(this);
  21276. return csg;
  21277. };
  21278. CSG.prototype.toPolygons = function () {
  21279. return this.polygons;
  21280. };
  21281. CSG.prototype.union = function (csg) {
  21282. var a = new Node(this.clone().polygons);
  21283. var b = new Node(csg.clone().polygons);
  21284. a.clipTo(b);
  21285. b.clipTo(a);
  21286. b.invert();
  21287. b.clipTo(a);
  21288. b.invert();
  21289. a.build(b.allPolygons());
  21290. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21291. };
  21292. CSG.prototype.unionInPlace = function (csg) {
  21293. var a = new Node(this.polygons);
  21294. var b = new Node(csg.polygons);
  21295. a.clipTo(b);
  21296. b.clipTo(a);
  21297. b.invert();
  21298. b.clipTo(a);
  21299. b.invert();
  21300. a.build(b.allPolygons());
  21301. this.polygons = a.allPolygons();
  21302. };
  21303. CSG.prototype.subtract = function (csg) {
  21304. var a = new Node(this.clone().polygons);
  21305. var b = new Node(csg.clone().polygons);
  21306. a.invert();
  21307. a.clipTo(b);
  21308. b.clipTo(a);
  21309. b.invert();
  21310. b.clipTo(a);
  21311. b.invert();
  21312. a.build(b.allPolygons());
  21313. a.invert();
  21314. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21315. };
  21316. CSG.prototype.subtractInPlace = function (csg) {
  21317. var a = new Node(this.polygons);
  21318. var b = new Node(csg.polygons);
  21319. a.invert();
  21320. a.clipTo(b);
  21321. b.clipTo(a);
  21322. b.invert();
  21323. b.clipTo(a);
  21324. b.invert();
  21325. a.build(b.allPolygons());
  21326. a.invert();
  21327. this.polygons = a.allPolygons();
  21328. };
  21329. CSG.prototype.intersect = function (csg) {
  21330. var a = new Node(this.clone().polygons);
  21331. var b = new Node(csg.clone().polygons);
  21332. a.invert();
  21333. b.clipTo(a);
  21334. b.invert();
  21335. a.clipTo(b);
  21336. b.clipTo(a);
  21337. a.build(b.allPolygons());
  21338. a.invert();
  21339. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21340. };
  21341. CSG.prototype.intersectInPlace = function (csg) {
  21342. var a = new Node(this.polygons);
  21343. var b = new Node(csg.polygons);
  21344. a.invert();
  21345. b.clipTo(a);
  21346. b.invert();
  21347. a.clipTo(b);
  21348. b.clipTo(a);
  21349. a.build(b.allPolygons());
  21350. a.invert();
  21351. this.polygons = a.allPolygons();
  21352. };
  21353. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21354. // not modified.
  21355. CSG.prototype.inverse = function () {
  21356. var csg = this.clone();
  21357. csg.inverseInPlace();
  21358. return csg;
  21359. };
  21360. CSG.prototype.inverseInPlace = function () {
  21361. this.polygons.map(function (p) {
  21362. p.flip();
  21363. });
  21364. };
  21365. // This is used to keep meshes transformations so they can be restored
  21366. // when we build back a Babylon Mesh
  21367. // NB : All CSG operations are performed in world coordinates
  21368. CSG.prototype.copyTransformAttributes = function (csg) {
  21369. this.matrix = csg.matrix;
  21370. this.position = csg.position;
  21371. this.rotation = csg.rotation;
  21372. this.scaling = csg.scaling;
  21373. return this;
  21374. };
  21375. // Build Raw mesh from CSG
  21376. // Coordinates here are in world space
  21377. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21378. var matrix = this.matrix.clone();
  21379. matrix.invert();
  21380. 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;
  21381. if (keepSubMeshes) {
  21382. // Sort Polygons, since subMeshes are indices range
  21383. polygons.sort(function (a, b) {
  21384. if (a.shared.meshId === b.shared.meshId) {
  21385. return a.shared.subMeshId - b.shared.subMeshId;
  21386. }
  21387. else {
  21388. return a.shared.meshId - b.shared.meshId;
  21389. }
  21390. });
  21391. }
  21392. for (var i = 0, il = polygons.length; i < il; i++) {
  21393. polygon = polygons[i];
  21394. // Building SubMeshes
  21395. if (!subMesh_dict[polygon.shared.meshId]) {
  21396. subMesh_dict[polygon.shared.meshId] = {};
  21397. }
  21398. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21399. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21400. indexStart: +Infinity,
  21401. indexEnd: -Infinity,
  21402. materialIndex: polygon.shared.materialIndex
  21403. };
  21404. }
  21405. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21406. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21407. polygonIndices[0] = 0;
  21408. polygonIndices[1] = j - 1;
  21409. polygonIndices[2] = j;
  21410. for (var k = 0; k < 3; k++) {
  21411. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21412. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21413. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21414. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21415. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21416. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21417. // Check if 2 points can be merged
  21418. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  21419. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21420. uvs.push(uv.x, uv.y);
  21421. normals.push(normal.x, normal.y, normal.z);
  21422. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21423. }
  21424. indices.push(vertex_idx);
  21425. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21426. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21427. currentIndex++;
  21428. }
  21429. }
  21430. }
  21431. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21432. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21433. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21434. mesh.setIndices(indices);
  21435. if (keepSubMeshes) {
  21436. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21437. var materialIndexOffset = 0, materialMaxIndex;
  21438. mesh.subMeshes.length = 0;
  21439. for (var m in subMesh_dict) {
  21440. materialMaxIndex = -1;
  21441. for (var sm in subMesh_dict[m]) {
  21442. subMesh_obj = subMesh_dict[m][sm];
  21443. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21444. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21445. }
  21446. materialIndexOffset += ++materialMaxIndex;
  21447. }
  21448. }
  21449. return mesh;
  21450. };
  21451. // Build Mesh from CSG taking material and transforms into account
  21452. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21453. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21454. mesh.material = material;
  21455. mesh.position.copyFrom(this.position);
  21456. mesh.rotation.copyFrom(this.rotation);
  21457. mesh.scaling.copyFrom(this.scaling);
  21458. mesh.computeWorldMatrix(true);
  21459. return mesh;
  21460. };
  21461. return CSG;
  21462. })();
  21463. BABYLON.CSG = CSG;
  21464. })(BABYLON || (BABYLON = {}));
  21465. //# sourceMappingURL=babylon.csg.js.map
  21466. var BABYLON;
  21467. (function (BABYLON) {
  21468. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21469. __extends(OculusDistortionCorrectionPostProcess, _super);
  21470. //ANY
  21471. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21472. var _this = this;
  21473. _super.call(this, name, "oculusDistortionCorrection", [
  21474. 'LensCenter',
  21475. 'Scale',
  21476. 'ScaleIn',
  21477. 'HmdWarpParam'
  21478. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21479. this._isRightEye = isRightEye;
  21480. this._distortionFactors = cameraSettings.DistortionK;
  21481. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21482. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21483. this.onSizeChanged = function () {
  21484. _this.aspectRatio = _this.width * .5 / _this.height;
  21485. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21486. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21487. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21488. };
  21489. this.onApply = function (effect) {
  21490. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21491. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21492. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21493. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21494. };
  21495. }
  21496. return OculusDistortionCorrectionPostProcess;
  21497. })(BABYLON.PostProcess);
  21498. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21499. })(BABYLON || (BABYLON = {}));
  21500. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21501. // 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
  21502. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21503. var BABYLON;
  21504. (function (BABYLON) {
  21505. (function (JoystickAxis) {
  21506. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21507. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21508. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21509. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21510. var JoystickAxis = BABYLON.JoystickAxis;
  21511. var VirtualJoystick = (function () {
  21512. function VirtualJoystick(leftJoystick) {
  21513. var _this = this;
  21514. if (leftJoystick) {
  21515. this._leftJoystick = true;
  21516. }
  21517. else {
  21518. this._leftJoystick = false;
  21519. }
  21520. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21521. VirtualJoystick._globalJoystickIndex++;
  21522. // By default left & right arrow keys are moving the X
  21523. // and up & down keys are moving the Y
  21524. this._axisTargetedByLeftAndRight = 0 /* X */;
  21525. this._axisTargetedByUpAndDown = 1 /* Y */;
  21526. this.reverseLeftRight = false;
  21527. this.reverseUpDown = false;
  21528. // collections of pointers
  21529. this._touches = new BABYLON.SmartCollection();
  21530. this.deltaPosition = BABYLON.Vector3.Zero();
  21531. this._joystickSensibility = 25;
  21532. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21533. this._rotationSpeed = 25;
  21534. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21535. this._rotateOnAxisRelativeToMesh = false;
  21536. // injecting a canvas element on top of the canvas 3D game
  21537. if (!VirtualJoystick.vjCanvas) {
  21538. window.addEventListener("resize", function () {
  21539. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21540. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21541. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21542. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21543. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21544. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21545. }, false);
  21546. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21547. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21548. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21549. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21550. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21551. VirtualJoystick.vjCanvas.style.width = "100%";
  21552. VirtualJoystick.vjCanvas.style.height = "100%";
  21553. VirtualJoystick.vjCanvas.style.position = "absolute";
  21554. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21555. VirtualJoystick.vjCanvas.style.top = "0px";
  21556. VirtualJoystick.vjCanvas.style.left = "0px";
  21557. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21558. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21559. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21560. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21561. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21562. document.body.appendChild(VirtualJoystick.vjCanvas);
  21563. }
  21564. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21565. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21566. this.pressed = false;
  21567. // default joystick color
  21568. this._joystickColor = "cyan";
  21569. this._joystickPointerID = -1;
  21570. // current joystick position
  21571. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21572. // origin joystick position
  21573. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21574. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21575. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21576. _this._onPointerDown(evt);
  21577. }, false);
  21578. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21579. _this._onPointerMove(evt);
  21580. }, false);
  21581. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21582. _this._onPointerUp(evt);
  21583. }, false);
  21584. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21585. _this._onPointerUp(evt);
  21586. }, false);
  21587. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21588. evt.preventDefault(); // Disables system menu
  21589. }, false);
  21590. requestAnimationFrame(function () {
  21591. _this._drawVirtualJoystick();
  21592. });
  21593. }
  21594. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21595. this._joystickSensibility = newJoystickSensibility;
  21596. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21597. };
  21598. VirtualJoystick.prototype._onPointerDown = function (e) {
  21599. var positionOnScreenCondition;
  21600. e.preventDefault();
  21601. if (this._leftJoystick === true) {
  21602. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21603. }
  21604. else {
  21605. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21606. }
  21607. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21608. // First contact will be dedicated to the virtual joystick
  21609. this._joystickPointerID = e.pointerId;
  21610. this._joystickPointerStartPos.x = e.clientX;
  21611. this._joystickPointerStartPos.y = e.clientY;
  21612. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21613. this._deltaJoystickVector.x = 0;
  21614. this._deltaJoystickVector.y = 0;
  21615. this.pressed = true;
  21616. this._touches.add(e.pointerId.toString(), e);
  21617. }
  21618. else {
  21619. // You can only trigger the action buttons with a joystick declared
  21620. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21621. this._action();
  21622. this._touches.add(e.pointerId.toString(), e);
  21623. }
  21624. }
  21625. };
  21626. VirtualJoystick.prototype._onPointerMove = function (e) {
  21627. // If the current pointer is the one associated to the joystick (first touch contact)
  21628. if (this._joystickPointerID == e.pointerId) {
  21629. this._joystickPointerPos.x = e.clientX;
  21630. this._joystickPointerPos.y = e.clientY;
  21631. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21632. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21633. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21634. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21635. switch (this._axisTargetedByLeftAndRight) {
  21636. case 0 /* X */:
  21637. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21638. break;
  21639. case 1 /* Y */:
  21640. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21641. break;
  21642. case 2 /* Z */:
  21643. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21644. break;
  21645. }
  21646. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21647. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21648. switch (this._axisTargetedByUpAndDown) {
  21649. case 0 /* X */:
  21650. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21651. break;
  21652. case 1 /* Y */:
  21653. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21654. break;
  21655. case 2 /* Z */:
  21656. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21657. break;
  21658. }
  21659. }
  21660. else {
  21661. if (this._touches.item(e.pointerId.toString())) {
  21662. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21663. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21664. }
  21665. }
  21666. };
  21667. VirtualJoystick.prototype._onPointerUp = function (e) {
  21668. this._clearCanvas();
  21669. if (this._joystickPointerID == e.pointerId) {
  21670. this._joystickPointerID = -1;
  21671. this.pressed = false;
  21672. }
  21673. this._deltaJoystickVector.x = 0;
  21674. this._deltaJoystickVector.y = 0;
  21675. this._touches.remove(e.pointerId.toString());
  21676. };
  21677. /**
  21678. * Change the color of the virtual joystick
  21679. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21680. */
  21681. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21682. this._joystickColor = newColor;
  21683. };
  21684. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21685. this._action = action;
  21686. };
  21687. // Define which axis you'd like to control for left & right
  21688. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21689. switch (axis) {
  21690. case 0 /* X */:
  21691. case 1 /* Y */:
  21692. case 2 /* Z */:
  21693. this._axisTargetedByLeftAndRight = axis;
  21694. break;
  21695. default:
  21696. this._axisTargetedByLeftAndRight = 0 /* X */;
  21697. break;
  21698. }
  21699. };
  21700. // Define which axis you'd like to control for up & down
  21701. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21702. switch (axis) {
  21703. case 0 /* X */:
  21704. case 1 /* Y */:
  21705. case 2 /* Z */:
  21706. this._axisTargetedByUpAndDown = axis;
  21707. break;
  21708. default:
  21709. this._axisTargetedByUpAndDown = 1 /* Y */;
  21710. break;
  21711. }
  21712. };
  21713. VirtualJoystick.prototype._clearCanvas = function () {
  21714. if (this._leftJoystick) {
  21715. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21716. }
  21717. else {
  21718. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21719. }
  21720. };
  21721. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21722. var _this = this;
  21723. if (this.pressed) {
  21724. this._clearCanvas();
  21725. this._touches.forEach(function (touch) {
  21726. if (touch.pointerId === _this._joystickPointerID) {
  21727. VirtualJoystick.vjCanvasContext.beginPath();
  21728. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21729. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21730. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21731. VirtualJoystick.vjCanvasContext.stroke();
  21732. VirtualJoystick.vjCanvasContext.beginPath();
  21733. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21734. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21735. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21736. VirtualJoystick.vjCanvasContext.stroke();
  21737. VirtualJoystick.vjCanvasContext.beginPath();
  21738. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21739. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21740. VirtualJoystick.vjCanvasContext.stroke();
  21741. }
  21742. else {
  21743. VirtualJoystick.vjCanvasContext.beginPath();
  21744. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21745. VirtualJoystick.vjCanvasContext.beginPath();
  21746. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21747. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21748. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21749. VirtualJoystick.vjCanvasContext.stroke();
  21750. }
  21751. ;
  21752. });
  21753. }
  21754. requestAnimationFrame(function () {
  21755. _this._drawVirtualJoystick();
  21756. });
  21757. };
  21758. VirtualJoystick.prototype.releaseCanvas = function () {
  21759. if (VirtualJoystick.vjCanvas) {
  21760. document.body.removeChild(VirtualJoystick.vjCanvas);
  21761. VirtualJoystick.vjCanvas = null;
  21762. }
  21763. };
  21764. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21765. VirtualJoystick._globalJoystickIndex = 0;
  21766. return VirtualJoystick;
  21767. })();
  21768. BABYLON.VirtualJoystick = VirtualJoystick;
  21769. })(BABYLON || (BABYLON = {}));
  21770. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21771. var BABYLON;
  21772. (function (BABYLON) {
  21773. var OculusRiftDevKit2013_Metric = {
  21774. HResolution: 1280,
  21775. VResolution: 800,
  21776. HScreenSize: 0.149759993,
  21777. VScreenSize: 0.0935999975,
  21778. VScreenCenter: 0.0467999987,
  21779. EyeToScreenDistance: 0.0410000011,
  21780. LensSeparationDistance: 0.0635000020,
  21781. InterpupillaryDistance: 0.0640000030,
  21782. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21783. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21784. PostProcessScaleFactor: 1.714605507808412,
  21785. LensCenterOffset: 0.151976421
  21786. };
  21787. var _OculusInnerCamera = (function (_super) {
  21788. __extends(_OculusInnerCamera, _super);
  21789. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21790. _super.call(this, name, position, scene);
  21791. this._workMatrix = new BABYLON.Matrix();
  21792. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21793. // Constants
  21794. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21795. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21796. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21797. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21798. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21799. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21800. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21801. // Postprocess
  21802. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21803. }
  21804. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21805. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21806. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21807. return this._projectionMatrix;
  21808. };
  21809. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21810. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21811. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21812. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21813. // Computing target and final matrix
  21814. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21815. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21816. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21817. return this._viewMatrix;
  21818. };
  21819. return _OculusInnerCamera;
  21820. })(BABYLON.FreeCamera);
  21821. var OculusCamera = (function (_super) {
  21822. __extends(OculusCamera, _super);
  21823. function OculusCamera(name, position, scene) {
  21824. _super.call(this, name, position, scene);
  21825. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21826. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21827. this.subCameras.push(this._leftCamera);
  21828. this.subCameras.push(this._rightCamera);
  21829. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21830. }
  21831. OculusCamera.prototype._update = function () {
  21832. this._leftCamera.position.copyFrom(this.position);
  21833. this._rightCamera.position.copyFrom(this.position);
  21834. this._updateCamera(this._leftCamera);
  21835. this._updateCamera(this._rightCamera);
  21836. _super.prototype._update.call(this);
  21837. };
  21838. OculusCamera.prototype._updateCamera = function (camera) {
  21839. camera.minZ = this.minZ;
  21840. camera.maxZ = this.maxZ;
  21841. camera.rotation.x = this.rotation.x;
  21842. camera.rotation.y = this.rotation.y;
  21843. camera.rotation.z = this.rotation.z;
  21844. };
  21845. // Oculus events
  21846. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21847. var yaw = evt.alpha / 180 * Math.PI;
  21848. var pitch = evt.beta / 180 * Math.PI;
  21849. var roll = evt.gamma / 180 * Math.PI;
  21850. if (!this._offsetOrientation) {
  21851. this._offsetOrientation = {
  21852. yaw: yaw,
  21853. pitch: pitch,
  21854. roll: roll
  21855. };
  21856. return;
  21857. }
  21858. else {
  21859. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21860. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21861. this.rotation.z += this._offsetOrientation.roll - roll;
  21862. this._offsetOrientation.yaw = yaw;
  21863. this._offsetOrientation.pitch = pitch;
  21864. this._offsetOrientation.roll = roll;
  21865. }
  21866. };
  21867. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21868. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21869. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21870. };
  21871. OculusCamera.prototype.detachControl = function (element) {
  21872. _super.prototype.detachControl.call(this, element);
  21873. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21874. };
  21875. return OculusCamera;
  21876. })(BABYLON.FreeCamera);
  21877. BABYLON.OculusCamera = OculusCamera;
  21878. })(BABYLON || (BABYLON = {}));
  21879. //# sourceMappingURL=babylon.oculusCamera.js.map
  21880. var BABYLON;
  21881. (function (BABYLON) {
  21882. var OculusRiftDevKit2013_Metric = {
  21883. HResolution: 1280,
  21884. VResolution: 800,
  21885. HScreenSize: 0.149759993,
  21886. VScreenSize: 0.0935999975,
  21887. VScreenCenter: 0.0467999987,
  21888. EyeToScreenDistance: 0.0410000011,
  21889. LensSeparationDistance: 0.0635000020,
  21890. InterpupillaryDistance: 0.0640000030,
  21891. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21892. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21893. PostProcessScaleFactor: 1.714605507808412,
  21894. LensCenterOffset: 0.151976421
  21895. };
  21896. var _OculusInnerGamepadCamera = (function (_super) {
  21897. __extends(_OculusInnerGamepadCamera, _super);
  21898. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21899. _super.call(this, name, position, scene);
  21900. this._workMatrix = new BABYLON.Matrix();
  21901. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21902. // Constants
  21903. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21904. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21905. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21906. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21907. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21908. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21909. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21910. // Postprocess
  21911. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21912. }
  21913. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21914. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21915. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21916. return this._projectionMatrix;
  21917. };
  21918. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21919. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21920. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21921. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21922. // Computing target and final matrix
  21923. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21924. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21925. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21926. return this._viewMatrix;
  21927. };
  21928. return _OculusInnerGamepadCamera;
  21929. })(BABYLON.FreeCamera);
  21930. var OculusGamepadCamera = (function (_super) {
  21931. __extends(OculusGamepadCamera, _super);
  21932. function OculusGamepadCamera(name, position, scene) {
  21933. var _this = this;
  21934. _super.call(this, name, position, scene);
  21935. this.angularSensibility = 200;
  21936. this.moveSensibility = 75;
  21937. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21938. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21939. this.subCameras.push(this._leftCamera);
  21940. this.subCameras.push(this._rightCamera);
  21941. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21942. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21943. _this._onNewGameConnected(gamepad);
  21944. });
  21945. }
  21946. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21947. // Only the first gamepad can control the camera
  21948. if (gamepad.index === 0) {
  21949. this._gamepad = gamepad;
  21950. }
  21951. };
  21952. OculusGamepadCamera.prototype._update = function () {
  21953. this._leftCamera.position.copyFrom(this.position);
  21954. this._rightCamera.position.copyFrom(this.position);
  21955. this._updateCamera(this._leftCamera);
  21956. this._updateCamera(this._rightCamera);
  21957. _super.prototype._update.call(this);
  21958. };
  21959. OculusGamepadCamera.prototype._checkInputs = function () {
  21960. if (!this._gamepad) {
  21961. return;
  21962. }
  21963. var LSValues = this._gamepad.leftStick;
  21964. var normalizedLX = LSValues.x / this.moveSensibility;
  21965. var normalizedLY = LSValues.y / this.moveSensibility;
  21966. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21967. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21968. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21969. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21970. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21971. };
  21972. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21973. camera.minZ = this.minZ;
  21974. camera.maxZ = this.maxZ;
  21975. camera.rotation.x = this.rotation.x;
  21976. camera.rotation.y = this.rotation.y;
  21977. camera.rotation.z = this.rotation.z;
  21978. };
  21979. // Oculus events
  21980. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21981. var yaw = evt.alpha / 180 * Math.PI;
  21982. var pitch = evt.beta / 180 * Math.PI;
  21983. var roll = evt.gamma / 180 * Math.PI;
  21984. if (!this._offsetOrientation) {
  21985. this._offsetOrientation = {
  21986. yaw: yaw,
  21987. pitch: pitch,
  21988. roll: roll
  21989. };
  21990. return;
  21991. }
  21992. else {
  21993. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21994. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21995. this.rotation.z += this._offsetOrientation.roll - roll;
  21996. this._offsetOrientation.yaw = yaw;
  21997. this._offsetOrientation.pitch = pitch;
  21998. this._offsetOrientation.roll = roll;
  21999. }
  22000. };
  22001. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  22002. _super.prototype.attachControl.call(this, element, noPreventDefault);
  22003. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  22004. };
  22005. OculusGamepadCamera.prototype.detachControl = function (element) {
  22006. _super.prototype.detachControl.call(this, element);
  22007. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  22008. };
  22009. OculusGamepadCamera.prototype.dispose = function () {
  22010. this._gamepads.dispose();
  22011. _super.prototype.dispose.call(this);
  22012. };
  22013. return OculusGamepadCamera;
  22014. })(BABYLON.FreeCamera);
  22015. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  22016. })(BABYLON || (BABYLON = {}));
  22017. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  22018. var BABYLON;
  22019. (function (BABYLON) {
  22020. // We're mainly based on the logic defined into the FreeCamera code
  22021. var VirtualJoysticksCamera = (function (_super) {
  22022. __extends(VirtualJoysticksCamera, _super);
  22023. function VirtualJoysticksCamera(name, position, scene) {
  22024. _super.call(this, name, position, scene);
  22025. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  22026. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  22027. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  22028. this._leftjoystick.setJoystickSensibility(0.15);
  22029. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  22030. this._rightjoystick.setAxisForUpDown(0 /* X */);
  22031. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  22032. this._rightjoystick.reverseUpDown = true;
  22033. this._rightjoystick.setJoystickSensibility(0.05);
  22034. this._rightjoystick.setJoystickColor("yellow");
  22035. }
  22036. VirtualJoysticksCamera.prototype._checkInputs = function () {
  22037. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22038. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  22039. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22040. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  22041. if (!this._leftjoystick.pressed) {
  22042. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  22043. }
  22044. if (!this._rightjoystick.pressed) {
  22045. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  22046. }
  22047. };
  22048. VirtualJoysticksCamera.prototype.dispose = function () {
  22049. this._leftjoystick.releaseCanvas();
  22050. _super.prototype.dispose.call(this);
  22051. };
  22052. return VirtualJoysticksCamera;
  22053. })(BABYLON.FreeCamera);
  22054. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  22055. })(BABYLON || (BABYLON = {}));
  22056. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  22057. var BABYLON;
  22058. (function (BABYLON) {
  22059. var ShaderMaterial = (function (_super) {
  22060. __extends(ShaderMaterial, _super);
  22061. function ShaderMaterial(name, scene, shaderPath, options) {
  22062. _super.call(this, name, scene);
  22063. this._textures = new Array();
  22064. this._floats = new Array();
  22065. this._floatsArrays = {};
  22066. this._colors3 = new Array();
  22067. this._colors4 = new Array();
  22068. this._vectors2 = new Array();
  22069. this._vectors3 = new Array();
  22070. this._matrices = new Array();
  22071. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  22072. this._shaderPath = shaderPath;
  22073. options.needAlphaBlending = options.needAlphaBlending || false;
  22074. options.needAlphaTesting = options.needAlphaTesting || false;
  22075. options.attributes = options.attributes || ["position", "normal", "uv"];
  22076. options.uniforms = options.uniforms || ["worldViewProjection"];
  22077. options.samplers = options.samplers || [];
  22078. this._options = options;
  22079. }
  22080. ShaderMaterial.prototype.needAlphaBlending = function () {
  22081. return this._options.needAlphaBlending;
  22082. };
  22083. ShaderMaterial.prototype.needAlphaTesting = function () {
  22084. return this._options.needAlphaTesting;
  22085. };
  22086. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  22087. if (this._options.uniforms.indexOf(uniformName) === -1) {
  22088. this._options.uniforms.push(uniformName);
  22089. }
  22090. };
  22091. ShaderMaterial.prototype.setTexture = function (name, texture) {
  22092. if (this._options.samplers.indexOf(name) === -1) {
  22093. this._options.samplers.push(name);
  22094. }
  22095. this._textures[name] = texture;
  22096. return this;
  22097. };
  22098. ShaderMaterial.prototype.setFloat = function (name, value) {
  22099. this._checkUniform(name);
  22100. this._floats[name] = value;
  22101. return this;
  22102. };
  22103. ShaderMaterial.prototype.setFloats = function (name, value) {
  22104. this._checkUniform(name);
  22105. this._floatsArrays[name] = value;
  22106. return this;
  22107. };
  22108. ShaderMaterial.prototype.setColor3 = function (name, value) {
  22109. this._checkUniform(name);
  22110. this._colors3[name] = value;
  22111. return this;
  22112. };
  22113. ShaderMaterial.prototype.setColor4 = function (name, value) {
  22114. this._checkUniform(name);
  22115. this._colors4[name] = value;
  22116. return this;
  22117. };
  22118. ShaderMaterial.prototype.setVector2 = function (name, value) {
  22119. this._checkUniform(name);
  22120. this._vectors2[name] = value;
  22121. return this;
  22122. };
  22123. ShaderMaterial.prototype.setVector3 = function (name, value) {
  22124. this._checkUniform(name);
  22125. this._vectors3[name] = value;
  22126. return this;
  22127. };
  22128. ShaderMaterial.prototype.setMatrix = function (name, value) {
  22129. this._checkUniform(name);
  22130. this._matrices[name] = value;
  22131. return this;
  22132. };
  22133. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  22134. var scene = this.getScene();
  22135. var engine = scene.getEngine();
  22136. if (!this.checkReadyOnEveryCall) {
  22137. if (this._renderId === scene.getRenderId()) {
  22138. return true;
  22139. }
  22140. }
  22141. // Instances
  22142. var defines = [];
  22143. var fallbacks = new BABYLON.EffectFallbacks();
  22144. if (useInstances) {
  22145. defines.push("#define INSTANCES");
  22146. }
  22147. // Bones
  22148. if (mesh && mesh.useBones) {
  22149. defines.push("#define BONES");
  22150. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22151. defines.push("#define BONES4");
  22152. fallbacks.addFallback(0, "BONES4");
  22153. }
  22154. // Alpha test
  22155. if (engine.getAlphaTesting()) {
  22156. defines.push("#define ALPHATEST");
  22157. }
  22158. var previousEffect = this._effect;
  22159. var join = defines.join("\n");
  22160. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  22161. if (!this._effect.isReady()) {
  22162. return false;
  22163. }
  22164. if (previousEffect !== this._effect) {
  22165. scene.resetCachedMaterial();
  22166. }
  22167. this._renderId = scene.getRenderId();
  22168. return true;
  22169. };
  22170. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22171. var scene = this.getScene();
  22172. if (this._options.uniforms.indexOf("world") !== -1) {
  22173. this._effect.setMatrix("world", world);
  22174. }
  22175. if (this._options.uniforms.indexOf("worldView") !== -1) {
  22176. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  22177. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  22178. }
  22179. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22180. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22181. }
  22182. };
  22183. ShaderMaterial.prototype.bind = function (world, mesh) {
  22184. // Std values
  22185. this.bindOnlyWorldMatrix(world);
  22186. if (this.getScene().getCachedMaterial() !== this) {
  22187. if (this._options.uniforms.indexOf("view") !== -1) {
  22188. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22189. }
  22190. if (this._options.uniforms.indexOf("projection") !== -1) {
  22191. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22192. }
  22193. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22194. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22195. }
  22196. // Bones
  22197. if (mesh && mesh.useBones) {
  22198. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22199. }
  22200. for (var name in this._textures) {
  22201. this._effect.setTexture(name, this._textures[name]);
  22202. }
  22203. for (name in this._floats) {
  22204. this._effect.setFloat(name, this._floats[name]);
  22205. }
  22206. for (name in this._floatsArrays) {
  22207. this._effect.setArray(name, this._floatsArrays[name]);
  22208. }
  22209. for (name in this._colors3) {
  22210. this._effect.setColor3(name, this._colors3[name]);
  22211. }
  22212. for (name in this._colors4) {
  22213. var color = this._colors4[name];
  22214. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22215. }
  22216. for (name in this._vectors2) {
  22217. this._effect.setVector2(name, this._vectors2[name]);
  22218. }
  22219. for (name in this._vectors3) {
  22220. this._effect.setVector3(name, this._vectors3[name]);
  22221. }
  22222. for (name in this._matrices) {
  22223. this._effect.setMatrix(name, this._matrices[name]);
  22224. }
  22225. }
  22226. _super.prototype.bind.call(this, world, mesh);
  22227. };
  22228. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22229. for (var name in this._textures) {
  22230. this._textures[name].dispose();
  22231. }
  22232. this._textures = [];
  22233. _super.prototype.dispose.call(this, forceDisposeEffect);
  22234. };
  22235. return ShaderMaterial;
  22236. })(BABYLON.Material);
  22237. BABYLON.ShaderMaterial = ShaderMaterial;
  22238. })(BABYLON || (BABYLON = {}));
  22239. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22240. (function (BABYLON) {
  22241. var VertexData = (function () {
  22242. function VertexData() {
  22243. }
  22244. VertexData.prototype.set = function (data, kind) {
  22245. switch (kind) {
  22246. case BABYLON.VertexBuffer.PositionKind:
  22247. this.positions = data;
  22248. break;
  22249. case BABYLON.VertexBuffer.NormalKind:
  22250. this.normals = data;
  22251. break;
  22252. case BABYLON.VertexBuffer.UVKind:
  22253. this.uvs = data;
  22254. break;
  22255. case BABYLON.VertexBuffer.UV2Kind:
  22256. this.uv2s = data;
  22257. break;
  22258. case BABYLON.VertexBuffer.ColorKind:
  22259. this.colors = data;
  22260. break;
  22261. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22262. this.matricesIndices = data;
  22263. break;
  22264. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22265. this.matricesWeights = data;
  22266. break;
  22267. }
  22268. };
  22269. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22270. this._applyTo(mesh, updatable);
  22271. };
  22272. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22273. this._applyTo(geometry, updatable);
  22274. };
  22275. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22276. this._update(mesh);
  22277. };
  22278. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22279. this._update(geometry);
  22280. };
  22281. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22282. if (this.positions) {
  22283. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22284. }
  22285. if (this.normals) {
  22286. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22287. }
  22288. if (this.uvs) {
  22289. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22290. }
  22291. if (this.uv2s) {
  22292. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22293. }
  22294. if (this.colors) {
  22295. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22296. }
  22297. if (this.matricesIndices) {
  22298. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22299. }
  22300. if (this.matricesWeights) {
  22301. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22302. }
  22303. if (this.indices) {
  22304. meshOrGeometry.setIndices(this.indices);
  22305. }
  22306. };
  22307. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22308. if (this.positions) {
  22309. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22310. }
  22311. if (this.normals) {
  22312. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22313. }
  22314. if (this.uvs) {
  22315. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22316. }
  22317. if (this.uv2s) {
  22318. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22319. }
  22320. if (this.colors) {
  22321. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22322. }
  22323. if (this.matricesIndices) {
  22324. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22325. }
  22326. if (this.matricesWeights) {
  22327. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22328. }
  22329. if (this.indices) {
  22330. meshOrGeometry.setIndices(this.indices);
  22331. }
  22332. };
  22333. VertexData.prototype.transform = function (matrix) {
  22334. var transformed = BABYLON.Vector3.Zero();
  22335. if (this.positions) {
  22336. var position = BABYLON.Vector3.Zero();
  22337. for (var index = 0; index < this.positions.length; index += 3) {
  22338. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22339. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22340. this.positions[index] = transformed.x;
  22341. this.positions[index + 1] = transformed.y;
  22342. this.positions[index + 2] = transformed.z;
  22343. }
  22344. }
  22345. if (this.normals) {
  22346. var normal = BABYLON.Vector3.Zero();
  22347. for (index = 0; index < this.normals.length; index += 3) {
  22348. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22349. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22350. this.normals[index] = transformed.x;
  22351. this.normals[index + 1] = transformed.y;
  22352. this.normals[index + 2] = transformed.z;
  22353. }
  22354. }
  22355. };
  22356. VertexData.prototype.merge = function (other) {
  22357. if (other.indices) {
  22358. if (!this.indices) {
  22359. this.indices = [];
  22360. }
  22361. var offset = this.positions ? this.positions.length / 3 : 0;
  22362. for (var index = 0; index < other.indices.length; index++) {
  22363. this.indices.push(other.indices[index] + offset);
  22364. }
  22365. }
  22366. if (other.positions) {
  22367. if (!this.positions) {
  22368. this.positions = [];
  22369. }
  22370. for (index = 0; index < other.positions.length; index++) {
  22371. this.positions.push(other.positions[index]);
  22372. }
  22373. }
  22374. if (other.normals) {
  22375. if (!this.normals) {
  22376. this.normals = [];
  22377. }
  22378. for (index = 0; index < other.normals.length; index++) {
  22379. this.normals.push(other.normals[index]);
  22380. }
  22381. }
  22382. if (other.uvs) {
  22383. if (!this.uvs) {
  22384. this.uvs = [];
  22385. }
  22386. for (index = 0; index < other.uvs.length; index++) {
  22387. this.uvs.push(other.uvs[index]);
  22388. }
  22389. }
  22390. if (other.uv2s) {
  22391. if (!this.uv2s) {
  22392. this.uv2s = [];
  22393. }
  22394. for (index = 0; index < other.uv2s.length; index++) {
  22395. this.uv2s.push(other.uv2s[index]);
  22396. }
  22397. }
  22398. if (other.matricesIndices) {
  22399. if (!this.matricesIndices) {
  22400. this.matricesIndices = [];
  22401. }
  22402. for (index = 0; index < other.matricesIndices.length; index++) {
  22403. this.matricesIndices.push(other.matricesIndices[index]);
  22404. }
  22405. }
  22406. if (other.matricesWeights) {
  22407. if (!this.matricesWeights) {
  22408. this.matricesWeights = [];
  22409. }
  22410. for (index = 0; index < other.matricesWeights.length; index++) {
  22411. this.matricesWeights.push(other.matricesWeights[index]);
  22412. }
  22413. }
  22414. if (other.colors) {
  22415. if (!this.colors) {
  22416. this.colors = [];
  22417. }
  22418. for (index = 0; index < other.colors.length; index++) {
  22419. this.colors.push(other.colors[index]);
  22420. }
  22421. }
  22422. };
  22423. // Statics
  22424. VertexData.ExtractFromMesh = function (mesh) {
  22425. return VertexData._ExtractFrom(mesh);
  22426. };
  22427. VertexData.ExtractFromGeometry = function (geometry) {
  22428. return VertexData._ExtractFrom(geometry);
  22429. };
  22430. VertexData._ExtractFrom = function (meshOrGeometry) {
  22431. var result = new VertexData();
  22432. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22433. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22434. }
  22435. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22436. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22437. }
  22438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22439. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22440. }
  22441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22442. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22443. }
  22444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22445. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22446. }
  22447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22448. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22449. }
  22450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22451. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22452. }
  22453. result.indices = meshOrGeometry.getIndices();
  22454. return result;
  22455. };
  22456. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22457. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22458. closeArray = closeArray || false;
  22459. closePath = closePath || false;
  22460. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22461. offset = offset || defaultOffset;
  22462. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22463. var positions = [];
  22464. var indices = [];
  22465. var normals = [];
  22466. var uvs = [];
  22467. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22468. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22469. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22470. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22471. var minlg; // minimal length among all paths from pathArray
  22472. var lg = []; // array of path lengths : nb of vertex per path
  22473. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22474. var p; // path iterator
  22475. var i; // point iterator
  22476. var j; // point iterator
  22477. // if single path in pathArray
  22478. if (pathArray.length < 2) {
  22479. var ar1 = [];
  22480. var ar2 = [];
  22481. for (i = 0; i < pathArray[0].length - offset; i++) {
  22482. ar1.push(pathArray[0][i]);
  22483. ar2.push(pathArray[0][i + offset]);
  22484. }
  22485. pathArray = [ar1, ar2];
  22486. }
  22487. // positions and horizontal distances (u)
  22488. var idc = 0;
  22489. minlg = pathArray[0].length;
  22490. for (p = 0; p < pathArray.length; p++) {
  22491. uTotalDistance[p] = 0;
  22492. us[p] = [0];
  22493. var path = pathArray[p];
  22494. var l = path.length;
  22495. minlg = (minlg < l) ? minlg : l;
  22496. lg[p] = l;
  22497. idx[p] = idc;
  22498. j = 0;
  22499. while (j < l) {
  22500. positions.push(path[j].x, path[j].y, path[j].z);
  22501. if (j > 0) {
  22502. var vectlg = path[j].subtract(path[j - 1]).length();
  22503. var dist = vectlg + uTotalDistance[p];
  22504. us[p].push(dist);
  22505. uTotalDistance[p] = dist;
  22506. }
  22507. j++;
  22508. }
  22509. if (closePath) {
  22510. vectlg = path[0].subtract(path[j - 1]).length();
  22511. dist = vectlg + uTotalDistance[p];
  22512. uTotalDistance[p] = dist;
  22513. }
  22514. idc += l;
  22515. }
  22516. for (i = 0; i < minlg; i++) {
  22517. vTotalDistance[i] = 0;
  22518. vs[i] = [0];
  22519. var path1;
  22520. var path2;
  22521. for (p = 0; p < pathArray.length - 1; p++) {
  22522. path1 = pathArray[p];
  22523. path2 = pathArray[p + 1];
  22524. vectlg = path2[i].subtract(path1[i]).length();
  22525. dist = vectlg + vTotalDistance[i];
  22526. vs[i].push(dist);
  22527. vTotalDistance[i] = dist;
  22528. }
  22529. if (closeArray) {
  22530. path1 = pathArray[p];
  22531. path2 = pathArray[0];
  22532. vectlg = path2[i].subtract(path1[i]).length();
  22533. dist = vectlg + vTotalDistance[i];
  22534. vTotalDistance[i] = dist;
  22535. }
  22536. }
  22537. // uvs
  22538. var u;
  22539. var v;
  22540. for (p = 0; p < pathArray.length; p++) {
  22541. for (i = 0; i < minlg; i++) {
  22542. u = us[p][i] / uTotalDistance[p];
  22543. v = vs[i][p] / vTotalDistance[i];
  22544. uvs.push(u, v);
  22545. }
  22546. }
  22547. // indices
  22548. p = 0; // path index
  22549. var pi = 0; // positions array index
  22550. var l1 = lg[p] - 1; // path1 length
  22551. var l2 = lg[p + 1] - 1; // path2 length
  22552. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22553. var shft = idx[1] - idx[0]; // shift
  22554. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22555. var t1; // two consecutive triangles, so 4 points : point1
  22556. var t2; // point2
  22557. var t3; // point3
  22558. var t4; // point4
  22559. while (pi <= min && p < path1nb) {
  22560. // 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
  22561. t1 = pi;
  22562. t2 = pi + shft;
  22563. t3 = pi + 1;
  22564. t4 = pi + shft + 1;
  22565. indices.push(pi, pi + shft, pi + 1);
  22566. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22567. pi += 1;
  22568. if (pi === min) {
  22569. if (closePath) {
  22570. indices.push(pi, pi + shft, idx[p]);
  22571. indices.push(idx[p] + shft, idx[p], pi + shft);
  22572. t3 = idx[p];
  22573. t4 = idx[p] + shft;
  22574. }
  22575. p++;
  22576. if (p === lg.length - 1) {
  22577. shft = idx[0] - idx[p];
  22578. l1 = lg[p] - 1;
  22579. l2 = lg[0] - 1;
  22580. }
  22581. else {
  22582. shft = idx[p + 1] - idx[p];
  22583. l1 = lg[p] - 1;
  22584. l2 = lg[p + 1] - 1;
  22585. }
  22586. pi = idx[p];
  22587. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22588. }
  22589. }
  22590. // normals
  22591. VertexData.ComputeNormals(positions, indices, normals);
  22592. // sides
  22593. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22594. // Result
  22595. var vertexData = new VertexData();
  22596. vertexData.indices = indices;
  22597. vertexData.positions = positions;
  22598. vertexData.normals = normals;
  22599. vertexData.uvs = uvs;
  22600. return vertexData;
  22601. };
  22602. VertexData.CreateBox = function (size, sideOrientation) {
  22603. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22604. var normalsSource = [
  22605. new BABYLON.Vector3(0, 0, 1),
  22606. new BABYLON.Vector3(0, 0, -1),
  22607. new BABYLON.Vector3(1, 0, 0),
  22608. new BABYLON.Vector3(-1, 0, 0),
  22609. new BABYLON.Vector3(0, 1, 0),
  22610. new BABYLON.Vector3(0, -1, 0)
  22611. ];
  22612. var indices = [];
  22613. var positions = [];
  22614. var normals = [];
  22615. var uvs = [];
  22616. size = size || 1;
  22617. for (var index = 0; index < normalsSource.length; index++) {
  22618. var normal = normalsSource[index];
  22619. // Get two vectors perpendicular to the face normal and to each other.
  22620. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22621. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22622. // Six indices (two triangles) per face.
  22623. var verticesLength = positions.length / 3;
  22624. indices.push(verticesLength);
  22625. indices.push(verticesLength + 1);
  22626. indices.push(verticesLength + 2);
  22627. indices.push(verticesLength);
  22628. indices.push(verticesLength + 2);
  22629. indices.push(verticesLength + 3);
  22630. // Four vertices per face.
  22631. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22632. positions.push(vertex.x, vertex.y, vertex.z);
  22633. normals.push(normal.x, normal.y, normal.z);
  22634. uvs.push(1.0, 1.0);
  22635. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22636. positions.push(vertex.x, vertex.y, vertex.z);
  22637. normals.push(normal.x, normal.y, normal.z);
  22638. uvs.push(0.0, 1.0);
  22639. vertex = normal.add(side1).add(side2).scale(size / 2);
  22640. positions.push(vertex.x, vertex.y, vertex.z);
  22641. normals.push(normal.x, normal.y, normal.z);
  22642. uvs.push(0.0, 0.0);
  22643. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22644. positions.push(vertex.x, vertex.y, vertex.z);
  22645. normals.push(normal.x, normal.y, normal.z);
  22646. uvs.push(1.0, 0.0);
  22647. }
  22648. // sides
  22649. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22650. // Result
  22651. var vertexData = new VertexData();
  22652. vertexData.indices = indices;
  22653. vertexData.positions = positions;
  22654. vertexData.normals = normals;
  22655. vertexData.uvs = uvs;
  22656. return vertexData;
  22657. };
  22658. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22659. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22660. segments = segments || 32;
  22661. diameter = diameter || 1;
  22662. var radius = diameter / 2;
  22663. var totalZRotationSteps = 2 + segments;
  22664. var totalYRotationSteps = 2 * totalZRotationSteps;
  22665. var indices = [];
  22666. var positions = [];
  22667. var normals = [];
  22668. var uvs = [];
  22669. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22670. var normalizedZ = zRotationStep / totalZRotationSteps;
  22671. var angleZ = (normalizedZ * Math.PI);
  22672. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22673. var normalizedY = yRotationStep / totalYRotationSteps;
  22674. var angleY = normalizedY * Math.PI * 2;
  22675. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22676. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22677. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22678. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22679. var vertex = complete.scale(radius);
  22680. var normal = BABYLON.Vector3.Normalize(vertex);
  22681. positions.push(vertex.x, vertex.y, vertex.z);
  22682. normals.push(normal.x, normal.y, normal.z);
  22683. uvs.push(normalizedZ, normalizedY);
  22684. }
  22685. if (zRotationStep > 0) {
  22686. var verticesCount = positions.length / 3;
  22687. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22688. indices.push((firstIndex));
  22689. indices.push((firstIndex + 1));
  22690. indices.push(firstIndex + totalYRotationSteps + 1);
  22691. indices.push((firstIndex + totalYRotationSteps + 1));
  22692. indices.push((firstIndex + 1));
  22693. indices.push((firstIndex + totalYRotationSteps + 2));
  22694. }
  22695. }
  22696. }
  22697. // Sides
  22698. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22699. // Result
  22700. var vertexData = new VertexData();
  22701. vertexData.indices = indices;
  22702. vertexData.positions = positions;
  22703. vertexData.normals = normals;
  22704. vertexData.uvs = uvs;
  22705. return vertexData;
  22706. };
  22707. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22708. if (subdivisions === void 0) { subdivisions = 1; }
  22709. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22710. var radiusTop = diameterTop / 2;
  22711. var radiusBottom = diameterBottom / 2;
  22712. var indices = [];
  22713. var positions = [];
  22714. var normals = [];
  22715. var uvs = [];
  22716. height = height || 1;
  22717. diameterTop = diameterTop || 0.5;
  22718. diameterBottom = diameterBottom || 1;
  22719. tessellation = tessellation || 16;
  22720. subdivisions = subdivisions || 1;
  22721. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22722. var getCircleVector = function (i) {
  22723. var angle = (i * 2.0 * Math.PI / tessellation);
  22724. var dx = Math.cos(angle);
  22725. var dz = Math.sin(angle);
  22726. return new BABYLON.Vector3(dx, 0, dz);
  22727. };
  22728. var createCylinderCap = function (isTop) {
  22729. var radius = isTop ? radiusTop : radiusBottom;
  22730. if (radius === 0) {
  22731. return;
  22732. }
  22733. var vbase = positions.length / 3;
  22734. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22735. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22736. if (!isTop) {
  22737. offset.scaleInPlace(-1);
  22738. textureScale.x = -textureScale.x;
  22739. }
  22740. for (var i = 0; i < tessellation; i++) {
  22741. var circleVector = getCircleVector(i);
  22742. var position = circleVector.scale(radius).add(offset);
  22743. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22744. positions.push(position.x, position.y, position.z);
  22745. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22746. }
  22747. for (i = 0; i < tessellation - 2; i++) {
  22748. if (!isTop) {
  22749. indices.push(vbase);
  22750. indices.push(vbase + (i + 2) % tessellation);
  22751. indices.push(vbase + (i + 1) % tessellation);
  22752. }
  22753. else {
  22754. indices.push(vbase);
  22755. indices.push(vbase + (i + 1) % tessellation);
  22756. indices.push(vbase + (i + 2) % tessellation);
  22757. }
  22758. }
  22759. };
  22760. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22761. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22762. var stride = tessellation + 1;
  22763. for (var i = 0; i <= tessellation; i++) {
  22764. var circleVector = getCircleVector(i);
  22765. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22766. var position, radius = radiusBottom;
  22767. for (var s = 0; s <= subdivisions; s++) {
  22768. // Update variables
  22769. position = circleVector.scale(radius);
  22770. position.addInPlace(base.add(offset.scale(s)));
  22771. textureCoordinate.y += 1 / subdivisions;
  22772. radius += (radiusTop - radiusBottom) / subdivisions;
  22773. // Push in arrays
  22774. positions.push(position.x, position.y, position.z);
  22775. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22776. }
  22777. }
  22778. subdivisions += 1;
  22779. for (s = 0; s < subdivisions - 1; s++) {
  22780. for (i = 0; i <= tessellation; i++) {
  22781. indices.push(i * subdivisions + s);
  22782. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22783. indices.push(i * subdivisions + (s + 1));
  22784. indices.push(i * subdivisions + (s + 1));
  22785. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22786. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22787. }
  22788. }
  22789. // Create flat triangle fan caps to seal the top and bottom.
  22790. createCylinderCap(true);
  22791. createCylinderCap(false);
  22792. // Normals
  22793. VertexData.ComputeNormals(positions, indices, normals);
  22794. // Sides
  22795. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22796. // Result
  22797. var vertexData = new VertexData();
  22798. vertexData.indices = indices;
  22799. vertexData.positions = positions;
  22800. vertexData.normals = normals;
  22801. vertexData.uvs = uvs;
  22802. return vertexData;
  22803. };
  22804. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22805. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22806. var indices = [];
  22807. var positions = [];
  22808. var normals = [];
  22809. var uvs = [];
  22810. diameter = diameter || 1;
  22811. thickness = thickness || 0.5;
  22812. tessellation = tessellation || 16;
  22813. var stride = tessellation + 1;
  22814. for (var i = 0; i <= tessellation; i++) {
  22815. var u = i / tessellation;
  22816. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22817. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22818. for (var j = 0; j <= tessellation; j++) {
  22819. var v = 1 - j / tessellation;
  22820. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22821. var dx = Math.cos(innerAngle);
  22822. var dy = Math.sin(innerAngle);
  22823. // Create a vertex.
  22824. var normal = new BABYLON.Vector3(dx, dy, 0);
  22825. var position = normal.scale(thickness / 2);
  22826. var textureCoordinate = new BABYLON.Vector2(u, v);
  22827. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22828. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22829. positions.push(position.x, position.y, position.z);
  22830. normals.push(normal.x, normal.y, normal.z);
  22831. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22832. // And create indices for two triangles.
  22833. var nextI = (i + 1) % stride;
  22834. var nextJ = (j + 1) % stride;
  22835. indices.push(i * stride + j);
  22836. indices.push(i * stride + nextJ);
  22837. indices.push(nextI * stride + j);
  22838. indices.push(i * stride + nextJ);
  22839. indices.push(nextI * stride + nextJ);
  22840. indices.push(nextI * stride + j);
  22841. }
  22842. }
  22843. // Sides
  22844. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22845. // Result
  22846. var vertexData = new VertexData();
  22847. vertexData.indices = indices;
  22848. vertexData.positions = positions;
  22849. vertexData.normals = normals;
  22850. vertexData.uvs = uvs;
  22851. return vertexData;
  22852. };
  22853. VertexData.CreateLines = function (points) {
  22854. var indices = [];
  22855. var positions = [];
  22856. for (var index = 0; index < points.length; index++) {
  22857. positions.push(points[index].x, points[index].y, points[index].z);
  22858. if (index > 0) {
  22859. indices.push(index - 1);
  22860. indices.push(index);
  22861. }
  22862. }
  22863. // Result
  22864. var vertexData = new VertexData();
  22865. vertexData.indices = indices;
  22866. vertexData.positions = positions;
  22867. return vertexData;
  22868. };
  22869. VertexData.CreateGround = function (width, height, subdivisions) {
  22870. var indices = [];
  22871. var positions = [];
  22872. var normals = [];
  22873. var uvs = [];
  22874. var row, col;
  22875. width = width || 1;
  22876. height = height || 1;
  22877. subdivisions = subdivisions || 1;
  22878. for (row = 0; row <= subdivisions; row++) {
  22879. for (col = 0; col <= subdivisions; col++) {
  22880. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22881. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22882. positions.push(position.x, position.y, position.z);
  22883. normals.push(normal.x, normal.y, normal.z);
  22884. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22885. }
  22886. }
  22887. for (row = 0; row < subdivisions; row++) {
  22888. for (col = 0; col < subdivisions; col++) {
  22889. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22890. indices.push(col + 1 + row * (subdivisions + 1));
  22891. indices.push(col + row * (subdivisions + 1));
  22892. indices.push(col + (row + 1) * (subdivisions + 1));
  22893. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22894. indices.push(col + row * (subdivisions + 1));
  22895. }
  22896. }
  22897. // Result
  22898. var vertexData = new VertexData();
  22899. vertexData.indices = indices;
  22900. vertexData.positions = positions;
  22901. vertexData.normals = normals;
  22902. vertexData.uvs = uvs;
  22903. return vertexData;
  22904. };
  22905. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22906. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22907. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22908. var indices = [];
  22909. var positions = [];
  22910. var normals = [];
  22911. var uvs = [];
  22912. var row, col, tileRow, tileCol;
  22913. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22914. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22915. precision.w = (precision.w < 1) ? 1 : precision.w;
  22916. precision.h = (precision.h < 1) ? 1 : precision.h;
  22917. var tileSize = {
  22918. 'w': (xmax - xmin) / subdivisions.w,
  22919. 'h': (zmax - zmin) / subdivisions.h
  22920. };
  22921. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22922. // Indices
  22923. var base = positions.length / 3;
  22924. var rowLength = precision.w + 1;
  22925. for (row = 0; row < precision.h; row++) {
  22926. for (col = 0; col < precision.w; col++) {
  22927. var square = [
  22928. base + col + row * rowLength,
  22929. base + (col + 1) + row * rowLength,
  22930. base + (col + 1) + (row + 1) * rowLength,
  22931. base + col + (row + 1) * rowLength
  22932. ];
  22933. indices.push(square[1]);
  22934. indices.push(square[2]);
  22935. indices.push(square[3]);
  22936. indices.push(square[0]);
  22937. indices.push(square[1]);
  22938. indices.push(square[3]);
  22939. }
  22940. }
  22941. // Position, normals and uvs
  22942. var position = BABYLON.Vector3.Zero();
  22943. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22944. for (row = 0; row <= precision.h; row++) {
  22945. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22946. for (col = 0; col <= precision.w; col++) {
  22947. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22948. position.y = 0;
  22949. positions.push(position.x, position.y, position.z);
  22950. normals.push(normal.x, normal.y, normal.z);
  22951. uvs.push(col / precision.w, row / precision.h);
  22952. }
  22953. }
  22954. }
  22955. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22956. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22957. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22958. }
  22959. }
  22960. // Result
  22961. var vertexData = new VertexData();
  22962. vertexData.indices = indices;
  22963. vertexData.positions = positions;
  22964. vertexData.normals = normals;
  22965. vertexData.uvs = uvs;
  22966. return vertexData;
  22967. };
  22968. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22969. var indices = [];
  22970. var positions = [];
  22971. var normals = [];
  22972. var uvs = [];
  22973. var row, col;
  22974. for (row = 0; row <= subdivisions; row++) {
  22975. for (col = 0; col <= subdivisions; col++) {
  22976. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22977. // Compute height
  22978. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22979. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22980. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22981. var r = buffer[pos] / 255.0;
  22982. var g = buffer[pos + 1] / 255.0;
  22983. var b = buffer[pos + 2] / 255.0;
  22984. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22985. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22986. // Add vertex
  22987. positions.push(position.x, position.y, position.z);
  22988. normals.push(0, 0, 0);
  22989. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22990. }
  22991. }
  22992. for (row = 0; row < subdivisions; row++) {
  22993. for (col = 0; col < subdivisions; col++) {
  22994. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22995. indices.push(col + 1 + row * (subdivisions + 1));
  22996. indices.push(col + row * (subdivisions + 1));
  22997. indices.push(col + (row + 1) * (subdivisions + 1));
  22998. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22999. indices.push(col + row * (subdivisions + 1));
  23000. }
  23001. }
  23002. // Normals
  23003. VertexData.ComputeNormals(positions, indices, normals);
  23004. // Result
  23005. var vertexData = new VertexData();
  23006. vertexData.indices = indices;
  23007. vertexData.positions = positions;
  23008. vertexData.normals = normals;
  23009. vertexData.uvs = uvs;
  23010. return vertexData;
  23011. };
  23012. VertexData.CreatePlane = function (size, sideOrientation) {
  23013. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23014. var indices = [];
  23015. var positions = [];
  23016. var normals = [];
  23017. var uvs = [];
  23018. size = size || 1;
  23019. // Vertices
  23020. var halfSize = size / 2.0;
  23021. positions.push(-halfSize, -halfSize, 0);
  23022. normals.push(0, 0, -1.0);
  23023. uvs.push(0.0, 0.0);
  23024. positions.push(halfSize, -halfSize, 0);
  23025. normals.push(0, 0, -1.0);
  23026. uvs.push(1.0, 0.0);
  23027. positions.push(halfSize, halfSize, 0);
  23028. normals.push(0, 0, -1.0);
  23029. uvs.push(1.0, 1.0);
  23030. positions.push(-halfSize, halfSize, 0);
  23031. normals.push(0, 0, -1.0);
  23032. uvs.push(0.0, 1.0);
  23033. // Indices
  23034. indices.push(0);
  23035. indices.push(1);
  23036. indices.push(2);
  23037. indices.push(0);
  23038. indices.push(2);
  23039. indices.push(3);
  23040. // Sides
  23041. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23042. // Result
  23043. var vertexData = new VertexData();
  23044. vertexData.indices = indices;
  23045. vertexData.positions = positions;
  23046. vertexData.normals = normals;
  23047. vertexData.uvs = uvs;
  23048. return vertexData;
  23049. };
  23050. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  23051. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23052. var positions = [];
  23053. var indices = [];
  23054. var normals = [];
  23055. var uvs = [];
  23056. // positions and uvs
  23057. positions.push(0, 0, 0); // disc center first
  23058. uvs.push(0.5, 0.5);
  23059. var step = Math.PI * 2 / tessellation;
  23060. for (var a = 0; a < Math.PI * 2; a += step) {
  23061. var x = Math.cos(a);
  23062. var y = Math.sin(a);
  23063. var u = (x + 1) / 2;
  23064. var v = (1 - y) / 2;
  23065. positions.push(radius * x, radius * y, 0);
  23066. uvs.push(u, v);
  23067. }
  23068. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23069. uvs.push(uvs[2], uvs[3]);
  23070. //indices
  23071. var vertexNb = positions.length / 3;
  23072. for (var i = 1; i < vertexNb - 1; i++) {
  23073. indices.push(i + 1, 0, i);
  23074. }
  23075. // result
  23076. VertexData.ComputeNormals(positions, indices, normals);
  23077. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23078. var vertexData = new VertexData();
  23079. vertexData.indices = indices;
  23080. vertexData.positions = positions;
  23081. vertexData.normals = normals;
  23082. vertexData.uvs = uvs;
  23083. return vertexData;
  23084. };
  23085. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23086. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  23087. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23088. var indices = [];
  23089. var positions = [];
  23090. var normals = [];
  23091. var uvs = [];
  23092. radius = radius || 2;
  23093. tube = tube || 0.5;
  23094. radialSegments = radialSegments || 32;
  23095. tubularSegments = tubularSegments || 32;
  23096. p = p || 2;
  23097. q = q || 3;
  23098. // Helper
  23099. var getPos = function (angle) {
  23100. var cu = Math.cos(angle);
  23101. var su = Math.sin(angle);
  23102. var quOverP = q / p * angle;
  23103. var cs = Math.cos(quOverP);
  23104. var tx = radius * (2 + cs) * 0.5 * cu;
  23105. var ty = radius * (2 + cs) * su * 0.5;
  23106. var tz = radius * Math.sin(quOverP) * 0.5;
  23107. return new BABYLON.Vector3(tx, ty, tz);
  23108. };
  23109. for (var i = 0; i <= radialSegments; i++) {
  23110. var modI = i % radialSegments;
  23111. var u = modI / radialSegments * 2 * p * Math.PI;
  23112. var p1 = getPos(u);
  23113. var p2 = getPos(u + 0.01);
  23114. var tang = p2.subtract(p1);
  23115. var n = p2.add(p1);
  23116. var bitan = BABYLON.Vector3.Cross(tang, n);
  23117. n = BABYLON.Vector3.Cross(bitan, tang);
  23118. bitan.normalize();
  23119. n.normalize();
  23120. for (var j = 0; j < tubularSegments; j++) {
  23121. var modJ = j % tubularSegments;
  23122. var v = modJ / tubularSegments * 2 * Math.PI;
  23123. var cx = -tube * Math.cos(v);
  23124. var cy = tube * Math.sin(v);
  23125. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23126. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23127. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23128. uvs.push(i / radialSegments);
  23129. uvs.push(j / tubularSegments);
  23130. }
  23131. }
  23132. for (i = 0; i < radialSegments; i++) {
  23133. for (j = 0; j < tubularSegments; j++) {
  23134. var jNext = (j + 1) % tubularSegments;
  23135. var a = i * tubularSegments + j;
  23136. var b = (i + 1) * tubularSegments + j;
  23137. var c = (i + 1) * tubularSegments + jNext;
  23138. var d = i * tubularSegments + jNext;
  23139. indices.push(d);
  23140. indices.push(b);
  23141. indices.push(a);
  23142. indices.push(d);
  23143. indices.push(c);
  23144. indices.push(b);
  23145. }
  23146. }
  23147. // Normals
  23148. VertexData.ComputeNormals(positions, indices, normals);
  23149. // Sides
  23150. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23151. // Result
  23152. var vertexData = new VertexData();
  23153. vertexData.indices = indices;
  23154. vertexData.positions = positions;
  23155. vertexData.normals = normals;
  23156. vertexData.uvs = uvs;
  23157. return vertexData;
  23158. };
  23159. // Tools
  23160. /**
  23161. * @param {any} - positions (number[] or Float32Array)
  23162. * @param {any} - indices (number[] or Uint16Array)
  23163. * @param {any} - normals (number[] or Float32Array)
  23164. */
  23165. VertexData.ComputeNormals = function (positions, indices, normals) {
  23166. var positionVectors = [];
  23167. var facesOfVertices = [];
  23168. var index;
  23169. for (index = 0; index < positions.length; index += 3) {
  23170. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  23171. positionVectors.push(vector3);
  23172. facesOfVertices.push([]);
  23173. }
  23174. // Compute normals
  23175. var facesNormals = [];
  23176. for (index = 0; index < indices.length / 3; index++) {
  23177. var i1 = indices[index * 3];
  23178. var i2 = indices[index * 3 + 1];
  23179. var i3 = indices[index * 3 + 2];
  23180. var p1 = positionVectors[i1];
  23181. var p2 = positionVectors[i2];
  23182. var p3 = positionVectors[i3];
  23183. var p1p2 = p1.subtract(p2);
  23184. var p3p2 = p3.subtract(p2);
  23185. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23186. facesOfVertices[i1].push(index);
  23187. facesOfVertices[i2].push(index);
  23188. facesOfVertices[i3].push(index);
  23189. }
  23190. for (index = 0; index < positionVectors.length; index++) {
  23191. var faces = facesOfVertices[index];
  23192. var normal = BABYLON.Vector3.Zero();
  23193. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  23194. normal.addInPlace(facesNormals[faces[faceIndex]]);
  23195. }
  23196. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  23197. normals[index * 3] = normal.x;
  23198. normals[index * 3 + 1] = normal.y;
  23199. normals[index * 3 + 2] = normal.z;
  23200. }
  23201. };
  23202. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23203. var li = indices.length;
  23204. var ln = normals.length;
  23205. var i;
  23206. var n;
  23207. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23208. switch (sideOrientation) {
  23209. case BABYLON.Mesh.FRONTSIDE:
  23210. break;
  23211. case BABYLON.Mesh.BACKSIDE:
  23212. var tmp;
  23213. for (i = 0; i < li; i += 3) {
  23214. tmp = indices[i];
  23215. indices[i] = indices[i + 2];
  23216. indices[i + 2] = tmp;
  23217. }
  23218. for (n = 0; n < ln; n++) {
  23219. normals[n] = -normals[n];
  23220. }
  23221. break;
  23222. case BABYLON.Mesh.DOUBLESIDE:
  23223. // positions
  23224. var lp = positions.length;
  23225. var l = lp / 3;
  23226. for (var p = 0; p < lp; p++) {
  23227. positions[lp + p] = positions[p];
  23228. }
  23229. for (i = 0; i < li; i += 3) {
  23230. indices[i + li] = indices[i + 2] + l;
  23231. indices[i + 1 + li] = indices[i + 1] + l;
  23232. indices[i + 2 + li] = indices[i] + l;
  23233. }
  23234. for (n = 0; n < ln; n++) {
  23235. normals[ln + n] = -normals[n];
  23236. }
  23237. // uvs
  23238. var lu = uvs.length;
  23239. for (var u = 0; u < lu; u++) {
  23240. uvs[u + lu] = uvs[u];
  23241. }
  23242. break;
  23243. }
  23244. };
  23245. return VertexData;
  23246. })();
  23247. BABYLON.VertexData = VertexData;
  23248. })(BABYLON || (BABYLON = {}));
  23249. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23250. var BABYLON;
  23251. (function (BABYLON) {
  23252. var buildCamera = function (that, name) {
  23253. that._leftCamera.isIntermediate = true;
  23254. that.subCameras.push(that._leftCamera);
  23255. that.subCameras.push(that._rightCamera);
  23256. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23257. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23258. that._anaglyphPostProcess.onApply = function (effect) {
  23259. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23260. };
  23261. that._update();
  23262. };
  23263. var AnaglyphArcRotateCamera = (function (_super) {
  23264. __extends(AnaglyphArcRotateCamera, _super);
  23265. // ANY
  23266. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23267. _super.call(this, name, alpha, beta, radius, target, scene);
  23268. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23269. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23270. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23271. buildCamera(this, name);
  23272. }
  23273. AnaglyphArcRotateCamera.prototype._update = function () {
  23274. this._updateCamera(this._leftCamera);
  23275. this._updateCamera(this._rightCamera);
  23276. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23277. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23278. _super.prototype._update.call(this);
  23279. };
  23280. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23281. camera.beta = this.beta;
  23282. camera.radius = this.radius;
  23283. camera.minZ = this.minZ;
  23284. camera.maxZ = this.maxZ;
  23285. camera.fov = this.fov;
  23286. camera.target = this.target;
  23287. };
  23288. return AnaglyphArcRotateCamera;
  23289. })(BABYLON.ArcRotateCamera);
  23290. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23291. var AnaglyphFreeCamera = (function (_super) {
  23292. __extends(AnaglyphFreeCamera, _super);
  23293. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23294. _super.call(this, name, position, scene);
  23295. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23296. this._transformMatrix = new BABYLON.Matrix();
  23297. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23298. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23299. buildCamera(this, name);
  23300. }
  23301. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23302. var target = this.getTarget();
  23303. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23304. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23305. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23306. };
  23307. AnaglyphFreeCamera.prototype._update = function () {
  23308. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23309. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23310. this._updateCamera(this._leftCamera);
  23311. this._updateCamera(this._rightCamera);
  23312. _super.prototype._update.call(this);
  23313. };
  23314. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23315. camera.minZ = this.minZ;
  23316. camera.maxZ = this.maxZ;
  23317. camera.fov = this.fov;
  23318. camera.viewport = this.viewport;
  23319. camera.setTarget(this.getTarget());
  23320. };
  23321. return AnaglyphFreeCamera;
  23322. })(BABYLON.FreeCamera);
  23323. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23324. })(BABYLON || (BABYLON = {}));
  23325. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23326. var BABYLON;
  23327. (function (BABYLON) {
  23328. var AnaglyphPostProcess = (function (_super) {
  23329. __extends(AnaglyphPostProcess, _super);
  23330. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23331. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23332. }
  23333. return AnaglyphPostProcess;
  23334. })(BABYLON.PostProcess);
  23335. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23336. })(BABYLON || (BABYLON = {}));
  23337. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23338. (function (BABYLON) {
  23339. var Tags = (function () {
  23340. function Tags() {
  23341. }
  23342. Tags.EnableFor = function (obj) {
  23343. obj._tags = obj._tags || {};
  23344. obj.hasTags = function () {
  23345. return Tags.HasTags(obj);
  23346. };
  23347. obj.addTags = function (tagsString) {
  23348. return Tags.AddTagsTo(obj, tagsString);
  23349. };
  23350. obj.removeTags = function (tagsString) {
  23351. return Tags.RemoveTagsFrom(obj, tagsString);
  23352. };
  23353. obj.matchesTagsQuery = function (tagsQuery) {
  23354. return Tags.MatchesQuery(obj, tagsQuery);
  23355. };
  23356. };
  23357. Tags.DisableFor = function (obj) {
  23358. delete obj._tags;
  23359. delete obj.hasTags;
  23360. delete obj.addTags;
  23361. delete obj.removeTags;
  23362. delete obj.matchesTagsQuery;
  23363. };
  23364. Tags.HasTags = function (obj) {
  23365. if (!obj._tags) {
  23366. return false;
  23367. }
  23368. return !BABYLON.Tools.IsEmpty(obj._tags);
  23369. };
  23370. Tags.GetTags = function (obj) {
  23371. if (!obj._tags) {
  23372. return null;
  23373. }
  23374. return obj._tags;
  23375. };
  23376. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23377. // a tag cannot start with '||', '&&', and '!'
  23378. // it cannot contain whitespaces
  23379. Tags.AddTagsTo = function (obj, tagsString) {
  23380. if (!tagsString) {
  23381. return;
  23382. }
  23383. var tags = tagsString.split(" ");
  23384. for (var t in tags) {
  23385. Tags._AddTagTo(obj, tags[t]);
  23386. }
  23387. };
  23388. Tags._AddTagTo = function (obj, tag) {
  23389. tag = tag.trim();
  23390. if (tag === "" || tag === "true" || tag === "false") {
  23391. return;
  23392. }
  23393. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23394. return;
  23395. }
  23396. Tags.EnableFor(obj);
  23397. obj._tags[tag] = true;
  23398. };
  23399. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23400. if (!Tags.HasTags(obj)) {
  23401. return;
  23402. }
  23403. var tags = tagsString.split(" ");
  23404. for (var t in tags) {
  23405. Tags._RemoveTagFrom(obj, tags[t]);
  23406. }
  23407. };
  23408. Tags._RemoveTagFrom = function (obj, tag) {
  23409. delete obj._tags[tag];
  23410. };
  23411. Tags.MatchesQuery = function (obj, tagsQuery) {
  23412. if (tagsQuery === undefined) {
  23413. return true;
  23414. }
  23415. if (tagsQuery === "") {
  23416. return Tags.HasTags(obj);
  23417. }
  23418. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23419. };
  23420. return Tags;
  23421. })();
  23422. BABYLON.Tags = Tags;
  23423. })(BABYLON || (BABYLON = {}));
  23424. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23425. (function (BABYLON) {
  23426. var Internals;
  23427. (function (Internals) {
  23428. var AndOrNotEvaluator = (function () {
  23429. function AndOrNotEvaluator() {
  23430. }
  23431. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23432. if (!query.match(/\([^\(\)]*\)/g)) {
  23433. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23434. }
  23435. else {
  23436. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23437. // remove parenthesis
  23438. r = r.slice(1, r.length - 1);
  23439. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23440. });
  23441. }
  23442. if (query === "true") {
  23443. return true;
  23444. }
  23445. if (query === "false") {
  23446. return false;
  23447. }
  23448. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23449. };
  23450. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23451. evaluateCallback = evaluateCallback || (function (r) {
  23452. return r === "true" ? true : false;
  23453. });
  23454. var result;
  23455. var or = parenthesisContent.split("||");
  23456. for (var i in or) {
  23457. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23458. var and = ori.split("&&");
  23459. if (and.length > 1) {
  23460. for (var j = 0; j < and.length; ++j) {
  23461. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23462. if (andj !== "true" && andj !== "false") {
  23463. if (andj[0] === "!") {
  23464. result = !evaluateCallback(andj.substring(1));
  23465. }
  23466. else {
  23467. result = evaluateCallback(andj);
  23468. }
  23469. }
  23470. else {
  23471. result = andj === "true" ? true : false;
  23472. }
  23473. if (!result) {
  23474. ori = "false";
  23475. break;
  23476. }
  23477. }
  23478. }
  23479. if (result || ori === "true") {
  23480. result = true;
  23481. break;
  23482. }
  23483. // result equals false (or undefined)
  23484. if (ori !== "true" && ori !== "false") {
  23485. if (ori[0] === "!") {
  23486. result = !evaluateCallback(ori.substring(1));
  23487. }
  23488. else {
  23489. result = evaluateCallback(ori);
  23490. }
  23491. }
  23492. else {
  23493. result = ori === "true" ? true : false;
  23494. }
  23495. }
  23496. // the whole parenthesis scope is replaced by 'true' or 'false'
  23497. return result ? "true" : "false";
  23498. };
  23499. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23500. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23501. // remove whitespaces
  23502. r = r.replace(/[\s]/g, function () { return ""; });
  23503. return r.length % 2 ? "!" : "";
  23504. });
  23505. booleanString = booleanString.trim();
  23506. if (booleanString === "!true") {
  23507. booleanString = "false";
  23508. }
  23509. else if (booleanString === "!false") {
  23510. booleanString = "true";
  23511. }
  23512. return booleanString;
  23513. };
  23514. return AndOrNotEvaluator;
  23515. })();
  23516. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23517. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23518. })(BABYLON || (BABYLON = {}));
  23519. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23520. (function (BABYLON) {
  23521. var PostProcessRenderPass = (function () {
  23522. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23523. this._enabled = true;
  23524. this._refCount = 0;
  23525. this._name = name;
  23526. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23527. this.setRenderList(renderList);
  23528. this._renderTexture.onBeforeRender = beforeRender;
  23529. this._renderTexture.onAfterRender = afterRender;
  23530. this._scene = scene;
  23531. this._renderList = renderList;
  23532. }
  23533. // private
  23534. PostProcessRenderPass.prototype._incRefCount = function () {
  23535. if (this._refCount === 0) {
  23536. this._scene.customRenderTargets.push(this._renderTexture);
  23537. }
  23538. return ++this._refCount;
  23539. };
  23540. PostProcessRenderPass.prototype._decRefCount = function () {
  23541. this._refCount--;
  23542. if (this._refCount <= 0) {
  23543. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23544. }
  23545. return this._refCount;
  23546. };
  23547. PostProcessRenderPass.prototype._update = function () {
  23548. this.setRenderList(this._renderList);
  23549. };
  23550. // public
  23551. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23552. this._renderTexture.renderList = renderList;
  23553. };
  23554. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23555. return this._renderTexture;
  23556. };
  23557. return PostProcessRenderPass;
  23558. })();
  23559. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23560. })(BABYLON || (BABYLON = {}));
  23561. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23562. (function (BABYLON) {
  23563. var PostProcessRenderEffect = (function () {
  23564. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23565. this._engine = engine;
  23566. this._name = name;
  23567. this._singleInstance = singleInstance || true;
  23568. this._getPostProcess = getPostProcess;
  23569. this._cameras = [];
  23570. this._indicesForCamera = [];
  23571. this._postProcesses = {};
  23572. this._renderPasses = {};
  23573. this._renderEffectAsPasses = {};
  23574. }
  23575. PostProcessRenderEffect.prototype._update = function () {
  23576. for (var renderPassName in this._renderPasses) {
  23577. this._renderPasses[renderPassName]._update();
  23578. }
  23579. };
  23580. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23581. this._renderPasses[renderPass._name] = renderPass;
  23582. this._linkParameters();
  23583. };
  23584. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23585. delete this._renderPasses[renderPass._name];
  23586. this._linkParameters();
  23587. };
  23588. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23589. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23590. this._linkParameters();
  23591. };
  23592. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23593. for (var renderPassName in this._renderPasses) {
  23594. if (renderPassName === passName) {
  23595. return this._renderPasses[passName];
  23596. }
  23597. }
  23598. };
  23599. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23600. this._renderPasses = {};
  23601. this._linkParameters();
  23602. };
  23603. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23604. var cameraKey;
  23605. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23606. for (var i = 0; i < _cam.length; i++) {
  23607. var camera = _cam[i];
  23608. var cameraName = camera.name;
  23609. if (this._singleInstance) {
  23610. cameraKey = 0;
  23611. }
  23612. else {
  23613. cameraKey = cameraName;
  23614. }
  23615. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23616. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23617. if (!this._indicesForCamera[cameraName]) {
  23618. this._indicesForCamera[cameraName] = [];
  23619. }
  23620. this._indicesForCamera[cameraName].push(index);
  23621. if (this._cameras.indexOf(camera) === -1) {
  23622. this._cameras[cameraName] = camera;
  23623. }
  23624. for (var passName in this._renderPasses) {
  23625. this._renderPasses[passName]._incRefCount();
  23626. }
  23627. }
  23628. this._linkParameters();
  23629. };
  23630. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23631. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23632. for (var i = 0; i < _cam.length; i++) {
  23633. var camera = _cam[i];
  23634. var cameraName = camera.name;
  23635. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23636. var index = this._cameras.indexOf(cameraName);
  23637. this._indicesForCamera.splice(index, 1);
  23638. this._cameras.splice(index, 1);
  23639. for (var passName in this._renderPasses) {
  23640. this._renderPasses[passName]._decRefCount();
  23641. }
  23642. }
  23643. };
  23644. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23645. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23646. for (var i = 0; i < _cam.length; i++) {
  23647. var camera = _cam[i];
  23648. var cameraName = camera.name;
  23649. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23650. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23651. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23652. }
  23653. }
  23654. for (var passName in this._renderPasses) {
  23655. this._renderPasses[passName]._incRefCount();
  23656. }
  23657. }
  23658. };
  23659. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23660. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23661. for (var i = 0; i < _cam.length; i++) {
  23662. var camera = _cam[i];
  23663. var cameraName = camera.Name;
  23664. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23665. for (var passName in this._renderPasses) {
  23666. this._renderPasses[passName]._decRefCount();
  23667. }
  23668. }
  23669. };
  23670. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23671. if (this._singleInstance) {
  23672. return this._postProcesses[0];
  23673. }
  23674. else {
  23675. return this._postProcesses[camera.name];
  23676. }
  23677. };
  23678. PostProcessRenderEffect.prototype._linkParameters = function () {
  23679. var _this = this;
  23680. for (var index in this._postProcesses) {
  23681. if (this.applyParameters) {
  23682. this.applyParameters(this._postProcesses[index]);
  23683. }
  23684. this._postProcesses[index].onBeforeRender = function (effect) {
  23685. _this._linkTextures(effect);
  23686. };
  23687. }
  23688. };
  23689. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23690. for (var renderPassName in this._renderPasses) {
  23691. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23692. }
  23693. for (var renderEffectName in this._renderEffectAsPasses) {
  23694. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23695. }
  23696. };
  23697. return PostProcessRenderEffect;
  23698. })();
  23699. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23700. })(BABYLON || (BABYLON = {}));
  23701. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23702. (function (BABYLON) {
  23703. var PostProcessRenderPipeline = (function () {
  23704. function PostProcessRenderPipeline(engine, name) {
  23705. this._engine = engine;
  23706. this._name = name;
  23707. this._renderEffects = {};
  23708. this._renderEffectsForIsolatedPass = {};
  23709. this._cameras = [];
  23710. }
  23711. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23712. this._renderEffects[renderEffect._name] = renderEffect;
  23713. };
  23714. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23715. var renderEffects = this._renderEffects[renderEffectName];
  23716. if (!renderEffects) {
  23717. return;
  23718. }
  23719. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23720. };
  23721. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23722. var renderEffects = this._renderEffects[renderEffectName];
  23723. if (!renderEffects) {
  23724. return;
  23725. }
  23726. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23727. };
  23728. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23729. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23730. var indicesToDelete = [];
  23731. for (var i = 0; i < _cam.length; i++) {
  23732. var camera = _cam[i];
  23733. var cameraName = camera.name;
  23734. if (this._cameras.indexOf(camera) === -1) {
  23735. this._cameras[cameraName] = camera;
  23736. }
  23737. else if (unique) {
  23738. indicesToDelete.push(i);
  23739. }
  23740. }
  23741. for (var i = 0; i < indicesToDelete.length; i++) {
  23742. cameras.splice(indicesToDelete[i], 1);
  23743. }
  23744. for (var renderEffectName in this._renderEffects) {
  23745. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23746. }
  23747. };
  23748. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23749. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23750. for (var renderEffectName in this._renderEffects) {
  23751. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23752. }
  23753. for (var i = 0; i < _cam.length; i++) {
  23754. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23755. }
  23756. };
  23757. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23758. var _this = this;
  23759. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23760. var pass = null;
  23761. for (var renderEffectName in this._renderEffects) {
  23762. pass = this._renderEffects[renderEffectName].getPass(passName);
  23763. if (pass != null) {
  23764. break;
  23765. }
  23766. }
  23767. if (pass === null) {
  23768. return;
  23769. }
  23770. for (var renderEffectName in this._renderEffects) {
  23771. this._renderEffects[renderEffectName]._disable(_cam);
  23772. }
  23773. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23774. for (var i = 0; i < _cam.length; i++) {
  23775. var camera = _cam[i];
  23776. var cameraName = camera.name;
  23777. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23778. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23779. });
  23780. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23781. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23782. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23783. }
  23784. };
  23785. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23786. var _this = this;
  23787. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23788. for (var i = 0; i < _cam.length; i++) {
  23789. var camera = _cam[i];
  23790. var cameraName = camera.name;
  23791. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23792. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23793. });
  23794. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23795. }
  23796. for (var renderEffectName in this._renderEffects) {
  23797. this._renderEffects[renderEffectName]._enable(_cam);
  23798. }
  23799. };
  23800. PostProcessRenderPipeline.prototype._update = function () {
  23801. for (var renderEffectName in this._renderEffects) {
  23802. this._renderEffects[renderEffectName]._update();
  23803. }
  23804. for (var i = 0; i < this._cameras.length; i++) {
  23805. var cameraName = this._cameras[i].name;
  23806. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23807. this._renderEffectsForIsolatedPass[cameraName]._update();
  23808. }
  23809. }
  23810. };
  23811. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23812. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23813. return PostProcessRenderPipeline;
  23814. })();
  23815. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23816. })(BABYLON || (BABYLON = {}));
  23817. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23818. (function (BABYLON) {
  23819. var PostProcessRenderPipelineManager = (function () {
  23820. function PostProcessRenderPipelineManager() {
  23821. this._renderPipelines = {};
  23822. }
  23823. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23824. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23825. };
  23826. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23827. var renderPipeline = this._renderPipelines[renderPipelineName];
  23828. if (!renderPipeline) {
  23829. return;
  23830. }
  23831. renderPipeline._attachCameras(cameras, unique);
  23832. };
  23833. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23834. var renderPipeline = this._renderPipelines[renderPipelineName];
  23835. if (!renderPipeline) {
  23836. return;
  23837. }
  23838. renderPipeline._detachCameras(cameras);
  23839. };
  23840. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23841. var renderPipeline = this._renderPipelines[renderPipelineName];
  23842. if (!renderPipeline) {
  23843. return;
  23844. }
  23845. renderPipeline._enableEffect(renderEffectName, cameras);
  23846. };
  23847. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23848. var renderPipeline = this._renderPipelines[renderPipelineName];
  23849. if (!renderPipeline) {
  23850. return;
  23851. }
  23852. renderPipeline._disableEffect(renderEffectName, cameras);
  23853. };
  23854. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23855. var renderPipeline = this._renderPipelines[renderPipelineName];
  23856. if (!renderPipeline) {
  23857. return;
  23858. }
  23859. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23860. };
  23861. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23862. var renderPipeline = this._renderPipelines[renderPipelineName];
  23863. if (!renderPipeline) {
  23864. return;
  23865. }
  23866. renderPipeline._disableDisplayOnlyPass(cameras);
  23867. };
  23868. PostProcessRenderPipelineManager.prototype.update = function () {
  23869. for (var renderPipelineName in this._renderPipelines) {
  23870. this._renderPipelines[renderPipelineName]._update();
  23871. }
  23872. };
  23873. return PostProcessRenderPipelineManager;
  23874. })();
  23875. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23876. })(BABYLON || (BABYLON = {}));
  23877. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23878. var BABYLON;
  23879. (function (BABYLON) {
  23880. var DisplayPassPostProcess = (function (_super) {
  23881. __extends(DisplayPassPostProcess, _super);
  23882. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23883. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23884. }
  23885. return DisplayPassPostProcess;
  23886. })(BABYLON.PostProcess);
  23887. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23888. })(BABYLON || (BABYLON = {}));
  23889. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23890. (function (BABYLON) {
  23891. var BoundingBoxRenderer = (function () {
  23892. function BoundingBoxRenderer(scene) {
  23893. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23894. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23895. this.showBackLines = true;
  23896. this.renderList = new BABYLON.SmartArray(32);
  23897. this._scene = scene;
  23898. }
  23899. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23900. if (this._colorShader) {
  23901. return;
  23902. }
  23903. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23904. attributes: ["position"],
  23905. uniforms: ["worldViewProjection", "color"]
  23906. });
  23907. var engine = this._scene.getEngine();
  23908. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23909. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23910. 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]);
  23911. };
  23912. BoundingBoxRenderer.prototype.reset = function () {
  23913. this.renderList.reset();
  23914. };
  23915. BoundingBoxRenderer.prototype.render = function () {
  23916. if (this.renderList.length === 0) {
  23917. return;
  23918. }
  23919. this._prepareRessources();
  23920. if (!this._colorShader.isReady()) {
  23921. return;
  23922. }
  23923. var engine = this._scene.getEngine();
  23924. engine.setDepthWrite(false);
  23925. this._colorShader._preBind();
  23926. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23927. var boundingBox = this.renderList.data[boundingBoxIndex];
  23928. var min = boundingBox.minimum;
  23929. var max = boundingBox.maximum;
  23930. var diff = max.subtract(min);
  23931. var median = min.add(diff.scale(0.5));
  23932. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23933. // VBOs
  23934. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23935. if (this.showBackLines) {
  23936. // Back
  23937. engine.setDepthFunctionToGreaterOrEqual();
  23938. this._scene.resetCachedMaterial();
  23939. this._colorShader.setColor4("color", this.backColor.toColor4());
  23940. this._colorShader.bind(worldMatrix);
  23941. // Draw order
  23942. engine.draw(false, 0, 24);
  23943. }
  23944. // Front
  23945. engine.setDepthFunctionToLess();
  23946. this._scene.resetCachedMaterial();
  23947. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23948. this._colorShader.bind(worldMatrix);
  23949. // Draw order
  23950. engine.draw(false, 0, 24);
  23951. }
  23952. this._colorShader.unbind();
  23953. engine.setDepthFunctionToLessOrEqual();
  23954. engine.setDepthWrite(true);
  23955. };
  23956. BoundingBoxRenderer.prototype.dispose = function () {
  23957. if (!this._colorShader) {
  23958. return;
  23959. }
  23960. this._colorShader.dispose();
  23961. this._vb.dispose();
  23962. this._scene.getEngine()._releaseBuffer(this._ib);
  23963. };
  23964. return BoundingBoxRenderer;
  23965. })();
  23966. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23967. })(BABYLON || (BABYLON = {}));
  23968. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23969. (function (BABYLON) {
  23970. var Internals;
  23971. (function (Internals) {
  23972. /*
  23973. * Based on jsTGALoader - Javascript loader for TGA file
  23974. * By Vincent Thibault
  23975. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23976. */
  23977. var TGATools = (function () {
  23978. function TGATools() {
  23979. }
  23980. TGATools.GetTGAHeader = function (data) {
  23981. var offset = 0;
  23982. var header = {
  23983. id_length: data[offset++],
  23984. colormap_type: data[offset++],
  23985. image_type: data[offset++],
  23986. colormap_index: data[offset++] | data[offset++] << 8,
  23987. colormap_length: data[offset++] | data[offset++] << 8,
  23988. colormap_size: data[offset++],
  23989. origin: [
  23990. data[offset++] | data[offset++] << 8,
  23991. data[offset++] | data[offset++] << 8
  23992. ],
  23993. width: data[offset++] | data[offset++] << 8,
  23994. height: data[offset++] | data[offset++] << 8,
  23995. pixel_size: data[offset++],
  23996. flags: data[offset++]
  23997. };
  23998. return header;
  23999. };
  24000. TGATools.UploadContent = function (gl, data) {
  24001. // Not enough data to contain header ?
  24002. if (data.length < 19) {
  24003. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  24004. return;
  24005. }
  24006. // Read Header
  24007. var offset = 18;
  24008. var header = TGATools.GetTGAHeader(data);
  24009. // Assume it's a valid Targa file.
  24010. if (header.id_length + offset > data.length) {
  24011. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  24012. return;
  24013. }
  24014. // Skip not needed data
  24015. offset += header.id_length;
  24016. var use_rle = false;
  24017. var use_pal = false;
  24018. var use_rgb = false;
  24019. var use_grey = false;
  24020. switch (header.image_type) {
  24021. case TGATools._TYPE_RLE_INDEXED:
  24022. use_rle = true;
  24023. case TGATools._TYPE_INDEXED:
  24024. use_pal = true;
  24025. break;
  24026. case TGATools._TYPE_RLE_RGB:
  24027. use_rle = true;
  24028. case TGATools._TYPE_RGB:
  24029. use_rgb = true;
  24030. break;
  24031. case TGATools._TYPE_RLE_GREY:
  24032. use_rle = true;
  24033. case TGATools._TYPE_GREY:
  24034. use_grey = true;
  24035. break;
  24036. }
  24037. var pixel_data;
  24038. var numAlphaBits = header.flags & 0xf;
  24039. var pixel_size = header.pixel_size >> 3;
  24040. var pixel_total = header.width * header.height * pixel_size;
  24041. // Read palettes
  24042. var palettes;
  24043. if (use_pal) {
  24044. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  24045. }
  24046. // Read LRE
  24047. if (use_rle) {
  24048. pixel_data = new Uint8Array(pixel_total);
  24049. var c, count, i;
  24050. var localOffset = 0;
  24051. var pixels = new Uint8Array(pixel_size);
  24052. while (offset < pixel_total && localOffset < pixel_total) {
  24053. c = data[offset++];
  24054. count = (c & 0x7f) + 1;
  24055. // RLE pixels
  24056. if (c & 0x80) {
  24057. for (i = 0; i < pixel_size; ++i) {
  24058. pixels[i] = data[offset++];
  24059. }
  24060. for (i = 0; i < count; ++i) {
  24061. pixel_data.set(pixels, localOffset + i * pixel_size);
  24062. }
  24063. localOffset += pixel_size * count;
  24064. }
  24065. else {
  24066. count *= pixel_size;
  24067. for (i = 0; i < count; ++i) {
  24068. pixel_data[localOffset + i] = data[offset++];
  24069. }
  24070. localOffset += count;
  24071. }
  24072. }
  24073. }
  24074. else {
  24075. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  24076. }
  24077. // Load to texture
  24078. var x_start, y_start, x_step, y_step, y_end, x_end;
  24079. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  24080. default:
  24081. case TGATools._ORIGIN_UL:
  24082. x_start = 0;
  24083. x_step = 1;
  24084. x_end = header.width;
  24085. y_start = 0;
  24086. y_step = 1;
  24087. y_end = header.height;
  24088. break;
  24089. case TGATools._ORIGIN_BL:
  24090. x_start = 0;
  24091. x_step = 1;
  24092. x_end = header.width;
  24093. y_start = header.height - 1;
  24094. y_step = -1;
  24095. y_end = -1;
  24096. break;
  24097. case TGATools._ORIGIN_UR:
  24098. x_start = header.width - 1;
  24099. x_step = -1;
  24100. x_end = -1;
  24101. y_start = 0;
  24102. y_step = 1;
  24103. y_end = header.height;
  24104. break;
  24105. case TGATools._ORIGIN_BR:
  24106. x_start = header.width - 1;
  24107. x_step = -1;
  24108. x_end = -1;
  24109. y_start = header.height - 1;
  24110. y_step = -1;
  24111. y_end = -1;
  24112. break;
  24113. }
  24114. // Load the specify method
  24115. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  24116. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  24117. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  24118. };
  24119. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24120. var image = pixel_data, colormap = palettes;
  24121. var width = header.width, height = header.height;
  24122. var color, i = 0, x, y;
  24123. var imageData = new Uint8Array(width * height * 4);
  24124. for (y = y_start; y !== y_end; y += y_step) {
  24125. for (x = x_start; x !== x_end; x += x_step, i++) {
  24126. color = image[i];
  24127. imageData[(x + width * y) * 4 + 3] = 255;
  24128. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  24129. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  24130. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  24131. }
  24132. }
  24133. return imageData;
  24134. };
  24135. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24136. var image = pixel_data;
  24137. var width = header.width, height = header.height;
  24138. var color, i = 0, x, y;
  24139. var imageData = new Uint8Array(width * height * 4);
  24140. for (y = y_start; y !== y_end; y += y_step) {
  24141. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24142. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  24143. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  24144. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  24145. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  24146. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  24147. }
  24148. }
  24149. return imageData;
  24150. };
  24151. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24152. var image = pixel_data;
  24153. var width = header.width, height = header.height;
  24154. var i = 0, x, y;
  24155. var imageData = new Uint8Array(width * height * 4);
  24156. for (y = y_start; y !== y_end; y += y_step) {
  24157. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  24158. imageData[(x + width * y) * 4 + 3] = 255;
  24159. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24160. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24161. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24162. }
  24163. }
  24164. return imageData;
  24165. };
  24166. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24167. var image = pixel_data;
  24168. var width = header.width, height = header.height;
  24169. var i = 0, x, y;
  24170. var imageData = new Uint8Array(width * height * 4);
  24171. for (y = y_start; y !== y_end; y += y_step) {
  24172. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  24173. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24174. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24175. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24176. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  24177. }
  24178. }
  24179. return imageData;
  24180. };
  24181. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24182. var image = pixel_data;
  24183. var width = header.width, height = header.height;
  24184. var color, i = 0, x, y;
  24185. var imageData = new Uint8Array(width * height * 4);
  24186. for (y = y_start; y !== y_end; y += y_step) {
  24187. for (x = x_start; x !== x_end; x += x_step, i++) {
  24188. color = image[i];
  24189. imageData[(x + width * y) * 4 + 0] = color;
  24190. imageData[(x + width * y) * 4 + 1] = color;
  24191. imageData[(x + width * y) * 4 + 2] = color;
  24192. imageData[(x + width * y) * 4 + 3] = 255;
  24193. }
  24194. }
  24195. return imageData;
  24196. };
  24197. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24198. var image = pixel_data;
  24199. var width = header.width, height = header.height;
  24200. var i = 0, x, y;
  24201. var imageData = new Uint8Array(width * height * 4);
  24202. for (y = y_start; y !== y_end; y += y_step) {
  24203. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24204. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  24205. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  24206. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24207. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  24208. }
  24209. }
  24210. return imageData;
  24211. };
  24212. TGATools._TYPE_NO_DATA = 0;
  24213. TGATools._TYPE_INDEXED = 1;
  24214. TGATools._TYPE_RGB = 2;
  24215. TGATools._TYPE_GREY = 3;
  24216. TGATools._TYPE_RLE_INDEXED = 9;
  24217. TGATools._TYPE_RLE_RGB = 10;
  24218. TGATools._TYPE_RLE_GREY = 11;
  24219. TGATools._ORIGIN_MASK = 0x30;
  24220. TGATools._ORIGIN_SHIFT = 0x04;
  24221. TGATools._ORIGIN_BL = 0x00;
  24222. TGATools._ORIGIN_BR = 0x01;
  24223. TGATools._ORIGIN_UL = 0x02;
  24224. TGATools._ORIGIN_UR = 0x03;
  24225. return TGATools;
  24226. })();
  24227. Internals.TGATools = TGATools;
  24228. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24229. })(BABYLON || (BABYLON = {}));
  24230. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24231. (function (BABYLON) {
  24232. var Internals;
  24233. (function (Internals) {
  24234. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24235. // All values and structures referenced from:
  24236. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24237. var DDS_MAGIC = 0x20534444;
  24238. 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;
  24239. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24240. 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;
  24241. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24242. function FourCCToInt32(value) {
  24243. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24244. }
  24245. function Int32ToFourCC(value) {
  24246. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24247. }
  24248. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24249. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24250. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24251. var headerLengthInt = 31; // The header length in 32 bit ints
  24252. // Offsets into the header array
  24253. var off_magic = 0;
  24254. var off_size = 1;
  24255. var off_flags = 2;
  24256. var off_height = 3;
  24257. var off_width = 4;
  24258. var off_mipmapCount = 7;
  24259. var off_pfFlags = 20;
  24260. var off_pfFourCC = 21;
  24261. var off_RGBbpp = 22;
  24262. var off_RMask = 23;
  24263. var off_GMask = 24;
  24264. var off_BMask = 25;
  24265. var off_AMask = 26;
  24266. var off_caps1 = 27;
  24267. var off_caps2 = 28;
  24268. ;
  24269. var DDSTools = (function () {
  24270. function DDSTools() {
  24271. }
  24272. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24273. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24274. var mipmapCount = 1;
  24275. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24276. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24277. }
  24278. return {
  24279. width: header[off_width],
  24280. height: header[off_height],
  24281. mipmapCount: mipmapCount,
  24282. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24283. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24284. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24285. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24286. };
  24287. };
  24288. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24289. var byteArray = new Uint8Array(dataLength);
  24290. var srcData = new Uint8Array(arrayBuffer);
  24291. var index = 0;
  24292. for (var y = height - 1; y >= 0; y--) {
  24293. for (var x = 0; x < width; x++) {
  24294. var srcPos = dataOffset + (x + y * width) * 4;
  24295. byteArray[index + 2] = srcData[srcPos];
  24296. byteArray[index + 1] = srcData[srcPos + 1];
  24297. byteArray[index] = srcData[srcPos + 2];
  24298. byteArray[index + 3] = srcData[srcPos + 3];
  24299. index += 4;
  24300. }
  24301. }
  24302. return byteArray;
  24303. };
  24304. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24305. var byteArray = new Uint8Array(dataLength);
  24306. var srcData = new Uint8Array(arrayBuffer);
  24307. var index = 0;
  24308. for (var y = height - 1; y >= 0; y--) {
  24309. for (var x = 0; x < width; x++) {
  24310. var srcPos = dataOffset + (x + y * width) * 3;
  24311. byteArray[index + 2] = srcData[srcPos];
  24312. byteArray[index + 1] = srcData[srcPos + 1];
  24313. byteArray[index] = srcData[srcPos + 2];
  24314. index += 3;
  24315. }
  24316. }
  24317. return byteArray;
  24318. };
  24319. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24320. var byteArray = new Uint8Array(dataLength);
  24321. var srcData = new Uint8Array(arrayBuffer);
  24322. var index = 0;
  24323. for (var y = height - 1; y >= 0; y--) {
  24324. for (var x = 0; x < width; x++) {
  24325. var srcPos = dataOffset + (x + y * width);
  24326. byteArray[index] = srcData[srcPos];
  24327. index++;
  24328. }
  24329. }
  24330. return byteArray;
  24331. };
  24332. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24333. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24334. if (header[off_magic] != DDS_MAGIC) {
  24335. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24336. return;
  24337. }
  24338. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24339. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24340. return;
  24341. }
  24342. if (info.isFourCC) {
  24343. fourCC = header[off_pfFourCC];
  24344. switch (fourCC) {
  24345. case FOURCC_DXT1:
  24346. blockBytes = 8;
  24347. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24348. break;
  24349. case FOURCC_DXT3:
  24350. blockBytes = 16;
  24351. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24352. break;
  24353. case FOURCC_DXT5:
  24354. blockBytes = 16;
  24355. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24356. break;
  24357. default:
  24358. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24359. return;
  24360. }
  24361. }
  24362. mipmapCount = 1;
  24363. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24364. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24365. }
  24366. var bpp = header[off_RGBbpp];
  24367. for (var face = 0; face < faces; face++) {
  24368. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24369. width = header[off_width];
  24370. height = header[off_height];
  24371. dataOffset = header[off_size] + 4;
  24372. for (i = 0; i < mipmapCount; ++i) {
  24373. if (info.isRGB) {
  24374. if (bpp == 24) {
  24375. dataLength = width * height * 3;
  24376. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24377. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24378. }
  24379. else {
  24380. dataLength = width * height * 4;
  24381. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24382. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24383. }
  24384. }
  24385. else if (info.isLuminance) {
  24386. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24387. var unpaddedRowSize = width;
  24388. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24389. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24390. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24391. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24392. }
  24393. else {
  24394. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24395. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24396. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24397. }
  24398. dataOffset += dataLength;
  24399. width *= 0.5;
  24400. height *= 0.5;
  24401. width = Math.max(1.0, width);
  24402. height = Math.max(1.0, height);
  24403. }
  24404. }
  24405. };
  24406. return DDSTools;
  24407. })();
  24408. Internals.DDSTools = DDSTools;
  24409. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24410. })(BABYLON || (BABYLON = {}));
  24411. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24412. (function (BABYLON) {
  24413. var SmartArray = (function () {
  24414. function SmartArray(capacity) {
  24415. this.length = 0;
  24416. this._duplicateId = 0;
  24417. this.data = new Array(capacity);
  24418. this._id = SmartArray._GlobalId++;
  24419. }
  24420. SmartArray.prototype.push = function (value) {
  24421. this.data[this.length++] = value;
  24422. if (this.length > this.data.length) {
  24423. this.data.length *= 2;
  24424. }
  24425. if (!value.__smartArrayFlags) {
  24426. value.__smartArrayFlags = {};
  24427. }
  24428. value.__smartArrayFlags[this._id] = this._duplicateId;
  24429. };
  24430. SmartArray.prototype.pushNoDuplicate = function (value) {
  24431. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24432. return;
  24433. }
  24434. this.push(value);
  24435. };
  24436. SmartArray.prototype.sort = function (compareFn) {
  24437. this.data.sort(compareFn);
  24438. };
  24439. SmartArray.prototype.reset = function () {
  24440. this.length = 0;
  24441. this._duplicateId++;
  24442. };
  24443. SmartArray.prototype.concat = function (array) {
  24444. if (array.length === 0) {
  24445. return;
  24446. }
  24447. if (this.length + array.length > this.data.length) {
  24448. this.data.length = (this.length + array.length) * 2;
  24449. }
  24450. for (var index = 0; index < array.length; index++) {
  24451. this.data[this.length++] = (array.data || array)[index];
  24452. }
  24453. };
  24454. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24455. if (array.length === 0) {
  24456. return;
  24457. }
  24458. if (this.length + array.length > this.data.length) {
  24459. this.data.length = (this.length + array.length) * 2;
  24460. }
  24461. for (var index = 0; index < array.length; index++) {
  24462. var item = (array.data || array)[index];
  24463. this.pushNoDuplicate(item);
  24464. }
  24465. };
  24466. SmartArray.prototype.indexOf = function (value) {
  24467. var position = this.data.indexOf(value);
  24468. if (position >= this.length) {
  24469. return -1;
  24470. }
  24471. return position;
  24472. };
  24473. // Statics
  24474. SmartArray._GlobalId = 0;
  24475. return SmartArray;
  24476. })();
  24477. BABYLON.SmartArray = SmartArray;
  24478. })(BABYLON || (BABYLON = {}));
  24479. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24480. (function (BABYLON) {
  24481. var CannonJSPlugin = (function () {
  24482. function CannonJSPlugin() {
  24483. this._registeredMeshes = [];
  24484. this._physicsMaterials = [];
  24485. this.updateBodyPosition = function (mesh) {
  24486. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24487. var registeredMesh = this._registeredMeshes[index];
  24488. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24489. var body = registeredMesh.body;
  24490. var center = mesh.getBoundingInfo().boundingBox.center;
  24491. body.position.set(center.x, center.z, center.y);
  24492. body.quaternion.x = mesh.rotationQuaternion.x;
  24493. body.quaternion.z = mesh.rotationQuaternion.y;
  24494. body.quaternion.y = mesh.rotationQuaternion.z;
  24495. body.quaternion.w = -mesh.rotationQuaternion.w;
  24496. return;
  24497. }
  24498. }
  24499. };
  24500. }
  24501. CannonJSPlugin.prototype.initialize = function (iterations) {
  24502. if (iterations === void 0) { iterations = 10; }
  24503. this._world = new CANNON.World();
  24504. this._world.broadphase = new CANNON.NaiveBroadphase();
  24505. this._world.solver.iterations = iterations;
  24506. };
  24507. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24508. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24509. };
  24510. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24511. this._world.step(delta);
  24512. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24513. var registeredMesh = this._registeredMeshes[index];
  24514. if (registeredMesh.isChild) {
  24515. continue;
  24516. }
  24517. // Body position
  24518. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24519. var deltaPos = registeredMesh.delta;
  24520. if (deltaPos) {
  24521. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24522. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24523. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24524. }
  24525. else {
  24526. registeredMesh.mesh.position.x = bodyX;
  24527. registeredMesh.mesh.position.y = bodyZ;
  24528. registeredMesh.mesh.position.z = bodyY;
  24529. }
  24530. if (!registeredMesh.mesh.rotationQuaternion) {
  24531. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24532. }
  24533. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24534. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24535. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24536. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24537. }
  24538. };
  24539. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24540. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24541. };
  24542. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24543. this.unregisterMesh(mesh);
  24544. mesh.computeWorldMatrix(true);
  24545. switch (impostor) {
  24546. case BABYLON.PhysicsEngine.SphereImpostor:
  24547. var bbox = mesh.getBoundingInfo().boundingBox;
  24548. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24549. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24550. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24551. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24552. case BABYLON.PhysicsEngine.BoxImpostor:
  24553. bbox = mesh.getBoundingInfo().boundingBox;
  24554. var min = bbox.minimumWorld;
  24555. var max = bbox.maximumWorld;
  24556. var box = max.subtract(min).scale(0.5);
  24557. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24558. case BABYLON.PhysicsEngine.PlaneImpostor:
  24559. return this._createPlane(mesh, options);
  24560. case BABYLON.PhysicsEngine.MeshImpostor:
  24561. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24562. var rawFaces = mesh.getIndices();
  24563. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24564. }
  24565. return null;
  24566. };
  24567. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24568. var shape = new CANNON.Sphere(radius);
  24569. if (!options) {
  24570. return shape;
  24571. }
  24572. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24573. };
  24574. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24575. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24576. if (!options) {
  24577. return shape;
  24578. }
  24579. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24580. };
  24581. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24582. var shape = new CANNON.Plane();
  24583. if (!options) {
  24584. return shape;
  24585. }
  24586. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24587. };
  24588. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24589. var verts = [], faces = [];
  24590. mesh.computeWorldMatrix(true);
  24591. for (var i = 0; i < rawVerts.length; i += 3) {
  24592. var transformed = BABYLON.Vector3.Zero();
  24593. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24594. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24595. }
  24596. for (var j = 0; j < rawFaces.length; j += 3) {
  24597. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24598. }
  24599. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24600. if (!options) {
  24601. return shape;
  24602. }
  24603. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24604. };
  24605. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24606. var index;
  24607. var mat;
  24608. for (index = 0; index < this._physicsMaterials.length; index++) {
  24609. mat = this._physicsMaterials[index];
  24610. if (mat.friction === friction && mat.restitution === restitution) {
  24611. return mat;
  24612. }
  24613. }
  24614. var currentMat = new CANNON.Material();
  24615. currentMat.friction = friction;
  24616. currentMat.restitution = restitution;
  24617. this._physicsMaterials.push(currentMat);
  24618. for (index = 0; index < this._physicsMaterials.length; index++) {
  24619. mat = this._physicsMaterials[index];
  24620. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24621. contactMaterial.contactEquationStiffness = 1e10;
  24622. contactMaterial.contactEquationRegularizationTime = 10;
  24623. this._world.addContactMaterial(contactMaterial);
  24624. }
  24625. return currentMat;
  24626. };
  24627. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24628. var initialRotation = null;
  24629. if (mesh.rotationQuaternion) {
  24630. initialRotation = mesh.rotationQuaternion.clone();
  24631. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24632. }
  24633. // The delta between the mesh position and the mesh bounding box center
  24634. var bbox = mesh.getBoundingInfo().boundingBox;
  24635. var deltaPosition = mesh.position.subtract(bbox.center);
  24636. var material = this._addMaterial(friction, restitution);
  24637. var body = new CANNON.RigidBody(mass, shape, material);
  24638. if (initialRotation) {
  24639. body.quaternion.x = initialRotation.x;
  24640. body.quaternion.z = initialRotation.y;
  24641. body.quaternion.y = initialRotation.z;
  24642. body.quaternion.w = -initialRotation.w;
  24643. }
  24644. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24645. this._world.add(body);
  24646. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24647. return body;
  24648. };
  24649. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24650. var compoundShape = new CANNON.Compound();
  24651. for (var index = 0; index < parts.length; index++) {
  24652. var mesh = parts[index].mesh;
  24653. var shape = this.registerMesh(mesh, parts[index].impostor);
  24654. if (index == 0) {
  24655. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24656. }
  24657. else {
  24658. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24659. }
  24660. }
  24661. var initialMesh = parts[0].mesh;
  24662. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24663. body.parts = parts;
  24664. return body;
  24665. };
  24666. CannonJSPlugin.prototype._unbindBody = function (body) {
  24667. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24668. var registeredMesh = this._registeredMeshes[index];
  24669. if (registeredMesh.body === body) {
  24670. registeredMesh.body = null;
  24671. registeredMesh.delta = 0;
  24672. }
  24673. }
  24674. };
  24675. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24676. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24677. var registeredMesh = this._registeredMeshes[index];
  24678. if (registeredMesh.mesh === mesh) {
  24679. // Remove body
  24680. if (registeredMesh.body) {
  24681. this._world.remove(registeredMesh.body);
  24682. this._unbindBody(registeredMesh.body);
  24683. }
  24684. this._registeredMeshes.splice(index, 1);
  24685. return;
  24686. }
  24687. }
  24688. };
  24689. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24690. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24691. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24692. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24693. var registeredMesh = this._registeredMeshes[index];
  24694. if (registeredMesh.mesh === mesh) {
  24695. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24696. return;
  24697. }
  24698. }
  24699. };
  24700. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24701. var body1 = null, body2 = null;
  24702. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24703. var registeredMesh = this._registeredMeshes[index];
  24704. if (registeredMesh.mesh === mesh1) {
  24705. body1 = registeredMesh.body;
  24706. }
  24707. else if (registeredMesh.mesh === mesh2) {
  24708. body2 = registeredMesh.body;
  24709. }
  24710. }
  24711. if (!body1 || !body2) {
  24712. return false;
  24713. }
  24714. 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));
  24715. this._world.addConstraint(constraint);
  24716. return true;
  24717. };
  24718. CannonJSPlugin.prototype.dispose = function () {
  24719. while (this._registeredMeshes.length) {
  24720. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24721. }
  24722. };
  24723. CannonJSPlugin.prototype.isSupported = function () {
  24724. return window.CANNON !== undefined;
  24725. };
  24726. return CannonJSPlugin;
  24727. })();
  24728. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24729. })(BABYLON || (BABYLON = {}));
  24730. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24731. var BABYLON;
  24732. (function (BABYLON) {
  24733. var Condition = (function () {
  24734. function Condition(actionManager) {
  24735. this._actionManager = actionManager;
  24736. }
  24737. Condition.prototype.isValid = function () {
  24738. return true;
  24739. };
  24740. Condition.prototype._getProperty = function (propertyPath) {
  24741. return this._actionManager._getProperty(propertyPath);
  24742. };
  24743. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24744. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24745. };
  24746. return Condition;
  24747. })();
  24748. BABYLON.Condition = Condition;
  24749. var ValueCondition = (function (_super) {
  24750. __extends(ValueCondition, _super);
  24751. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24752. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24753. _super.call(this, actionManager);
  24754. this.propertyPath = propertyPath;
  24755. this.value = value;
  24756. this.operator = operator;
  24757. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24758. this._property = this._getProperty(this.propertyPath);
  24759. }
  24760. Object.defineProperty(ValueCondition, "IsEqual", {
  24761. get: function () {
  24762. return ValueCondition._IsEqual;
  24763. },
  24764. enumerable: true,
  24765. configurable: true
  24766. });
  24767. Object.defineProperty(ValueCondition, "IsDifferent", {
  24768. get: function () {
  24769. return ValueCondition._IsDifferent;
  24770. },
  24771. enumerable: true,
  24772. configurable: true
  24773. });
  24774. Object.defineProperty(ValueCondition, "IsGreater", {
  24775. get: function () {
  24776. return ValueCondition._IsGreater;
  24777. },
  24778. enumerable: true,
  24779. configurable: true
  24780. });
  24781. Object.defineProperty(ValueCondition, "IsLesser", {
  24782. get: function () {
  24783. return ValueCondition._IsLesser;
  24784. },
  24785. enumerable: true,
  24786. configurable: true
  24787. });
  24788. // Methods
  24789. ValueCondition.prototype.isValid = function () {
  24790. switch (this.operator) {
  24791. case ValueCondition.IsGreater:
  24792. return this._target[this._property] > this.value;
  24793. case ValueCondition.IsLesser:
  24794. return this._target[this._property] < this.value;
  24795. case ValueCondition.IsEqual:
  24796. case ValueCondition.IsDifferent:
  24797. var check;
  24798. if (this.value.equals) {
  24799. check = this.value.equals(this._target[this._property]);
  24800. }
  24801. else {
  24802. check = this.value === this._target[this._property];
  24803. }
  24804. return this.operator === ValueCondition.IsEqual ? check : !check;
  24805. }
  24806. return false;
  24807. };
  24808. // Statics
  24809. ValueCondition._IsEqual = 0;
  24810. ValueCondition._IsDifferent = 1;
  24811. ValueCondition._IsGreater = 2;
  24812. ValueCondition._IsLesser = 3;
  24813. return ValueCondition;
  24814. })(Condition);
  24815. BABYLON.ValueCondition = ValueCondition;
  24816. var PredicateCondition = (function (_super) {
  24817. __extends(PredicateCondition, _super);
  24818. function PredicateCondition(actionManager, predicate) {
  24819. _super.call(this, actionManager);
  24820. this.predicate = predicate;
  24821. }
  24822. PredicateCondition.prototype.isValid = function () {
  24823. return this.predicate();
  24824. };
  24825. return PredicateCondition;
  24826. })(Condition);
  24827. BABYLON.PredicateCondition = PredicateCondition;
  24828. var StateCondition = (function (_super) {
  24829. __extends(StateCondition, _super);
  24830. function StateCondition(actionManager, target, value) {
  24831. _super.call(this, actionManager);
  24832. this.value = value;
  24833. this._target = target;
  24834. }
  24835. // Methods
  24836. StateCondition.prototype.isValid = function () {
  24837. return this._target.state === this.value;
  24838. };
  24839. return StateCondition;
  24840. })(Condition);
  24841. BABYLON.StateCondition = StateCondition;
  24842. })(BABYLON || (BABYLON = {}));
  24843. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24844. (function (BABYLON) {
  24845. var Action = (function () {
  24846. function Action(triggerOptions, condition) {
  24847. this.triggerOptions = triggerOptions;
  24848. if (triggerOptions.parameter) {
  24849. this.trigger = triggerOptions.trigger;
  24850. this._triggerParameter = triggerOptions.parameter;
  24851. }
  24852. else {
  24853. this.trigger = triggerOptions;
  24854. }
  24855. this._nextActiveAction = this;
  24856. this._condition = condition;
  24857. }
  24858. // Methods
  24859. Action.prototype._prepare = function () {
  24860. };
  24861. Action.prototype.getTriggerParameter = function () {
  24862. return this._triggerParameter;
  24863. };
  24864. Action.prototype._executeCurrent = function (evt) {
  24865. if (this._nextActiveAction._condition) {
  24866. var condition = this._nextActiveAction._condition;
  24867. var currentRenderId = this._actionManager.getScene().getRenderId();
  24868. // We cache the current evaluation for the current frame
  24869. if (condition._evaluationId === currentRenderId) {
  24870. if (!condition._currentResult) {
  24871. return;
  24872. }
  24873. }
  24874. else {
  24875. condition._evaluationId = currentRenderId;
  24876. if (!condition.isValid()) {
  24877. condition._currentResult = false;
  24878. return;
  24879. }
  24880. condition._currentResult = true;
  24881. }
  24882. }
  24883. this._nextActiveAction.execute(evt);
  24884. if (this._nextActiveAction._child) {
  24885. if (!this._nextActiveAction._child._actionManager) {
  24886. this._nextActiveAction._child._actionManager = this._actionManager;
  24887. }
  24888. this._nextActiveAction = this._nextActiveAction._child;
  24889. }
  24890. else {
  24891. this._nextActiveAction = this;
  24892. }
  24893. };
  24894. Action.prototype.execute = function (evt) {
  24895. };
  24896. Action.prototype.then = function (action) {
  24897. this._child = action;
  24898. action._actionManager = this._actionManager;
  24899. action._prepare();
  24900. return action;
  24901. };
  24902. Action.prototype._getProperty = function (propertyPath) {
  24903. return this._actionManager._getProperty(propertyPath);
  24904. };
  24905. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24906. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24907. };
  24908. return Action;
  24909. })();
  24910. BABYLON.Action = Action;
  24911. })(BABYLON || (BABYLON = {}));
  24912. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24913. (function (BABYLON) {
  24914. /**
  24915. * ActionEvent is the event beint sent when an action is triggered.
  24916. */
  24917. var ActionEvent = (function () {
  24918. /**
  24919. * @constructor
  24920. * @param source The mesh that triggered the action.
  24921. * @param pointerX the X mouse cursor position at the time of the event
  24922. * @param pointerY the Y mouse cursor position at the time of the event
  24923. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24924. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24925. */
  24926. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24927. this.source = source;
  24928. this.pointerX = pointerX;
  24929. this.pointerY = pointerY;
  24930. this.meshUnderPointer = meshUnderPointer;
  24931. this.sourceEvent = sourceEvent;
  24932. }
  24933. /**
  24934. * Helper function to auto-create an ActionEvent from a source mesh.
  24935. * @param source the source mesh that triggered the event
  24936. * @param evt {Event} The original (browser) event
  24937. */
  24938. ActionEvent.CreateNew = function (source, evt) {
  24939. var scene = source.getScene();
  24940. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24941. };
  24942. /**
  24943. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24944. * @param scene the scene where the event occurred
  24945. * @param evt {Event} The original (browser) event
  24946. */
  24947. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24948. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24949. };
  24950. return ActionEvent;
  24951. })();
  24952. BABYLON.ActionEvent = ActionEvent;
  24953. /**
  24954. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24955. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24956. */
  24957. var ActionManager = (function () {
  24958. function ActionManager(scene) {
  24959. // Members
  24960. this.actions = new Array();
  24961. this._scene = scene;
  24962. scene._actionManagers.push(this);
  24963. }
  24964. Object.defineProperty(ActionManager, "NothingTrigger", {
  24965. get: function () {
  24966. return ActionManager._NothingTrigger;
  24967. },
  24968. enumerable: true,
  24969. configurable: true
  24970. });
  24971. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24972. get: function () {
  24973. return ActionManager._OnPickTrigger;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24979. get: function () {
  24980. return ActionManager._OnLeftPickTrigger;
  24981. },
  24982. enumerable: true,
  24983. configurable: true
  24984. });
  24985. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24986. get: function () {
  24987. return ActionManager._OnRightPickTrigger;
  24988. },
  24989. enumerable: true,
  24990. configurable: true
  24991. });
  24992. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24993. get: function () {
  24994. return ActionManager._OnCenterPickTrigger;
  24995. },
  24996. enumerable: true,
  24997. configurable: true
  24998. });
  24999. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25000. get: function () {
  25001. return ActionManager._OnPointerOverTrigger;
  25002. },
  25003. enumerable: true,
  25004. configurable: true
  25005. });
  25006. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25007. get: function () {
  25008. return ActionManager._OnPointerOutTrigger;
  25009. },
  25010. enumerable: true,
  25011. configurable: true
  25012. });
  25013. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25014. get: function () {
  25015. return ActionManager._OnEveryFrameTrigger;
  25016. },
  25017. enumerable: true,
  25018. configurable: true
  25019. });
  25020. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25021. get: function () {
  25022. return ActionManager._OnIntersectionEnterTrigger;
  25023. },
  25024. enumerable: true,
  25025. configurable: true
  25026. });
  25027. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25028. get: function () {
  25029. return ActionManager._OnIntersectionExitTrigger;
  25030. },
  25031. enumerable: true,
  25032. configurable: true
  25033. });
  25034. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25035. get: function () {
  25036. return ActionManager._OnKeyDownTrigger;
  25037. },
  25038. enumerable: true,
  25039. configurable: true
  25040. });
  25041. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25042. get: function () {
  25043. return ActionManager._OnKeyUpTrigger;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. // Methods
  25049. ActionManager.prototype.dispose = function () {
  25050. var index = this._scene._actionManagers.indexOf(this);
  25051. if (index > -1) {
  25052. this._scene._actionManagers.splice(index, 1);
  25053. }
  25054. };
  25055. ActionManager.prototype.getScene = function () {
  25056. return this._scene;
  25057. };
  25058. /**
  25059. * Does this action manager handles actions of any of the given triggers
  25060. * @param {number[]} triggers - the triggers to be tested
  25061. * @return {boolean} whether one (or more) of the triggers is handeled
  25062. */
  25063. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25064. for (var index = 0; index < this.actions.length; index++) {
  25065. var action = this.actions[index];
  25066. if (triggers.indexOf(action.trigger) > -1) {
  25067. return true;
  25068. }
  25069. }
  25070. return false;
  25071. };
  25072. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25073. /**
  25074. * Does this action manager has pointer triggers
  25075. * @return {boolean} whether or not it has pointer triggers
  25076. */
  25077. get: function () {
  25078. for (var index = 0; index < this.actions.length; index++) {
  25079. var action = this.actions[index];
  25080. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25081. return true;
  25082. }
  25083. }
  25084. return false;
  25085. },
  25086. enumerable: true,
  25087. configurable: true
  25088. });
  25089. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25090. /**
  25091. * Does this action manager has pick triggers
  25092. * @return {boolean} whether or not it has pick triggers
  25093. */
  25094. get: function () {
  25095. for (var index = 0; index < this.actions.length; index++) {
  25096. var action = this.actions[index];
  25097. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25098. return true;
  25099. }
  25100. }
  25101. return false;
  25102. },
  25103. enumerable: true,
  25104. configurable: true
  25105. });
  25106. /**
  25107. * Registers an action to this action manager
  25108. * @param {BABYLON.Action} action - the action to be registered
  25109. * @return {BABYLON.Action} the action amended (prepared) after registration
  25110. */
  25111. ActionManager.prototype.registerAction = function (action) {
  25112. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25113. if (this.getScene().actionManager !== this) {
  25114. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25115. return null;
  25116. }
  25117. }
  25118. this.actions.push(action);
  25119. action._actionManager = this;
  25120. action._prepare();
  25121. return action;
  25122. };
  25123. /**
  25124. * Process a specific trigger
  25125. * @param {number} trigger - the trigger to process
  25126. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25127. */
  25128. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25129. for (var index = 0; index < this.actions.length; index++) {
  25130. var action = this.actions[index];
  25131. if (action.trigger === trigger) {
  25132. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  25133. var parameter = action.getTriggerParameter();
  25134. if (parameter) {
  25135. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25136. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25137. if (actualkey !== parameter.toLowerCase()) {
  25138. continue;
  25139. }
  25140. }
  25141. }
  25142. action._executeCurrent(evt);
  25143. }
  25144. }
  25145. };
  25146. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25147. var properties = propertyPath.split(".");
  25148. for (var index = 0; index < properties.length - 1; index++) {
  25149. target = target[properties[index]];
  25150. }
  25151. return target;
  25152. };
  25153. ActionManager.prototype._getProperty = function (propertyPath) {
  25154. var properties = propertyPath.split(".");
  25155. return properties[properties.length - 1];
  25156. };
  25157. // Statics
  25158. ActionManager._NothingTrigger = 0;
  25159. ActionManager._OnPickTrigger = 1;
  25160. ActionManager._OnLeftPickTrigger = 2;
  25161. ActionManager._OnRightPickTrigger = 3;
  25162. ActionManager._OnCenterPickTrigger = 4;
  25163. ActionManager._OnPointerOverTrigger = 5;
  25164. ActionManager._OnPointerOutTrigger = 6;
  25165. ActionManager._OnEveryFrameTrigger = 7;
  25166. ActionManager._OnIntersectionEnterTrigger = 8;
  25167. ActionManager._OnIntersectionExitTrigger = 9;
  25168. ActionManager._OnKeyDownTrigger = 10;
  25169. ActionManager._OnKeyUpTrigger = 11;
  25170. return ActionManager;
  25171. })();
  25172. BABYLON.ActionManager = ActionManager;
  25173. })(BABYLON || (BABYLON = {}));
  25174. //# sourceMappingURL=babylon.actionManager.js.map
  25175. var BABYLON;
  25176. (function (BABYLON) {
  25177. var InterpolateValueAction = (function (_super) {
  25178. __extends(InterpolateValueAction, _super);
  25179. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  25180. if (duration === void 0) { duration = 1000; }
  25181. _super.call(this, triggerOptions, condition);
  25182. this.propertyPath = propertyPath;
  25183. this.value = value;
  25184. this.duration = duration;
  25185. this.stopOtherAnimations = stopOtherAnimations;
  25186. this._target = target;
  25187. }
  25188. InterpolateValueAction.prototype._prepare = function () {
  25189. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25190. this._property = this._getProperty(this.propertyPath);
  25191. };
  25192. InterpolateValueAction.prototype.execute = function () {
  25193. var scene = this._actionManager.getScene();
  25194. var keys = [
  25195. {
  25196. frame: 0,
  25197. value: this._target[this._property]
  25198. },
  25199. {
  25200. frame: 100,
  25201. value: this.value
  25202. }
  25203. ];
  25204. var dataType;
  25205. if (typeof this.value === "number") {
  25206. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25207. }
  25208. else if (this.value instanceof BABYLON.Color3) {
  25209. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25210. }
  25211. else if (this.value instanceof BABYLON.Vector3) {
  25212. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25213. }
  25214. else if (this.value instanceof BABYLON.Matrix) {
  25215. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25216. }
  25217. else if (this.value instanceof BABYLON.Quaternion) {
  25218. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25219. }
  25220. else {
  25221. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25222. return;
  25223. }
  25224. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25225. animation.setKeys(keys);
  25226. if (this.stopOtherAnimations) {
  25227. scene.stopAnimation(this._target);
  25228. }
  25229. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25230. };
  25231. return InterpolateValueAction;
  25232. })(BABYLON.Action);
  25233. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25234. })(BABYLON || (BABYLON = {}));
  25235. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25236. var BABYLON;
  25237. (function (BABYLON) {
  25238. var SwitchBooleanAction = (function (_super) {
  25239. __extends(SwitchBooleanAction, _super);
  25240. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25241. _super.call(this, triggerOptions, condition);
  25242. this.propertyPath = propertyPath;
  25243. this._target = target;
  25244. }
  25245. SwitchBooleanAction.prototype._prepare = function () {
  25246. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25247. this._property = this._getProperty(this.propertyPath);
  25248. };
  25249. SwitchBooleanAction.prototype.execute = function () {
  25250. this._target[this._property] = !this._target[this._property];
  25251. };
  25252. return SwitchBooleanAction;
  25253. })(BABYLON.Action);
  25254. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25255. var SetStateAction = (function (_super) {
  25256. __extends(SetStateAction, _super);
  25257. function SetStateAction(triggerOptions, target, value, condition) {
  25258. _super.call(this, triggerOptions, condition);
  25259. this.value = value;
  25260. this._target = target;
  25261. }
  25262. SetStateAction.prototype.execute = function () {
  25263. this._target.state = this.value;
  25264. };
  25265. return SetStateAction;
  25266. })(BABYLON.Action);
  25267. BABYLON.SetStateAction = SetStateAction;
  25268. var SetValueAction = (function (_super) {
  25269. __extends(SetValueAction, _super);
  25270. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25271. _super.call(this, triggerOptions, condition);
  25272. this.propertyPath = propertyPath;
  25273. this.value = value;
  25274. this._target = target;
  25275. }
  25276. SetValueAction.prototype._prepare = function () {
  25277. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25278. this._property = this._getProperty(this.propertyPath);
  25279. };
  25280. SetValueAction.prototype.execute = function () {
  25281. this._target[this._property] = this.value;
  25282. };
  25283. return SetValueAction;
  25284. })(BABYLON.Action);
  25285. BABYLON.SetValueAction = SetValueAction;
  25286. var IncrementValueAction = (function (_super) {
  25287. __extends(IncrementValueAction, _super);
  25288. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25289. _super.call(this, triggerOptions, condition);
  25290. this.propertyPath = propertyPath;
  25291. this.value = value;
  25292. this._target = target;
  25293. }
  25294. IncrementValueAction.prototype._prepare = function () {
  25295. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25296. this._property = this._getProperty(this.propertyPath);
  25297. if (typeof this._target[this._property] !== "number") {
  25298. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25299. }
  25300. };
  25301. IncrementValueAction.prototype.execute = function () {
  25302. this._target[this._property] += this.value;
  25303. };
  25304. return IncrementValueAction;
  25305. })(BABYLON.Action);
  25306. BABYLON.IncrementValueAction = IncrementValueAction;
  25307. var PlayAnimationAction = (function (_super) {
  25308. __extends(PlayAnimationAction, _super);
  25309. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25310. _super.call(this, triggerOptions, condition);
  25311. this.from = from;
  25312. this.to = to;
  25313. this.loop = loop;
  25314. this._target = target;
  25315. }
  25316. PlayAnimationAction.prototype._prepare = function () {
  25317. };
  25318. PlayAnimationAction.prototype.execute = function () {
  25319. var scene = this._actionManager.getScene();
  25320. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25321. };
  25322. return PlayAnimationAction;
  25323. })(BABYLON.Action);
  25324. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25325. var StopAnimationAction = (function (_super) {
  25326. __extends(StopAnimationAction, _super);
  25327. function StopAnimationAction(triggerOptions, target, condition) {
  25328. _super.call(this, triggerOptions, condition);
  25329. this._target = target;
  25330. }
  25331. StopAnimationAction.prototype._prepare = function () {
  25332. };
  25333. StopAnimationAction.prototype.execute = function () {
  25334. var scene = this._actionManager.getScene();
  25335. scene.stopAnimation(this._target);
  25336. };
  25337. return StopAnimationAction;
  25338. })(BABYLON.Action);
  25339. BABYLON.StopAnimationAction = StopAnimationAction;
  25340. var DoNothingAction = (function (_super) {
  25341. __extends(DoNothingAction, _super);
  25342. function DoNothingAction(triggerOptions, condition) {
  25343. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25344. _super.call(this, triggerOptions, condition);
  25345. }
  25346. DoNothingAction.prototype.execute = function () {
  25347. };
  25348. return DoNothingAction;
  25349. })(BABYLON.Action);
  25350. BABYLON.DoNothingAction = DoNothingAction;
  25351. var CombineAction = (function (_super) {
  25352. __extends(CombineAction, _super);
  25353. function CombineAction(triggerOptions, children, condition) {
  25354. _super.call(this, triggerOptions, condition);
  25355. this.children = children;
  25356. }
  25357. CombineAction.prototype._prepare = function () {
  25358. for (var index = 0; index < this.children.length; index++) {
  25359. this.children[index]._actionManager = this._actionManager;
  25360. this.children[index]._prepare();
  25361. }
  25362. };
  25363. CombineAction.prototype.execute = function (evt) {
  25364. for (var index = 0; index < this.children.length; index++) {
  25365. this.children[index].execute(evt);
  25366. }
  25367. };
  25368. return CombineAction;
  25369. })(BABYLON.Action);
  25370. BABYLON.CombineAction = CombineAction;
  25371. var ExecuteCodeAction = (function (_super) {
  25372. __extends(ExecuteCodeAction, _super);
  25373. function ExecuteCodeAction(triggerOptions, func, condition) {
  25374. _super.call(this, triggerOptions, condition);
  25375. this.func = func;
  25376. }
  25377. ExecuteCodeAction.prototype.execute = function (evt) {
  25378. this.func(evt);
  25379. };
  25380. return ExecuteCodeAction;
  25381. })(BABYLON.Action);
  25382. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25383. var SetParentAction = (function (_super) {
  25384. __extends(SetParentAction, _super);
  25385. function SetParentAction(triggerOptions, target, parent, condition) {
  25386. _super.call(this, triggerOptions, condition);
  25387. this._target = target;
  25388. this._parent = parent;
  25389. }
  25390. SetParentAction.prototype._prepare = function () {
  25391. };
  25392. SetParentAction.prototype.execute = function () {
  25393. if (this._target.parent === this._parent) {
  25394. return;
  25395. }
  25396. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25397. invertParentWorldMatrix.invert();
  25398. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25399. this._target.parent = this._parent;
  25400. };
  25401. return SetParentAction;
  25402. })(BABYLON.Action);
  25403. BABYLON.SetParentAction = SetParentAction;
  25404. var PlaySoundAction = (function (_super) {
  25405. __extends(PlaySoundAction, _super);
  25406. function PlaySoundAction(triggerOptions, sound, condition) {
  25407. _super.call(this, triggerOptions, condition);
  25408. this._sound = sound;
  25409. }
  25410. PlaySoundAction.prototype._prepare = function () {
  25411. };
  25412. PlaySoundAction.prototype.execute = function () {
  25413. if (this._sound !== undefined)
  25414. this._sound.play();
  25415. };
  25416. return PlaySoundAction;
  25417. })(BABYLON.Action);
  25418. BABYLON.PlaySoundAction = PlaySoundAction;
  25419. var StopSoundAction = (function (_super) {
  25420. __extends(StopSoundAction, _super);
  25421. function StopSoundAction(triggerOptions, sound, condition) {
  25422. _super.call(this, triggerOptions, condition);
  25423. this._sound = sound;
  25424. }
  25425. StopSoundAction.prototype._prepare = function () {
  25426. };
  25427. StopSoundAction.prototype.execute = function () {
  25428. if (this._sound !== undefined)
  25429. this._sound.stop();
  25430. };
  25431. return StopSoundAction;
  25432. })(BABYLON.Action);
  25433. BABYLON.StopSoundAction = StopSoundAction;
  25434. })(BABYLON || (BABYLON = {}));
  25435. //# sourceMappingURL=babylon.directActions.js.map
  25436. var BABYLON;
  25437. (function (BABYLON) {
  25438. var Geometry = (function () {
  25439. function Geometry(id, scene, vertexData, updatable, mesh) {
  25440. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25441. this._totalVertices = 0;
  25442. this._indices = [];
  25443. this._isDisposed = false;
  25444. this.id = id;
  25445. this._engine = scene.getEngine();
  25446. this._meshes = [];
  25447. this._scene = scene;
  25448. // vertexData
  25449. if (vertexData) {
  25450. this.setAllVerticesData(vertexData, updatable);
  25451. }
  25452. else {
  25453. this._totalVertices = 0;
  25454. this._indices = [];
  25455. }
  25456. // applyToMesh
  25457. if (mesh) {
  25458. this.applyToMesh(mesh);
  25459. mesh.computeWorldMatrix(true);
  25460. }
  25461. }
  25462. Geometry.prototype.getScene = function () {
  25463. return this._scene;
  25464. };
  25465. Geometry.prototype.getEngine = function () {
  25466. return this._engine;
  25467. };
  25468. Geometry.prototype.isReady = function () {
  25469. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25470. };
  25471. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25472. vertexData.applyToGeometry(this, updatable);
  25473. this.notifyUpdate();
  25474. };
  25475. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25476. this._vertexBuffers = this._vertexBuffers || {};
  25477. if (this._vertexBuffers[kind]) {
  25478. this._vertexBuffers[kind].dispose();
  25479. }
  25480. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25481. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25482. stride = this._vertexBuffers[kind].getStrideSize();
  25483. this._totalVertices = data.length / stride;
  25484. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25485. var meshes = this._meshes;
  25486. var numOfMeshes = meshes.length;
  25487. for (var index = 0; index < numOfMeshes; index++) {
  25488. var mesh = meshes[index];
  25489. mesh._resetPointsArrayCache();
  25490. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25491. mesh._createGlobalSubMesh();
  25492. mesh.computeWorldMatrix(true);
  25493. }
  25494. }
  25495. this.notifyUpdate(kind);
  25496. };
  25497. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25498. var vertexBuffer = this.getVertexBuffer(kind);
  25499. if (!vertexBuffer) {
  25500. return;
  25501. }
  25502. vertexBuffer.updateDirectly(data, offset);
  25503. this.notifyUpdate(kind);
  25504. };
  25505. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25506. var vertexBuffer = this.getVertexBuffer(kind);
  25507. if (!vertexBuffer) {
  25508. return;
  25509. }
  25510. vertexBuffer.update(data);
  25511. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25512. var extend;
  25513. var stride = vertexBuffer.getStrideSize();
  25514. this._totalVertices = data.length / stride;
  25515. if (updateExtends) {
  25516. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25517. }
  25518. var meshes = this._meshes;
  25519. var numOfMeshes = meshes.length;
  25520. for (var index = 0; index < numOfMeshes; index++) {
  25521. var mesh = meshes[index];
  25522. mesh._resetPointsArrayCache();
  25523. if (updateExtends) {
  25524. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25525. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25526. var subMesh = mesh.subMeshes[subIndex];
  25527. subMesh.refreshBoundingInfo();
  25528. }
  25529. }
  25530. }
  25531. }
  25532. this.notifyUpdate(kind);
  25533. };
  25534. Geometry.prototype.getTotalVertices = function () {
  25535. if (!this.isReady()) {
  25536. return 0;
  25537. }
  25538. return this._totalVertices;
  25539. };
  25540. Geometry.prototype.getVerticesData = function (kind) {
  25541. var vertexBuffer = this.getVertexBuffer(kind);
  25542. if (!vertexBuffer) {
  25543. return null;
  25544. }
  25545. return vertexBuffer.getData();
  25546. };
  25547. Geometry.prototype.getVertexBuffer = function (kind) {
  25548. if (!this.isReady()) {
  25549. return null;
  25550. }
  25551. return this._vertexBuffers[kind];
  25552. };
  25553. Geometry.prototype.getVertexBuffers = function () {
  25554. if (!this.isReady()) {
  25555. return null;
  25556. }
  25557. return this._vertexBuffers;
  25558. };
  25559. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25560. if (!this._vertexBuffers) {
  25561. if (this._delayInfo) {
  25562. return this._delayInfo.indexOf(kind) !== -1;
  25563. }
  25564. return false;
  25565. }
  25566. return this._vertexBuffers[kind] !== undefined;
  25567. };
  25568. Geometry.prototype.getVerticesDataKinds = function () {
  25569. var result = [];
  25570. if (!this._vertexBuffers && this._delayInfo) {
  25571. for (var kind in this._delayInfo) {
  25572. result.push(kind);
  25573. }
  25574. }
  25575. else {
  25576. for (kind in this._vertexBuffers) {
  25577. result.push(kind);
  25578. }
  25579. }
  25580. return result;
  25581. };
  25582. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25583. if (this._indexBuffer) {
  25584. this._engine._releaseBuffer(this._indexBuffer);
  25585. }
  25586. this._indices = indices;
  25587. if (this._meshes.length !== 0 && this._indices) {
  25588. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25589. }
  25590. if (totalVertices !== undefined) {
  25591. this._totalVertices = totalVertices;
  25592. }
  25593. var meshes = this._meshes;
  25594. var numOfMeshes = meshes.length;
  25595. for (var index = 0; index < numOfMeshes; index++) {
  25596. meshes[index]._createGlobalSubMesh();
  25597. }
  25598. this.notifyUpdate();
  25599. };
  25600. Geometry.prototype.getTotalIndices = function () {
  25601. if (!this.isReady()) {
  25602. return 0;
  25603. }
  25604. return this._indices.length;
  25605. };
  25606. Geometry.prototype.getIndices = function () {
  25607. if (!this.isReady()) {
  25608. return null;
  25609. }
  25610. return this._indices;
  25611. };
  25612. Geometry.prototype.getIndexBuffer = function () {
  25613. if (!this.isReady()) {
  25614. return null;
  25615. }
  25616. return this._indexBuffer;
  25617. };
  25618. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25619. var meshes = this._meshes;
  25620. var index = meshes.indexOf(mesh);
  25621. if (index === -1) {
  25622. return;
  25623. }
  25624. for (var kind in this._vertexBuffers) {
  25625. this._vertexBuffers[kind].dispose();
  25626. }
  25627. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25628. this._indexBuffer = null;
  25629. }
  25630. meshes.splice(index, 1);
  25631. mesh._geometry = null;
  25632. if (meshes.length === 0 && shouldDispose) {
  25633. this.dispose();
  25634. }
  25635. };
  25636. Geometry.prototype.applyToMesh = function (mesh) {
  25637. if (mesh._geometry === this) {
  25638. return;
  25639. }
  25640. var previousGeometry = mesh._geometry;
  25641. if (previousGeometry) {
  25642. previousGeometry.releaseForMesh(mesh);
  25643. }
  25644. var meshes = this._meshes;
  25645. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25646. mesh._geometry = this;
  25647. this._scene.pushGeometry(this);
  25648. meshes.push(mesh);
  25649. if (this.isReady()) {
  25650. this._applyToMesh(mesh);
  25651. }
  25652. else {
  25653. mesh._boundingInfo = this._boundingInfo;
  25654. }
  25655. };
  25656. Geometry.prototype._applyToMesh = function (mesh) {
  25657. var numOfMeshes = this._meshes.length;
  25658. for (var kind in this._vertexBuffers) {
  25659. if (numOfMeshes === 1) {
  25660. this._vertexBuffers[kind].create();
  25661. }
  25662. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25663. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25664. mesh._resetPointsArrayCache();
  25665. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25666. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25667. mesh._createGlobalSubMesh();
  25668. //bounding info was just created again, world matrix should be applied again.
  25669. mesh._updateBoundingInfo();
  25670. }
  25671. }
  25672. // indexBuffer
  25673. if (numOfMeshes === 1 && this._indices) {
  25674. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25675. }
  25676. if (this._indexBuffer) {
  25677. this._indexBuffer.references = numOfMeshes;
  25678. }
  25679. };
  25680. Geometry.prototype.notifyUpdate = function (kind) {
  25681. if (this.onGeometryUpdated) {
  25682. this.onGeometryUpdated(this, kind);
  25683. }
  25684. };
  25685. Geometry.prototype.load = function (scene, onLoaded) {
  25686. var _this = this;
  25687. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25688. return;
  25689. }
  25690. if (this.isReady()) {
  25691. if (onLoaded) {
  25692. onLoaded();
  25693. }
  25694. return;
  25695. }
  25696. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25697. scene._addPendingData(this);
  25698. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25699. _this._delayLoadingFunction(JSON.parse(data), _this);
  25700. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25701. _this._delayInfo = [];
  25702. scene._removePendingData(_this);
  25703. var meshes = _this._meshes;
  25704. var numOfMeshes = meshes.length;
  25705. for (var index = 0; index < numOfMeshes; index++) {
  25706. _this._applyToMesh(meshes[index]);
  25707. }
  25708. if (onLoaded) {
  25709. onLoaded();
  25710. }
  25711. }, function () {
  25712. }, scene.database);
  25713. };
  25714. Geometry.prototype.isDisposed = function () {
  25715. return this._isDisposed;
  25716. };
  25717. Geometry.prototype.dispose = function () {
  25718. var meshes = this._meshes;
  25719. var numOfMeshes = meshes.length;
  25720. var index;
  25721. for (index = 0; index < numOfMeshes; index++) {
  25722. this.releaseForMesh(meshes[index]);
  25723. }
  25724. this._meshes = [];
  25725. for (var kind in this._vertexBuffers) {
  25726. this._vertexBuffers[kind].dispose();
  25727. }
  25728. this._vertexBuffers = [];
  25729. this._totalVertices = 0;
  25730. if (this._indexBuffer) {
  25731. this._engine._releaseBuffer(this._indexBuffer);
  25732. }
  25733. this._indexBuffer = null;
  25734. this._indices = [];
  25735. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25736. this.delayLoadingFile = null;
  25737. this._delayLoadingFunction = null;
  25738. this._delayInfo = [];
  25739. this._boundingInfo = null; // todo: .dispose()
  25740. this._scene.removeGeometry(this);
  25741. this._isDisposed = true;
  25742. };
  25743. Geometry.prototype.copy = function (id) {
  25744. var vertexData = new BABYLON.VertexData();
  25745. vertexData.indices = [];
  25746. var indices = this.getIndices();
  25747. for (var index = 0; index < indices.length; index++) {
  25748. vertexData.indices.push(indices[index]);
  25749. }
  25750. var updatable = false;
  25751. var stopChecking = false;
  25752. for (var kind in this._vertexBuffers) {
  25753. // using slice() to make a copy of the array and not just reference it
  25754. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25755. if (!stopChecking) {
  25756. updatable = this.getVertexBuffer(kind).isUpdatable();
  25757. stopChecking = !updatable;
  25758. }
  25759. }
  25760. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25761. geometry.delayLoadState = this.delayLoadState;
  25762. geometry.delayLoadingFile = this.delayLoadingFile;
  25763. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25764. for (kind in this._delayInfo) {
  25765. geometry._delayInfo = geometry._delayInfo || [];
  25766. geometry._delayInfo.push(kind);
  25767. }
  25768. // Bounding info
  25769. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25770. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25771. return geometry;
  25772. };
  25773. // Statics
  25774. Geometry.ExtractFromMesh = function (mesh, id) {
  25775. var geometry = mesh._geometry;
  25776. if (!geometry) {
  25777. return null;
  25778. }
  25779. return geometry.copy(id);
  25780. };
  25781. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25782. // be aware Math.random() could cause collisions
  25783. Geometry.RandomId = function () {
  25784. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25785. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25786. return v.toString(16);
  25787. });
  25788. };
  25789. return Geometry;
  25790. })();
  25791. BABYLON.Geometry = Geometry;
  25792. /////// Primitives //////////////////////////////////////////////
  25793. var Geometry;
  25794. (function (Geometry) {
  25795. var Primitives;
  25796. (function (Primitives) {
  25797. /// Abstract class
  25798. var _Primitive = (function (_super) {
  25799. __extends(_Primitive, _super);
  25800. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25801. this._beingRegenerated = true;
  25802. this._canBeRegenerated = canBeRegenerated;
  25803. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25804. this._beingRegenerated = false;
  25805. }
  25806. _Primitive.prototype.canBeRegenerated = function () {
  25807. return this._canBeRegenerated;
  25808. };
  25809. _Primitive.prototype.regenerate = function () {
  25810. if (!this._canBeRegenerated) {
  25811. return;
  25812. }
  25813. this._beingRegenerated = true;
  25814. this.setAllVerticesData(this._regenerateVertexData(), false);
  25815. this._beingRegenerated = false;
  25816. };
  25817. _Primitive.prototype.asNewGeometry = function (id) {
  25818. return _super.prototype.copy.call(this, id);
  25819. };
  25820. // overrides
  25821. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25822. if (!this._beingRegenerated) {
  25823. return;
  25824. }
  25825. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25826. };
  25827. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25828. if (!this._beingRegenerated) {
  25829. return;
  25830. }
  25831. _super.prototype.setVerticesData.call(this, kind, data, false);
  25832. };
  25833. // to override
  25834. // protected
  25835. _Primitive.prototype._regenerateVertexData = function () {
  25836. throw new Error("Abstract method");
  25837. };
  25838. _Primitive.prototype.copy = function (id) {
  25839. throw new Error("Must be overriden in sub-classes.");
  25840. };
  25841. return _Primitive;
  25842. })(Geometry);
  25843. Primitives._Primitive = _Primitive;
  25844. var Ribbon = (function (_super) {
  25845. __extends(Ribbon, _super);
  25846. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25847. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25848. this.pathArray = pathArray;
  25849. this.closeArray = closeArray;
  25850. this.closePath = closePath;
  25851. this.offset = offset;
  25852. this.side = side;
  25853. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25854. }
  25855. Ribbon.prototype._regenerateVertexData = function () {
  25856. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25857. };
  25858. Ribbon.prototype.copy = function (id) {
  25859. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25860. };
  25861. return Ribbon;
  25862. })(_Primitive);
  25863. Primitives.Ribbon = Ribbon;
  25864. var Box = (function (_super) {
  25865. __extends(Box, _super);
  25866. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25867. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25868. this.size = size;
  25869. this.side = side;
  25870. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25871. }
  25872. Box.prototype._regenerateVertexData = function () {
  25873. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25874. };
  25875. Box.prototype.copy = function (id) {
  25876. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25877. };
  25878. return Box;
  25879. })(_Primitive);
  25880. Primitives.Box = Box;
  25881. var Sphere = (function (_super) {
  25882. __extends(Sphere, _super);
  25883. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25884. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25885. this.segments = segments;
  25886. this.diameter = diameter;
  25887. this.side = side;
  25888. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25889. }
  25890. Sphere.prototype._regenerateVertexData = function () {
  25891. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25892. };
  25893. Sphere.prototype.copy = function (id) {
  25894. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25895. };
  25896. return Sphere;
  25897. })(_Primitive);
  25898. Primitives.Sphere = Sphere;
  25899. var Cylinder = (function (_super) {
  25900. __extends(Cylinder, _super);
  25901. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25902. if (subdivisions === void 0) { subdivisions = 1; }
  25903. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25904. this.height = height;
  25905. this.diameterTop = diameterTop;
  25906. this.diameterBottom = diameterBottom;
  25907. this.tessellation = tessellation;
  25908. this.subdivisions = subdivisions;
  25909. this.side = side;
  25910. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25911. }
  25912. Cylinder.prototype._regenerateVertexData = function () {
  25913. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25914. };
  25915. Cylinder.prototype.copy = function (id) {
  25916. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25917. };
  25918. return Cylinder;
  25919. })(_Primitive);
  25920. Primitives.Cylinder = Cylinder;
  25921. var Torus = (function (_super) {
  25922. __extends(Torus, _super);
  25923. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25924. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25925. this.diameter = diameter;
  25926. this.thickness = thickness;
  25927. this.tessellation = tessellation;
  25928. this.side = side;
  25929. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25930. }
  25931. Torus.prototype._regenerateVertexData = function () {
  25932. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25933. };
  25934. Torus.prototype.copy = function (id) {
  25935. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25936. };
  25937. return Torus;
  25938. })(_Primitive);
  25939. Primitives.Torus = Torus;
  25940. var Ground = (function (_super) {
  25941. __extends(Ground, _super);
  25942. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25943. this.width = width;
  25944. this.height = height;
  25945. this.subdivisions = subdivisions;
  25946. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25947. }
  25948. Ground.prototype._regenerateVertexData = function () {
  25949. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25950. };
  25951. Ground.prototype.copy = function (id) {
  25952. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25953. };
  25954. return Ground;
  25955. })(_Primitive);
  25956. Primitives.Ground = Ground;
  25957. var TiledGround = (function (_super) {
  25958. __extends(TiledGround, _super);
  25959. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25960. this.xmin = xmin;
  25961. this.zmin = zmin;
  25962. this.xmax = xmax;
  25963. this.zmax = zmax;
  25964. this.subdivisions = subdivisions;
  25965. this.precision = precision;
  25966. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25967. }
  25968. TiledGround.prototype._regenerateVertexData = function () {
  25969. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25970. };
  25971. TiledGround.prototype.copy = function (id) {
  25972. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25973. };
  25974. return TiledGround;
  25975. })(_Primitive);
  25976. Primitives.TiledGround = TiledGround;
  25977. var Plane = (function (_super) {
  25978. __extends(Plane, _super);
  25979. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25980. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25981. this.size = size;
  25982. this.side = side;
  25983. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25984. }
  25985. Plane.prototype._regenerateVertexData = function () {
  25986. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25987. };
  25988. Plane.prototype.copy = function (id) {
  25989. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25990. };
  25991. return Plane;
  25992. })(_Primitive);
  25993. Primitives.Plane = Plane;
  25994. var TorusKnot = (function (_super) {
  25995. __extends(TorusKnot, _super);
  25996. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25997. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25998. this.radius = radius;
  25999. this.tube = tube;
  26000. this.radialSegments = radialSegments;
  26001. this.tubularSegments = tubularSegments;
  26002. this.p = p;
  26003. this.q = q;
  26004. this.side = side;
  26005. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26006. }
  26007. TorusKnot.prototype._regenerateVertexData = function () {
  26008. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  26009. };
  26010. TorusKnot.prototype.copy = function (id) {
  26011. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26012. };
  26013. return TorusKnot;
  26014. })(_Primitive);
  26015. Primitives.TorusKnot = TorusKnot;
  26016. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26017. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26018. })(BABYLON || (BABYLON = {}));
  26019. //# sourceMappingURL=babylon.geometry.js.map
  26020. var BABYLON;
  26021. (function (BABYLON) {
  26022. var Gamepads = (function () {
  26023. function Gamepads(ongamedpadconnected) {
  26024. var _this = this;
  26025. this.babylonGamepads = [];
  26026. this.oneGamepadConnected = false;
  26027. this.isMonitoring = false;
  26028. this.gamepadEventSupported = 'GamepadEvent' in window;
  26029. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  26030. 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=";
  26031. this._callbackGamepadConnected = ongamedpadconnected;
  26032. if (this.gamepadSupportAvailable) {
  26033. // Checking if the gamepad connected event is supported (like in Firefox)
  26034. if (this.gamepadEventSupported) {
  26035. window.addEventListener('gamepadconnected', function (evt) {
  26036. _this._onGamepadConnected(evt);
  26037. }, false);
  26038. window.addEventListener('gamepaddisconnected', function (evt) {
  26039. _this._onGamepadDisconnected(evt);
  26040. }, false);
  26041. }
  26042. else {
  26043. this._startMonitoringGamepads();
  26044. }
  26045. if (!this.oneGamepadConnected) {
  26046. this._insertGamepadDOMInstructions();
  26047. }
  26048. }
  26049. else {
  26050. this._insertGamepadDOMNotSupported();
  26051. }
  26052. }
  26053. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  26054. Gamepads.gamepadDOMInfo = document.createElement("div");
  26055. var buttonAImage = document.createElement("img");
  26056. buttonAImage.src = this.buttonADataURL;
  26057. var spanMessage = document.createElement("span");
  26058. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  26059. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  26060. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26061. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26062. Gamepads.gamepadDOMInfo.style.width = "100%";
  26063. Gamepads.gamepadDOMInfo.style.height = "48px";
  26064. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26065. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26066. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26067. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26068. buttonAImage.style.position = "relative";
  26069. buttonAImage.style.bottom = "8px";
  26070. spanMessage.style.position = "relative";
  26071. spanMessage.style.fontSize = "32px";
  26072. spanMessage.style.bottom = "32px";
  26073. spanMessage.style.color = "green";
  26074. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26075. };
  26076. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  26077. Gamepads.gamepadDOMInfo = document.createElement("div");
  26078. var spanMessage = document.createElement("span");
  26079. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  26080. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26081. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26082. Gamepads.gamepadDOMInfo.style.width = "100%";
  26083. Gamepads.gamepadDOMInfo.style.height = "40px";
  26084. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26085. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26086. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26087. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26088. spanMessage.style.position = "relative";
  26089. spanMessage.style.fontSize = "32px";
  26090. spanMessage.style.color = "red";
  26091. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26092. };
  26093. Gamepads.prototype.dispose = function () {
  26094. if (Gamepads.gamepadDOMInfo) {
  26095. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26096. }
  26097. };
  26098. Gamepads.prototype._onGamepadConnected = function (evt) {
  26099. var newGamepad = this._addNewGamepad(evt.gamepad);
  26100. if (this._callbackGamepadConnected)
  26101. this._callbackGamepadConnected(newGamepad);
  26102. this._startMonitoringGamepads();
  26103. };
  26104. Gamepads.prototype._addNewGamepad = function (gamepad) {
  26105. if (!this.oneGamepadConnected) {
  26106. this.oneGamepadConnected = true;
  26107. if (Gamepads.gamepadDOMInfo) {
  26108. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26109. Gamepads.gamepadDOMInfo = null;
  26110. }
  26111. }
  26112. var newGamepad;
  26113. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  26114. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  26115. }
  26116. else {
  26117. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  26118. }
  26119. this.babylonGamepads.push(newGamepad);
  26120. return newGamepad;
  26121. };
  26122. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  26123. for (var i in this.babylonGamepads) {
  26124. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  26125. this.babylonGamepads.splice(i, 1);
  26126. break;
  26127. }
  26128. }
  26129. // If no gamepads are left, stop the polling loop.
  26130. if (this.babylonGamepads.length == 0) {
  26131. this._stopMonitoringGamepads();
  26132. }
  26133. };
  26134. Gamepads.prototype._startMonitoringGamepads = function () {
  26135. if (!this.isMonitoring) {
  26136. this.isMonitoring = true;
  26137. this._checkGamepadsStatus();
  26138. }
  26139. };
  26140. Gamepads.prototype._stopMonitoringGamepads = function () {
  26141. this.isMonitoring = false;
  26142. };
  26143. Gamepads.prototype._checkGamepadsStatus = function () {
  26144. var _this = this;
  26145. // updating gamepad objects
  26146. this._updateGamepadObjects();
  26147. for (var i in this.babylonGamepads) {
  26148. this.babylonGamepads[i].update();
  26149. }
  26150. if (this.isMonitoring) {
  26151. if (window.requestAnimationFrame) {
  26152. window.requestAnimationFrame(function () {
  26153. _this._checkGamepadsStatus();
  26154. });
  26155. }
  26156. else if (window.mozRequestAnimationFrame) {
  26157. window.mozRequestAnimationFrame(function () {
  26158. _this._checkGamepadsStatus();
  26159. });
  26160. }
  26161. else if (window.webkitRequestAnimationFrame) {
  26162. window.webkitRequestAnimationFrame(function () {
  26163. _this._checkGamepadsStatus();
  26164. });
  26165. }
  26166. }
  26167. };
  26168. // This function is called only on Chrome, which does not yet support
  26169. // connection/disconnection events, but requires you to monitor
  26170. // an array for changes.
  26171. Gamepads.prototype._updateGamepadObjects = function () {
  26172. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  26173. for (var i = 0; i < gamepads.length; i++) {
  26174. if (gamepads[i]) {
  26175. if (!(gamepads[i].index in this.babylonGamepads)) {
  26176. var newGamepad = this._addNewGamepad(gamepads[i]);
  26177. if (this._callbackGamepadConnected) {
  26178. this._callbackGamepadConnected(newGamepad);
  26179. }
  26180. }
  26181. else {
  26182. this.babylonGamepads[i].browserGamepad = gamepads[i];
  26183. }
  26184. }
  26185. }
  26186. };
  26187. return Gamepads;
  26188. })();
  26189. BABYLON.Gamepads = Gamepads;
  26190. var StickValues = (function () {
  26191. function StickValues(x, y) {
  26192. this.x = x;
  26193. this.y = y;
  26194. }
  26195. return StickValues;
  26196. })();
  26197. BABYLON.StickValues = StickValues;
  26198. var Gamepad = (function () {
  26199. function Gamepad(id, index, browserGamepad) {
  26200. this.id = id;
  26201. this.index = index;
  26202. this.browserGamepad = browserGamepad;
  26203. if (this.browserGamepad.axes.length >= 2) {
  26204. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26205. }
  26206. if (this.browserGamepad.axes.length >= 4) {
  26207. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26208. }
  26209. }
  26210. Gamepad.prototype.onleftstickchanged = function (callback) {
  26211. this._onleftstickchanged = callback;
  26212. };
  26213. Gamepad.prototype.onrightstickchanged = function (callback) {
  26214. this._onrightstickchanged = callback;
  26215. };
  26216. Object.defineProperty(Gamepad.prototype, "leftStick", {
  26217. get: function () {
  26218. return this._leftStick;
  26219. },
  26220. set: function (newValues) {
  26221. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26222. this._onleftstickchanged(newValues);
  26223. }
  26224. this._leftStick = newValues;
  26225. },
  26226. enumerable: true,
  26227. configurable: true
  26228. });
  26229. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26230. get: function () {
  26231. return this._rightStick;
  26232. },
  26233. set: function (newValues) {
  26234. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26235. this._onrightstickchanged(newValues);
  26236. }
  26237. this._rightStick = newValues;
  26238. },
  26239. enumerable: true,
  26240. configurable: true
  26241. });
  26242. Gamepad.prototype.update = function () {
  26243. if (this._leftStick) {
  26244. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26245. }
  26246. if (this._rightStick) {
  26247. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26248. }
  26249. };
  26250. return Gamepad;
  26251. })();
  26252. BABYLON.Gamepad = Gamepad;
  26253. var GenericPad = (function (_super) {
  26254. __extends(GenericPad, _super);
  26255. function GenericPad(id, index, gamepad) {
  26256. _super.call(this, id, index, gamepad);
  26257. this.id = id;
  26258. this.index = index;
  26259. this.gamepad = gamepad;
  26260. this._buttons = new Array(gamepad.buttons.length);
  26261. }
  26262. GenericPad.prototype.onbuttondown = function (callback) {
  26263. this._onbuttondown = callback;
  26264. };
  26265. GenericPad.prototype.onbuttonup = function (callback) {
  26266. this._onbuttonup = callback;
  26267. };
  26268. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26269. if (newValue !== currentValue) {
  26270. if (this._onbuttondown && newValue === 1) {
  26271. this._onbuttondown(buttonIndex);
  26272. }
  26273. if (this._onbuttonup && newValue === 0) {
  26274. this._onbuttonup(buttonIndex);
  26275. }
  26276. }
  26277. return newValue;
  26278. };
  26279. GenericPad.prototype.update = function () {
  26280. _super.prototype.update.call(this);
  26281. for (var index = 0; index < this._buttons.length; index++) {
  26282. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26283. }
  26284. };
  26285. return GenericPad;
  26286. })(Gamepad);
  26287. BABYLON.GenericPad = GenericPad;
  26288. (function (Xbox360Button) {
  26289. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26290. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26291. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26292. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26293. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26294. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26295. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26296. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26297. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26298. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26299. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26300. var Xbox360Button = BABYLON.Xbox360Button;
  26301. (function (Xbox360Dpad) {
  26302. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26303. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26304. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26305. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26306. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26307. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26308. var Xbox360Pad = (function (_super) {
  26309. __extends(Xbox360Pad, _super);
  26310. function Xbox360Pad() {
  26311. _super.apply(this, arguments);
  26312. this._leftTrigger = 0;
  26313. this._rightTrigger = 0;
  26314. this._buttonA = 0;
  26315. this._buttonB = 0;
  26316. this._buttonX = 0;
  26317. this._buttonY = 0;
  26318. this._buttonBack = 0;
  26319. this._buttonStart = 0;
  26320. this._buttonLB = 0;
  26321. this._buttonRB = 0;
  26322. this._buttonLeftStick = 0;
  26323. this._buttonRightStick = 0;
  26324. this._dPadUp = 0;
  26325. this._dPadDown = 0;
  26326. this._dPadLeft = 0;
  26327. this._dPadRight = 0;
  26328. }
  26329. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26330. this._onlefttriggerchanged = callback;
  26331. };
  26332. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26333. this._onrighttriggerchanged = callback;
  26334. };
  26335. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26336. get: function () {
  26337. return this._leftTrigger;
  26338. },
  26339. set: function (newValue) {
  26340. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26341. this._onlefttriggerchanged(newValue);
  26342. }
  26343. this._leftTrigger = newValue;
  26344. },
  26345. enumerable: true,
  26346. configurable: true
  26347. });
  26348. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26349. get: function () {
  26350. return this._rightTrigger;
  26351. },
  26352. set: function (newValue) {
  26353. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26354. this._onrighttriggerchanged(newValue);
  26355. }
  26356. this._rightTrigger = newValue;
  26357. },
  26358. enumerable: true,
  26359. configurable: true
  26360. });
  26361. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26362. this._onbuttondown = callback;
  26363. };
  26364. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26365. this._onbuttonup = callback;
  26366. };
  26367. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26368. this._ondpaddown = callback;
  26369. };
  26370. Xbox360Pad.prototype.ondpadup = function (callback) {
  26371. this._ondpadup = callback;
  26372. };
  26373. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26374. if (newValue !== currentValue) {
  26375. if (this._onbuttondown && newValue === 1) {
  26376. this._onbuttondown(buttonType);
  26377. }
  26378. if (this._onbuttonup && newValue === 0) {
  26379. this._onbuttonup(buttonType);
  26380. }
  26381. }
  26382. return newValue;
  26383. };
  26384. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26385. if (newValue !== currentValue) {
  26386. if (this._ondpaddown && newValue === 1) {
  26387. this._ondpaddown(buttonType);
  26388. }
  26389. if (this._ondpadup && newValue === 0) {
  26390. this._ondpadup(buttonType);
  26391. }
  26392. }
  26393. return newValue;
  26394. };
  26395. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26396. get: function () {
  26397. return this._buttonA;
  26398. },
  26399. set: function (value) {
  26400. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26401. },
  26402. enumerable: true,
  26403. configurable: true
  26404. });
  26405. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26406. get: function () {
  26407. return this._buttonB;
  26408. },
  26409. set: function (value) {
  26410. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26411. },
  26412. enumerable: true,
  26413. configurable: true
  26414. });
  26415. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26416. get: function () {
  26417. return this._buttonX;
  26418. },
  26419. set: function (value) {
  26420. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26421. },
  26422. enumerable: true,
  26423. configurable: true
  26424. });
  26425. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26426. get: function () {
  26427. return this._buttonY;
  26428. },
  26429. set: function (value) {
  26430. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26431. },
  26432. enumerable: true,
  26433. configurable: true
  26434. });
  26435. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26436. get: function () {
  26437. return this._buttonStart;
  26438. },
  26439. set: function (value) {
  26440. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26441. },
  26442. enumerable: true,
  26443. configurable: true
  26444. });
  26445. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26446. get: function () {
  26447. return this._buttonBack;
  26448. },
  26449. set: function (value) {
  26450. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26451. },
  26452. enumerable: true,
  26453. configurable: true
  26454. });
  26455. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26456. get: function () {
  26457. return this._buttonLB;
  26458. },
  26459. set: function (value) {
  26460. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26461. },
  26462. enumerable: true,
  26463. configurable: true
  26464. });
  26465. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26466. get: function () {
  26467. return this._buttonRB;
  26468. },
  26469. set: function (value) {
  26470. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26471. },
  26472. enumerable: true,
  26473. configurable: true
  26474. });
  26475. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26476. get: function () {
  26477. return this._buttonLeftStick;
  26478. },
  26479. set: function (value) {
  26480. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26481. },
  26482. enumerable: true,
  26483. configurable: true
  26484. });
  26485. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26486. get: function () {
  26487. return this._buttonRightStick;
  26488. },
  26489. set: function (value) {
  26490. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26491. },
  26492. enumerable: true,
  26493. configurable: true
  26494. });
  26495. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26496. get: function () {
  26497. return this._dPadUp;
  26498. },
  26499. set: function (value) {
  26500. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26501. },
  26502. enumerable: true,
  26503. configurable: true
  26504. });
  26505. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26506. get: function () {
  26507. return this._dPadDown;
  26508. },
  26509. set: function (value) {
  26510. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26511. },
  26512. enumerable: true,
  26513. configurable: true
  26514. });
  26515. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26516. get: function () {
  26517. return this._dPadLeft;
  26518. },
  26519. set: function (value) {
  26520. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26521. },
  26522. enumerable: true,
  26523. configurable: true
  26524. });
  26525. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26526. get: function () {
  26527. return this._dPadRight;
  26528. },
  26529. set: function (value) {
  26530. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26531. },
  26532. enumerable: true,
  26533. configurable: true
  26534. });
  26535. Xbox360Pad.prototype.update = function () {
  26536. _super.prototype.update.call(this);
  26537. this.buttonA = this.browserGamepad.buttons[0].value;
  26538. this.buttonB = this.browserGamepad.buttons[1].value;
  26539. this.buttonX = this.browserGamepad.buttons[2].value;
  26540. this.buttonY = this.browserGamepad.buttons[3].value;
  26541. this.buttonLB = this.browserGamepad.buttons[4].value;
  26542. this.buttonRB = this.browserGamepad.buttons[5].value;
  26543. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26544. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26545. this.buttonBack = this.browserGamepad.buttons[8].value;
  26546. this.buttonStart = this.browserGamepad.buttons[9].value;
  26547. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26548. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26549. this.dPadUp = this.browserGamepad.buttons[12].value;
  26550. this.dPadDown = this.browserGamepad.buttons[13].value;
  26551. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26552. this.dPadRight = this.browserGamepad.buttons[15].value;
  26553. };
  26554. return Xbox360Pad;
  26555. })(Gamepad);
  26556. BABYLON.Xbox360Pad = Xbox360Pad;
  26557. })(BABYLON || (BABYLON = {}));
  26558. //# sourceMappingURL=babylon.gamepads.js.map
  26559. var BABYLON;
  26560. (function (BABYLON) {
  26561. // We're mainly based on the logic defined into the FreeCamera code
  26562. var GamepadCamera = (function (_super) {
  26563. __extends(GamepadCamera, _super);
  26564. function GamepadCamera(name, position, scene) {
  26565. var _this = this;
  26566. _super.call(this, name, position, scene);
  26567. this.angularSensibility = 200;
  26568. this.moveSensibility = 75;
  26569. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26570. _this._onNewGameConnected(gamepad);
  26571. });
  26572. }
  26573. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26574. // Only the first gamepad can control the camera
  26575. if (gamepad.index === 0) {
  26576. this._gamepad = gamepad;
  26577. }
  26578. };
  26579. GamepadCamera.prototype._checkInputs = function () {
  26580. if (!this._gamepad) {
  26581. return;
  26582. }
  26583. var LSValues = this._gamepad.leftStick;
  26584. var normalizedLX = LSValues.x / this.moveSensibility;
  26585. var normalizedLY = LSValues.y / this.moveSensibility;
  26586. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26587. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26588. var RSValues = this._gamepad.rightStick;
  26589. var normalizedRX = RSValues.x / this.angularSensibility;
  26590. var normalizedRY = RSValues.y / this.angularSensibility;
  26591. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26592. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26593. ;
  26594. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26595. var speed = this._computeLocalCameraSpeed() * 50.0;
  26596. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26597. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26598. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26599. };
  26600. GamepadCamera.prototype.dispose = function () {
  26601. this._gamepads.dispose();
  26602. _super.prototype.dispose.call(this);
  26603. };
  26604. return GamepadCamera;
  26605. })(BABYLON.FreeCamera);
  26606. BABYLON.GamepadCamera = GamepadCamera;
  26607. })(BABYLON || (BABYLON = {}));
  26608. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26609. var BABYLON;
  26610. (function (BABYLON) {
  26611. var LinesMesh = (function (_super) {
  26612. __extends(LinesMesh, _super);
  26613. function LinesMesh(name, scene, updatable) {
  26614. if (updatable === void 0) { updatable = false; }
  26615. _super.call(this, name, scene);
  26616. this.color = new BABYLON.Color3(1, 1, 1);
  26617. this.alpha = 1;
  26618. this._indices = new Array();
  26619. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26620. attributes: ["position"],
  26621. uniforms: ["worldViewProjection", "color"],
  26622. needAlphaBlending: true
  26623. });
  26624. }
  26625. Object.defineProperty(LinesMesh.prototype, "material", {
  26626. get: function () {
  26627. return this._colorShader;
  26628. },
  26629. enumerable: true,
  26630. configurable: true
  26631. });
  26632. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26633. get: function () {
  26634. return false;
  26635. },
  26636. enumerable: true,
  26637. configurable: true
  26638. });
  26639. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26640. get: function () {
  26641. return false;
  26642. },
  26643. enumerable: true,
  26644. configurable: true
  26645. });
  26646. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26647. var engine = this.getScene().getEngine();
  26648. var indexToBind = this._geometry.getIndexBuffer();
  26649. // VBOs
  26650. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26651. // Color
  26652. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26653. };
  26654. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26655. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26656. return;
  26657. }
  26658. var engine = this.getScene().getEngine();
  26659. // Draw order
  26660. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26661. };
  26662. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26663. return null;
  26664. };
  26665. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26666. this._colorShader.dispose();
  26667. _super.prototype.dispose.call(this, doNotRecurse);
  26668. };
  26669. return LinesMesh;
  26670. })(BABYLON.Mesh);
  26671. BABYLON.LinesMesh = LinesMesh;
  26672. })(BABYLON || (BABYLON = {}));
  26673. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26674. (function (BABYLON) {
  26675. var OutlineRenderer = (function () {
  26676. function OutlineRenderer(scene) {
  26677. this._scene = scene;
  26678. }
  26679. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26680. var _this = this;
  26681. if (useOverlay === void 0) { useOverlay = false; }
  26682. var scene = this._scene;
  26683. var engine = this._scene.getEngine();
  26684. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26685. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26686. return;
  26687. }
  26688. var mesh = subMesh.getRenderingMesh();
  26689. var material = subMesh.getMaterial();
  26690. engine.enableEffect(this._effect);
  26691. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26692. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26693. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26694. // Bones
  26695. if (mesh.useBones) {
  26696. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26697. }
  26698. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26699. // Alpha test
  26700. if (material && material.needAlphaTesting()) {
  26701. var alphaTexture = material.getAlphaTestTexture();
  26702. this._effect.setTexture("diffuseSampler", alphaTexture);
  26703. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26704. }
  26705. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26706. _this._effect.setMatrix("world", world);
  26707. });
  26708. };
  26709. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26710. var defines = [];
  26711. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26712. var mesh = subMesh.getMesh();
  26713. var material = subMesh.getMaterial();
  26714. // Alpha test
  26715. if (material && material.needAlphaTesting()) {
  26716. defines.push("#define ALPHATEST");
  26717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26718. attribs.push(BABYLON.VertexBuffer.UVKind);
  26719. defines.push("#define UV1");
  26720. }
  26721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26722. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26723. defines.push("#define UV2");
  26724. }
  26725. }
  26726. // Bones
  26727. if (mesh.useBones) {
  26728. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26729. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26730. defines.push("#define BONES");
  26731. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26732. }
  26733. // Instances
  26734. if (useInstances) {
  26735. defines.push("#define INSTANCES");
  26736. attribs.push("world0");
  26737. attribs.push("world1");
  26738. attribs.push("world2");
  26739. attribs.push("world3");
  26740. }
  26741. // Get correct effect
  26742. var join = defines.join("\n");
  26743. if (this._cachedDefines !== join) {
  26744. this._cachedDefines = join;
  26745. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26746. }
  26747. return this._effect.isReady();
  26748. };
  26749. return OutlineRenderer;
  26750. })();
  26751. BABYLON.OutlineRenderer = OutlineRenderer;
  26752. })(BABYLON || (BABYLON = {}));
  26753. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26754. (function (BABYLON) {
  26755. var MeshAssetTask = (function () {
  26756. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26757. this.name = name;
  26758. this.meshesNames = meshesNames;
  26759. this.rootUrl = rootUrl;
  26760. this.sceneFilename = sceneFilename;
  26761. this.isCompleted = false;
  26762. }
  26763. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26764. var _this = this;
  26765. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26766. _this.loadedMeshes = meshes;
  26767. _this.loadedParticleSystems = particleSystems;
  26768. _this.loadedSkeletons = skeletons;
  26769. _this.isCompleted = true;
  26770. if (_this.onSuccess) {
  26771. _this.onSuccess(_this);
  26772. }
  26773. onSuccess();
  26774. }, null, function () {
  26775. if (_this.onError) {
  26776. _this.onError(_this);
  26777. }
  26778. onError();
  26779. });
  26780. };
  26781. return MeshAssetTask;
  26782. })();
  26783. BABYLON.MeshAssetTask = MeshAssetTask;
  26784. var TextFileAssetTask = (function () {
  26785. function TextFileAssetTask(name, url) {
  26786. this.name = name;
  26787. this.url = url;
  26788. this.isCompleted = false;
  26789. }
  26790. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26791. var _this = this;
  26792. BABYLON.Tools.LoadFile(this.url, function (data) {
  26793. _this.text = data;
  26794. _this.isCompleted = true;
  26795. if (_this.onSuccess) {
  26796. _this.onSuccess(_this);
  26797. }
  26798. onSuccess();
  26799. }, null, scene.database, false, function () {
  26800. if (_this.onError) {
  26801. _this.onError(_this);
  26802. }
  26803. onError();
  26804. });
  26805. };
  26806. return TextFileAssetTask;
  26807. })();
  26808. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26809. var BinaryFileAssetTask = (function () {
  26810. function BinaryFileAssetTask(name, url) {
  26811. this.name = name;
  26812. this.url = url;
  26813. this.isCompleted = false;
  26814. }
  26815. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26816. var _this = this;
  26817. BABYLON.Tools.LoadFile(this.url, function (data) {
  26818. _this.data = data;
  26819. _this.isCompleted = true;
  26820. if (_this.onSuccess) {
  26821. _this.onSuccess(_this);
  26822. }
  26823. onSuccess();
  26824. }, null, scene.database, true, function () {
  26825. if (_this.onError) {
  26826. _this.onError(_this);
  26827. }
  26828. onError();
  26829. });
  26830. };
  26831. return BinaryFileAssetTask;
  26832. })();
  26833. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26834. var ImageAssetTask = (function () {
  26835. function ImageAssetTask(name, url) {
  26836. this.name = name;
  26837. this.url = url;
  26838. this.isCompleted = false;
  26839. }
  26840. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26841. var _this = this;
  26842. var img = new Image();
  26843. img.onload = function () {
  26844. _this.image = img;
  26845. _this.isCompleted = true;
  26846. if (_this.onSuccess) {
  26847. _this.onSuccess(_this);
  26848. }
  26849. onSuccess();
  26850. };
  26851. img.onerror = function () {
  26852. if (_this.onError) {
  26853. _this.onError(_this);
  26854. }
  26855. onError();
  26856. };
  26857. img.src = this.url;
  26858. };
  26859. return ImageAssetTask;
  26860. })();
  26861. BABYLON.ImageAssetTask = ImageAssetTask;
  26862. var TextureAssetTask = (function () {
  26863. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26865. this.name = name;
  26866. this.url = url;
  26867. this.noMipmap = noMipmap;
  26868. this.invertY = invertY;
  26869. this.samplingMode = samplingMode;
  26870. this.isCompleted = false;
  26871. }
  26872. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26873. var _this = this;
  26874. var onload = function () {
  26875. _this.isCompleted = true;
  26876. if (_this.onSuccess) {
  26877. _this.onSuccess(_this);
  26878. }
  26879. onSuccess();
  26880. };
  26881. var onerror = function () {
  26882. if (_this.onError) {
  26883. _this.onError(_this);
  26884. }
  26885. onError();
  26886. };
  26887. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26888. };
  26889. return TextureAssetTask;
  26890. })();
  26891. BABYLON.TextureAssetTask = TextureAssetTask;
  26892. var AssetsManager = (function () {
  26893. function AssetsManager(scene) {
  26894. this._tasks = new Array();
  26895. this._waitingTasksCount = 0;
  26896. this.useDefaultLoadingScreen = true;
  26897. this._scene = scene;
  26898. }
  26899. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26900. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26901. this._tasks.push(task);
  26902. return task;
  26903. };
  26904. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26905. var task = new TextFileAssetTask(taskName, url);
  26906. this._tasks.push(task);
  26907. return task;
  26908. };
  26909. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26910. var task = new BinaryFileAssetTask(taskName, url);
  26911. this._tasks.push(task);
  26912. return task;
  26913. };
  26914. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26915. var task = new ImageAssetTask(taskName, url);
  26916. this._tasks.push(task);
  26917. return task;
  26918. };
  26919. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26921. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26922. this._tasks.push(task);
  26923. return task;
  26924. };
  26925. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26926. this._waitingTasksCount--;
  26927. if (this._waitingTasksCount === 0) {
  26928. if (this.onFinish) {
  26929. this.onFinish(this._tasks);
  26930. }
  26931. this._scene.getEngine().hideLoadingUI();
  26932. }
  26933. };
  26934. AssetsManager.prototype._runTask = function (task) {
  26935. var _this = this;
  26936. task.run(this._scene, function () {
  26937. if (_this.onTaskSuccess) {
  26938. _this.onTaskSuccess(task);
  26939. }
  26940. _this._decreaseWaitingTasksCount();
  26941. }, function () {
  26942. if (_this.onTaskError) {
  26943. _this.onTaskError(task);
  26944. }
  26945. _this._decreaseWaitingTasksCount();
  26946. });
  26947. };
  26948. AssetsManager.prototype.reset = function () {
  26949. this._tasks = new Array();
  26950. return this;
  26951. };
  26952. AssetsManager.prototype.load = function () {
  26953. this._waitingTasksCount = this._tasks.length;
  26954. if (this._waitingTasksCount === 0) {
  26955. if (this.onFinish) {
  26956. this.onFinish(this._tasks);
  26957. }
  26958. return this;
  26959. }
  26960. if (this.useDefaultLoadingScreen) {
  26961. this._scene.getEngine().displayLoadingUI();
  26962. }
  26963. for (var index = 0; index < this._tasks.length; index++) {
  26964. var task = this._tasks[index];
  26965. this._runTask(task);
  26966. }
  26967. return this;
  26968. };
  26969. return AssetsManager;
  26970. })();
  26971. BABYLON.AssetsManager = AssetsManager;
  26972. })(BABYLON || (BABYLON = {}));
  26973. //# sourceMappingURL=babylon.assetsManager.js.map
  26974. var BABYLON;
  26975. (function (BABYLON) {
  26976. var VRDeviceOrientationCamera = (function (_super) {
  26977. __extends(VRDeviceOrientationCamera, _super);
  26978. function VRDeviceOrientationCamera(name, position, scene) {
  26979. _super.call(this, name, position, scene);
  26980. this._alpha = 0;
  26981. this._beta = 0;
  26982. this._gamma = 0;
  26983. }
  26984. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26985. this._alpha = +evt.alpha | 0;
  26986. this._beta = +evt.beta | 0;
  26987. this._gamma = +evt.gamma | 0;
  26988. if (this._gamma < 0) {
  26989. this._gamma = 90 + this._gamma;
  26990. }
  26991. else {
  26992. // Incline it in the correct angle.
  26993. this._gamma = 270 - this._gamma;
  26994. }
  26995. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26996. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26997. this.rotation.z = this._beta / 180.0 * Math.PI;
  26998. };
  26999. return VRDeviceOrientationCamera;
  27000. })(BABYLON.OculusCamera);
  27001. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  27002. })(BABYLON || (BABYLON = {}));
  27003. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  27004. var BABYLON;
  27005. (function (BABYLON) {
  27006. var WebVRCamera = (function (_super) {
  27007. __extends(WebVRCamera, _super);
  27008. function WebVRCamera(name, position, scene) {
  27009. _super.call(this, name, position, scene);
  27010. this._hmdDevice = null;
  27011. this._sensorDevice = null;
  27012. this._cacheState = null;
  27013. this._cacheQuaternion = new BABYLON.Quaternion();
  27014. this._cacheRotation = BABYLON.Vector3.Zero();
  27015. this._vrEnabled = false;
  27016. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  27017. }
  27018. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  27019. var size = devices.length;
  27020. var i = 0;
  27021. // Reset devices.
  27022. this._sensorDevice = null;
  27023. this._hmdDevice = null;
  27024. while (i < size && this._hmdDevice === null) {
  27025. if (devices[i] instanceof HMDVRDevice) {
  27026. this._hmdDevice = devices[i];
  27027. }
  27028. i++;
  27029. }
  27030. i = 0;
  27031. while (i < size && this._sensorDevice === null) {
  27032. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  27033. this._sensorDevice = devices[i];
  27034. }
  27035. i++;
  27036. }
  27037. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  27038. };
  27039. WebVRCamera.prototype._update = function () {
  27040. if (this._vrEnabled) {
  27041. this._cacheState = this._sensorDevice.getState();
  27042. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  27043. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  27044. this.rotation.x = -this._cacheRotation.z;
  27045. this.rotation.y = -this._cacheRotation.y;
  27046. this.rotation.z = this._cacheRotation.x;
  27047. }
  27048. _super.prototype._update.call(this);
  27049. };
  27050. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  27051. _super.prototype.attachControl.call(this, element, noPreventDefault);
  27052. if (navigator.getVRDevices) {
  27053. navigator.getVRDevices().then(this._getWebVRDevices);
  27054. }
  27055. else if (navigator.mozGetVRDevices) {
  27056. navigator.mozGetVRDevices(this._getWebVRDevices);
  27057. }
  27058. };
  27059. WebVRCamera.prototype.detachControl = function (element) {
  27060. _super.prototype.detachControl.call(this, element);
  27061. this._vrEnabled = false;
  27062. };
  27063. return WebVRCamera;
  27064. })(BABYLON.OculusCamera);
  27065. BABYLON.WebVRCamera = WebVRCamera;
  27066. })(BABYLON || (BABYLON = {}));
  27067. //# sourceMappingURL=babylon.webVRCamera.js.map
  27068. var BABYLON;
  27069. (function (BABYLON) {
  27070. // Standard optimizations
  27071. var SceneOptimization = (function () {
  27072. function SceneOptimization(priority) {
  27073. if (priority === void 0) { priority = 0; }
  27074. this.priority = priority;
  27075. this.apply = function (scene) {
  27076. return true; // Return true if everything that can be done was applied
  27077. };
  27078. }
  27079. return SceneOptimization;
  27080. })();
  27081. BABYLON.SceneOptimization = SceneOptimization;
  27082. var TextureOptimization = (function (_super) {
  27083. __extends(TextureOptimization, _super);
  27084. function TextureOptimization(priority, maximumSize) {
  27085. var _this = this;
  27086. if (priority === void 0) { priority = 0; }
  27087. if (maximumSize === void 0) { maximumSize = 1024; }
  27088. _super.call(this, priority);
  27089. this.priority = priority;
  27090. this.maximumSize = maximumSize;
  27091. this.apply = function (scene) {
  27092. var allDone = true;
  27093. for (var index = 0; index < scene.textures.length; index++) {
  27094. var texture = scene.textures[index];
  27095. if (!texture.canRescale) {
  27096. continue;
  27097. }
  27098. var currentSize = texture.getSize();
  27099. var maxDimension = Math.max(currentSize.width, currentSize.height);
  27100. if (maxDimension > _this.maximumSize) {
  27101. texture.scale(0.5);
  27102. allDone = false;
  27103. }
  27104. }
  27105. return allDone;
  27106. };
  27107. }
  27108. return TextureOptimization;
  27109. })(SceneOptimization);
  27110. BABYLON.TextureOptimization = TextureOptimization;
  27111. var HardwareScalingOptimization = (function (_super) {
  27112. __extends(HardwareScalingOptimization, _super);
  27113. function HardwareScalingOptimization(priority, maximumScale) {
  27114. var _this = this;
  27115. if (priority === void 0) { priority = 0; }
  27116. if (maximumScale === void 0) { maximumScale = 2; }
  27117. _super.call(this, priority);
  27118. this.priority = priority;
  27119. this.maximumScale = maximumScale;
  27120. this._currentScale = 1;
  27121. this.apply = function (scene) {
  27122. _this._currentScale++;
  27123. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  27124. return _this._currentScale >= _this.maximumScale;
  27125. };
  27126. }
  27127. return HardwareScalingOptimization;
  27128. })(SceneOptimization);
  27129. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  27130. var ShadowsOptimization = (function (_super) {
  27131. __extends(ShadowsOptimization, _super);
  27132. function ShadowsOptimization() {
  27133. _super.apply(this, arguments);
  27134. this.apply = function (scene) {
  27135. scene.shadowsEnabled = false;
  27136. return true;
  27137. };
  27138. }
  27139. return ShadowsOptimization;
  27140. })(SceneOptimization);
  27141. BABYLON.ShadowsOptimization = ShadowsOptimization;
  27142. var PostProcessesOptimization = (function (_super) {
  27143. __extends(PostProcessesOptimization, _super);
  27144. function PostProcessesOptimization() {
  27145. _super.apply(this, arguments);
  27146. this.apply = function (scene) {
  27147. scene.postProcessesEnabled = false;
  27148. return true;
  27149. };
  27150. }
  27151. return PostProcessesOptimization;
  27152. })(SceneOptimization);
  27153. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  27154. var LensFlaresOptimization = (function (_super) {
  27155. __extends(LensFlaresOptimization, _super);
  27156. function LensFlaresOptimization() {
  27157. _super.apply(this, arguments);
  27158. this.apply = function (scene) {
  27159. scene.lensFlaresEnabled = false;
  27160. return true;
  27161. };
  27162. }
  27163. return LensFlaresOptimization;
  27164. })(SceneOptimization);
  27165. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  27166. var ParticlesOptimization = (function (_super) {
  27167. __extends(ParticlesOptimization, _super);
  27168. function ParticlesOptimization() {
  27169. _super.apply(this, arguments);
  27170. this.apply = function (scene) {
  27171. scene.particlesEnabled = false;
  27172. return true;
  27173. };
  27174. }
  27175. return ParticlesOptimization;
  27176. })(SceneOptimization);
  27177. BABYLON.ParticlesOptimization = ParticlesOptimization;
  27178. var RenderTargetsOptimization = (function (_super) {
  27179. __extends(RenderTargetsOptimization, _super);
  27180. function RenderTargetsOptimization() {
  27181. _super.apply(this, arguments);
  27182. this.apply = function (scene) {
  27183. scene.renderTargetsEnabled = false;
  27184. return true;
  27185. };
  27186. }
  27187. return RenderTargetsOptimization;
  27188. })(SceneOptimization);
  27189. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  27190. var MergeMeshesOptimization = (function (_super) {
  27191. __extends(MergeMeshesOptimization, _super);
  27192. function MergeMeshesOptimization() {
  27193. var _this = this;
  27194. _super.apply(this, arguments);
  27195. this._canBeMerged = function (abstractMesh) {
  27196. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  27197. return false;
  27198. }
  27199. var mesh = abstractMesh;
  27200. if (!mesh.isVisible || !mesh.isEnabled()) {
  27201. return false;
  27202. }
  27203. if (mesh.instances.length > 0) {
  27204. return false;
  27205. }
  27206. if (mesh.skeleton || mesh.hasLODLevels) {
  27207. return false;
  27208. }
  27209. return true;
  27210. };
  27211. this.apply = function (scene) {
  27212. var globalPool = scene.meshes.slice(0);
  27213. var globalLength = globalPool.length;
  27214. for (var index = 0; index < globalLength; index++) {
  27215. var currentPool = new Array();
  27216. var current = globalPool[index];
  27217. // Checks
  27218. if (!_this._canBeMerged(current)) {
  27219. continue;
  27220. }
  27221. currentPool.push(current);
  27222. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27223. var otherMesh = globalPool[subIndex];
  27224. if (!_this._canBeMerged(otherMesh)) {
  27225. continue;
  27226. }
  27227. if (otherMesh.material !== current.material) {
  27228. continue;
  27229. }
  27230. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27231. continue;
  27232. }
  27233. currentPool.push(otherMesh);
  27234. globalLength--;
  27235. globalPool.splice(subIndex, 1);
  27236. subIndex--;
  27237. }
  27238. if (currentPool.length < 2) {
  27239. continue;
  27240. }
  27241. // Merge meshes
  27242. BABYLON.Mesh.MergeMeshes(currentPool);
  27243. }
  27244. return true;
  27245. };
  27246. }
  27247. return MergeMeshesOptimization;
  27248. })(SceneOptimization);
  27249. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27250. // Options
  27251. var SceneOptimizerOptions = (function () {
  27252. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27253. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27254. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27255. this.targetFrameRate = targetFrameRate;
  27256. this.trackerDuration = trackerDuration;
  27257. this.optimizations = new Array();
  27258. }
  27259. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27260. var result = new SceneOptimizerOptions(targetFrameRate);
  27261. var priority = 0;
  27262. result.optimizations.push(new MergeMeshesOptimization(priority));
  27263. result.optimizations.push(new ShadowsOptimization(priority));
  27264. result.optimizations.push(new LensFlaresOptimization(priority));
  27265. // Next priority
  27266. priority++;
  27267. result.optimizations.push(new PostProcessesOptimization(priority));
  27268. result.optimizations.push(new ParticlesOptimization(priority));
  27269. // Next priority
  27270. priority++;
  27271. result.optimizations.push(new TextureOptimization(priority, 1024));
  27272. return result;
  27273. };
  27274. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27275. var result = new SceneOptimizerOptions(targetFrameRate);
  27276. var priority = 0;
  27277. result.optimizations.push(new MergeMeshesOptimization(priority));
  27278. result.optimizations.push(new ShadowsOptimization(priority));
  27279. result.optimizations.push(new LensFlaresOptimization(priority));
  27280. // Next priority
  27281. priority++;
  27282. result.optimizations.push(new PostProcessesOptimization(priority));
  27283. result.optimizations.push(new ParticlesOptimization(priority));
  27284. // Next priority
  27285. priority++;
  27286. result.optimizations.push(new TextureOptimization(priority, 512));
  27287. // Next priority
  27288. priority++;
  27289. result.optimizations.push(new RenderTargetsOptimization(priority));
  27290. // Next priority
  27291. priority++;
  27292. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27293. return result;
  27294. };
  27295. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27296. var result = new SceneOptimizerOptions(targetFrameRate);
  27297. var priority = 0;
  27298. result.optimizations.push(new MergeMeshesOptimization(priority));
  27299. result.optimizations.push(new ShadowsOptimization(priority));
  27300. result.optimizations.push(new LensFlaresOptimization(priority));
  27301. // Next priority
  27302. priority++;
  27303. result.optimizations.push(new PostProcessesOptimization(priority));
  27304. result.optimizations.push(new ParticlesOptimization(priority));
  27305. // Next priority
  27306. priority++;
  27307. result.optimizations.push(new TextureOptimization(priority, 256));
  27308. // Next priority
  27309. priority++;
  27310. result.optimizations.push(new RenderTargetsOptimization(priority));
  27311. // Next priority
  27312. priority++;
  27313. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27314. return result;
  27315. };
  27316. return SceneOptimizerOptions;
  27317. })();
  27318. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27319. // Scene optimizer tool
  27320. var SceneOptimizer = (function () {
  27321. function SceneOptimizer() {
  27322. }
  27323. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27324. // TODO: add an epsilon
  27325. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27326. if (onSuccess) {
  27327. onSuccess();
  27328. }
  27329. return;
  27330. }
  27331. // Apply current level of optimizations
  27332. var allDone = true;
  27333. var noOptimizationApplied = true;
  27334. for (var index = 0; index < options.optimizations.length; index++) {
  27335. var optimization = options.optimizations[index];
  27336. if (optimization.priority === currentPriorityLevel) {
  27337. noOptimizationApplied = false;
  27338. allDone = allDone && optimization.apply(scene);
  27339. }
  27340. }
  27341. // If no optimization was applied, this is a failure :(
  27342. if (noOptimizationApplied) {
  27343. if (onFailure) {
  27344. onFailure();
  27345. }
  27346. return;
  27347. }
  27348. // If all optimizations were done, move to next level
  27349. if (allDone) {
  27350. currentPriorityLevel++;
  27351. }
  27352. // Let's the system running for a specific amount of time before checking FPS
  27353. scene.executeWhenReady(function () {
  27354. setTimeout(function () {
  27355. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27356. }, options.trackerDuration);
  27357. });
  27358. };
  27359. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27360. if (!options) {
  27361. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27362. }
  27363. // Let's the system running for a specific amount of time before checking FPS
  27364. scene.executeWhenReady(function () {
  27365. setTimeout(function () {
  27366. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27367. }, options.trackerDuration);
  27368. });
  27369. };
  27370. return SceneOptimizer;
  27371. })();
  27372. BABYLON.SceneOptimizer = SceneOptimizer;
  27373. })(BABYLON || (BABYLON = {}));
  27374. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27375. (function (BABYLON) {
  27376. var Internals;
  27377. (function (Internals) {
  27378. var MeshLODLevel = (function () {
  27379. function MeshLODLevel(distance, mesh) {
  27380. this.distance = distance;
  27381. this.mesh = mesh;
  27382. }
  27383. return MeshLODLevel;
  27384. })();
  27385. Internals.MeshLODLevel = MeshLODLevel;
  27386. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27387. })(BABYLON || (BABYLON = {}));
  27388. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27389. (function (BABYLON) {
  27390. var AudioEngine = (function () {
  27391. function AudioEngine() {
  27392. this._audioContext = null;
  27393. this._audioContextInitialized = false;
  27394. this.canUseWebAudio = false;
  27395. this.WarnedWebAudioUnsupported = false;
  27396. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  27397. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  27398. this.canUseWebAudio = true;
  27399. }
  27400. }
  27401. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  27402. get: function () {
  27403. if (!this._audioContextInitialized) {
  27404. this._initializeAudioContext();
  27405. }
  27406. return this._audioContext;
  27407. },
  27408. enumerable: true,
  27409. configurable: true
  27410. });
  27411. AudioEngine.prototype._initializeAudioContext = function () {
  27412. try {
  27413. if (this.canUseWebAudio) {
  27414. this._audioContext = new AudioContext();
  27415. // create a global volume gain node
  27416. this.masterGain = this._audioContext.createGain();
  27417. this.masterGain.gain.value = 1;
  27418. this.masterGain.connect(this._audioContext.destination);
  27419. this._audioContextInitialized = true;
  27420. }
  27421. }
  27422. catch (e) {
  27423. this.canUseWebAudio = false;
  27424. BABYLON.Tools.Error("Web Audio: " + e.message);
  27425. }
  27426. };
  27427. AudioEngine.prototype.dispose = function () {
  27428. if (this.canUseWebAudio && this._audioContextInitialized) {
  27429. if (this._connectedAnalyser) {
  27430. this._connectedAnalyser.stopDebugCanvas();
  27431. this._connectedAnalyser.dispose();
  27432. this.masterGain.disconnect();
  27433. this.masterGain.connect(this._audioContext.destination);
  27434. this._connectedAnalyser = null;
  27435. }
  27436. this.masterGain.gain.value = 1;
  27437. }
  27438. this.WarnedWebAudioUnsupported = false;
  27439. };
  27440. AudioEngine.prototype.getGlobalVolume = function () {
  27441. if (this.canUseWebAudio && this._audioContextInitialized) {
  27442. return this.masterGain.gain.value;
  27443. }
  27444. else {
  27445. return -1;
  27446. }
  27447. };
  27448. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27449. if (this.canUseWebAudio && this._audioContextInitialized) {
  27450. this.masterGain.gain.value = newVolume;
  27451. }
  27452. };
  27453. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27454. if (this._connectedAnalyser) {
  27455. this._connectedAnalyser.stopDebugCanvas();
  27456. }
  27457. if (this.canUseWebAudio && this._audioContextInitialized) {
  27458. this._connectedAnalyser = analyser;
  27459. this.masterGain.disconnect();
  27460. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  27461. }
  27462. };
  27463. return AudioEngine;
  27464. })();
  27465. BABYLON.AudioEngine = AudioEngine;
  27466. })(BABYLON || (BABYLON = {}));
  27467. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27468. (function (BABYLON) {
  27469. var Sound = (function () {
  27470. /**
  27471. * Create a sound and attach it to a scene
  27472. * @param name Name of your sound
  27473. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27474. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27475. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27476. */
  27477. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27478. var _this = this;
  27479. this.autoplay = false;
  27480. this.loop = false;
  27481. this.useCustomAttenuation = false;
  27482. this.spatialSound = false;
  27483. this.refDistance = 1;
  27484. this.rolloffFactor = 1;
  27485. this.maxDistance = 100;
  27486. this.distanceModel = "linear";
  27487. this._panningModel = "equalpower";
  27488. this._playbackRate = 1;
  27489. this._startTime = 0;
  27490. this._startOffset = 0;
  27491. this._position = BABYLON.Vector3.Zero();
  27492. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27493. this._volume = 1;
  27494. this._isLoaded = false;
  27495. this._isReadyToPlay = false;
  27496. this.isPlaying = false;
  27497. this.isPaused = false;
  27498. this._isDirectional = false;
  27499. // Used if you'd like to create a directional sound.
  27500. // If not set, the sound will be omnidirectional
  27501. this._coneInnerAngle = 360;
  27502. this._coneOuterAngle = 360;
  27503. this._coneOuterGain = 0;
  27504. this.name = name;
  27505. this._scene = scene;
  27506. this._readyToPlayCallback = readyToPlayCallback;
  27507. // Default custom attenuation function is a linear attenuation
  27508. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27509. if (currentDistance < maxDistance) {
  27510. return currentVolume * (1 - currentDistance / maxDistance);
  27511. }
  27512. else {
  27513. return 0;
  27514. }
  27515. };
  27516. if (options) {
  27517. this.autoplay = options.autoplay || false;
  27518. this.loop = options.loop || false;
  27519. // if volume === 0, we need another way to check this option
  27520. if (options.volume !== undefined) {
  27521. this._volume = options.volume;
  27522. }
  27523. this.spatialSound = options.spatialSound || false;
  27524. this.maxDistance = options.maxDistance || 100;
  27525. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27526. this.rolloffFactor = options.rolloffFactor || 1;
  27527. this.refDistance = options.refDistance || 1;
  27528. this.distanceModel = options.distanceModel || "linear";
  27529. this._playbackRate = options.playbackRate || 1;
  27530. }
  27531. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27532. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27533. this._soundGain.gain.value = this._volume;
  27534. this._inputAudioNode = this._soundGain;
  27535. this._ouputAudioNode = this._soundGain;
  27536. if (this.spatialSound) {
  27537. this._createSpatialParameters();
  27538. }
  27539. this._scene.mainSoundTrack.AddSound(this);
  27540. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27541. if (urlOrArrayBuffer) {
  27542. // If it's an URL
  27543. if (typeof (urlOrArrayBuffer) === "string") {
  27544. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27545. _this._soundLoaded(data);
  27546. }, null, null, true);
  27547. }
  27548. else {
  27549. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27550. this._soundLoaded(urlOrArrayBuffer);
  27551. }
  27552. else {
  27553. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27554. }
  27555. }
  27556. }
  27557. }
  27558. else {
  27559. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27560. this._scene.mainSoundTrack.AddSound(this);
  27561. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27562. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27563. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27564. }
  27565. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27566. if (this._readyToPlayCallback) {
  27567. window.setTimeout(function () {
  27568. _this._readyToPlayCallback();
  27569. }, 1000);
  27570. }
  27571. }
  27572. }
  27573. Sound.prototype.dispose = function () {
  27574. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27575. if (this.isPlaying) {
  27576. this.stop();
  27577. }
  27578. this._isReadyToPlay = false;
  27579. if (this.soundTrackId === -1) {
  27580. this._scene.mainSoundTrack.RemoveSound(this);
  27581. }
  27582. else {
  27583. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27584. }
  27585. if (this._soundGain) {
  27586. this._soundGain.disconnect();
  27587. this._soundGain = null;
  27588. }
  27589. if (this._soundPanner) {
  27590. this._soundPanner.disconnect();
  27591. this._soundPanner = null;
  27592. }
  27593. if (this._soundSource) {
  27594. this._soundSource.disconnect();
  27595. this._soundSource = null;
  27596. }
  27597. this._audioBuffer = null;
  27598. if (this._connectedMesh) {
  27599. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27600. this._connectedMesh = null;
  27601. }
  27602. }
  27603. };
  27604. Sound.prototype._soundLoaded = function (audioData) {
  27605. var _this = this;
  27606. this._isLoaded = true;
  27607. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27608. _this._audioBuffer = buffer;
  27609. _this._isReadyToPlay = true;
  27610. if (_this.autoplay) {
  27611. _this.play();
  27612. }
  27613. if (_this._readyToPlayCallback) {
  27614. _this._readyToPlayCallback();
  27615. }
  27616. }, function (error) {
  27617. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27618. });
  27619. };
  27620. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27621. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27622. this._audioBuffer = audioBuffer;
  27623. this._isReadyToPlay = true;
  27624. }
  27625. };
  27626. Sound.prototype.updateOptions = function (options) {
  27627. if (options) {
  27628. this.loop = options.loop || this.loop;
  27629. this.maxDistance = options.maxDistance || this.maxDistance;
  27630. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27631. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27632. this.refDistance = options.refDistance || this.refDistance;
  27633. this.distanceModel = options.distanceModel || this.distanceModel;
  27634. this._playbackRate = options.playbackRate || this._playbackRate;
  27635. }
  27636. };
  27637. Sound.prototype._createSpatialParameters = function () {
  27638. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27639. if (this._scene.headphone) {
  27640. this._panningModel = "HRTF";
  27641. }
  27642. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27643. if (this.useCustomAttenuation) {
  27644. // Tricks to disable in a way embedded Web Audio attenuation
  27645. this._soundPanner.distanceModel = "linear";
  27646. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27647. this._soundPanner.refDistance = 1;
  27648. this._soundPanner.rolloffFactor = 1;
  27649. this._soundPanner.panningModel = this._panningModel;
  27650. }
  27651. else {
  27652. this._soundPanner.distanceModel = this.distanceModel;
  27653. this._soundPanner.maxDistance = this.maxDistance;
  27654. this._soundPanner.refDistance = this.refDistance;
  27655. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27656. this._soundPanner.panningModel = this._panningModel;
  27657. }
  27658. this._soundPanner.connect(this._ouputAudioNode);
  27659. this._inputAudioNode = this._soundPanner;
  27660. }
  27661. };
  27662. Sound.prototype.switchPanningModelToHRTF = function () {
  27663. this._panningModel = "HRTF";
  27664. this._switchPanningModel();
  27665. };
  27666. Sound.prototype.switchPanningModelToEqualPower = function () {
  27667. this._panningModel = "equalpower";
  27668. this._switchPanningModel();
  27669. };
  27670. Sound.prototype._switchPanningModel = function () {
  27671. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27672. this._soundPanner.panningModel = this._panningModel;
  27673. }
  27674. };
  27675. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27676. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27677. this._ouputAudioNode.disconnect();
  27678. this._ouputAudioNode.connect(soundTrackAudioNode);
  27679. }
  27680. };
  27681. /**
  27682. * Transform this sound into a directional source
  27683. * @param coneInnerAngle Size of the inner cone in degree
  27684. * @param coneOuterAngle Size of the outer cone in degree
  27685. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27686. */
  27687. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27688. if (coneOuterAngle < coneInnerAngle) {
  27689. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27690. return;
  27691. }
  27692. this._coneInnerAngle = coneInnerAngle;
  27693. this._coneOuterAngle = coneOuterAngle;
  27694. this._coneOuterGain = coneOuterGain;
  27695. this._isDirectional = true;
  27696. if (this.isPlaying && this.loop) {
  27697. this.stop();
  27698. this.play();
  27699. }
  27700. };
  27701. Sound.prototype.setPosition = function (newPosition) {
  27702. this._position = newPosition;
  27703. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27704. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27705. }
  27706. };
  27707. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27708. this._localDirection = newLocalDirection;
  27709. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27710. this._updateDirection();
  27711. }
  27712. };
  27713. Sound.prototype._updateDirection = function () {
  27714. var mat = this._connectedMesh.getWorldMatrix();
  27715. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27716. direction.normalize();
  27717. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27718. };
  27719. Sound.prototype.updateDistanceFromListener = function () {
  27720. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27721. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27722. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27723. }
  27724. };
  27725. Sound.prototype.setAttenuationFunction = function (callback) {
  27726. this._customAttenuationFunction = callback;
  27727. };
  27728. /**
  27729. * Play the sound
  27730. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27731. */
  27732. Sound.prototype.play = function (time) {
  27733. var _this = this;
  27734. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27735. try {
  27736. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27737. if (!this._soundSource) {
  27738. if (this.spatialSound) {
  27739. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27740. if (this._isDirectional) {
  27741. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27742. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27743. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27744. if (this._connectedMesh) {
  27745. this._updateDirection();
  27746. }
  27747. else {
  27748. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27749. }
  27750. }
  27751. }
  27752. }
  27753. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27754. this._soundSource.buffer = this._audioBuffer;
  27755. this._soundSource.connect(this._inputAudioNode);
  27756. this._soundSource.loop = this.loop;
  27757. this._soundSource.playbackRate.value = this._playbackRate;
  27758. this._startTime = startTime;
  27759. this._soundSource.onended = function () {
  27760. _this._onended();
  27761. };
  27762. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27763. this.isPlaying = true;
  27764. this.isPaused = false;
  27765. }
  27766. catch (ex) {
  27767. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27768. }
  27769. }
  27770. };
  27771. Sound.prototype._onended = function () {
  27772. this.isPlaying = false;
  27773. if (this.onended) {
  27774. this.onended();
  27775. }
  27776. };
  27777. /**
  27778. * Stop the sound
  27779. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27780. */
  27781. Sound.prototype.stop = function (time) {
  27782. if (this.isPlaying) {
  27783. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27784. this._soundSource.stop(stopTime);
  27785. this.isPlaying = false;
  27786. }
  27787. };
  27788. Sound.prototype.pause = function () {
  27789. if (this.isPlaying) {
  27790. this.stop(0);
  27791. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27792. this.isPaused = true;
  27793. }
  27794. };
  27795. Sound.prototype.setVolume = function (newVolume, time) {
  27796. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27797. if (time) {
  27798. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27799. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27800. }
  27801. else {
  27802. this._soundGain.gain.value = newVolume;
  27803. }
  27804. }
  27805. this._volume = newVolume;
  27806. };
  27807. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27808. this._playbackRate = newPlaybackRate;
  27809. if (this.isPlaying) {
  27810. this._soundSource.playbackRate.value = this._playbackRate;
  27811. }
  27812. };
  27813. Sound.prototype.getVolume = function () {
  27814. return this._volume;
  27815. };
  27816. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27817. var _this = this;
  27818. this._connectedMesh = meshToConnectTo;
  27819. if (!this.spatialSound) {
  27820. this._createSpatialParameters();
  27821. this.spatialSound = true;
  27822. if (this.isPlaying && this.loop) {
  27823. this.stop();
  27824. this.play();
  27825. }
  27826. }
  27827. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27828. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27829. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27830. };
  27831. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27832. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27833. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27834. this._updateDirection();
  27835. }
  27836. };
  27837. return Sound;
  27838. })();
  27839. BABYLON.Sound = Sound;
  27840. })(BABYLON || (BABYLON = {}));
  27841. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27842. (function (BABYLON) {
  27843. var SoundTrack = (function () {
  27844. function SoundTrack(scene, options) {
  27845. this.id = -1;
  27846. this._isMainTrack = false;
  27847. this._scene = scene;
  27848. this._audioEngine = BABYLON.Engine.audioEngine;
  27849. this.soundCollection = new Array();
  27850. if (this._audioEngine.canUseWebAudio) {
  27851. this._trackGain = this._audioEngine.audioContext.createGain();
  27852. this._trackGain.connect(this._audioEngine.masterGain);
  27853. if (options) {
  27854. if (options.volume) {
  27855. this._trackGain.gain.value = options.volume;
  27856. }
  27857. if (options.mainTrack) {
  27858. this._isMainTrack = options.mainTrack;
  27859. }
  27860. }
  27861. }
  27862. if (!this._isMainTrack) {
  27863. this._scene.soundTracks.push(this);
  27864. this.id = this._scene.soundTracks.length - 1;
  27865. }
  27866. }
  27867. SoundTrack.prototype.dispose = function () {
  27868. if (this._audioEngine.canUseWebAudio) {
  27869. if (this._connectedAnalyser) {
  27870. this._connectedAnalyser.stopDebugCanvas();
  27871. }
  27872. while (this.soundCollection.length) {
  27873. this.soundCollection[0].dispose();
  27874. }
  27875. this._trackGain.disconnect();
  27876. this._trackGain = null;
  27877. }
  27878. };
  27879. SoundTrack.prototype.AddSound = function (sound) {
  27880. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27881. sound.connectToSoundTrackAudioNode(this._trackGain);
  27882. }
  27883. if (sound.soundTrackId) {
  27884. if (sound.soundTrackId === -1) {
  27885. this._scene.mainSoundTrack.RemoveSound(sound);
  27886. }
  27887. else {
  27888. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27889. }
  27890. }
  27891. this.soundCollection.push(sound);
  27892. sound.soundTrackId = this.id;
  27893. };
  27894. SoundTrack.prototype.RemoveSound = function (sound) {
  27895. var index = this.soundCollection.indexOf(sound);
  27896. if (index !== -1) {
  27897. this.soundCollection.splice(index, 1);
  27898. }
  27899. };
  27900. SoundTrack.prototype.setVolume = function (newVolume) {
  27901. if (this._audioEngine.canUseWebAudio) {
  27902. this._trackGain.gain.value = newVolume;
  27903. }
  27904. };
  27905. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27906. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27907. for (var i = 0; i < this.soundCollection.length; i++) {
  27908. this.soundCollection[i].switchPanningModelToHRTF();
  27909. }
  27910. }
  27911. };
  27912. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27913. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27914. for (var i = 0; i < this.soundCollection.length; i++) {
  27915. this.soundCollection[i].switchPanningModelToEqualPower();
  27916. }
  27917. }
  27918. };
  27919. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27920. if (this._connectedAnalyser) {
  27921. this._connectedAnalyser.stopDebugCanvas();
  27922. }
  27923. this._connectedAnalyser = analyser;
  27924. if (this._audioEngine.canUseWebAudio) {
  27925. this._trackGain.disconnect();
  27926. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27927. }
  27928. };
  27929. return SoundTrack;
  27930. })();
  27931. BABYLON.SoundTrack = SoundTrack;
  27932. })(BABYLON || (BABYLON = {}));
  27933. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27934. (function (BABYLON) {
  27935. var DebugLayer = (function () {
  27936. function DebugLayer(scene) {
  27937. var _this = this;
  27938. this._transformationMatrix = BABYLON.Matrix.Identity();
  27939. this._enabled = false;
  27940. this._labelsEnabled = false;
  27941. this._displayStatistics = true;
  27942. this._displayTree = false;
  27943. this._displayLogs = false;
  27944. this._identityMatrix = BABYLON.Matrix.Identity();
  27945. this.axisRatio = 0.02;
  27946. this.accentColor = "orange";
  27947. this._scene = scene;
  27948. this._syncPositions = function () {
  27949. var engine = _this._scene.getEngine();
  27950. var canvasRect = engine.getRenderingCanvasClientRect();
  27951. if (_this._showUI) {
  27952. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27953. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27954. _this._statsDiv.style.width = "400px";
  27955. _this._statsDiv.style.height = "auto";
  27956. _this._statsSubsetDiv.style.maxHeight = "240px";
  27957. _this._optionsDiv.style.left = "0px";
  27958. _this._optionsDiv.style.top = "10px";
  27959. _this._optionsDiv.style.width = "200px";
  27960. _this._optionsDiv.style.height = "auto";
  27961. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27962. _this._logDiv.style.left = "0px";
  27963. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27964. _this._logDiv.style.width = "600px";
  27965. _this._logDiv.style.height = "160px";
  27966. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27967. _this._treeDiv.style.top = "10px";
  27968. _this._treeDiv.style.width = "300px";
  27969. _this._treeDiv.style.height = "auto";
  27970. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27971. }
  27972. _this._globalDiv.style.left = canvasRect.left + "px";
  27973. _this._globalDiv.style.top = canvasRect.top + "px";
  27974. _this._drawingCanvas.style.left = "0px";
  27975. _this._drawingCanvas.style.top = "0px";
  27976. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27977. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27978. var devicePixelRatio = window.devicePixelRatio || 1;
  27979. var context = _this._drawingContext;
  27980. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27981. _this._ratio = devicePixelRatio / backingStoreRatio;
  27982. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27983. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27984. };
  27985. this._onCanvasClick = function (evt) {
  27986. _this._clickPosition = {
  27987. x: evt.clientX * _this._ratio,
  27988. y: evt.clientY * _this._ratio
  27989. };
  27990. };
  27991. this._syncUI = function () {
  27992. if (_this._showUI) {
  27993. if (_this._displayStatistics) {
  27994. _this._displayStats();
  27995. _this._statsDiv.style.display = "";
  27996. }
  27997. else {
  27998. _this._statsDiv.style.display = "none";
  27999. }
  28000. if (_this._displayLogs) {
  28001. _this._logDiv.style.display = "";
  28002. }
  28003. else {
  28004. _this._logDiv.style.display = "none";
  28005. }
  28006. if (_this._displayTree) {
  28007. _this._treeDiv.style.display = "";
  28008. if (_this._needToRefreshMeshesTree) {
  28009. _this._needToRefreshMeshesTree = false;
  28010. _this._refreshMeshesTreeContent();
  28011. }
  28012. }
  28013. else {
  28014. _this._treeDiv.style.display = "none";
  28015. }
  28016. }
  28017. };
  28018. this._syncData = function () {
  28019. if (_this._labelsEnabled || !_this._showUI) {
  28020. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28021. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28022. var engine = _this._scene.getEngine();
  28023. var viewport = _this._camera.viewport;
  28024. var globalViewport = viewport.toGlobal(engine);
  28025. // Meshes
  28026. var meshes = _this._camera.getActiveMeshes();
  28027. for (var index = 0; index < meshes.length; index++) {
  28028. var mesh = meshes.data[index];
  28029. var position = mesh.getBoundingInfo().boundingSphere.center;
  28030. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28031. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28032. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28033. }
  28034. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28035. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  28036. mesh.renderOverlay = !mesh.renderOverlay;
  28037. }, function () {
  28038. return mesh.renderOverlay ? 'red' : 'black';
  28039. });
  28040. }
  28041. }
  28042. // Cameras
  28043. var cameras = _this._scene.cameras;
  28044. for (index = 0; index < cameras.length; index++) {
  28045. var camera = cameras[index];
  28046. if (camera === _this._camera) {
  28047. continue;
  28048. }
  28049. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28050. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28051. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28052. _this._camera.detachControl(engine.getRenderingCanvas());
  28053. _this._camera = camera;
  28054. _this._camera.attachControl(engine.getRenderingCanvas());
  28055. }, function () {
  28056. return "purple";
  28057. });
  28058. }
  28059. }
  28060. // Lights
  28061. var lights = _this._scene.lights;
  28062. for (index = 0; index < lights.length; index++) {
  28063. var light = lights[index];
  28064. if (light.position) {
  28065. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28066. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28067. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28068. light.setEnabled(!light.isEnabled());
  28069. }, function () {
  28070. return light.isEnabled() ? "orange" : "gray";
  28071. });
  28072. }
  28073. }
  28074. }
  28075. }
  28076. _this._clickPosition = undefined;
  28077. };
  28078. }
  28079. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28080. while (this._treeSubsetDiv.hasChildNodes()) {
  28081. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28082. }
  28083. // Add meshes
  28084. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28085. sortedArray.sort(function (a, b) {
  28086. if (a.name === b.name) {
  28087. return 0;
  28088. }
  28089. return (a.name > b.name) ? 1 : -1;
  28090. });
  28091. for (var index = 0; index < sortedArray.length; index++) {
  28092. var mesh = sortedArray[index];
  28093. if (!mesh.isEnabled()) {
  28094. continue;
  28095. }
  28096. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28097. m.isVisible = element.checked;
  28098. }, mesh);
  28099. }
  28100. };
  28101. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28102. this._drawingContext.beginPath();
  28103. this._drawingContext.moveTo(zero.x, zero.y);
  28104. this._drawingContext.lineTo(unit.x, unit.y);
  28105. this._drawingContext.strokeStyle = color;
  28106. this._drawingContext.lineWidth = 4;
  28107. this._drawingContext.stroke();
  28108. this._drawingContext.font = "normal 14px Segoe UI";
  28109. this._drawingContext.fillStyle = color;
  28110. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28111. };
  28112. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28113. var position = mesh.getBoundingInfo().boundingSphere.center;
  28114. var worldMatrix = mesh.getWorldMatrix();
  28115. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28116. var unit = (unprojectedVector.subtract(position)).length();
  28117. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28118. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28119. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28120. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28121. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28122. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28123. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28124. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28125. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28126. };
  28127. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28128. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28129. this._drawingContext.font = "normal 12px Segoe UI";
  28130. var textMetrics = this._drawingContext.measureText(text);
  28131. var centerX = projectedPosition.x - textMetrics.width / 2;
  28132. var centerY = projectedPosition.y;
  28133. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28134. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28135. onClick();
  28136. }
  28137. this._drawingContext.beginPath();
  28138. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28139. this._drawingContext.fillStyle = getFillStyle();
  28140. this._drawingContext.globalAlpha = 0.5;
  28141. this._drawingContext.fill();
  28142. this._drawingContext.globalAlpha = 1.0;
  28143. this._drawingContext.strokeStyle = '#FFFFFF';
  28144. this._drawingContext.lineWidth = 1;
  28145. this._drawingContext.stroke();
  28146. this._drawingContext.fillStyle = "#FFFFFF";
  28147. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28148. this._drawingContext.beginPath();
  28149. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28150. this._drawingContext.fill();
  28151. }
  28152. };
  28153. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28154. if (!this._clickPosition) {
  28155. return false;
  28156. }
  28157. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28158. return false;
  28159. }
  28160. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28161. return false;
  28162. }
  28163. return true;
  28164. };
  28165. DebugLayer.prototype.isVisible = function () {
  28166. return this._enabled;
  28167. };
  28168. DebugLayer.prototype.hide = function () {
  28169. if (!this._enabled) {
  28170. return;
  28171. }
  28172. this._enabled = false;
  28173. var engine = this._scene.getEngine();
  28174. this._scene.unregisterBeforeRender(this._syncData);
  28175. this._scene.unregisterAfterRender(this._syncUI);
  28176. document.body.removeChild(this._globalDiv);
  28177. window.removeEventListener("resize", this._syncPositions);
  28178. this._scene.forceShowBoundingBoxes = false;
  28179. this._scene.forceWireframe = false;
  28180. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28181. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28182. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28183. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28184. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28185. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28186. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28187. this._scene.shadowsEnabled = true;
  28188. this._scene.particlesEnabled = true;
  28189. this._scene.postProcessesEnabled = true;
  28190. this._scene.collisionsEnabled = true;
  28191. this._scene.lightsEnabled = true;
  28192. this._scene.texturesEnabled = true;
  28193. this._scene.lensFlaresEnabled = true;
  28194. this._scene.proceduralTexturesEnabled = true;
  28195. this._scene.renderTargetsEnabled = true;
  28196. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28197. };
  28198. DebugLayer.prototype.show = function (showUI, camera) {
  28199. if (showUI === void 0) { showUI = true; }
  28200. if (camera === void 0) { camera = null; }
  28201. if (this._enabled) {
  28202. return;
  28203. }
  28204. this._enabled = true;
  28205. if (camera) {
  28206. this._camera = camera;
  28207. }
  28208. else {
  28209. this._camera = this._scene.activeCamera;
  28210. }
  28211. this._showUI = showUI;
  28212. var engine = this._scene.getEngine();
  28213. this._globalDiv = document.createElement("div");
  28214. document.body.appendChild(this._globalDiv);
  28215. this._generateDOMelements();
  28216. window.addEventListener("resize", this._syncPositions);
  28217. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28218. this._syncPositions();
  28219. this._scene.registerBeforeRender(this._syncData);
  28220. this._scene.registerAfterRender(this._syncUI);
  28221. };
  28222. DebugLayer.prototype._clearLabels = function () {
  28223. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28224. for (var index = 0; index < this._scene.meshes.length; index++) {
  28225. var mesh = this._scene.meshes[index];
  28226. mesh.renderOverlay = false;
  28227. }
  28228. };
  28229. DebugLayer.prototype._generateheader = function (root, text) {
  28230. var header = document.createElement("div");
  28231. header.innerHTML = text + "&nbsp;";
  28232. header.style.textAlign = "right";
  28233. header.style.width = "100%";
  28234. header.style.color = "white";
  28235. header.style.backgroundColor = "Black";
  28236. header.style.padding = "5px 5px 4px 0px";
  28237. header.style.marginLeft = "-5px";
  28238. header.style.fontWeight = "bold";
  28239. root.appendChild(header);
  28240. };
  28241. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28242. var label = document.createElement("label");
  28243. label.innerHTML = title;
  28244. label.style.color = color;
  28245. root.appendChild(label);
  28246. root.appendChild(document.createElement("br"));
  28247. };
  28248. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28249. if (tag === void 0) { tag = null; }
  28250. var label = document.createElement("label");
  28251. var boundingBoxesCheckbox = document.createElement("input");
  28252. boundingBoxesCheckbox.type = "checkbox";
  28253. boundingBoxesCheckbox.checked = initialState;
  28254. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28255. task(evt.target, tag);
  28256. });
  28257. label.appendChild(boundingBoxesCheckbox);
  28258. var container = document.createElement("span");
  28259. var leftPart = document.createElement("span");
  28260. var rightPart = document.createElement("span");
  28261. rightPart.style.cssFloat = "right";
  28262. leftPart.innerHTML = leftTitle;
  28263. rightPart.innerHTML = rightTitle;
  28264. rightPart.style.fontSize = "12px";
  28265. rightPart.style.maxWidth = "200px";
  28266. container.appendChild(leftPart);
  28267. container.appendChild(rightPart);
  28268. label.appendChild(container);
  28269. root.appendChild(label);
  28270. root.appendChild(document.createElement("br"));
  28271. };
  28272. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28273. if (tag === void 0) { tag = null; }
  28274. var label = document.createElement("label");
  28275. var checkBox = document.createElement("input");
  28276. checkBox.type = "checkbox";
  28277. checkBox.checked = initialState;
  28278. checkBox.addEventListener("change", function (evt) {
  28279. task(evt.target, tag);
  28280. });
  28281. label.appendChild(checkBox);
  28282. label.appendChild(document.createTextNode(title));
  28283. root.appendChild(label);
  28284. root.appendChild(document.createElement("br"));
  28285. };
  28286. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28287. if (tag === void 0) { tag = null; }
  28288. var button = document.createElement("button");
  28289. button.innerHTML = title;
  28290. button.style.height = "24px";
  28291. button.style.color = "#444444";
  28292. button.style.border = "1px solid white";
  28293. button.className = "debugLayerButton";
  28294. button.addEventListener("click", function (evt) {
  28295. task(evt.target, tag);
  28296. });
  28297. root.appendChild(button);
  28298. root.appendChild(document.createElement("br"));
  28299. };
  28300. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28301. if (tag === void 0) { tag = null; }
  28302. var label = document.createElement("label");
  28303. var boundingBoxesRadio = document.createElement("input");
  28304. boundingBoxesRadio.type = "radio";
  28305. boundingBoxesRadio.name = name;
  28306. boundingBoxesRadio.checked = initialState;
  28307. boundingBoxesRadio.addEventListener("change", function (evt) {
  28308. task(evt.target, tag);
  28309. });
  28310. label.appendChild(boundingBoxesRadio);
  28311. label.appendChild(document.createTextNode(title));
  28312. root.appendChild(label);
  28313. root.appendChild(document.createElement("br"));
  28314. };
  28315. DebugLayer.prototype._generateDOMelements = function () {
  28316. var _this = this;
  28317. this._globalDiv.id = "DebugLayer";
  28318. this._globalDiv.style.position = "absolute";
  28319. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28320. this._globalDiv.style.fontSize = "14px";
  28321. this._globalDiv.style.color = "white";
  28322. // Drawing canvas
  28323. this._drawingCanvas = document.createElement("canvas");
  28324. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28325. this._drawingCanvas.style.position = "absolute";
  28326. this._drawingCanvas.style.pointerEvents = "none";
  28327. this._drawingContext = this._drawingCanvas.getContext("2d");
  28328. this._globalDiv.appendChild(this._drawingCanvas);
  28329. if (this._showUI) {
  28330. var background = "rgba(128, 128, 128, 0.4)";
  28331. var border = "rgb(180, 180, 180) solid 1px";
  28332. // Stats
  28333. this._statsDiv = document.createElement("div");
  28334. this._statsDiv.id = "DebugLayerStats";
  28335. this._statsDiv.style.border = border;
  28336. this._statsDiv.style.position = "absolute";
  28337. this._statsDiv.style.background = background;
  28338. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28339. this._generateheader(this._statsDiv, "STATISTICS");
  28340. this._statsSubsetDiv = document.createElement("div");
  28341. this._statsSubsetDiv.style.paddingTop = "5px";
  28342. this._statsSubsetDiv.style.paddingBottom = "5px";
  28343. this._statsSubsetDiv.style.overflowY = "auto";
  28344. this._statsDiv.appendChild(this._statsSubsetDiv);
  28345. // Tree
  28346. this._treeDiv = document.createElement("div");
  28347. this._treeDiv.id = "DebugLayerTree";
  28348. this._treeDiv.style.border = border;
  28349. this._treeDiv.style.position = "absolute";
  28350. this._treeDiv.style.background = background;
  28351. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28352. this._treeDiv.style.display = "none";
  28353. this._generateheader(this._treeDiv, "MESHES TREE");
  28354. this._treeSubsetDiv = document.createElement("div");
  28355. this._treeSubsetDiv.style.paddingTop = "5px";
  28356. this._treeSubsetDiv.style.paddingRight = "5px";
  28357. this._treeSubsetDiv.style.overflowY = "auto";
  28358. this._treeSubsetDiv.style.maxHeight = "300px";
  28359. this._treeDiv.appendChild(this._treeSubsetDiv);
  28360. this._needToRefreshMeshesTree = true;
  28361. // Logs
  28362. this._logDiv = document.createElement("div");
  28363. this._logDiv.style.border = border;
  28364. this._logDiv.id = "DebugLayerLogs";
  28365. this._logDiv.style.position = "absolute";
  28366. this._logDiv.style.background = background;
  28367. this._logDiv.style.padding = "0px 0px 0px 5px";
  28368. this._logDiv.style.display = "none";
  28369. this._generateheader(this._logDiv, "LOGS");
  28370. this._logSubsetDiv = document.createElement("div");
  28371. this._logSubsetDiv.style.height = "127px";
  28372. this._logSubsetDiv.style.paddingTop = "5px";
  28373. this._logSubsetDiv.style.overflowY = "auto";
  28374. this._logSubsetDiv.style.fontSize = "12px";
  28375. this._logSubsetDiv.style.fontFamily = "consolas";
  28376. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28377. this._logDiv.appendChild(this._logSubsetDiv);
  28378. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28379. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28380. };
  28381. // Options
  28382. this._optionsDiv = document.createElement("div");
  28383. this._optionsDiv.id = "DebugLayerOptions";
  28384. this._optionsDiv.style.border = border;
  28385. this._optionsDiv.style.position = "absolute";
  28386. this._optionsDiv.style.background = background;
  28387. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28388. this._optionsDiv.style.overflowY = "auto";
  28389. this._generateheader(this._optionsDiv, "OPTIONS");
  28390. this._optionsSubsetDiv = document.createElement("div");
  28391. this._optionsSubsetDiv.style.paddingTop = "5px";
  28392. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28393. this._optionsSubsetDiv.style.overflowY = "auto";
  28394. this._optionsSubsetDiv.style.maxHeight = "200px";
  28395. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28396. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28397. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28398. _this._displayStatistics = element.checked;
  28399. });
  28400. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28401. _this._displayLogs = element.checked;
  28402. });
  28403. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28404. _this._displayTree = element.checked;
  28405. _this._needToRefreshMeshesTree = true;
  28406. });
  28407. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28408. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28409. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28410. _this._scene.forceShowBoundingBoxes = element.checked;
  28411. });
  28412. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28413. _this._labelsEnabled = element.checked;
  28414. if (!_this._labelsEnabled) {
  28415. _this._clearLabels();
  28416. }
  28417. });
  28418. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28419. if (element.checked) {
  28420. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28421. }
  28422. else {
  28423. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28424. }
  28425. });
  28426. ;
  28427. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28428. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28429. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28430. if (element.checked) {
  28431. _this._scene.forceWireframe = false;
  28432. _this._scene.forcePointsCloud = false;
  28433. }
  28434. });
  28435. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28436. if (element.checked) {
  28437. _this._scene.forceWireframe = true;
  28438. _this._scene.forcePointsCloud = false;
  28439. }
  28440. });
  28441. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28442. if (element.checked) {
  28443. _this._scene.forceWireframe = false;
  28444. _this._scene.forcePointsCloud = true;
  28445. }
  28446. });
  28447. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28448. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28449. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28450. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28451. });
  28452. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28453. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28454. });
  28455. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28456. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28457. });
  28458. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28459. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28460. });
  28461. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28462. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28463. });
  28464. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28465. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28466. });
  28467. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28468. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28469. });
  28470. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28471. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28472. });
  28473. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28474. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28475. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28476. _this._scene.animationsEnabled = element.checked;
  28477. });
  28478. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28479. _this._scene.collisionsEnabled = element.checked;
  28480. });
  28481. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28482. _this._scene.fogEnabled = element.checked;
  28483. });
  28484. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28485. _this._scene.lensFlaresEnabled = element.checked;
  28486. });
  28487. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28488. _this._scene.lightsEnabled = element.checked;
  28489. });
  28490. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28491. _this._scene.particlesEnabled = element.checked;
  28492. });
  28493. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28494. _this._scene.postProcessesEnabled = element.checked;
  28495. });
  28496. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28497. _this._scene.proceduralTexturesEnabled = element.checked;
  28498. });
  28499. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28500. _this._scene.renderTargetsEnabled = element.checked;
  28501. });
  28502. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28503. _this._scene.shadowsEnabled = element.checked;
  28504. });
  28505. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28506. _this._scene.skeletonsEnabled = element.checked;
  28507. });
  28508. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28509. _this._scene.spritesEnabled = element.checked;
  28510. });
  28511. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28512. _this._scene.texturesEnabled = element.checked;
  28513. });
  28514. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28515. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28516. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28517. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28518. if (element.checked) {
  28519. _this._scene.headphone = true;
  28520. }
  28521. });
  28522. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28523. if (element.checked) {
  28524. _this._scene.headphone = false;
  28525. }
  28526. });
  28527. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28528. _this._scene.audioEnabled = !element.checked;
  28529. });
  28530. }
  28531. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28532. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28533. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28534. _this._scene.dumpNextRenderTargets = true;
  28535. });
  28536. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28537. this._globalDiv.appendChild(this._statsDiv);
  28538. this._globalDiv.appendChild(this._logDiv);
  28539. this._globalDiv.appendChild(this._optionsDiv);
  28540. this._globalDiv.appendChild(this._treeDiv);
  28541. }
  28542. };
  28543. DebugLayer.prototype._displayStats = function () {
  28544. var scene = this._scene;
  28545. var engine = scene.getEngine();
  28546. var glInfo = engine.getGlInfo();
  28547. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active indices: " + scene.getActiveIndices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  28548. if (this.customStatsFunction) {
  28549. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28550. }
  28551. };
  28552. return DebugLayer;
  28553. })();
  28554. BABYLON.DebugLayer = DebugLayer;
  28555. })(BABYLON || (BABYLON = {}));
  28556. //# sourceMappingURL=babylon.debugLayer.js.map
  28557. var BABYLON;
  28558. (function (BABYLON) {
  28559. var RawTexture = (function (_super) {
  28560. __extends(RawTexture, _super);
  28561. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28562. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28563. if (invertY === void 0) { invertY = false; }
  28564. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28565. _super.call(this, null, scene, !generateMipMaps, invertY);
  28566. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28567. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28568. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28569. }
  28570. // Statics
  28571. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28572. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28573. if (invertY === void 0) { invertY = false; }
  28574. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28575. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28576. };
  28577. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28578. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28579. if (invertY === void 0) { invertY = false; }
  28580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28581. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28582. };
  28583. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28584. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28585. if (invertY === void 0) { invertY = false; }
  28586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28587. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28588. };
  28589. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28590. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28591. if (invertY === void 0) { invertY = false; }
  28592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28593. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28594. };
  28595. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28596. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28597. if (invertY === void 0) { invertY = false; }
  28598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28599. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28600. };
  28601. return RawTexture;
  28602. })(BABYLON.Texture);
  28603. BABYLON.RawTexture = RawTexture;
  28604. })(BABYLON || (BABYLON = {}));
  28605. //# sourceMappingURL=babylon.rawTexture.js.map
  28606. var BABYLON;
  28607. (function (BABYLON) {
  28608. var IndexedVector2 = (function (_super) {
  28609. __extends(IndexedVector2, _super);
  28610. function IndexedVector2(original, index) {
  28611. _super.call(this, original.x, original.y);
  28612. this.index = index;
  28613. }
  28614. return IndexedVector2;
  28615. })(BABYLON.Vector2);
  28616. var PolygonPoints = (function () {
  28617. function PolygonPoints() {
  28618. this.elements = new Array();
  28619. }
  28620. PolygonPoints.prototype.add = function (originalPoints) {
  28621. var _this = this;
  28622. var result = new Array();
  28623. originalPoints.forEach(function (point) {
  28624. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28625. var newPoint = new IndexedVector2(point, _this.elements.length);
  28626. result.push(newPoint);
  28627. _this.elements.push(newPoint);
  28628. }
  28629. });
  28630. return result;
  28631. };
  28632. PolygonPoints.prototype.computeBounds = function () {
  28633. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28634. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28635. this.elements.forEach(function (point) {
  28636. // x
  28637. if (point.x < lmin.x) {
  28638. lmin.x = point.x;
  28639. }
  28640. else if (point.x > lmax.x) {
  28641. lmax.x = point.x;
  28642. }
  28643. // y
  28644. if (point.y < lmin.y) {
  28645. lmin.y = point.y;
  28646. }
  28647. else if (point.y > lmax.y) {
  28648. lmax.y = point.y;
  28649. }
  28650. });
  28651. return {
  28652. min: lmin,
  28653. max: lmax,
  28654. width: lmax.x - lmin.x,
  28655. height: lmax.y - lmin.y
  28656. };
  28657. };
  28658. return PolygonPoints;
  28659. })();
  28660. var Polygon = (function () {
  28661. function Polygon() {
  28662. }
  28663. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28664. return [
  28665. new BABYLON.Vector2(xmin, ymin),
  28666. new BABYLON.Vector2(xmax, ymin),
  28667. new BABYLON.Vector2(xmax, ymax),
  28668. new BABYLON.Vector2(xmin, ymax)
  28669. ];
  28670. };
  28671. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28672. if (cx === void 0) { cx = 0; }
  28673. if (cy === void 0) { cy = 0; }
  28674. if (numberOfSides === void 0) { numberOfSides = 32; }
  28675. var result = new Array();
  28676. var angle = 0;
  28677. var increment = (Math.PI * 2) / numberOfSides;
  28678. for (var i = 0; i < numberOfSides; i++) {
  28679. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28680. angle -= increment;
  28681. }
  28682. return result;
  28683. };
  28684. Polygon.Parse = function (input) {
  28685. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28686. var i, result = [];
  28687. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28688. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28689. }
  28690. return result;
  28691. };
  28692. Polygon.StartingAt = function (x, y) {
  28693. return BABYLON.Path2.StartingAt(x, y);
  28694. };
  28695. return Polygon;
  28696. })();
  28697. BABYLON.Polygon = Polygon;
  28698. var PolygonMeshBuilder = (function () {
  28699. function PolygonMeshBuilder(name, contours, scene) {
  28700. this._points = new PolygonPoints();
  28701. if (!("poly2tri" in window)) {
  28702. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28703. }
  28704. this._name = name;
  28705. this._scene = scene;
  28706. var points;
  28707. if (contours instanceof BABYLON.Path2) {
  28708. points = contours.getPoints();
  28709. }
  28710. else {
  28711. points = contours;
  28712. }
  28713. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28714. }
  28715. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28716. this._swctx.addHole(this._points.add(hole));
  28717. return this;
  28718. };
  28719. PolygonMeshBuilder.prototype.build = function (updatable) {
  28720. if (updatable === void 0) { updatable = false; }
  28721. var result = new BABYLON.Mesh(this._name, this._scene);
  28722. var normals = [];
  28723. var positions = [];
  28724. var uvs = [];
  28725. var bounds = this._points.computeBounds();
  28726. this._points.elements.forEach(function (p) {
  28727. normals.push(0, 1.0, 0);
  28728. positions.push(p.x, 0, p.y);
  28729. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28730. });
  28731. var indices = [];
  28732. this._swctx.triangulate();
  28733. this._swctx.getTriangles().forEach(function (triangle) {
  28734. triangle.getPoints().forEach(function (point) {
  28735. indices.push(point.index);
  28736. });
  28737. });
  28738. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28739. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28740. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28741. result.setIndices(indices);
  28742. return result;
  28743. };
  28744. return PolygonMeshBuilder;
  28745. })();
  28746. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28747. })(BABYLON || (BABYLON = {}));
  28748. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28749. (function (BABYLON) {
  28750. var SimplificationSettings = (function () {
  28751. function SimplificationSettings(quality, distance, optimizeMesh) {
  28752. this.quality = quality;
  28753. this.distance = distance;
  28754. this.optimizeMesh = optimizeMesh;
  28755. }
  28756. return SimplificationSettings;
  28757. })();
  28758. BABYLON.SimplificationSettings = SimplificationSettings;
  28759. var SimplificationQueue = (function () {
  28760. function SimplificationQueue() {
  28761. this.running = false;
  28762. this._simplificationArray = [];
  28763. }
  28764. SimplificationQueue.prototype.addTask = function (task) {
  28765. this._simplificationArray.push(task);
  28766. };
  28767. SimplificationQueue.prototype.executeNext = function () {
  28768. var task = this._simplificationArray.pop();
  28769. if (task) {
  28770. this.running = true;
  28771. this.runSimplification(task);
  28772. }
  28773. else {
  28774. this.running = false;
  28775. }
  28776. };
  28777. SimplificationQueue.prototype.runSimplification = function (task) {
  28778. var _this = this;
  28779. if (task.parallelProcessing) {
  28780. //parallel simplifier
  28781. task.settings.forEach(function (setting) {
  28782. var simplifier = _this.getSimplifier(task);
  28783. simplifier.simplify(setting, function (newMesh) {
  28784. task.mesh.addLODLevel(setting.distance, newMesh);
  28785. newMesh.isVisible = true;
  28786. //check if it is the last
  28787. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28788. //all done, run the success callback.
  28789. task.successCallback();
  28790. }
  28791. _this.executeNext();
  28792. });
  28793. });
  28794. }
  28795. else {
  28796. //single simplifier.
  28797. var simplifier = this.getSimplifier(task);
  28798. var runDecimation = function (setting, callback) {
  28799. simplifier.simplify(setting, function (newMesh) {
  28800. task.mesh.addLODLevel(setting.distance, newMesh);
  28801. newMesh.isVisible = true;
  28802. //run the next quality level
  28803. callback();
  28804. });
  28805. };
  28806. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28807. runDecimation(task.settings[loop.index], function () {
  28808. loop.executeNext();
  28809. });
  28810. }, function () {
  28811. //execution ended, run the success callback.
  28812. if (task.successCallback) {
  28813. task.successCallback();
  28814. }
  28815. _this.executeNext();
  28816. });
  28817. }
  28818. };
  28819. SimplificationQueue.prototype.getSimplifier = function (task) {
  28820. switch (task.simplificationType) {
  28821. case 0 /* QUADRATIC */:
  28822. default:
  28823. return new QuadraticErrorSimplification(task.mesh);
  28824. }
  28825. };
  28826. return SimplificationQueue;
  28827. })();
  28828. BABYLON.SimplificationQueue = SimplificationQueue;
  28829. /**
  28830. * The implemented types of simplification.
  28831. * At the moment only Quadratic Error Decimation is implemented.
  28832. */
  28833. (function (SimplificationType) {
  28834. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28835. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28836. var SimplificationType = BABYLON.SimplificationType;
  28837. var DecimationTriangle = (function () {
  28838. function DecimationTriangle(vertices) {
  28839. this.vertices = vertices;
  28840. this.error = new Array(4);
  28841. this.deleted = false;
  28842. this.isDirty = false;
  28843. this.deletePending = false;
  28844. this.borderFactor = 0;
  28845. }
  28846. return DecimationTriangle;
  28847. })();
  28848. BABYLON.DecimationTriangle = DecimationTriangle;
  28849. var DecimationVertex = (function () {
  28850. function DecimationVertex(position, id) {
  28851. this.position = position;
  28852. this.id = id;
  28853. this.isBorder = true;
  28854. this.q = new QuadraticMatrix();
  28855. this.triangleCount = 0;
  28856. this.triangleStart = 0;
  28857. this.originalOffsets = [];
  28858. }
  28859. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28860. this.position.copyFrom(newPosition);
  28861. };
  28862. return DecimationVertex;
  28863. })();
  28864. BABYLON.DecimationVertex = DecimationVertex;
  28865. var QuadraticMatrix = (function () {
  28866. function QuadraticMatrix(data) {
  28867. this.data = new Array(10);
  28868. for (var i = 0; i < 10; ++i) {
  28869. if (data && data[i]) {
  28870. this.data[i] = data[i];
  28871. }
  28872. else {
  28873. this.data[i] = 0;
  28874. }
  28875. }
  28876. }
  28877. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28878. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28879. return det;
  28880. };
  28881. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28882. for (var i = 0; i < 10; ++i) {
  28883. this.data[i] += matrix.data[i];
  28884. }
  28885. };
  28886. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28887. for (var i = 0; i < 10; ++i) {
  28888. this.data[i] += data[i];
  28889. }
  28890. };
  28891. QuadraticMatrix.prototype.add = function (matrix) {
  28892. var m = new QuadraticMatrix();
  28893. for (var i = 0; i < 10; ++i) {
  28894. m.data[i] = this.data[i] + matrix.data[i];
  28895. }
  28896. return m;
  28897. };
  28898. QuadraticMatrix.FromData = function (a, b, c, d) {
  28899. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28900. };
  28901. //returning an array to avoid garbage collection
  28902. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28903. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28904. };
  28905. return QuadraticMatrix;
  28906. })();
  28907. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28908. var Reference = (function () {
  28909. function Reference(vertexId, triangleId) {
  28910. this.vertexId = vertexId;
  28911. this.triangleId = triangleId;
  28912. }
  28913. return Reference;
  28914. })();
  28915. BABYLON.Reference = Reference;
  28916. /**
  28917. * An implementation of the Quadratic Error simplification algorithm.
  28918. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28919. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28920. * @author RaananW
  28921. */
  28922. var QuadraticErrorSimplification = (function () {
  28923. function QuadraticErrorSimplification(_mesh) {
  28924. this._mesh = _mesh;
  28925. this.initialized = false;
  28926. this.syncIterations = 5000;
  28927. this.aggressiveness = 7;
  28928. this.decimationIterations = 100;
  28929. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28930. }
  28931. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28932. var _this = this;
  28933. this.initDecimatedMesh();
  28934. //iterating through the submeshes array, one after the other.
  28935. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28936. _this.initWithMesh(loop.index, function () {
  28937. _this.runDecimation(settings, loop.index, function () {
  28938. loop.executeNext();
  28939. });
  28940. }, settings.optimizeMesh);
  28941. }, function () {
  28942. setTimeout(function () {
  28943. successCallback(_this._reconstructedMesh);
  28944. }, 0);
  28945. });
  28946. };
  28947. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28948. var _this = this;
  28949. var gCount = 0;
  28950. triangle.vertices.forEach(function (vertex) {
  28951. var count = 0;
  28952. var vPos = vertex.position;
  28953. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28954. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28955. ++count;
  28956. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28957. ++count;
  28958. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28959. ++count;
  28960. if (count > 1) {
  28961. ++gCount;
  28962. }
  28963. ;
  28964. });
  28965. if (gCount > 1) {
  28966. console.log(triangle, gCount);
  28967. }
  28968. return gCount > 1;
  28969. };
  28970. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28971. var _this = this;
  28972. var targetCount = ~~(this.triangles.length * settings.quality);
  28973. var deletedTriangles = 0;
  28974. var triangleCount = this.triangles.length;
  28975. var iterationFunction = function (iteration, callback) {
  28976. setTimeout(function () {
  28977. if (iteration % 5 === 0) {
  28978. _this.updateMesh(iteration === 0);
  28979. }
  28980. for (var i = 0; i < _this.triangles.length; ++i) {
  28981. _this.triangles[i].isDirty = false;
  28982. }
  28983. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28984. var trianglesIterator = function (i) {
  28985. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28986. var t = _this.triangles[tIdx];
  28987. if (!t)
  28988. return;
  28989. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28990. return;
  28991. }
  28992. for (var j = 0; j < 3; ++j) {
  28993. if (t.error[j] < threshold) {
  28994. var deleted0 = [];
  28995. var deleted1 = [];
  28996. var v0 = t.vertices[j];
  28997. var v1 = t.vertices[(j + 1) % 3];
  28998. if (v0.isBorder !== v1.isBorder)
  28999. continue;
  29000. var p = BABYLON.Vector3.Zero();
  29001. var n = BABYLON.Vector3.Zero();
  29002. var uv = BABYLON.Vector2.Zero();
  29003. var color = new BABYLON.Color4(0, 0, 0, 1);
  29004. _this.calculateError(v0, v1, p, n, uv, color);
  29005. var delTr = [];
  29006. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29007. continue;
  29008. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29009. continue;
  29010. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29011. continue;
  29012. var uniqueArray = [];
  29013. delTr.forEach(function (deletedT) {
  29014. if (uniqueArray.indexOf(deletedT) === -1) {
  29015. deletedT.deletePending = true;
  29016. uniqueArray.push(deletedT);
  29017. }
  29018. });
  29019. if (uniqueArray.length % 2 != 0) {
  29020. continue;
  29021. }
  29022. v0.q = v1.q.add(v0.q);
  29023. v0.updatePosition(p);
  29024. var tStart = _this.references.length;
  29025. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29026. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29027. var tCount = _this.references.length - tStart;
  29028. if (tCount <= v0.triangleCount) {
  29029. if (tCount) {
  29030. for (var c = 0; c < tCount; c++) {
  29031. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29032. }
  29033. }
  29034. }
  29035. else {
  29036. v0.triangleStart = tStart;
  29037. }
  29038. v0.triangleCount = tCount;
  29039. break;
  29040. }
  29041. }
  29042. };
  29043. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  29044. return (triangleCount - deletedTriangles <= targetCount);
  29045. });
  29046. }, 0);
  29047. };
  29048. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29049. if (triangleCount - deletedTriangles <= targetCount)
  29050. loop.breakLoop();
  29051. else {
  29052. iterationFunction(loop.index, function () {
  29053. loop.executeNext();
  29054. });
  29055. }
  29056. }, function () {
  29057. setTimeout(function () {
  29058. //reconstruct this part of the mesh
  29059. _this.reconstructMesh(submeshIndex);
  29060. successCallback();
  29061. }, 0);
  29062. });
  29063. };
  29064. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29065. var _this = this;
  29066. this.vertices = [];
  29067. this.triangles = [];
  29068. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29069. var indices = this._mesh.getIndices();
  29070. var submesh = this._mesh.subMeshes[submeshIndex];
  29071. var findInVertices = function (positionToSearch) {
  29072. if (optimizeMesh) {
  29073. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29074. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29075. return _this.vertices[ii];
  29076. }
  29077. }
  29078. }
  29079. return null;
  29080. };
  29081. var vertexReferences = [];
  29082. var vertexInit = function (i) {
  29083. var offset = i + submesh.verticesStart;
  29084. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29085. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29086. vertex.originalOffsets.push(offset);
  29087. if (vertex.id == _this.vertices.length) {
  29088. _this.vertices.push(vertex);
  29089. }
  29090. vertexReferences.push(vertex.id);
  29091. };
  29092. //var totalVertices = mesh.getTotalVertices();
  29093. var totalVertices = submesh.verticesCount;
  29094. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29095. var indicesInit = function (i) {
  29096. var offset = (submesh.indexStart / 3) + i;
  29097. var pos = (offset * 3);
  29098. var i0 = indices[pos + 0];
  29099. var i1 = indices[pos + 1];
  29100. var i2 = indices[pos + 2];
  29101. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29102. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29103. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29104. var triangle = new DecimationTriangle([v0, v1, v2]);
  29105. triangle.originalOffset = pos;
  29106. _this.triangles.push(triangle);
  29107. };
  29108. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29109. _this.init(callback);
  29110. });
  29111. });
  29112. };
  29113. QuadraticErrorSimplification.prototype.init = function (callback) {
  29114. var _this = this;
  29115. var triangleInit1 = function (i) {
  29116. var t = _this.triangles[i];
  29117. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29118. for (var j = 0; j < 3; j++) {
  29119. 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))));
  29120. }
  29121. };
  29122. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29123. var triangleInit2 = function (i) {
  29124. var t = _this.triangles[i];
  29125. for (var j = 0; j < 3; ++j) {
  29126. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29127. }
  29128. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29129. };
  29130. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29131. _this.initialized = true;
  29132. callback();
  29133. });
  29134. });
  29135. };
  29136. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29137. var newTriangles = [];
  29138. var i;
  29139. for (i = 0; i < this.vertices.length; ++i) {
  29140. this.vertices[i].triangleCount = 0;
  29141. }
  29142. var t;
  29143. var j;
  29144. for (i = 0; i < this.triangles.length; ++i) {
  29145. if (!this.triangles[i].deleted) {
  29146. t = this.triangles[i];
  29147. for (j = 0; j < 3; ++j) {
  29148. t.vertices[j].triangleCount = 1;
  29149. }
  29150. newTriangles.push(t);
  29151. }
  29152. }
  29153. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  29154. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  29155. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  29156. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  29157. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29158. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29159. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29160. var vertexCount = 0;
  29161. for (i = 0; i < this.vertices.length; ++i) {
  29162. var vertex = this.vertices[i];
  29163. vertex.id = vertexCount;
  29164. if (vertex.triangleCount) {
  29165. vertex.originalOffsets.forEach(function (originalOffset) {
  29166. newPositionData.push(vertex.position.x);
  29167. newPositionData.push(vertex.position.y);
  29168. newPositionData.push(vertex.position.z);
  29169. newNormalData.push(normalData[originalOffset * 3]);
  29170. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29171. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29172. if (uvs && uvs.length) {
  29173. newUVsData.push(uvs[(originalOffset * 2)]);
  29174. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29175. }
  29176. else if (colorsData && colorsData.length) {
  29177. newColorsData.push(colorsData[(originalOffset * 4)]);
  29178. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29179. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29180. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29181. }
  29182. ++vertexCount;
  29183. });
  29184. }
  29185. }
  29186. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29187. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29188. var submeshesArray = this._reconstructedMesh.subMeshes;
  29189. this._reconstructedMesh.subMeshes = [];
  29190. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29191. var originalIndices = this._mesh.getIndices();
  29192. for (i = 0; i < newTriangles.length; ++i) {
  29193. var t = newTriangles[i];
  29194. //now get the new referencing point for each vertex
  29195. [0, 1, 2].forEach(function (idx) {
  29196. var id = originalIndices[t.originalOffset + idx];
  29197. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29198. if (offset < 0)
  29199. offset = 0;
  29200. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29201. });
  29202. }
  29203. //overwriting the old vertex buffers and indices.
  29204. this._reconstructedMesh.setIndices(newIndicesArray);
  29205. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29206. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29207. if (newUVsData.length > 0)
  29208. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29209. if (newColorsData.length > 0)
  29210. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29211. //create submesh
  29212. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29213. if (submeshIndex > 0) {
  29214. this._reconstructedMesh.subMeshes = [];
  29215. submeshesArray.forEach(function (submesh) {
  29216. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29217. });
  29218. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29219. }
  29220. };
  29221. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29222. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29223. this._reconstructedMesh.material = this._mesh.material;
  29224. this._reconstructedMesh.parent = this._mesh.parent;
  29225. this._reconstructedMesh.isVisible = false;
  29226. };
  29227. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29228. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29229. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29230. if (t.deleted)
  29231. continue;
  29232. var s = this.references[vertex1.triangleStart + i].vertexId;
  29233. var v1 = t.vertices[(s + 1) % 3];
  29234. var v2 = t.vertices[(s + 2) % 3];
  29235. if ((v1 === vertex2 || v2 === vertex2)) {
  29236. deletedArray[i] = true;
  29237. delTr.push(t);
  29238. continue;
  29239. }
  29240. var d1 = v1.position.subtract(point);
  29241. d1 = d1.normalize();
  29242. var d2 = v2.position.subtract(point);
  29243. d2 = d2.normalize();
  29244. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29245. return true;
  29246. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29247. deletedArray[i] = false;
  29248. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29249. return true;
  29250. }
  29251. return false;
  29252. };
  29253. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29254. var newDeleted = deletedTriangles;
  29255. for (var i = 0; i < vertex.triangleCount; ++i) {
  29256. var ref = this.references[vertex.triangleStart + i];
  29257. var t = this.triangles[ref.triangleId];
  29258. if (t.deleted)
  29259. continue;
  29260. if (deletedArray[i] && t.deletePending) {
  29261. t.deleted = true;
  29262. newDeleted++;
  29263. continue;
  29264. }
  29265. t.vertices[ref.vertexId] = origVertex;
  29266. t.isDirty = true;
  29267. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29268. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29269. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29270. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29271. this.references.push(ref);
  29272. }
  29273. return newDeleted;
  29274. };
  29275. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29276. for (var i = 0; i < this.vertices.length; ++i) {
  29277. var vCount = [];
  29278. var vId = [];
  29279. var v = this.vertices[i];
  29280. var j;
  29281. for (j = 0; j < v.triangleCount; ++j) {
  29282. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29283. for (var ii = 0; ii < 3; ii++) {
  29284. var ofs = 0;
  29285. var vv = triangle.vertices[ii];
  29286. while (ofs < vCount.length) {
  29287. if (vId[ofs] === vv.id)
  29288. break;
  29289. ++ofs;
  29290. }
  29291. if (ofs === vCount.length) {
  29292. vCount.push(1);
  29293. vId.push(vv.id);
  29294. }
  29295. else {
  29296. vCount[ofs]++;
  29297. }
  29298. }
  29299. }
  29300. for (j = 0; j < vCount.length; ++j) {
  29301. if (vCount[j] === 1) {
  29302. this.vertices[vId[j]].isBorder = true;
  29303. }
  29304. else {
  29305. this.vertices[vId[j]].isBorder = false;
  29306. }
  29307. }
  29308. }
  29309. };
  29310. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29311. if (identifyBorders === void 0) { identifyBorders = false; }
  29312. var i;
  29313. if (!identifyBorders) {
  29314. var newTrianglesVector = [];
  29315. for (i = 0; i < this.triangles.length; ++i) {
  29316. if (!this.triangles[i].deleted) {
  29317. newTrianglesVector.push(this.triangles[i]);
  29318. }
  29319. }
  29320. this.triangles = newTrianglesVector;
  29321. }
  29322. for (i = 0; i < this.vertices.length; ++i) {
  29323. this.vertices[i].triangleCount = 0;
  29324. this.vertices[i].triangleStart = 0;
  29325. }
  29326. var t;
  29327. var j;
  29328. var v;
  29329. for (i = 0; i < this.triangles.length; ++i) {
  29330. t = this.triangles[i];
  29331. for (j = 0; j < 3; ++j) {
  29332. v = t.vertices[j];
  29333. v.triangleCount++;
  29334. }
  29335. }
  29336. var tStart = 0;
  29337. for (i = 0; i < this.vertices.length; ++i) {
  29338. this.vertices[i].triangleStart = tStart;
  29339. tStart += this.vertices[i].triangleCount;
  29340. this.vertices[i].triangleCount = 0;
  29341. }
  29342. var newReferences = new Array(this.triangles.length * 3);
  29343. for (i = 0; i < this.triangles.length; ++i) {
  29344. t = this.triangles[i];
  29345. for (j = 0; j < 3; ++j) {
  29346. v = t.vertices[j];
  29347. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29348. v.triangleCount++;
  29349. }
  29350. }
  29351. this.references = newReferences;
  29352. if (identifyBorders) {
  29353. this.identifyBorder();
  29354. }
  29355. };
  29356. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29357. var x = point.x;
  29358. var y = point.y;
  29359. var z = point.z;
  29360. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29361. };
  29362. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29363. var q = vertex1.q.add(vertex2.q);
  29364. var border = vertex1.isBorder && vertex2.isBorder;
  29365. var error = 0;
  29366. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29367. if (qDet !== 0 && !border) {
  29368. if (!pointResult) {
  29369. pointResult = BABYLON.Vector3.Zero();
  29370. }
  29371. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29372. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29373. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29374. error = this.vertexError(q, pointResult);
  29375. }
  29376. else {
  29377. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29378. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29379. var error1 = this.vertexError(q, vertex1.position);
  29380. var error2 = this.vertexError(q, vertex2.position);
  29381. var error3 = this.vertexError(q, p3);
  29382. error = Math.min(error1, error2, error3);
  29383. if (error === error1) {
  29384. if (pointResult) {
  29385. pointResult.copyFrom(vertex1.position);
  29386. }
  29387. }
  29388. else if (error === error2) {
  29389. if (pointResult) {
  29390. pointResult.copyFrom(vertex2.position);
  29391. }
  29392. }
  29393. else {
  29394. if (pointResult) {
  29395. pointResult.copyFrom(p3);
  29396. }
  29397. }
  29398. }
  29399. return error;
  29400. };
  29401. return QuadraticErrorSimplification;
  29402. })();
  29403. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29404. })(BABYLON || (BABYLON = {}));
  29405. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29406. (function (BABYLON) {
  29407. var Analyser = (function () {
  29408. function Analyser(scene) {
  29409. this.SMOOTHING = 0.75;
  29410. this.FFT_SIZE = 512;
  29411. this.BARGRAPHAMPLITUDE = 256;
  29412. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29413. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29414. this._scene = scene;
  29415. this._audioEngine = BABYLON.Engine.audioEngine;
  29416. if (this._audioEngine.canUseWebAudio) {
  29417. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29418. this._webAudioAnalyser.minDecibels = -140;
  29419. this._webAudioAnalyser.maxDecibels = 0;
  29420. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29421. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29422. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29423. }
  29424. }
  29425. Analyser.prototype.getFrequencyBinCount = function () {
  29426. if (this._audioEngine.canUseWebAudio) {
  29427. return this._webAudioAnalyser.frequencyBinCount;
  29428. }
  29429. else {
  29430. return 0;
  29431. }
  29432. };
  29433. Analyser.prototype.getByteFrequencyData = function () {
  29434. if (this._audioEngine.canUseWebAudio) {
  29435. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29436. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29437. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29438. }
  29439. return this._byteFreqs;
  29440. };
  29441. Analyser.prototype.getByteTimeDomainData = function () {
  29442. if (this._audioEngine.canUseWebAudio) {
  29443. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29444. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29445. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29446. }
  29447. return this._byteTime;
  29448. };
  29449. Analyser.prototype.getFloatFrequencyData = function () {
  29450. if (this._audioEngine.canUseWebAudio) {
  29451. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29452. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29453. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29454. }
  29455. return this._floatFreqs;
  29456. };
  29457. Analyser.prototype.drawDebugCanvas = function () {
  29458. var _this = this;
  29459. if (this._audioEngine.canUseWebAudio) {
  29460. if (!this._debugCanvas) {
  29461. this._debugCanvas = document.createElement("canvas");
  29462. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29463. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29464. this._debugCanvas.style.position = "absolute";
  29465. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29466. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29467. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29468. document.body.appendChild(this._debugCanvas);
  29469. this._registerFunc = function () {
  29470. _this.drawDebugCanvas();
  29471. };
  29472. this._scene.registerBeforeRender(this._registerFunc);
  29473. }
  29474. if (this._registerFunc) {
  29475. var workingArray = this.getByteFrequencyData();
  29476. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29477. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29478. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29479. var value = workingArray[i];
  29480. var percent = value / this.BARGRAPHAMPLITUDE;
  29481. var height = this.DEBUGCANVASSIZE.height * percent;
  29482. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29483. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29484. var hue = i / this.getFrequencyBinCount() * 360;
  29485. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29486. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29487. }
  29488. }
  29489. }
  29490. };
  29491. Analyser.prototype.stopDebugCanvas = function () {
  29492. if (this._debugCanvas) {
  29493. this._scene.unregisterBeforeRender(this._registerFunc);
  29494. this._registerFunc = null;
  29495. document.body.removeChild(this._debugCanvas);
  29496. this._debugCanvas = null;
  29497. this._debugCanvasContext = null;
  29498. }
  29499. };
  29500. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29501. if (this._audioEngine.canUseWebAudio) {
  29502. inputAudioNode.connect(this._webAudioAnalyser);
  29503. this._webAudioAnalyser.connect(outputAudioNode);
  29504. }
  29505. };
  29506. Analyser.prototype.dispose = function () {
  29507. if (this._audioEngine.canUseWebAudio) {
  29508. this._webAudioAnalyser.disconnect();
  29509. }
  29510. };
  29511. return Analyser;
  29512. })();
  29513. BABYLON.Analyser = Analyser;
  29514. })(BABYLON || (BABYLON = {}));
  29515. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29516. (function (BABYLON) {
  29517. var DepthRenderer = (function () {
  29518. function DepthRenderer(scene, type) {
  29519. var _this = this;
  29520. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29521. this._viewMatrix = BABYLON.Matrix.Zero();
  29522. this._projectionMatrix = BABYLON.Matrix.Zero();
  29523. this._transformMatrix = BABYLON.Matrix.Zero();
  29524. this._worldViewProjection = BABYLON.Matrix.Zero();
  29525. this._scene = scene;
  29526. var engine = scene.getEngine();
  29527. // Render target
  29528. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29529. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29530. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29531. this._depthMap.refreshRate = 1;
  29532. this._depthMap.renderParticles = false;
  29533. this._depthMap.renderList = null;
  29534. // Custom render function
  29535. var renderSubMesh = function (subMesh) {
  29536. var mesh = subMesh.getRenderingMesh();
  29537. var scene = _this._scene;
  29538. var engine = scene.getEngine();
  29539. // Culling
  29540. engine.setState(subMesh.getMaterial().backFaceCulling);
  29541. // Managing instances
  29542. var batch = mesh._getInstancesRenderList(subMesh._id);
  29543. if (batch.mustReturn) {
  29544. return;
  29545. }
  29546. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29547. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29548. engine.enableEffect(_this._effect);
  29549. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29550. var material = subMesh.getMaterial();
  29551. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29552. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29553. // Alpha test
  29554. if (material && material.needAlphaTesting()) {
  29555. var alphaTexture = material.getAlphaTestTexture();
  29556. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29557. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29558. }
  29559. // Bones
  29560. if (mesh.useBones) {
  29561. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29562. }
  29563. // Draw
  29564. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29565. }
  29566. };
  29567. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29568. var index;
  29569. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29570. renderSubMesh(opaqueSubMeshes.data[index]);
  29571. }
  29572. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29573. renderSubMesh(alphaTestSubMeshes.data[index]);
  29574. }
  29575. };
  29576. }
  29577. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29578. var defines = [];
  29579. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29580. var mesh = subMesh.getMesh();
  29581. var scene = mesh.getScene();
  29582. var material = subMesh.getMaterial();
  29583. // Alpha test
  29584. if (material && material.needAlphaTesting()) {
  29585. defines.push("#define ALPHATEST");
  29586. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29587. attribs.push(BABYLON.VertexBuffer.UVKind);
  29588. defines.push("#define UV1");
  29589. }
  29590. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29591. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29592. defines.push("#define UV2");
  29593. }
  29594. }
  29595. // Bones
  29596. if (mesh.useBones) {
  29597. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29598. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29599. defines.push("#define BONES");
  29600. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29601. }
  29602. // Instances
  29603. if (useInstances) {
  29604. defines.push("#define INSTANCES");
  29605. attribs.push("world0");
  29606. attribs.push("world1");
  29607. attribs.push("world2");
  29608. attribs.push("world3");
  29609. }
  29610. // Get correct effect
  29611. var join = defines.join("\n");
  29612. if (this._cachedDefines !== join) {
  29613. this._cachedDefines = join;
  29614. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29615. }
  29616. return this._effect.isReady();
  29617. };
  29618. DepthRenderer.prototype.getDepthMap = function () {
  29619. return this._depthMap;
  29620. };
  29621. // Methods
  29622. DepthRenderer.prototype.dispose = function () {
  29623. this._depthMap.dispose();
  29624. };
  29625. return DepthRenderer;
  29626. })();
  29627. BABYLON.DepthRenderer = DepthRenderer;
  29628. })(BABYLON || (BABYLON = {}));
  29629. //# sourceMappingURL=babylon.depthRenderer.js.map
  29630. var BABYLON;
  29631. (function (BABYLON) {
  29632. var SSAORenderingPipeline = (function (_super) {
  29633. __extends(SSAORenderingPipeline, _super);
  29634. /**
  29635. * @constructor
  29636. * @param {string} name - The rendering pipeline name
  29637. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29638. * @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 }
  29639. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29640. */
  29641. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29642. var _this = this;
  29643. _super.call(this, scene.getEngine(), name);
  29644. // Members
  29645. /**
  29646. * The PassPostProcess id in the pipeline that contains the original scene color
  29647. * @type {string}
  29648. */
  29649. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29650. /**
  29651. * The SSAO PostProcess id in the pipeline
  29652. * @type {string}
  29653. */
  29654. this.SSAORenderEffect = "SSAORenderEffect";
  29655. /**
  29656. * The horizontal blur PostProcess id in the pipeline
  29657. * @type {string}
  29658. */
  29659. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29660. /**
  29661. * The vertical blur PostProcess id in the pipeline
  29662. * @type {string}
  29663. */
  29664. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29665. /**
  29666. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29667. * @type {string}
  29668. */
  29669. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29670. /**
  29671. * The output strength of the SSAO post-process. Default value is 1.0.
  29672. * @type {number}
  29673. */
  29674. this.totalStrength = 1.0;
  29675. /**
  29676. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29677. * @type {number}
  29678. */
  29679. this.radius = 0.0002;
  29680. /**
  29681. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29682. * Must not be equal to fallOff and superior to fallOff.
  29683. * Default value is 0.0075
  29684. * @type {number}
  29685. */
  29686. this.area = 0.0075;
  29687. /**
  29688. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29689. * Must not be equal to area and inferior to area.
  29690. * Default value is 0.0002
  29691. * @type {number}
  29692. */
  29693. this.fallOff = 0.0002;
  29694. this._firstUpdate = true;
  29695. this._scene = scene;
  29696. // Set up assets
  29697. this._createRandomTexture();
  29698. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29699. var ssaoRatio = ratio.ssaoRatio || ratio;
  29700. var combineRatio = ratio.combineRatio || ratio;
  29701. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29702. this._createSSAOPostProcess(ssaoRatio);
  29703. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29704. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29705. this._createSSAOCombinePostProcess(combineRatio);
  29706. // Set up pipeline
  29707. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29708. return _this._originalColorPostProcess;
  29709. }, true));
  29710. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29711. return _this._ssaoPostProcess;
  29712. }, true));
  29713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29714. return _this._blurHPostProcess;
  29715. }, true));
  29716. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29717. return _this._blurVPostProcess;
  29718. }, true));
  29719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29720. return _this._ssaoCombinePostProcess;
  29721. }, true));
  29722. // Finish
  29723. scene.postProcessRenderPipelineManager.addPipeline(this);
  29724. if (cameras)
  29725. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29726. }
  29727. // Public Methods
  29728. /**
  29729. * Returns the horizontal blur PostProcess
  29730. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29731. */
  29732. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29733. return this._blurHPostProcess;
  29734. };
  29735. /**
  29736. * Returns the vertical blur PostProcess
  29737. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29738. */
  29739. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29740. return this._blurVPostProcess;
  29741. };
  29742. /**
  29743. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29744. */
  29745. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29746. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29747. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29748. this._originalColorPostProcess = undefined;
  29749. this._ssaoPostProcess = undefined;
  29750. this._blurHPostProcess = undefined;
  29751. this._blurVPostProcess = undefined;
  29752. this._ssaoCombinePostProcess = undefined;
  29753. this._randomTexture.dispose();
  29754. if (disableDepthRender)
  29755. this._scene.disableDepthRenderer();
  29756. };
  29757. // Private Methods
  29758. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29759. var _this = this;
  29760. var sampleSphere = [
  29761. 0.5381,
  29762. 0.1856,
  29763. -0.4319,
  29764. 0.1379,
  29765. 0.2486,
  29766. 0.4430,
  29767. 0.3371,
  29768. 0.5679,
  29769. -0.0057,
  29770. -0.6999,
  29771. -0.0451,
  29772. -0.0019,
  29773. 0.0689,
  29774. -0.1598,
  29775. -0.8547,
  29776. 0.0560,
  29777. 0.0069,
  29778. -0.1843,
  29779. -0.0146,
  29780. 0.1402,
  29781. 0.0762,
  29782. 0.0100,
  29783. -0.1924,
  29784. -0.0344,
  29785. -0.3577,
  29786. -0.5301,
  29787. -0.4358,
  29788. -0.3169,
  29789. 0.1063,
  29790. 0.0158,
  29791. 0.0103,
  29792. -0.5869,
  29793. 0.0046,
  29794. -0.0897,
  29795. -0.4940,
  29796. 0.3287,
  29797. 0.7119,
  29798. -0.0154,
  29799. -0.0918,
  29800. -0.0533,
  29801. 0.0596,
  29802. -0.5411,
  29803. 0.0352,
  29804. -0.0631,
  29805. 0.5460,
  29806. -0.4776,
  29807. 0.2847,
  29808. -0.0271
  29809. ];
  29810. var samplesFactor = 1.0 / 16.0;
  29811. 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);
  29812. this._ssaoPostProcess.onApply = function (effect) {
  29813. if (_this._firstUpdate) {
  29814. effect.setArray3("sampleSphere", sampleSphere);
  29815. effect.setFloat("samplesFactor", samplesFactor);
  29816. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29817. _this._firstUpdate = false;
  29818. }
  29819. effect.setFloat("totalStrength", _this.totalStrength);
  29820. effect.setFloat("radius", _this.radius);
  29821. effect.setFloat("area", _this.area);
  29822. effect.setFloat("fallOff", _this.fallOff);
  29823. effect.setTexture("textureSampler", _this._depthTexture);
  29824. effect.setTexture("randomSampler", _this._randomTexture);
  29825. };
  29826. };
  29827. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29828. var _this = this;
  29829. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29830. this._ssaoCombinePostProcess.onApply = function (effect) {
  29831. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29832. };
  29833. };
  29834. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29835. var size = 512;
  29836. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29837. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29838. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29839. var context = this._randomTexture.getContext();
  29840. var rand = function (min, max) {
  29841. return Math.random() * (max - min) + min;
  29842. };
  29843. for (var x = 0; x < size; x++) {
  29844. for (var y = 0; y < size; y++) {
  29845. var randVector = BABYLON.Vector3.Zero();
  29846. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29847. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29848. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29849. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29850. context.fillRect(x, y, 1, 1);
  29851. }
  29852. }
  29853. this._randomTexture.update(false);
  29854. };
  29855. return SSAORenderingPipeline;
  29856. })(BABYLON.PostProcessRenderPipeline);
  29857. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29858. })(BABYLON || (BABYLON = {}));
  29859. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29860. var BABYLON;
  29861. (function (BABYLON) {
  29862. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29863. var VolumetricLightScatteringPostProcess = (function (_super) {
  29864. __extends(VolumetricLightScatteringPostProcess, _super);
  29865. /**
  29866. * @constructor
  29867. * @param {string} name - The post-process name
  29868. * @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)
  29869. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29870. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29871. * @param {number} samples - The post-process quality, default 100
  29872. * @param {number} samplingMode - The post-process filtering mode
  29873. * @param {BABYLON.Engine} engine - The babylon engine
  29874. * @param {boolean} reusable - If the post-process is reusable
  29875. */
  29876. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29877. var _this = this;
  29878. if (samples === void 0) { samples = 100; }
  29879. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29880. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29881. this._screenCoordinates = BABYLON.Vector2.Zero();
  29882. /**
  29883. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29884. * @type {boolean}
  29885. */
  29886. this.useCustomMeshPosition = false;
  29887. /**
  29888. * If the post-process should inverse the light scattering direction
  29889. * @type {boolean}
  29890. */
  29891. this.invert = true;
  29892. /**
  29893. * Array containing the excluded meshes not rendered in the internal pass
  29894. */
  29895. this.excludedMeshes = new Array();
  29896. this.exposure = 0.3;
  29897. this.decay = 0.96815;
  29898. this.weight = 0.58767;
  29899. this.density = 0.926;
  29900. var scene = camera.getScene();
  29901. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29902. // Configure mesh
  29903. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29904. // Configure
  29905. this._createPass(scene, ratio.passRatio || ratio);
  29906. this.onApply = function (effect) {
  29907. _this._updateMeshScreenCoordinates(scene);
  29908. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29909. effect.setFloat("exposure", _this.exposure);
  29910. effect.setFloat("decay", _this.decay);
  29911. effect.setFloat("weight", _this.weight);
  29912. effect.setFloat("density", _this.density);
  29913. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29914. };
  29915. }
  29916. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29917. var mesh = subMesh.getMesh();
  29918. var defines = [];
  29919. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29920. var material = subMesh.getMaterial();
  29921. var needUV = false;
  29922. // Render this.mesh as default
  29923. if (mesh === this.mesh) {
  29924. defines.push("#define BASIC_RENDER");
  29925. defines.push("#define NEED_UV");
  29926. needUV = true;
  29927. }
  29928. // Alpha test
  29929. if (material) {
  29930. if (material.needAlphaTesting() || mesh === this.mesh)
  29931. defines.push("#define ALPHATEST");
  29932. if (material.opacityTexture !== undefined) {
  29933. defines.push("#define OPACITY");
  29934. if (material.opacityTexture.getAlphaFromRGB)
  29935. defines.push("#define OPACITYRGB");
  29936. if (!needUV)
  29937. defines.push("#define NEED_UV");
  29938. }
  29939. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29940. attribs.push(BABYLON.VertexBuffer.UVKind);
  29941. defines.push("#define UV1");
  29942. }
  29943. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29944. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29945. defines.push("#define UV2");
  29946. }
  29947. }
  29948. // Bones
  29949. if (mesh.useBones) {
  29950. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29951. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29952. defines.push("#define BONES");
  29953. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29954. }
  29955. // Instances
  29956. if (useInstances) {
  29957. defines.push("#define INSTANCES");
  29958. attribs.push("world0");
  29959. attribs.push("world1");
  29960. attribs.push("world2");
  29961. attribs.push("world3");
  29962. }
  29963. // Get correct effect
  29964. var join = defines.join("\n");
  29965. if (this._cachedDefines !== join) {
  29966. this._cachedDefines = join;
  29967. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29968. }
  29969. return this._volumetricLightScatteringPass.isReady();
  29970. };
  29971. /**
  29972. * Sets the new light position for light scattering effect
  29973. * @param {BABYLON.Vector3} The new custom light position
  29974. */
  29975. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29976. this._customMeshPosition = position;
  29977. };
  29978. /**
  29979. * Returns the light position for light scattering effect
  29980. * @return {BABYLON.Vector3} The custom light position
  29981. */
  29982. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29983. return this._customMeshPosition;
  29984. };
  29985. /**
  29986. * Disposes the internal assets and detaches the post-process from the camera
  29987. */
  29988. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29989. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29990. if (rttIndex !== -1) {
  29991. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29992. }
  29993. this._volumetricLightScatteringRTT.dispose();
  29994. _super.prototype.dispose.call(this, camera);
  29995. };
  29996. /**
  29997. * Returns the render target texture used by the post-process
  29998. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29999. */
  30000. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  30001. return this._volumetricLightScatteringRTT;
  30002. };
  30003. // Private methods
  30004. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  30005. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  30006. return true;
  30007. }
  30008. return false;
  30009. };
  30010. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  30011. var _this = this;
  30012. var engine = scene.getEngine();
  30013. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  30014. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30015. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30016. this._volumetricLightScatteringRTT.renderList = null;
  30017. this._volumetricLightScatteringRTT.renderParticles = false;
  30018. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  30019. // Custom render function for submeshes
  30020. var renderSubMesh = function (subMesh) {
  30021. var mesh = subMesh.getRenderingMesh();
  30022. if (_this._meshExcluded(mesh)) {
  30023. return;
  30024. }
  30025. var scene = mesh.getScene();
  30026. var engine = scene.getEngine();
  30027. // Culling
  30028. engine.setState(subMesh.getMaterial().backFaceCulling);
  30029. // Managing instances
  30030. var batch = mesh._getInstancesRenderList(subMesh._id);
  30031. if (batch.mustReturn) {
  30032. return;
  30033. }
  30034. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30035. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30036. engine.enableEffect(_this._volumetricLightScatteringPass);
  30037. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  30038. var material = subMesh.getMaterial();
  30039. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  30040. // Alpha test
  30041. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  30042. var alphaTexture = material.getAlphaTestTexture();
  30043. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  30044. if (alphaTexture) {
  30045. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30046. }
  30047. if (material.opacityTexture !== undefined) {
  30048. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  30049. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  30050. }
  30051. }
  30052. // Bones
  30053. if (mesh.useBones) {
  30054. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30055. }
  30056. // Draw
  30057. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  30058. }
  30059. };
  30060. // Render target texture callbacks
  30061. var savedSceneClearColor;
  30062. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  30063. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  30064. savedSceneClearColor = scene.clearColor;
  30065. scene.clearColor = sceneClearColor;
  30066. };
  30067. this._volumetricLightScatteringRTT.onAfterRender = function () {
  30068. scene.clearColor = savedSceneClearColor;
  30069. };
  30070. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  30071. var engine = scene.getEngine();
  30072. var index;
  30073. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30074. renderSubMesh(opaqueSubMeshes.data[index]);
  30075. }
  30076. engine.setAlphaTesting(true);
  30077. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30078. renderSubMesh(alphaTestSubMeshes.data[index]);
  30079. }
  30080. engine.setAlphaTesting(false);
  30081. if (transparentSubMeshes.length) {
  30082. for (index = 0; index < transparentSubMeshes.length; index++) {
  30083. var submesh = transparentSubMeshes.data[index];
  30084. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  30085. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  30086. }
  30087. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  30088. sortedArray.sort(function (a, b) {
  30089. // Alpha index first
  30090. if (a._alphaIndex > b._alphaIndex) {
  30091. return 1;
  30092. }
  30093. if (a._alphaIndex < b._alphaIndex) {
  30094. return -1;
  30095. }
  30096. // Then distance to camera
  30097. if (a._distanceToCamera < b._distanceToCamera) {
  30098. return 1;
  30099. }
  30100. if (a._distanceToCamera > b._distanceToCamera) {
  30101. return -1;
  30102. }
  30103. return 0;
  30104. });
  30105. // Render sub meshes
  30106. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  30107. for (index = 0; index < sortedArray.length; index++) {
  30108. renderSubMesh(sortedArray[index]);
  30109. }
  30110. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30111. }
  30112. };
  30113. };
  30114. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  30115. var transform = scene.getTransformMatrix();
  30116. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  30117. this._screenCoordinates.x = pos.x / this._viewPort.width;
  30118. this._screenCoordinates.y = pos.y / this._viewPort.height;
  30119. if (this.invert)
  30120. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  30121. };
  30122. // Static methods
  30123. /**
  30124. * Creates a default mesh for the Volumeric Light Scattering post-process
  30125. * @param {string} The mesh name
  30126. * @param {BABYLON.Scene} The scene where to create the mesh
  30127. * @return {BABYLON.Mesh} the default mesh
  30128. */
  30129. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  30130. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  30131. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  30132. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  30133. return mesh;
  30134. };
  30135. return VolumetricLightScatteringPostProcess;
  30136. })(BABYLON.PostProcess);
  30137. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  30138. })(BABYLON || (BABYLON = {}));
  30139. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  30140. var BABYLON;
  30141. (function (BABYLON) {
  30142. var LensRenderingPipeline = (function (_super) {
  30143. __extends(LensRenderingPipeline, _super);
  30144. /**
  30145. * @constructor
  30146. *
  30147. * Effect parameters are as follow:
  30148. * {
  30149. * chromatic_aberration: number; // from 0 to x (1 for realism)
  30150. * edge_blur: number; // from 0 to x (1 for realism)
  30151. * distortion: number; // from 0 to x (1 for realism)
  30152. * grain_amount: number; // from 0 to 1
  30153. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  30154. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  30155. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  30156. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  30157. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  30158. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  30159. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  30160. * }
  30161. * Note: if an effect parameter is unset, effect is disabled
  30162. *
  30163. * @param {string} name - The rendering pipeline name
  30164. * @param {object} parameters - An object containing all parameters (see above)
  30165. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30166. * @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)
  30167. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30168. */
  30169. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  30170. var _this = this;
  30171. if (ratio === void 0) { ratio = 1.0; }
  30172. _super.call(this, scene.getEngine(), name);
  30173. // Lens effects can be of the following:
  30174. // - chromatic aberration (slight shift of RGB colors)
  30175. // - blur on the edge of the lens
  30176. // - lens distortion
  30177. // - depth-of-field blur & highlights enhancing
  30178. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  30179. // - grain effect (noise or custom texture)
  30180. // Two additional texture samplers are needed:
  30181. // - depth map (for depth-of-field)
  30182. // - grain texture
  30183. /**
  30184. * The chromatic aberration PostProcess id in the pipeline
  30185. * @type {string}
  30186. */
  30187. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  30188. /**
  30189. * The highlights enhancing PostProcess id in the pipeline
  30190. * @type {string}
  30191. */
  30192. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  30193. /**
  30194. * The depth-of-field PostProcess id in the pipeline
  30195. * @type {string}
  30196. */
  30197. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  30198. this._scene = scene;
  30199. // Fetch texture samplers
  30200. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30201. if (parameters.grain_texture) {
  30202. this._grainTexture = parameters.grain_texture;
  30203. }
  30204. else {
  30205. this._createGrainTexture();
  30206. }
  30207. // save parameters
  30208. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  30209. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  30210. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  30211. this._distortion = parameters.distortion ? parameters.distortion : 0;
  30212. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  30213. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  30214. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  30215. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  30216. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  30217. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  30218. // Create effects
  30219. this._createChromaticAberrationPostProcess(ratio);
  30220. this._createHighlightsPostProcess(ratio);
  30221. this._createDepthOfFieldPostProcess(ratio);
  30222. // Set up pipeline
  30223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  30224. return _this._chromaticAberrationPostProcess;
  30225. }, true));
  30226. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  30227. return _this._highlightsPostProcess;
  30228. }, true));
  30229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  30230. return _this._depthOfFieldPostProcess;
  30231. }, true));
  30232. if (this._highlightsGain == -1) {
  30233. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30234. }
  30235. // Finish
  30236. scene.postProcessRenderPipelineManager.addPipeline(this);
  30237. if (cameras) {
  30238. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30239. }
  30240. }
  30241. // public methods (self explanatory)
  30242. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30243. this._edgeBlur = amount;
  30244. };
  30245. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30246. this._edgeBlur = 0;
  30247. };
  30248. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30249. this._grainAmount = amount;
  30250. };
  30251. LensRenderingPipeline.prototype.disableGrain = function () {
  30252. this._grainAmount = 0;
  30253. };
  30254. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30255. this._chromaticAberration = amount;
  30256. };
  30257. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30258. this._chromaticAberration = 0;
  30259. };
  30260. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30261. this._distortion = amount;
  30262. };
  30263. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30264. this._distortion = 0;
  30265. };
  30266. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30267. this._dofDepth = amount;
  30268. };
  30269. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30270. this._dofDepth = -1;
  30271. };
  30272. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30273. this._dofAperture = amount;
  30274. };
  30275. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30276. this._dofPentagon = true;
  30277. };
  30278. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30279. this._dofPentagon = false;
  30280. };
  30281. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30282. this._blurNoise = true;
  30283. };
  30284. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30285. this._blurNoise = false;
  30286. };
  30287. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30288. this._highlightsGain = amount;
  30289. };
  30290. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30291. if (this._highlightsGain == -1) {
  30292. this._highlightsGain = 1.0;
  30293. }
  30294. this._highlightsThreshold = amount;
  30295. };
  30296. LensRenderingPipeline.prototype.disableHighlights = function () {
  30297. this._highlightsGain = -1;
  30298. };
  30299. /**
  30300. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30301. */
  30302. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30303. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30304. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30305. this._chromaticAberrationPostProcess = undefined;
  30306. this._highlightsPostProcess = undefined;
  30307. this._depthOfFieldPostProcess = undefined;
  30308. this._grainTexture.dispose();
  30309. if (disableDepthRender)
  30310. this._scene.disableDepthRenderer();
  30311. };
  30312. // colors shifting and distortion
  30313. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30314. var _this = this;
  30315. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30316. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30317. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30318. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30319. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30320. };
  30321. };
  30322. // highlights enhancing
  30323. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30324. var _this = this;
  30325. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30326. this._highlightsPostProcess.onApply = function (effect) {
  30327. effect.setFloat('gain', _this._highlightsGain);
  30328. effect.setFloat('threshold', _this._highlightsThreshold);
  30329. effect.setBool('pentagon', _this._dofPentagon);
  30330. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30331. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30332. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30333. };
  30334. };
  30335. // colors shifting and distortion
  30336. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30337. var _this = this;
  30338. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30339. "focus_depth",
  30340. "aperture",
  30341. "pentagon",
  30342. "maxZ",
  30343. "edge_blur",
  30344. "chromatic_aberration",
  30345. "distortion",
  30346. "blur_noise",
  30347. "grain_amount",
  30348. "screen_width",
  30349. "screen_height",
  30350. "highlights"
  30351. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30352. this._depthOfFieldPostProcess.onApply = function (effect) {
  30353. effect.setBool('blur_noise', _this._blurNoise);
  30354. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30355. effect.setFloat('grain_amount', _this._grainAmount);
  30356. effect.setTexture("depthSampler", _this._depthTexture);
  30357. effect.setTexture("grainSampler", _this._grainTexture);
  30358. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30359. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30360. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30361. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30362. effect.setFloat('distortion', _this._distortion);
  30363. effect.setFloat('focus_depth', _this._dofDepth);
  30364. effect.setFloat('aperture', _this._dofAperture);
  30365. effect.setFloat('edge_blur', _this._edgeBlur);
  30366. effect.setBool('highlights', (_this._highlightsGain != -1));
  30367. };
  30368. };
  30369. // creates a black and white random noise texture, 512x512
  30370. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30371. var size = 512;
  30372. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30373. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30374. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30375. var context = this._grainTexture.getContext();
  30376. var rand = function (min, max) {
  30377. return Math.random() * (max - min) + min;
  30378. };
  30379. var value;
  30380. for (var x = 0; x < size; x++) {
  30381. for (var y = 0; y < size; y++) {
  30382. value = Math.floor(rand(0.42, 0.58) * 255);
  30383. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30384. context.fillRect(x, y, 1, 1);
  30385. }
  30386. }
  30387. this._grainTexture.update(false);
  30388. };
  30389. return LensRenderingPipeline;
  30390. })(BABYLON.PostProcessRenderPipeline);
  30391. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30392. })(BABYLON || (BABYLON = {}));
  30393. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30394. // This post-process allows the modification of rendered colors by using
  30395. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30396. //
  30397. // The object needs to be provided an url to a texture containing the color
  30398. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30399. // Use an image editing software to tweak the LUT to match your needs.
  30400. //
  30401. // For an example of a color LUT, see here:
  30402. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30403. // For explanations on color grading, see here:
  30404. // http://udn.epicgames.com/Three/ColorGrading.html
  30405. //
  30406. var BABYLON;
  30407. (function (BABYLON) {
  30408. var ColorCorrectionPostProcess = (function (_super) {
  30409. __extends(ColorCorrectionPostProcess, _super);
  30410. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30411. var _this = this;
  30412. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30413. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30414. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30415. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30416. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30417. this.onApply = function (effect) {
  30418. effect.setTexture("colorTable", _this._colorTableTexture);
  30419. };
  30420. }
  30421. return ColorCorrectionPostProcess;
  30422. })(BABYLON.PostProcess);
  30423. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30424. })(BABYLON || (BABYLON = {}));
  30425. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30426. (function (BABYLON) {
  30427. var SmartCollection = (function () {
  30428. function SmartCollection(capacity) {
  30429. if (capacity === void 0) { capacity = 10; }
  30430. this.count = 0;
  30431. this._initialCapacity = capacity;
  30432. this.items = {};
  30433. this._keys = new Array(this._initialCapacity);
  30434. }
  30435. SmartCollection.prototype.add = function (key, item) {
  30436. if (this.items[key] != undefined) {
  30437. return -1;
  30438. }
  30439. this.items[key] = item;
  30440. //literal keys are always strings, but we keep source type of key in _keys array
  30441. this._keys[this.count++] = key;
  30442. if (this.count > this._keys.length) {
  30443. this._keys.length *= 2;
  30444. }
  30445. return this.count;
  30446. };
  30447. SmartCollection.prototype.remove = function (key) {
  30448. if (this.items[key] == undefined) {
  30449. return -1;
  30450. }
  30451. return this.removeItemOfIndex(this.indexOf(key));
  30452. };
  30453. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30454. if (index < this.count && index > -1) {
  30455. delete this.items[this._keys[index]];
  30456. while (index < this.count) {
  30457. this._keys[index] = this._keys[index + 1];
  30458. index++;
  30459. }
  30460. }
  30461. else {
  30462. return -1;
  30463. }
  30464. return --this.count;
  30465. };
  30466. SmartCollection.prototype.indexOf = function (key) {
  30467. for (var i = 0; i !== this.count; i++) {
  30468. if (this._keys[i] === key) {
  30469. return i;
  30470. }
  30471. }
  30472. return -1;
  30473. };
  30474. SmartCollection.prototype.item = function (key) {
  30475. return this.items[key];
  30476. };
  30477. SmartCollection.prototype.getAllKeys = function () {
  30478. if (this.count > 0) {
  30479. var keys = new Array(this.count);
  30480. for (var i = 0; i < this.count; i++) {
  30481. keys[i] = this._keys[i];
  30482. }
  30483. return keys;
  30484. }
  30485. else {
  30486. return undefined;
  30487. }
  30488. };
  30489. SmartCollection.prototype.getKeyByIndex = function (index) {
  30490. if (index < this.count && index > -1) {
  30491. return this._keys[index];
  30492. }
  30493. else {
  30494. return undefined;
  30495. }
  30496. };
  30497. SmartCollection.prototype.getItemByIndex = function (index) {
  30498. if (index < this.count && index > -1) {
  30499. return this.items[this._keys[index]];
  30500. }
  30501. else {
  30502. return undefined;
  30503. }
  30504. };
  30505. SmartCollection.prototype.empty = function () {
  30506. if (this.count > 0) {
  30507. this.count = 0;
  30508. this.items = {};
  30509. this._keys = new Array(this._initialCapacity);
  30510. }
  30511. };
  30512. SmartCollection.prototype.forEach = function (block) {
  30513. var key;
  30514. for (key in this.items) {
  30515. if (this.items.hasOwnProperty(key)) {
  30516. block(this.items[key]);
  30517. }
  30518. }
  30519. };
  30520. return SmartCollection;
  30521. })();
  30522. BABYLON.SmartCollection = SmartCollection;
  30523. })(BABYLON || (BABYLON = {}));
  30524. //# sourceMappingURL=babylon.smartCollection.js.map