babylon.scene.ts 245 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084
  1. module BABYLON {
  2. /**
  3. * Define an interface for all classes that will hold resources
  4. */
  5. export interface IDisposable {
  6. /**
  7. * Releases all held resources
  8. */
  9. dispose(): void;
  10. }
  11. /**
  12. * Interface used to let developers provide their own mesh selection mechanism
  13. */
  14. export interface IActiveMeshCandidateProvider {
  15. /**
  16. * Return the list of active meshes
  17. * @param scene defines the current scene
  18. * @returns the list of active meshes
  19. */
  20. getMeshes(scene: Scene): AbstractMesh[];
  21. /**
  22. * Indicates if the meshes have been checked to make sure they are isEnabled()
  23. */
  24. readonly checksIsEnabled: boolean;
  25. }
  26. /** @hidden */
  27. class ClickInfo {
  28. private _singleClick = false;
  29. private _doubleClick = false;
  30. private _hasSwiped = false;
  31. private _ignore = false;
  32. public get singleClick(): boolean {
  33. return this._singleClick;
  34. }
  35. public get doubleClick(): boolean {
  36. return this._doubleClick;
  37. }
  38. public get hasSwiped(): boolean {
  39. return this._hasSwiped;
  40. }
  41. public get ignore(): boolean {
  42. return this._ignore;
  43. }
  44. public set singleClick(b: boolean) {
  45. this._singleClick = b;
  46. }
  47. public set doubleClick(b: boolean) {
  48. this._doubleClick = b;
  49. }
  50. public set hasSwiped(b: boolean) {
  51. this._hasSwiped = b;
  52. }
  53. public set ignore(b: boolean) {
  54. this._ignore = b;
  55. }
  56. }
  57. /**
  58. * This class is used by the onRenderingGroupObservable
  59. */
  60. export class RenderingGroupInfo {
  61. /**
  62. * The Scene that being rendered
  63. */
  64. scene: Scene;
  65. /**
  66. * The camera currently used for the rendering pass
  67. */
  68. camera: Nullable<Camera>;
  69. /**
  70. * The ID of the renderingGroup being processed
  71. */
  72. renderingGroupId: number;
  73. /**
  74. * The rendering stage, can be either STAGE_PRECLEAR, STAGE_PREOPAQUE, STAGE_PRETRANSPARENT, STAGE_POSTTRANSPARENT
  75. */
  76. renderStage: number;
  77. /**
  78. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  79. * This stage will be fired no matter what
  80. */
  81. static STAGE_PRECLEAR = 1;
  82. /**
  83. * Called before opaque object are rendered.
  84. * This stage will be fired only if there's 3D Opaque content to render
  85. */
  86. static STAGE_PREOPAQUE = 2;
  87. /**
  88. * Called after the opaque objects are rendered and before the transparent ones
  89. * This stage will be fired only if there's 3D transparent content to render
  90. */
  91. static STAGE_PRETRANSPARENT = 3;
  92. /**
  93. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  94. * This stage will be fired no matter what
  95. */
  96. static STAGE_POSTTRANSPARENT = 4;
  97. }
  98. /**
  99. * Represents a scene to be rendered by the engine.
  100. * @see http://doc.babylonjs.com/features/scene
  101. */
  102. export class Scene implements IAnimatable {
  103. // Statics
  104. private static _FOGMODE_NONE = 0;
  105. private static _FOGMODE_EXP = 1;
  106. private static _FOGMODE_EXP2 = 2;
  107. private static _FOGMODE_LINEAR = 3;
  108. private static _uniqueIdCounter = 0;
  109. /**
  110. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  111. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112. */
  113. public static MinDeltaTime = 1.0;
  114. /**
  115. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  116. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  117. */
  118. public static MaxDeltaTime = 1000.0;
  119. /** The fog is deactivated */
  120. public static get FOGMODE_NONE(): number {
  121. return Scene._FOGMODE_NONE;
  122. }
  123. /** The fog density is following an exponential function */
  124. public static get FOGMODE_EXP(): number {
  125. return Scene._FOGMODE_EXP;
  126. }
  127. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  128. public static get FOGMODE_EXP2(): number {
  129. return Scene._FOGMODE_EXP2;
  130. }
  131. /** The fog density is following a linear function. */
  132. public static get FOGMODE_LINEAR(): number {
  133. return Scene._FOGMODE_LINEAR;
  134. }
  135. // Members
  136. /**
  137. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  138. */
  139. public autoClear = true;
  140. /**
  141. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  142. */
  143. public autoClearDepthAndStencil = true;
  144. /**
  145. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  146. */
  147. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  148. /**
  149. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  150. */
  151. public ambientColor = new Color3(0, 0, 0);
  152. /** @hidden */
  153. public _environmentBRDFTexture: BaseTexture;
  154. /** @hidden */
  155. protected _environmentTexture: BaseTexture;
  156. /**
  157. * Texture used in all pbr material as the reflection texture.
  158. * As in the majority of the scene they are the same (exception for multi room and so on),
  159. * this is easier to reference from here than from all the materials.
  160. */
  161. public get environmentTexture(): BaseTexture {
  162. return this._environmentTexture;
  163. }
  164. /**
  165. * Texture used in all pbr material as the reflection texture.
  166. * As in the majority of the scene they are the same (exception for multi room and so on),
  167. * this is easier to set here than in all the materials.
  168. */
  169. public set environmentTexture(value: BaseTexture) {
  170. if (this._environmentTexture === value) {
  171. return;
  172. }
  173. this._environmentTexture = value;
  174. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  175. }
  176. /** @hidden */
  177. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  178. /**
  179. * Default image processing configuration used either in the rendering
  180. * Forward main pass or through the imageProcessingPostProcess if present.
  181. * As in the majority of the scene they are the same (exception for multi camera),
  182. * this is easier to reference from here than from all the materials and post process.
  183. *
  184. * No setter as we it is a shared configuration, you can set the values instead.
  185. */
  186. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  187. return this._imageProcessingConfiguration;
  188. }
  189. private _forceWireframe = false;
  190. /**
  191. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  192. */
  193. public set forceWireframe(value: boolean) {
  194. if (this._forceWireframe === value) {
  195. return;
  196. }
  197. this._forceWireframe = value;
  198. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  199. }
  200. public get forceWireframe(): boolean {
  201. return this._forceWireframe;
  202. }
  203. private _forcePointsCloud = false;
  204. /**
  205. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  206. */
  207. public set forcePointsCloud(value: boolean) {
  208. if (this._forcePointsCloud === value) {
  209. return;
  210. }
  211. this._forcePointsCloud = value;
  212. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  213. }
  214. public get forcePointsCloud(): boolean {
  215. return this._forcePointsCloud;
  216. }
  217. /**
  218. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  219. */
  220. public forceShowBoundingBoxes = false;
  221. /**
  222. * Gets or sets the active clipplane
  223. */
  224. public clipPlane: Nullable<Plane>;
  225. /**
  226. * Gets or sets a boolean indicating if animations are enabled
  227. */
  228. public animationsEnabled = true;
  229. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  230. /**
  231. * Gets or sets the animation properties override
  232. */
  233. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  234. return this._animationPropertiesOverride;
  235. }
  236. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  237. this._animationPropertiesOverride = value;
  238. }
  239. /**
  240. * Gets or sets a boolean indicating if a constant deltatime has to be used
  241. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  242. */
  243. public useConstantAnimationDeltaTime = false;
  244. /**
  245. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  246. * Please note that it requires to run a ray cast through the scene on every frame
  247. */
  248. public constantlyUpdateMeshUnderPointer = false;
  249. /**
  250. * Defines the HTML cursor to use when hovering over interactive elements
  251. */
  252. public hoverCursor = "pointer";
  253. /**
  254. * Defines the HTML default cursor to use (empty by default)
  255. */
  256. public defaultCursor: string = "";
  257. /**
  258. * This is used to call preventDefault() on pointer down
  259. * in order to block unwanted artifacts like system double clicks
  260. */
  261. public preventDefaultOnPointerDown = true;
  262. // Metadata
  263. /**
  264. * Gets or sets user defined metadata
  265. */
  266. public metadata: any = null;
  267. /**
  268. * Gets the name of the plugin used to load this scene (null by default)
  269. */
  270. public loadingPluginName: string;
  271. /**
  272. * Use this array to add regular expressions used to disable offline support for specific urls
  273. */
  274. public disableOfflineSupportExceptionRules = new Array<RegExp>();
  275. // Events
  276. private _spritePredicate: (sprite: Sprite) => boolean;
  277. /**
  278. * An event triggered when the scene is disposed.
  279. */
  280. public onDisposeObservable = new Observable<Scene>();
  281. private _onDisposeObserver: Nullable<Observer<Scene>> = null;
  282. /** Sets a function to be executed when this scene is disposed. */
  283. public set onDispose(callback: () => void) {
  284. if (this._onDisposeObserver) {
  285. this.onDisposeObservable.remove(this._onDisposeObserver);
  286. }
  287. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  288. }
  289. /**
  290. * An event triggered before rendering the scene (right after animations and physics)
  291. */
  292. public onBeforeRenderObservable = new Observable<Scene>();
  293. private _onBeforeRenderObserver: Nullable<Observer<Scene>> = null;
  294. /** Sets a function to be executed before rendering this scene */
  295. public set beforeRender(callback: Nullable<() => void>) {
  296. if (this._onBeforeRenderObserver) {
  297. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  298. }
  299. if (callback) {
  300. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  301. }
  302. }
  303. /**
  304. * An event triggered after rendering the scene
  305. */
  306. public onAfterRenderObservable = new Observable<Scene>();
  307. private _onAfterRenderObserver: Nullable<Observer<Scene>> = null;
  308. /** Sets a function to be executed after rendering this scene */
  309. public set afterRender(callback: Nullable<() => void>) {
  310. if (this._onAfterRenderObserver) {
  311. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  312. }
  313. if (callback) {
  314. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  315. }
  316. }
  317. /**
  318. * An event triggered before animating the scene
  319. */
  320. public onBeforeAnimationsObservable = new Observable<Scene>();
  321. /**
  322. * An event triggered after animations processing
  323. */
  324. public onAfterAnimationsObservable = new Observable<Scene>();
  325. /**
  326. * An event triggered before draw calls are ready to be sent
  327. */
  328. public onBeforeDrawPhaseObservable = new Observable<Scene>();
  329. /**
  330. * An event triggered after draw calls have been sent
  331. */
  332. public onAfterDrawPhaseObservable = new Observable<Scene>();
  333. /**
  334. * An event triggered when physic simulation is about to be run
  335. */
  336. public onBeforePhysicsObservable = new Observable<Scene>();
  337. /**
  338. * An event triggered when physic simulation has been done
  339. */
  340. public onAfterPhysicsObservable = new Observable<Scene>();
  341. /**
  342. * An event triggered when the scene is ready
  343. */
  344. public onReadyObservable = new Observable<Scene>();
  345. /**
  346. * An event triggered before rendering a camera
  347. */
  348. public onBeforeCameraRenderObservable = new Observable<Camera>();
  349. private _onBeforeCameraRenderObserver: Nullable<Observer<Camera>> = null;
  350. /** Sets a function to be executed before rendering a camera*/
  351. public set beforeCameraRender(callback: () => void) {
  352. if (this._onBeforeCameraRenderObserver) {
  353. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  354. }
  355. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  356. }
  357. /**
  358. * An event triggered after rendering a camera
  359. */
  360. public onAfterCameraRenderObservable = new Observable<Camera>();
  361. private _onAfterCameraRenderObserver: Nullable<Observer<Camera>> = null;
  362. /** Sets a function to be executed after rendering a camera*/
  363. public set afterCameraRender(callback: () => void) {
  364. if (this._onAfterCameraRenderObserver) {
  365. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  366. }
  367. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  368. }
  369. /**
  370. * An event triggered when active meshes evaluation is about to start
  371. */
  372. public onBeforeActiveMeshesEvaluationObservable = new Observable<Scene>();
  373. /**
  374. * An event triggered when active meshes evaluation is done
  375. */
  376. public onAfterActiveMeshesEvaluationObservable = new Observable<Scene>();
  377. /**
  378. * An event triggered when particles rendering is about to start
  379. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  380. */
  381. public onBeforeParticlesRenderingObservable = new Observable<Scene>();
  382. /**
  383. * An event triggered when particles rendering is done
  384. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  385. */
  386. public onAfterParticlesRenderingObservable = new Observable<Scene>();
  387. /**
  388. * An event triggered when sprites rendering is about to start
  389. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  390. */
  391. public onBeforeSpritesRenderingObservable = new Observable<Scene>();
  392. /**
  393. * An event triggered when sprites rendering is done
  394. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  395. */
  396. public onAfterSpritesRenderingObservable = new Observable<Scene>();
  397. /**
  398. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  399. */
  400. public onDataLoadedObservable = new Observable<Scene>();
  401. /**
  402. * An event triggered when a camera is created
  403. */
  404. public onNewCameraAddedObservable = new Observable<Camera>();
  405. /**
  406. * An event triggered when a camera is removed
  407. */
  408. public onCameraRemovedObservable = new Observable<Camera>();
  409. /**
  410. * An event triggered when a light is created
  411. */
  412. public onNewLightAddedObservable = new Observable<Light>();
  413. /**
  414. * An event triggered when a light is removed
  415. */
  416. public onLightRemovedObservable = new Observable<Light>();
  417. /**
  418. * An event triggered when a geometry is created
  419. */
  420. public onNewGeometryAddedObservable = new Observable<Geometry>();
  421. /**
  422. * An event triggered when a geometry is removed
  423. */
  424. public onGeometryRemovedObservable = new Observable<Geometry>();
  425. /**
  426. * An event triggered when a transform node is created
  427. */
  428. public onNewTransformNodeAddedObservable = new Observable<TransformNode>();
  429. /**
  430. * An event triggered when a transform node is removed
  431. */
  432. public onTransformNodeRemovedObservable = new Observable<TransformNode>();
  433. /**
  434. * An event triggered when a mesh is created
  435. */
  436. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  437. /**
  438. * An event triggered when a mesh is removed
  439. */
  440. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  441. /**
  442. * An event triggered when render targets are about to be rendered
  443. * Can happen multiple times per frame.
  444. */
  445. public onBeforeRenderTargetsRenderObservable = new Observable<Scene>();
  446. /**
  447. * An event triggered when render targets were rendered.
  448. * Can happen multiple times per frame.
  449. */
  450. public onAfterRenderTargetsRenderObservable = new Observable<Scene>();
  451. /**
  452. * An event triggered before calculating deterministic simulation step
  453. */
  454. public onBeforeStepObservable = new Observable<Scene>();
  455. /**
  456. * An event triggered after calculating deterministic simulation step
  457. */
  458. public onAfterStepObservable = new Observable<Scene>();
  459. /**
  460. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  461. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  462. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  463. */
  464. public onRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  465. // Animations
  466. /**
  467. * Gets a list of Animations associated with the scene
  468. */
  469. public animations: Animation[] = [];
  470. private _registeredForLateAnimationBindings = new SmartArrayNoDuplicate<any>(256);
  471. // Pointers
  472. /**
  473. * Gets or sets a predicate used to select candidate meshes for a pointer down event
  474. */
  475. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  476. /**
  477. * Gets or sets a predicate used to select candidate meshes for a pointer up event
  478. */
  479. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  480. /**
  481. * Gets or sets a predicate used to select candidate meshes for a pointer move event
  482. */
  483. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  484. private _onPointerMove: (evt: PointerEvent) => void;
  485. private _onPointerDown: (evt: PointerEvent) => void;
  486. private _onPointerUp: (evt: PointerEvent) => void;
  487. /** Deprecated. Use onPointerObservable instead */
  488. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  489. /** Deprecated. Use onPointerObservable instead */
  490. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  491. /** Deprecated. Use onPointerObservable instead */
  492. public onPointerUp: (evt: PointerEvent, pickInfo: Nullable<PickingInfo>, type: PointerEventTypes) => void;
  493. /** Deprecated. Use onPointerObservable instead */
  494. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  495. // Gamepads
  496. private _gamepadManager: Nullable<GamepadManager>;
  497. /**
  498. * Gets the gamepad manager associated with the scene
  499. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  500. */
  501. public get gamepadManager(): GamepadManager {
  502. if (!this._gamepadManager) {
  503. this._gamepadManager = new GamepadManager(this);
  504. }
  505. return this._gamepadManager;
  506. }
  507. /**
  508. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  509. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  510. */
  511. public onPrePointerObservable = new Observable<PointerInfoPre>();
  512. /**
  513. * Observable event triggered each time an input event is received from the rendering canvas
  514. */
  515. public onPointerObservable = new Observable<PointerInfo>();
  516. /**
  517. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  518. */
  519. public get unTranslatedPointer(): Vector2 {
  520. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  521. }
  522. /** The distance in pixel that you have to move to prevent some events */
  523. public static DragMovementThreshold = 10; // in pixels
  524. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  525. public static LongPressDelay = 500; // in milliseconds
  526. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  527. public static DoubleClickDelay = 300; // in milliseconds
  528. /** If you need to check double click without raising a single click at first click, enable this flag */
  529. public static ExclusiveDoubleClickMode = false;
  530. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  531. private _initActionManager: (act: Nullable<ActionManager>, clickInfo: ClickInfo) => Nullable<ActionManager>;
  532. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  533. private _delayedSimpleClickTimeout: number;
  534. private _previousDelayedSimpleClickTimeout: number;
  535. private _meshPickProceed = false;
  536. private _previousButtonPressed: number;
  537. private _currentPickResult: Nullable<PickingInfo> = null;
  538. private _previousPickResult: Nullable<PickingInfo> = null;
  539. private _totalPointersPressed = 0;
  540. private _doubleClickOccured = false;
  541. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  542. public cameraToUseForPointers: Nullable<Camera> = null;
  543. private _pointerX: number;
  544. private _pointerY: number;
  545. private _unTranslatedPointerX: number;
  546. private _unTranslatedPointerY: number;
  547. private _startingPointerPosition = new Vector2(0, 0);
  548. private _previousStartingPointerPosition = new Vector2(0, 0);
  549. private _startingPointerTime = 0;
  550. private _previousStartingPointerTime = 0;
  551. // Deterministic lockstep
  552. private _timeAccumulator: number = 0;
  553. private _currentStepId: number = 0;
  554. private _currentInternalStep: number = 0;
  555. // Mirror
  556. /** @hidden */
  557. public _mirroredCameraPosition: Nullable<Vector3>;
  558. // Keyboard
  559. /**
  560. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  561. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  562. */
  563. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  564. /**
  565. * Observable event triggered each time an keyboard event is received from the hosting window
  566. */
  567. public onKeyboardObservable = new Observable<KeyboardInfo>();
  568. private _onKeyDown: (evt: KeyboardEvent) => void;
  569. private _onKeyUp: (evt: KeyboardEvent) => void;
  570. private _onCanvasFocusObserver: Nullable<Observer<Engine>>;
  571. private _onCanvasBlurObserver: Nullable<Observer<Engine>>;
  572. // Coordinates system
  573. private _useRightHandedSystem = false;
  574. /**
  575. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  576. */
  577. public set useRightHandedSystem(value: boolean) {
  578. if (this._useRightHandedSystem === value) {
  579. return;
  580. }
  581. this._useRightHandedSystem = value;
  582. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  583. }
  584. public get useRightHandedSystem(): boolean {
  585. return this._useRightHandedSystem;
  586. }
  587. /**
  588. * Sets the step Id used by deterministic lock step
  589. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  590. * @param newStepId defines the step Id
  591. */
  592. public setStepId(newStepId: number): void {
  593. this._currentStepId = newStepId;
  594. };
  595. /**
  596. * Gets the step Id used by deterministic lock step
  597. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  598. * @returns the step Id
  599. */
  600. public getStepId(): number {
  601. return this._currentStepId;
  602. };
  603. /**
  604. * Gets the internal step used by deterministic lock step
  605. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  606. * @returns the internal step
  607. */
  608. public getInternalStep(): number {
  609. return this._currentInternalStep;
  610. };
  611. // Fog
  612. private _fogEnabled = true;
  613. /**
  614. * Gets or sets a boolean indicating if fog is enabled on this scene
  615. * @see http://doc.babylonjs.com/babylon101/environment#fog
  616. */
  617. public set fogEnabled(value: boolean) {
  618. if (this._fogEnabled === value) {
  619. return;
  620. }
  621. this._fogEnabled = value;
  622. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  623. }
  624. public get fogEnabled(): boolean {
  625. return this._fogEnabled;
  626. }
  627. private _fogMode = Scene.FOGMODE_NONE;
  628. /**
  629. * Gets or sets the fog mode to use
  630. * @see http://doc.babylonjs.com/babylon101/environment#fog
  631. */
  632. public set fogMode(value: number) {
  633. if (this._fogMode === value) {
  634. return;
  635. }
  636. this._fogMode = value;
  637. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  638. }
  639. public get fogMode(): number {
  640. return this._fogMode;
  641. }
  642. /**
  643. * Gets or sets the fog color to use
  644. * @see http://doc.babylonjs.com/babylon101/environment#fog
  645. */
  646. public fogColor = new Color3(0.2, 0.2, 0.3);
  647. /**
  648. * Gets or sets the fog density to use
  649. * @see http://doc.babylonjs.com/babylon101/environment#fog
  650. */
  651. public fogDensity = 0.1;
  652. /**
  653. * Gets or sets the fog start distance to use
  654. * @see http://doc.babylonjs.com/babylon101/environment#fog
  655. */
  656. public fogStart = 0;
  657. /**
  658. * Gets or sets the fog end distance to use
  659. * @see http://doc.babylonjs.com/babylon101/environment#fog
  660. */
  661. public fogEnd = 1000.0;
  662. // Lights
  663. private _shadowsEnabled = true;
  664. /**
  665. * Gets or sets a boolean indicating if shadows are enabled on this scene
  666. */
  667. public set shadowsEnabled(value: boolean) {
  668. if (this._shadowsEnabled === value) {
  669. return;
  670. }
  671. this._shadowsEnabled = value;
  672. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  673. }
  674. public get shadowsEnabled(): boolean {
  675. return this._shadowsEnabled;
  676. }
  677. private _lightsEnabled = true;
  678. /**
  679. * Gets or sets a boolean indicating if lights are enabled on this scene
  680. */
  681. public set lightsEnabled(value: boolean) {
  682. if (this._lightsEnabled === value) {
  683. return;
  684. }
  685. this._lightsEnabled = value;
  686. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  687. }
  688. public get lightsEnabled(): boolean {
  689. return this._lightsEnabled;
  690. }
  691. /**
  692. * All of the lights added to this scene
  693. * @see http://doc.babylonjs.com/babylon101/lights
  694. */
  695. public lights = new Array<Light>();
  696. // Cameras
  697. /** All of the cameras added to this scene.
  698. * @see http://doc.babylonjs.com/babylon101/cameras
  699. */
  700. public cameras = new Array<Camera>();
  701. /** All of the active cameras added to this scene. */
  702. public activeCameras = new Array<Camera>();
  703. /** The current active camera */
  704. public activeCamera: Nullable<Camera>;
  705. // Meshes
  706. /**
  707. * All of the tranform nodes added to this scene
  708. * @see http://doc.babylonjs.com/how_to/transformnode
  709. */
  710. public transformNodes = new Array<TransformNode>();
  711. /**
  712. * All of the (abstract) meshes added to this scene
  713. */
  714. public meshes = new Array<AbstractMesh>();
  715. /**
  716. * All of the animation groups added to this scene
  717. * @see http://doc.babylonjs.com/how_to/group
  718. */
  719. public animationGroups = new Array<AnimationGroup>();
  720. // Geometries
  721. private _geometries = new Array<Geometry>();
  722. /**
  723. * All of the materials added to this scene
  724. * @see http://doc.babylonjs.com/babylon101/materials
  725. */
  726. public materials = new Array<Material>();
  727. /**
  728. * All of the multi-materials added to this scene
  729. * @see http://doc.babylonjs.com/how_to/multi_materials
  730. */
  731. public multiMaterials = new Array<MultiMaterial>();
  732. private _defaultMaterial: Material;
  733. /** The default material used on meshes when no material is affected */
  734. public get defaultMaterial(): Material {
  735. if (!this._defaultMaterial) {
  736. this._defaultMaterial = new StandardMaterial("default material", this);
  737. }
  738. return this._defaultMaterial;
  739. }
  740. /** The default material used on meshes when no material is affected */
  741. public set defaultMaterial(value: Material) {
  742. this._defaultMaterial = value;
  743. }
  744. // Textures
  745. private _texturesEnabled = true;
  746. /**
  747. * Gets or sets a boolean indicating if textures are enabled on this scene
  748. */
  749. public set texturesEnabled(value: boolean) {
  750. if (this._texturesEnabled === value) {
  751. return;
  752. }
  753. this._texturesEnabled = value;
  754. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  755. }
  756. public get texturesEnabled(): boolean {
  757. return this._texturesEnabled;
  758. }
  759. /**
  760. * All of the textures added to this scene
  761. */
  762. public textures = new Array<BaseTexture>();
  763. // Particles
  764. /**
  765. * Gets or sets a boolean indicating if particles are enabled on this scene
  766. */
  767. public particlesEnabled = true;
  768. /**
  769. * All of the particle systems added to this scene
  770. * @see http://doc.babylonjs.com/babylon101/particles
  771. */
  772. public particleSystems = new Array<IParticleSystem>();
  773. // Sprites
  774. /**
  775. * Gets or sets a boolean indicating if sprites are enabled on this scene
  776. */
  777. public spritesEnabled = true;
  778. /**
  779. * All of the sprite managers added to this scene
  780. * @see http://doc.babylonjs.com/babylon101/sprites
  781. */
  782. public spriteManagers = new Array<SpriteManager>();
  783. /**
  784. * The list of layers (background and foreground) of the scene
  785. */
  786. public layers = new Array<Layer>();
  787. /**
  788. * The list of effect layers (highlights/glow) added to the scene
  789. * @see http://doc.babylonjs.com/how_to/highlight_layer
  790. * @see http://doc.babylonjs.com/how_to/glow_layer
  791. */
  792. public effectLayers = new Array<EffectLayer>();
  793. // Skeletons
  794. private _skeletonsEnabled = true;
  795. /**
  796. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  797. */
  798. public set skeletonsEnabled(value: boolean) {
  799. if (this._skeletonsEnabled === value) {
  800. return;
  801. }
  802. this._skeletonsEnabled = value;
  803. this.markAllMaterialsAsDirty(Material.AttributesDirtyFlag);
  804. }
  805. public get skeletonsEnabled(): boolean {
  806. return this._skeletonsEnabled;
  807. }
  808. /**
  809. * The list of skeletons added to the scene
  810. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  811. */
  812. public skeletons = new Array<Skeleton>();
  813. // Morph targets
  814. /**
  815. * The list of morph target managers added to the scene
  816. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  817. */
  818. public morphTargetManagers = new Array<MorphTargetManager>();
  819. // Lens flares
  820. /**
  821. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  822. */
  823. public lensFlaresEnabled = true;
  824. /**
  825. * The list of lens flare system added to the scene
  826. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  827. */
  828. public lensFlareSystems = new Array<LensFlareSystem>();
  829. // Collisions
  830. /**
  831. * Gets or sets a boolean indicating if collisions are enabled on this scene
  832. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  833. */
  834. public collisionsEnabled = true;
  835. private _workerCollisions: boolean;
  836. /** @hidden */
  837. public collisionCoordinator: ICollisionCoordinator;
  838. /**
  839. * Defines the gravity applied to this scene (used only for collisions)
  840. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  841. */
  842. public gravity = new Vector3(0, -9.807, 0);
  843. // Postprocesses
  844. /**
  845. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  846. */
  847. public postProcessesEnabled = true;
  848. /**
  849. * The list of postprocesses added to the scene
  850. */
  851. public postProcesses = new Array<PostProcess>();
  852. /**
  853. * Gets the current postprocess manager
  854. */
  855. public postProcessManager: PostProcessManager;
  856. private _postProcessRenderPipelineManager: PostProcessRenderPipelineManager
  857. /**
  858. * Gets the postprocess render pipeline manager
  859. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  860. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  861. */
  862. public get postProcessRenderPipelineManager(): PostProcessRenderPipelineManager {
  863. if (!this._postProcessRenderPipelineManager) {
  864. this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  865. }
  866. return this._postProcessRenderPipelineManager;
  867. }
  868. // Customs render targets
  869. /**
  870. * Gets or sets a boolean indicating if render targets are enabled on this scene
  871. */
  872. public renderTargetsEnabled = true;
  873. /**
  874. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  875. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  876. */
  877. public dumpNextRenderTargets = false;
  878. /**
  879. * The list of user defined render targets added to the scene
  880. */
  881. public customRenderTargets = new Array<RenderTargetTexture>();
  882. /**
  883. * Defines if texture loading must be delayed
  884. * If true, textures will only be loaded when they need to be rendered
  885. */
  886. public useDelayedTextureLoading: boolean;
  887. /**
  888. * Gets the list of meshes imported to the scene through SceneLoader
  889. */
  890. public importedMeshesFiles = new Array<String>();
  891. // Probes
  892. /**
  893. * Gets or sets a boolean indicating if probes are enabled on this scene
  894. */
  895. public probesEnabled = true;
  896. /**
  897. * The list of reflection probes added to the scene
  898. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  899. */
  900. public reflectionProbes = new Array<ReflectionProbe>();
  901. // Database
  902. /**
  903. * @hidden
  904. */
  905. public database: Database;
  906. /**
  907. * Gets or sets the action manager associated with the scene
  908. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  909. */
  910. public actionManager: ActionManager;
  911. /** @hidden */
  912. public _actionManagers = new Array<ActionManager>();
  913. private _meshesForIntersections = new SmartArrayNoDuplicate<AbstractMesh>(256);
  914. // Procedural textures
  915. /**
  916. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  917. */
  918. public proceduralTexturesEnabled = true;
  919. /**
  920. * The list of procedural textures added to the scene
  921. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  922. */
  923. public proceduralTextures = new Array<ProceduralTexture>();
  924. // Sound Tracks
  925. private _mainSoundTrack: SoundTrack;
  926. /**
  927. * The list of sound tracks added to the scene
  928. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  929. */
  930. public soundTracks = new Array<SoundTrack>();
  931. private _audioEnabled = true;
  932. private _headphone = false;
  933. /**
  934. * Gets the main soundtrack associated with the scene
  935. */
  936. public get mainSoundTrack(): SoundTrack {
  937. if (!this._mainSoundTrack) {
  938. this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  939. }
  940. return this._mainSoundTrack;
  941. }
  942. /**
  943. * Gets or sets the VRExperienceHelper attached to the scene
  944. * @see http://doc.babylonjs.com/how_to/webvr_helper
  945. * @ignorenaming
  946. */
  947. public VRHelper: VRExperienceHelper;
  948. /**
  949. * Gets or sets the simplification queue attached to the scene
  950. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  951. */
  952. public simplificationQueue: SimplificationQueue;
  953. // Private
  954. private _engine: Engine;
  955. // Performance counters
  956. private _totalVertices = new PerfCounter();
  957. /** @hidden */
  958. public _activeIndices = new PerfCounter();
  959. /** @hidden */
  960. public _activeParticles = new PerfCounter();
  961. /** @hidden */
  962. public _activeBones = new PerfCounter();
  963. private _animationRatio: number;
  964. private _animationTimeLast: number;
  965. private _animationTime: number = 0;
  966. /**
  967. * Gets or sets a general scale for animation speed
  968. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  969. */
  970. public animationTimeScale: number = 1;
  971. /** @hidden */
  972. public _cachedMaterial: Nullable<Material>;
  973. /** @hidden */
  974. public _cachedEffect: Nullable<Effect>;
  975. /** @hidden */
  976. public _cachedVisibility: Nullable<number>;
  977. private _renderId = 0;
  978. private _executeWhenReadyTimeoutId = -1;
  979. private _intermediateRendering = false;
  980. private _viewUpdateFlag = -1;
  981. private _projectionUpdateFlag = -1;
  982. private _alternateViewUpdateFlag = -1;
  983. private _alternateProjectionUpdateFlag = -1;
  984. /** @hidden */
  985. public _toBeDisposed = new SmartArray<Nullable<IDisposable>>(256);
  986. private _activeRequests = new Array<IFileRequest>();
  987. private _pendingData = new Array();
  988. private _isDisposed = false;
  989. /**
  990. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  991. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  992. */
  993. public dispatchAllSubMeshesOfActiveMeshes: boolean = false;
  994. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  995. private _processedMaterials = new SmartArray<Material>(256);
  996. private _renderTargets = new SmartArrayNoDuplicate<RenderTargetTexture>(256);
  997. /** @hidden */
  998. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  999. private _activeSkeletons = new SmartArrayNoDuplicate<Skeleton>(32);
  1000. private _softwareSkinnedMeshes = new SmartArrayNoDuplicate<Mesh>(32);
  1001. private _renderingManager: RenderingManager;
  1002. private _physicsEngine: Nullable<PhysicsEngine>;
  1003. /** @hidden */
  1004. public _activeAnimatables = new Array<Animatable>();
  1005. private _transformMatrix = Matrix.Zero();
  1006. private _sceneUbo: UniformBuffer;
  1007. private _alternateSceneUbo: UniformBuffer;
  1008. private _pickWithRayInverseMatrix: Matrix;
  1009. private _boundingBoxRenderer: BoundingBoxRenderer;
  1010. private _outlineRenderer: OutlineRenderer;
  1011. private _viewMatrix: Matrix;
  1012. private _projectionMatrix: Matrix;
  1013. private _alternateViewMatrix: Matrix;
  1014. private _alternateProjectionMatrix: Matrix;
  1015. private _alternateTransformMatrix: Matrix;
  1016. private _useAlternateCameraConfiguration = false;
  1017. private _alternateRendering = false;
  1018. /** @hidden */
  1019. public _forcedViewPosition: Nullable<Vector3>;
  1020. /** @hidden */
  1021. public get _isAlternateRenderingEnabled(): boolean {
  1022. return this._alternateRendering;
  1023. }
  1024. private _frustumPlanes: Plane[];
  1025. /**
  1026. * Gets the list of frustum planes (built from the active camera)
  1027. */
  1028. public get frustumPlanes(): Plane[] {
  1029. return this._frustumPlanes;
  1030. }
  1031. /**
  1032. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  1033. * This is useful if there are more lights that the maximum simulteanous authorized
  1034. */
  1035. public requireLightSorting = false;
  1036. private _selectionOctree: Octree<AbstractMesh>;
  1037. private _pointerOverMesh: Nullable<AbstractMesh>;
  1038. private _pointerOverSprite: Nullable<Sprite>;
  1039. private _debugLayer: DebugLayer;
  1040. private _depthRenderer: { [id: string]: DepthRenderer } = {};
  1041. private _geometryBufferRenderer: Nullable<GeometryBufferRenderer>;
  1042. /**
  1043. * Gets the current geometry buffer associated to the scene.
  1044. */
  1045. public get geometryBufferRenderer(): Nullable<GeometryBufferRenderer> {
  1046. return this._geometryBufferRenderer;
  1047. }
  1048. /**
  1049. * Sets the current geometry buffer for the scene.
  1050. */
  1051. public set geometryBufferRenderer(geometryBufferRenderer: Nullable<GeometryBufferRenderer>) {
  1052. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  1053. this._geometryBufferRenderer = geometryBufferRenderer;
  1054. }
  1055. }
  1056. private _pickedDownMesh: Nullable<AbstractMesh>;
  1057. private _pickedUpMesh: Nullable<AbstractMesh>;
  1058. private _pickedDownSprite: Nullable<Sprite>;
  1059. private _externalData: StringDictionary<Object>;
  1060. private _uid: Nullable<string>;
  1061. /**
  1062. * Creates a new Scene
  1063. * @param engine defines the engine to use to render this scene
  1064. */
  1065. constructor(engine: Engine) {
  1066. this._engine = engine || Engine.LastCreatedEngine;
  1067. this._engine.scenes.push(this);
  1068. this._uid = null;
  1069. this._renderingManager = new RenderingManager(this);
  1070. this.postProcessManager = new PostProcessManager(this);
  1071. if (OutlineRenderer) {
  1072. this._outlineRenderer = new OutlineRenderer(this);
  1073. }
  1074. if (Tools.IsWindowObjectExist()) {
  1075. this.attachControl();
  1076. }
  1077. //simplification queue
  1078. if (SimplificationQueue) {
  1079. this.simplificationQueue = new SimplificationQueue();
  1080. }
  1081. //collision coordinator initialization. For now legacy per default.
  1082. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  1083. // Uniform Buffer
  1084. this._createUbo();
  1085. // Default Image processing definition.
  1086. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  1087. }
  1088. /**
  1089. * Gets the debug layer associated with the scene
  1090. * @see http://doc.babylonjs.com/features/playground_debuglayer
  1091. */
  1092. public get debugLayer(): DebugLayer {
  1093. if (!this._debugLayer) {
  1094. this._debugLayer = new DebugLayer(this);
  1095. }
  1096. return this._debugLayer;
  1097. }
  1098. public set workerCollisions(enabled: boolean) {
  1099. if (!CollisionCoordinatorLegacy) {
  1100. return;
  1101. }
  1102. enabled = (enabled && !!Worker && !!CollisionWorker);
  1103. this._workerCollisions = enabled;
  1104. if (this.collisionCoordinator) {
  1105. this.collisionCoordinator.destroy();
  1106. }
  1107. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  1108. this.collisionCoordinator.init(this);
  1109. }
  1110. /**
  1111. * Gets a boolean indicating if collisions are processed on a web worker
  1112. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  1113. */
  1114. public get workerCollisions(): boolean {
  1115. return this._workerCollisions;
  1116. }
  1117. /**
  1118. * Gets the octree used to boost mesh selection (picking)
  1119. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  1120. */
  1121. public get selectionOctree(): Octree<AbstractMesh> {
  1122. return this._selectionOctree;
  1123. }
  1124. /**
  1125. * Gets the mesh that is currently under the pointer
  1126. */
  1127. public get meshUnderPointer(): Nullable<AbstractMesh> {
  1128. return this._pointerOverMesh;
  1129. }
  1130. /**
  1131. * Gets the current on-screen X position of the pointer
  1132. */
  1133. public get pointerX(): number {
  1134. return this._pointerX;
  1135. }
  1136. /**
  1137. * Gets the current on-screen Y position of the pointer
  1138. */
  1139. public get pointerY(): number {
  1140. return this._pointerY;
  1141. }
  1142. /**
  1143. * Gets the cached material (ie. the latest rendered one)
  1144. * @returns the cached material
  1145. */
  1146. public getCachedMaterial(): Nullable<Material> {
  1147. return this._cachedMaterial;
  1148. }
  1149. /**
  1150. * Gets the cached effect (ie. the latest rendered one)
  1151. * @returns the cached effect
  1152. */
  1153. public getCachedEffect(): Nullable<Effect> {
  1154. return this._cachedEffect;
  1155. }
  1156. /**
  1157. * Gets the cached visibility state (ie. the latest rendered one)
  1158. * @returns the cached visibility state
  1159. */
  1160. public getCachedVisibility(): Nullable<number> {
  1161. return this._cachedVisibility;
  1162. }
  1163. /**
  1164. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  1165. * @param material defines the current material
  1166. * @param effect defines the current effect
  1167. * @param visibility defines the current visibility state
  1168. * @returns true if one parameter is not cached
  1169. */
  1170. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  1171. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  1172. }
  1173. /**
  1174. * Gets the bounding box renderer associated with the scene
  1175. * @returns a BoundingBoxRenderer
  1176. */
  1177. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  1178. if (!this._boundingBoxRenderer) {
  1179. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  1180. }
  1181. return this._boundingBoxRenderer;
  1182. }
  1183. /**
  1184. * Gets the outline renderer associated with the scene
  1185. * @returns a OutlineRenderer
  1186. */
  1187. public getOutlineRenderer(): OutlineRenderer {
  1188. return this._outlineRenderer;
  1189. }
  1190. /**
  1191. * Gets the engine associated with the scene
  1192. * @returns an Engine
  1193. */
  1194. public getEngine(): Engine {
  1195. return this._engine;
  1196. }
  1197. /**
  1198. * Gets the total number of vertices rendered per frame
  1199. * @returns the total number of vertices rendered per frame
  1200. */
  1201. public getTotalVertices(): number {
  1202. return this._totalVertices.current;
  1203. }
  1204. /**
  1205. * Gets the performance counter for total vertices
  1206. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1207. */
  1208. public get totalVerticesPerfCounter(): PerfCounter {
  1209. return this._totalVertices;
  1210. }
  1211. /**
  1212. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  1213. * @returns the total number of active indices rendered per frame
  1214. */
  1215. public getActiveIndices(): number {
  1216. return this._activeIndices.current;
  1217. }
  1218. /**
  1219. * Gets the performance counter for active indices
  1220. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1221. */
  1222. public get totalActiveIndicesPerfCounter(): PerfCounter {
  1223. return this._activeIndices;
  1224. }
  1225. /**
  1226. * Gets the total number of active particles rendered per frame
  1227. * @returns the total number of active particles rendered per frame
  1228. */
  1229. public getActiveParticles(): number {
  1230. return this._activeParticles.current;
  1231. }
  1232. /**
  1233. * Gets the performance counter for active particles
  1234. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1235. */
  1236. public get activeParticlesPerfCounter(): PerfCounter {
  1237. return this._activeParticles;
  1238. }
  1239. /**
  1240. * Gets the total number of active bones rendered per frame
  1241. * @returns the total number of active bones rendered per frame
  1242. */
  1243. public getActiveBones(): number {
  1244. return this._activeBones.current;
  1245. }
  1246. /**
  1247. * Gets the performance counter for active bones
  1248. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1249. */
  1250. public get activeBonesPerfCounter(): PerfCounter {
  1251. return this._activeBones;
  1252. }
  1253. /** @hidden */
  1254. public getInterFramePerfCounter(): number {
  1255. Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  1256. return 0;
  1257. }
  1258. /** @hidden */
  1259. public get interFramePerfCounter(): Nullable<PerfCounter> {
  1260. Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  1261. return null;
  1262. }
  1263. /** @hidden */
  1264. public getLastFrameDuration(): number {
  1265. Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  1266. return 0;
  1267. }
  1268. /** @hidden */
  1269. public get lastFramePerfCounter(): Nullable<PerfCounter> {
  1270. Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  1271. return null;
  1272. }
  1273. /** @hidden */
  1274. public getEvaluateActiveMeshesDuration(): number {
  1275. Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  1276. return 0;
  1277. }
  1278. /** @hidden */
  1279. public get evaluateActiveMeshesDurationPerfCounter(): Nullable<PerfCounter> {
  1280. Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  1281. return null;
  1282. }
  1283. /**
  1284. * Gets the array of active meshes
  1285. * @returns an array of AbstractMesh
  1286. */
  1287. public getActiveMeshes(): SmartArray<AbstractMesh> {
  1288. return this._activeMeshes;
  1289. }
  1290. /** @hidden */
  1291. public getRenderTargetsDuration(): number {
  1292. Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  1293. return 0;
  1294. }
  1295. /** @hidden */
  1296. public getRenderDuration(): number {
  1297. Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  1298. return 0;
  1299. }
  1300. /** @hidden */
  1301. public get renderDurationPerfCounter(): Nullable<PerfCounter> {
  1302. Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  1303. return null;
  1304. }
  1305. /** @hidden */
  1306. public getParticlesDuration(): number {
  1307. Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  1308. return 0;
  1309. }
  1310. /** @hidden */
  1311. public get particlesDurationPerfCounter(): Nullable<PerfCounter> {
  1312. Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  1313. return null;
  1314. }
  1315. /** @hidden */
  1316. public getSpritesDuration(): number {
  1317. Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  1318. return 0;
  1319. }
  1320. /** @hidden */
  1321. public get spriteDuractionPerfCounter(): Nullable<PerfCounter> {
  1322. Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  1323. return null;
  1324. }
  1325. /**
  1326. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  1327. * @returns a number
  1328. */
  1329. public getAnimationRatio(): number {
  1330. return this._animationRatio;
  1331. }
  1332. /**
  1333. * Gets an unique Id for the current frame
  1334. * @returns a number
  1335. */
  1336. public getRenderId(): number {
  1337. return this._renderId;
  1338. }
  1339. /** Call this function if you want to manually increment the render Id*/
  1340. public incrementRenderId(): void {
  1341. this._renderId++;
  1342. }
  1343. private _updatePointerPosition(evt: PointerEvent): void {
  1344. var canvasRect = this._engine.getRenderingCanvasClientRect();
  1345. if (!canvasRect) {
  1346. return;
  1347. }
  1348. this._pointerX = evt.clientX - canvasRect.left;
  1349. this._pointerY = evt.clientY - canvasRect.top;
  1350. this._unTranslatedPointerX = this._pointerX;
  1351. this._unTranslatedPointerY = this._pointerY;
  1352. }
  1353. private _createUbo(): void {
  1354. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  1355. this._sceneUbo.addUniform("viewProjection", 16);
  1356. this._sceneUbo.addUniform("view", 16);
  1357. }
  1358. private _createAlternateUbo(): void {
  1359. this._alternateSceneUbo = new UniformBuffer(this._engine, undefined, true);
  1360. this._alternateSceneUbo.addUniform("viewProjection", 16);
  1361. this._alternateSceneUbo.addUniform("view", 16);
  1362. }
  1363. // Pointers handling
  1364. /**
  1365. * Use this method to simulate a pointer move on a mesh
  1366. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1367. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1368. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1369. * @returns the current scene
  1370. */
  1371. public simulatePointerMove(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1372. let evt = new PointerEvent("pointermove", pointerEventInit);
  1373. return this._processPointerMove(pickResult, evt);
  1374. }
  1375. private _processPointerMove(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1376. var canvas = this._engine.getRenderingCanvas();
  1377. if (!canvas) {
  1378. return this;
  1379. }
  1380. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1381. this.setPointerOverSprite(null);
  1382. this.setPointerOverMesh(pickResult.pickedMesh);
  1383. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  1384. if (this._pointerOverMesh.actionManager.hoverCursor) {
  1385. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  1386. } else {
  1387. canvas.style.cursor = this.hoverCursor;
  1388. }
  1389. } else {
  1390. canvas.style.cursor = this.defaultCursor;
  1391. }
  1392. } else {
  1393. this.setPointerOverMesh(null);
  1394. // Sprites
  1395. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1396. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1397. this.setPointerOverSprite(pickResult.pickedSprite);
  1398. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  1399. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  1400. } else {
  1401. canvas.style.cursor = this.hoverCursor;
  1402. }
  1403. } else {
  1404. this.setPointerOverSprite(null);
  1405. // Restore pointer
  1406. canvas.style.cursor = this.defaultCursor;
  1407. }
  1408. }
  1409. if (pickResult) {
  1410. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1411. if (this.onPointerMove) {
  1412. this.onPointerMove(evt, pickResult, type);
  1413. }
  1414. if (this.onPointerObservable.hasObservers()) {
  1415. let pi = new PointerInfo(type, evt, pickResult);
  1416. this.onPointerObservable.notifyObservers(pi, type);
  1417. }
  1418. }
  1419. return this;
  1420. }
  1421. /**
  1422. * Use this method to simulate a pointer down on a mesh
  1423. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1424. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1425. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1426. * @returns the current scene
  1427. */
  1428. public simulatePointerDown(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1429. let evt = new PointerEvent("pointerdown", pointerEventInit);
  1430. return this._processPointerDown(pickResult, evt);
  1431. }
  1432. private _processPointerDown(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1433. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1434. this._pickedDownMesh = pickResult.pickedMesh;
  1435. var actionManager = pickResult.pickedMesh.actionManager;
  1436. if (actionManager) {
  1437. if (actionManager.hasPickTriggers) {
  1438. actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1439. switch (evt.button) {
  1440. case 0:
  1441. actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1442. break;
  1443. case 1:
  1444. actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1445. break;
  1446. case 2:
  1447. actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1448. break;
  1449. }
  1450. }
  1451. if (actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  1452. window.setTimeout(() => {
  1453. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  1454. (mesh: AbstractMesh): boolean => (<boolean>(mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger) && mesh == this._pickedDownMesh)),
  1455. false, this.cameraToUseForPointers);
  1456. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  1457. if (this._totalPointersPressed !== 0 &&
  1458. ((Date.now() - this._startingPointerTime) > Scene.LongPressDelay) &&
  1459. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  1460. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  1461. this._startingPointerTime = 0;
  1462. actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1463. }
  1464. }
  1465. }, Scene.LongPressDelay);
  1466. }
  1467. }
  1468. }
  1469. if (pickResult) {
  1470. let type = PointerEventTypes.POINTERDOWN;
  1471. if (this.onPointerDown) {
  1472. this.onPointerDown(evt, pickResult, type);
  1473. }
  1474. if (this.onPointerObservable.hasObservers()) {
  1475. let pi = new PointerInfo(type, evt, pickResult);
  1476. this.onPointerObservable.notifyObservers(pi, type);
  1477. }
  1478. }
  1479. return this;
  1480. }
  1481. /**
  1482. * Use this method to simulate a pointer up on a mesh
  1483. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1484. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1485. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1486. * @returns the current scene
  1487. */
  1488. public simulatePointerUp(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1489. let evt = new PointerEvent("pointerup", pointerEventInit);
  1490. let clickInfo = new ClickInfo();
  1491. clickInfo.singleClick = true;
  1492. clickInfo.ignore = true;
  1493. return this._processPointerUp(pickResult, evt, clickInfo);
  1494. }
  1495. private _processPointerUp(pickResult: Nullable<PickingInfo>, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  1496. if (pickResult && pickResult && pickResult.pickedMesh) {
  1497. this._pickedUpMesh = pickResult.pickedMesh;
  1498. if (this._pickedDownMesh === this._pickedUpMesh) {
  1499. if (this.onPointerPick) {
  1500. this.onPointerPick(evt, pickResult);
  1501. }
  1502. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1503. let type = PointerEventTypes.POINTERPICK;
  1504. let pi = new PointerInfo(type, evt, pickResult);
  1505. this.onPointerObservable.notifyObservers(pi, type);
  1506. }
  1507. }
  1508. if (pickResult.pickedMesh.actionManager) {
  1509. if (clickInfo.ignore) {
  1510. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1511. }
  1512. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  1513. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1514. }
  1515. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1516. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1517. }
  1518. }
  1519. }
  1520. if (this._pickedDownMesh &&
  1521. this._pickedDownMesh.actionManager &&
  1522. this._pickedDownMesh.actionManager.hasSpecificTrigger(ActionManager.OnPickOutTrigger) &&
  1523. this._pickedDownMesh !== this._pickedUpMesh) {
  1524. this._pickedDownMesh.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1525. }
  1526. let type = PointerEventTypes.POINTERUP;
  1527. if (this.onPointerObservable.hasObservers()) {
  1528. if (!clickInfo.ignore) {
  1529. if (!clickInfo.hasSwiped) {
  1530. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1531. let type = PointerEventTypes.POINTERTAP;
  1532. let pi = new PointerInfo(type, evt, pickResult);
  1533. this.onPointerObservable.notifyObservers(pi, type);
  1534. }
  1535. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1536. let type = PointerEventTypes.POINTERDOUBLETAP;
  1537. let pi = new PointerInfo(type, evt, pickResult);
  1538. this.onPointerObservable.notifyObservers(pi, type);
  1539. }
  1540. }
  1541. }
  1542. else {
  1543. let pi = new PointerInfo(type, evt, pickResult);
  1544. this.onPointerObservable.notifyObservers(pi, type);
  1545. }
  1546. }
  1547. if (this.onPointerUp) {
  1548. this.onPointerUp(evt, pickResult, type);
  1549. }
  1550. return this;
  1551. }
  1552. /**
  1553. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1554. * @param attachUp defines if you want to attach events to pointerup
  1555. * @param attachDown defines if you want to attach events to pointerdown
  1556. * @param attachMove defines if you want to attach events to pointermove
  1557. */
  1558. public attachControl(attachUp = true, attachDown = true, attachMove = true): void {
  1559. this._initActionManager = (act: Nullable<ActionManager>, clickInfo: ClickInfo): Nullable<ActionManager> => {
  1560. if (!this._meshPickProceed) {
  1561. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1562. this._currentPickResult = pickResult;
  1563. if (pickResult) {
  1564. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1565. }
  1566. this._meshPickProceed = true;
  1567. }
  1568. return act;
  1569. };
  1570. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => {
  1571. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1572. if ((Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1573. btn !== this._previousButtonPressed) {
  1574. this._doubleClickOccured = false;
  1575. clickInfo.singleClick = true;
  1576. clickInfo.ignore = false;
  1577. cb(clickInfo, this._currentPickResult);
  1578. }
  1579. }
  1580. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void): void => {
  1581. let clickInfo = new ClickInfo();
  1582. this._currentPickResult = null;
  1583. let act: Nullable<ActionManager> = null;
  1584. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1585. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1586. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1587. if (!checkPicking && ActionManager && ActionManager.HasPickTriggers) {
  1588. act = this._initActionManager(act, clickInfo);
  1589. if (act)
  1590. checkPicking = act.hasPickTriggers;
  1591. }
  1592. if (checkPicking) {
  1593. let btn = evt.button;
  1594. clickInfo.hasSwiped = Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1595. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1596. if (!clickInfo.hasSwiped) {
  1597. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1598. if (!checkSingleClickImmediately) {
  1599. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1600. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1601. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1602. act = this._initActionManager(act, clickInfo);
  1603. if (act)
  1604. checkSingleClickImmediately = !act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1605. }
  1606. }
  1607. if (checkSingleClickImmediately) {
  1608. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1609. if (Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1610. btn !== this._previousButtonPressed) {
  1611. clickInfo.singleClick = true;
  1612. cb(clickInfo, this._currentPickResult);
  1613. }
  1614. }
  1615. // at least one double click is required to be check and exclusive double click is enabled
  1616. else {
  1617. // wait that no double click has been raised during the double click delay
  1618. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1619. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1620. }
  1621. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1622. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1623. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1624. act = this._initActionManager(act, clickInfo);
  1625. if (act)
  1626. checkDoubleClick = act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1627. }
  1628. if (checkDoubleClick) {
  1629. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1630. if (btn === this._previousButtonPressed &&
  1631. Date.now() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1632. !this._doubleClickOccured
  1633. ) {
  1634. // pointer has not moved for 2 clicks, it's a double click
  1635. if (!clickInfo.hasSwiped &&
  1636. Math.abs(this._previousStartingPointerPosition.x - this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  1637. Math.abs(this._previousStartingPointerPosition.y - this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  1638. this._previousStartingPointerTime = 0;
  1639. this._doubleClickOccured = true;
  1640. clickInfo.doubleClick = true;
  1641. clickInfo.ignore = false;
  1642. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout) {
  1643. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1644. }
  1645. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1646. cb(clickInfo, this._currentPickResult);
  1647. }
  1648. // if the two successive clicks are too far, it's just two simple clicks
  1649. else {
  1650. this._doubleClickOccured = false;
  1651. this._previousStartingPointerTime = this._startingPointerTime;
  1652. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1653. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1654. this._previousButtonPressed = btn;
  1655. if (Scene.ExclusiveDoubleClickMode) {
  1656. if (this._previousDelayedSimpleClickTimeout) {
  1657. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1658. }
  1659. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1660. cb(clickInfo, this._previousPickResult);
  1661. }
  1662. else {
  1663. cb(clickInfo, this._currentPickResult);
  1664. }
  1665. }
  1666. }
  1667. // just the first click of the double has been raised
  1668. else {
  1669. this._doubleClickOccured = false;
  1670. this._previousStartingPointerTime = this._startingPointerTime;
  1671. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1672. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1673. this._previousButtonPressed = btn;
  1674. }
  1675. }
  1676. }
  1677. }
  1678. clickInfo.ignore = true;
  1679. cb(clickInfo, this._currentPickResult);
  1680. };
  1681. this._spritePredicate = (sprite: Sprite): boolean => {
  1682. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  1683. };
  1684. this._onPointerMove = (evt: PointerEvent) => {
  1685. this._updatePointerPosition(evt);
  1686. // PreObservable support
  1687. if (this.onPrePointerObservable.hasObservers()) {
  1688. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1689. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1690. this.onPrePointerObservable.notifyObservers(pi, type);
  1691. if (pi.skipOnPointerObservable) {
  1692. return;
  1693. }
  1694. }
  1695. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1696. return;
  1697. }
  1698. if (!this.pointerMovePredicate) {
  1699. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  1700. }
  1701. // Meshes
  1702. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1703. this._processPointerMove(pickResult, evt);
  1704. };
  1705. this._onPointerDown = (evt: PointerEvent) => {
  1706. this._totalPointersPressed++;
  1707. this._pickedDownMesh = null;
  1708. this._meshPickProceed = false;
  1709. this._updatePointerPosition(evt);
  1710. if (this.preventDefaultOnPointerDown && canvas) {
  1711. evt.preventDefault();
  1712. canvas.focus();
  1713. }
  1714. // PreObservable support
  1715. if (this.onPrePointerObservable.hasObservers()) {
  1716. let type = PointerEventTypes.POINTERDOWN;
  1717. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1718. this.onPrePointerObservable.notifyObservers(pi, type);
  1719. if (pi.skipOnPointerObservable) {
  1720. return;
  1721. }
  1722. }
  1723. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1724. return;
  1725. }
  1726. this._startingPointerPosition.x = this._pointerX;
  1727. this._startingPointerPosition.y = this._pointerY;
  1728. this._startingPointerTime = Date.now();
  1729. if (!this.pointerDownPredicate) {
  1730. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1731. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1732. };
  1733. }
  1734. // Meshes
  1735. this._pickedDownMesh = null;
  1736. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1737. this._processPointerDown(pickResult, evt);
  1738. // Sprites
  1739. this._pickedDownSprite = null;
  1740. if (this.spriteManagers.length > 0) {
  1741. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1742. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1743. if (pickResult.pickedSprite.actionManager) {
  1744. this._pickedDownSprite = pickResult.pickedSprite;
  1745. switch (evt.button) {
  1746. case 0:
  1747. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1748. break;
  1749. case 1:
  1750. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1751. break;
  1752. case 2:
  1753. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1754. break;
  1755. }
  1756. if (pickResult.pickedSprite.actionManager) {
  1757. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1758. }
  1759. }
  1760. }
  1761. }
  1762. };
  1763. this._onPointerUp = (evt: PointerEvent) => {
  1764. if (this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  1765. return; // So we need to test it the pointer down was pressed before.
  1766. }
  1767. this._totalPointersPressed--;
  1768. this._pickedUpMesh = null;
  1769. this._meshPickProceed = false;
  1770. this._updatePointerPosition(evt);
  1771. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => {
  1772. // PreObservable support
  1773. if (this.onPrePointerObservable.hasObservers()) {
  1774. if (!clickInfo.ignore) {
  1775. if (!clickInfo.hasSwiped) {
  1776. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1777. let type = PointerEventTypes.POINTERTAP;
  1778. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1779. this.onPrePointerObservable.notifyObservers(pi, type);
  1780. if (pi.skipOnPointerObservable) {
  1781. return;
  1782. }
  1783. }
  1784. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1785. let type = PointerEventTypes.POINTERDOUBLETAP;
  1786. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1787. this.onPrePointerObservable.notifyObservers(pi, type);
  1788. if (pi.skipOnPointerObservable) {
  1789. return;
  1790. }
  1791. }
  1792. }
  1793. }
  1794. else {
  1795. let type = PointerEventTypes.POINTERUP;
  1796. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1797. this.onPrePointerObservable.notifyObservers(pi, type);
  1798. if (pi.skipOnPointerObservable) {
  1799. return;
  1800. }
  1801. }
  1802. }
  1803. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1804. return;
  1805. }
  1806. if (!this.pointerUpPredicate) {
  1807. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1808. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1809. };
  1810. }
  1811. // Meshes
  1812. if (!this._meshPickProceed && (ActionManager && ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1813. this._initActionManager(null, clickInfo);
  1814. }
  1815. if (!pickResult) {
  1816. pickResult = this._currentPickResult;
  1817. }
  1818. this._processPointerUp(pickResult, evt, clickInfo);
  1819. // Sprites
  1820. if (this.spriteManagers.length > 0) {
  1821. let spritePickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1822. if (spritePickResult) {
  1823. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  1824. if (spritePickResult.pickedSprite.actionManager) {
  1825. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1826. if (spritePickResult.pickedSprite.actionManager) {
  1827. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  1828. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1829. }
  1830. }
  1831. }
  1832. }
  1833. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== spritePickResult.pickedSprite) {
  1834. this._pickedDownSprite.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  1835. }
  1836. }
  1837. }
  1838. this._previousPickResult = this._currentPickResult;
  1839. });
  1840. };
  1841. this._onKeyDown = (evt: KeyboardEvent) => {
  1842. let type = KeyboardEventTypes.KEYDOWN;
  1843. if (this.onPreKeyboardObservable.hasObservers()) {
  1844. let pi = new KeyboardInfoPre(type, evt);
  1845. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1846. if (pi.skipOnPointerObservable) {
  1847. return;
  1848. }
  1849. }
  1850. if (this.onKeyboardObservable.hasObservers()) {
  1851. let pi = new KeyboardInfo(type, evt);
  1852. this.onKeyboardObservable.notifyObservers(pi, type);
  1853. }
  1854. if (this.actionManager) {
  1855. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1856. }
  1857. };
  1858. this._onKeyUp = (evt: KeyboardEvent) => {
  1859. let type = KeyboardEventTypes.KEYUP;
  1860. if (this.onPreKeyboardObservable.hasObservers()) {
  1861. let pi = new KeyboardInfoPre(type, evt);
  1862. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1863. if (pi.skipOnPointerObservable) {
  1864. return;
  1865. }
  1866. }
  1867. if (this.onKeyboardObservable.hasObservers()) {
  1868. let pi = new KeyboardInfo(type, evt);
  1869. this.onKeyboardObservable.notifyObservers(pi, type);
  1870. }
  1871. if (this.actionManager) {
  1872. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1873. }
  1874. };
  1875. let engine = this.getEngine();
  1876. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(() => {
  1877. if (!canvas) {
  1878. return;
  1879. }
  1880. canvas.addEventListener("keydown", this._onKeyDown, false);
  1881. canvas.addEventListener("keyup", this._onKeyUp, false);
  1882. });
  1883. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(() => {
  1884. if (!canvas) {
  1885. return;
  1886. }
  1887. canvas.removeEventListener("keydown", this._onKeyDown);
  1888. canvas.removeEventListener("keyup", this._onKeyUp);
  1889. });
  1890. var eventPrefix = Tools.GetPointerPrefix();
  1891. var canvas = this._engine.getRenderingCanvas();
  1892. if (!canvas) {
  1893. return;
  1894. }
  1895. if (attachMove) {
  1896. canvas.addEventListener(eventPrefix + "move", <any>this._onPointerMove, false);
  1897. // Wheel
  1898. canvas.addEventListener('mousewheel', <any>this._onPointerMove, false);
  1899. canvas.addEventListener('DOMMouseScroll', <any>this._onPointerMove, false);
  1900. }
  1901. if (attachDown) {
  1902. canvas.addEventListener(eventPrefix + "down", <any>this._onPointerDown, false);
  1903. }
  1904. if (attachUp) {
  1905. window.addEventListener(eventPrefix + "up", <any>this._onPointerUp, false);
  1906. }
  1907. canvas.tabIndex = 1;
  1908. }
  1909. /** Detaches all event handlers*/
  1910. public detachControl() {
  1911. let engine = this.getEngine();
  1912. var eventPrefix = Tools.GetPointerPrefix();
  1913. var canvas = engine.getRenderingCanvas();
  1914. if (!canvas) {
  1915. return;
  1916. }
  1917. canvas.removeEventListener(eventPrefix + "move", <any>this._onPointerMove);
  1918. canvas.removeEventListener(eventPrefix + "down", <any>this._onPointerDown);
  1919. window.removeEventListener(eventPrefix + "up", <any>this._onPointerUp);
  1920. if (this._onCanvasBlurObserver) {
  1921. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1922. }
  1923. if (this._onCanvasFocusObserver) {
  1924. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1925. }
  1926. // Wheel
  1927. canvas.removeEventListener('mousewheel', <any>this._onPointerMove);
  1928. canvas.removeEventListener('DOMMouseScroll', <any>this._onPointerMove);
  1929. // Keyboard
  1930. canvas.removeEventListener("keydown", this._onKeyDown);
  1931. canvas.removeEventListener("keyup", this._onKeyUp);
  1932. // Observables
  1933. this.onKeyboardObservable.clear();
  1934. this.onPreKeyboardObservable.clear();
  1935. this.onPointerObservable.clear();
  1936. this.onPrePointerObservable.clear();
  1937. }
  1938. /**
  1939. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  1940. * Delay loaded resources are not taking in account
  1941. * @return true if all required resources are ready
  1942. */
  1943. public isReady(): boolean {
  1944. if (this._isDisposed) {
  1945. return false;
  1946. }
  1947. if (this._pendingData.length > 0) {
  1948. return false;
  1949. }
  1950. let index: number;
  1951. let engine = this.getEngine();
  1952. // Geometries
  1953. for (index = 0; index < this._geometries.length; index++) {
  1954. var geometry = this._geometries[index];
  1955. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1956. return false;
  1957. }
  1958. }
  1959. // Meshes
  1960. for (index = 0; index < this.meshes.length; index++) {
  1961. var mesh = this.meshes[index];
  1962. if (!mesh.isEnabled()) {
  1963. continue;
  1964. }
  1965. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1966. continue;
  1967. }
  1968. if (!mesh.isReady(true)) {
  1969. return false;
  1970. }
  1971. // Effect layers
  1972. let hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && (<Mesh>mesh).instances.length > 0;
  1973. for (var layer of this.effectLayers) {
  1974. if (!layer.hasMesh(mesh)) {
  1975. continue;
  1976. }
  1977. for (var subMesh of mesh.subMeshes) {
  1978. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  1979. return false;
  1980. }
  1981. }
  1982. }
  1983. }
  1984. // Post-processes
  1985. if (this.activeCameras && this.activeCameras.length > 0) {
  1986. for (var camera of this.activeCameras) {
  1987. if (!camera.isReady(true)) {
  1988. return false;
  1989. }
  1990. }
  1991. } else if (this.activeCamera) {
  1992. if (!this.activeCamera.isReady(true)) {
  1993. return false;
  1994. }
  1995. }
  1996. // Particles
  1997. for (var particleSystem of this.particleSystems) {
  1998. if (!particleSystem.isReady()) {
  1999. return false;
  2000. }
  2001. }
  2002. return true;
  2003. }
  2004. /** Resets all cached information relative to material (including effect and visibility) */
  2005. public resetCachedMaterial(): void {
  2006. this._cachedMaterial = null;
  2007. this._cachedEffect = null;
  2008. this._cachedVisibility = null;
  2009. }
  2010. /**
  2011. * Registers a function to be called before every frame render
  2012. * @param func defines the function to register
  2013. */
  2014. public registerBeforeRender(func: () => void): void {
  2015. this.onBeforeRenderObservable.add(func);
  2016. }
  2017. /**
  2018. * Unregisters a function called before every frame render
  2019. * @param func defines the function to unregister
  2020. */
  2021. public unregisterBeforeRender(func: () => void): void {
  2022. this.onBeforeRenderObservable.removeCallback(func);
  2023. }
  2024. /**
  2025. * Registers a function to be called after every frame render
  2026. * @param func defines the function to register
  2027. */
  2028. public registerAfterRender(func: () => void): void {
  2029. this.onAfterRenderObservable.add(func);
  2030. }
  2031. /**
  2032. * Unregisters a function called after every frame render
  2033. * @param func defines the function to unregister
  2034. */
  2035. public unregisterAfterRender(func: () => void): void {
  2036. this.onAfterRenderObservable.removeCallback(func);
  2037. }
  2038. private _executeOnceBeforeRender(func: () => void): void {
  2039. let execFunc = () => {
  2040. func();
  2041. setTimeout(() => {
  2042. this.unregisterBeforeRender(execFunc);
  2043. });
  2044. }
  2045. this.registerBeforeRender(execFunc);
  2046. }
  2047. /**
  2048. * The provided function will run before render once and will be disposed afterwards.
  2049. * A timeout delay can be provided so that the function will be executed in N ms.
  2050. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  2051. * @param func The function to be executed.
  2052. * @param timeout optional delay in ms
  2053. */
  2054. public executeOnceBeforeRender(func: () => void, timeout?: number): void {
  2055. if (timeout !== undefined) {
  2056. setTimeout(() => {
  2057. this._executeOnceBeforeRender(func);
  2058. }, timeout);
  2059. } else {
  2060. this._executeOnceBeforeRender(func);
  2061. }
  2062. }
  2063. /** @hidden */
  2064. public _addPendingData(data: any): void {
  2065. this._pendingData.push(data);
  2066. }
  2067. /** @hidden */
  2068. public _removePendingData(data: any): void {
  2069. var wasLoading = this.isLoading;
  2070. var index = this._pendingData.indexOf(data);
  2071. if (index !== -1) {
  2072. this._pendingData.splice(index, 1);
  2073. }
  2074. if (wasLoading && !this.isLoading) {
  2075. this.onDataLoadedObservable.notifyObservers(this);
  2076. }
  2077. }
  2078. /**
  2079. * Returns the number of items waiting to be loaded
  2080. * @returns the number of items waiting to be loaded
  2081. */
  2082. public getWaitingItemsCount(): number {
  2083. return this._pendingData.length;
  2084. }
  2085. /**
  2086. * Returns a boolean indicating if the scene is still loading data
  2087. */
  2088. public get isLoading(): boolean {
  2089. return this._pendingData.length > 0;
  2090. }
  2091. /**
  2092. * Registers a function to be executed when the scene is ready
  2093. * @param {Function} func - the function to be executed
  2094. */
  2095. public executeWhenReady(func: () => void): void {
  2096. this.onReadyObservable.add(func);
  2097. if (this._executeWhenReadyTimeoutId !== -1) {
  2098. return;
  2099. }
  2100. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2101. this._checkIsReady();
  2102. }, 150);
  2103. }
  2104. /**
  2105. * Returns a promise that resolves when the scene is ready
  2106. * @returns A promise that resolves when the scene is ready
  2107. */
  2108. public whenReadyAsync(): Promise<void> {
  2109. return new Promise(resolve => {
  2110. this.executeWhenReady(() => {
  2111. resolve();
  2112. });
  2113. });
  2114. }
  2115. /** @hidden */
  2116. public _checkIsReady() {
  2117. if (this.isReady()) {
  2118. this.onReadyObservable.notifyObservers(this);
  2119. this.onReadyObservable.clear();
  2120. this._executeWhenReadyTimeoutId = -1;
  2121. return;
  2122. }
  2123. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2124. this._checkIsReady();
  2125. }, 150);
  2126. }
  2127. // Animations
  2128. /**
  2129. * Will start the animation sequence of a given target
  2130. * @param target defines the target
  2131. * @param from defines from which frame should animation start
  2132. * @param to defines until which frame should animation run.
  2133. * @param weight defines the weight to apply to the animation (1.0 by default)
  2134. * @param loop defines if the animation loops
  2135. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  2136. * @param onAnimationEnd defines the function to be executed when the animation ends
  2137. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  2138. * @returns the animatable object created for this animation
  2139. */
  2140. public beginWeightedAnimation(target: any, from: number, to: number, weight = 1.0, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  2141. let returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  2142. returnedAnimatable.weight = weight;
  2143. return returnedAnimatable;
  2144. }
  2145. /**
  2146. * Will start the animation sequence of a given target
  2147. * @param target defines the target
  2148. * @param from defines from which frame should animation start
  2149. * @param to defines until which frame should animation run.
  2150. * @param loop defines if the animation loops
  2151. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  2152. * @param onAnimationEnd defines the function to be executed when the animation ends
  2153. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  2154. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  2155. * @returns the animatable object created for this animation
  2156. */
  2157. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable, stopCurrent = true): Animatable {
  2158. if (from > to && speedRatio > 0) {
  2159. speedRatio *= -1;
  2160. }
  2161. if (stopCurrent) {
  2162. this.stopAnimation(target);
  2163. }
  2164. if (!animatable) {
  2165. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  2166. }
  2167. // Local animations
  2168. if (target.animations) {
  2169. animatable.appendAnimations(target, target.animations);
  2170. }
  2171. // Children animations
  2172. if (target.getAnimatables) {
  2173. var animatables = target.getAnimatables();
  2174. for (var index = 0; index < animatables.length; index++) {
  2175. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  2176. }
  2177. }
  2178. animatable.reset();
  2179. return animatable;
  2180. }
  2181. /**
  2182. * Begin a new animation on a given node
  2183. * @param target defines the target where the animation will take place
  2184. * @param animations defines the list of animations to start
  2185. * @param from defines the initial value
  2186. * @param to defines the final value
  2187. * @param loop defines if you want animation to loop (off by default)
  2188. * @param speedRatio defines the speed ratio to apply to all animations
  2189. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  2190. * @returns the list of created animatables
  2191. */
  2192. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  2193. if (speedRatio === undefined) {
  2194. speedRatio = 1.0;
  2195. }
  2196. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  2197. return animatable;
  2198. }
  2199. /**
  2200. * Begin a new animation on a given node and its hierarchy
  2201. * @param target defines the root node where the animation will take place
  2202. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  2203. * @param animations defines the list of animations to start
  2204. * @param from defines the initial value
  2205. * @param to defines the final value
  2206. * @param loop defines if you want animation to loop (off by default)
  2207. * @param speedRatio defines the speed ratio to apply to all animations
  2208. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  2209. * @returns the list of animatables created for all nodes
  2210. */
  2211. public beginDirectHierarchyAnimation(target: Node, directDescendantsOnly: boolean, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable[] {
  2212. let children = target.getDescendants(directDescendantsOnly);
  2213. let result = [];
  2214. for (var child of children) {
  2215. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  2216. }
  2217. return result;
  2218. }
  2219. /**
  2220. * Gets the animatable associated with a specific target
  2221. * @param target defines the target of the animatable
  2222. * @returns the required animatable if found
  2223. */
  2224. public getAnimatableByTarget(target: any): Nullable<Animatable> {
  2225. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2226. if (this._activeAnimatables[index].target === target) {
  2227. return this._activeAnimatables[index];
  2228. }
  2229. }
  2230. return null;
  2231. }
  2232. /**
  2233. * Gets all animatables associated with a given target
  2234. * @param target defines the target to look animatables for
  2235. * @returns an array of Animatables
  2236. */
  2237. public getAllAnimatablesByTarget(target: any): Array<Animatable> {
  2238. let result = [];
  2239. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2240. if (this._activeAnimatables[index].target === target) {
  2241. result.push(this._activeAnimatables[index]);
  2242. }
  2243. }
  2244. return result;
  2245. }
  2246. /**
  2247. * Gets all animatable attached to the scene
  2248. */
  2249. public get animatables(): Animatable[] {
  2250. return this._activeAnimatables;
  2251. }
  2252. /**
  2253. * Will stop the animation of the given target
  2254. * @param target - the target
  2255. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  2256. */
  2257. public stopAnimation(target: any, animationName?: string): void {
  2258. var animatables = this.getAllAnimatablesByTarget(target);
  2259. for (var animatable of animatables) {
  2260. animatable.stop(animationName);
  2261. }
  2262. }
  2263. /**
  2264. * Stops and removes all animations that have been applied to the scene
  2265. */
  2266. public stopAllAnimations(): void {
  2267. if (this._activeAnimatables) {
  2268. for (let i = 0; i < this._activeAnimatables.length; i++) {
  2269. this._activeAnimatables[i].stop();
  2270. }
  2271. this._activeAnimatables = [];
  2272. }
  2273. for (var group of this.animationGroups) {
  2274. group.stop();
  2275. }
  2276. }
  2277. private _animate(): void {
  2278. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  2279. return;
  2280. }
  2281. // Getting time
  2282. var now = Tools.Now;
  2283. if (!this._animationTimeLast) {
  2284. if (this._pendingData.length > 0) {
  2285. return;
  2286. }
  2287. this._animationTimeLast = now;
  2288. }
  2289. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  2290. this._animationTime += deltaTime;
  2291. this._animationTimeLast = now;
  2292. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2293. this._activeAnimatables[index]._animate(this._animationTime);
  2294. }
  2295. // Late animation bindings
  2296. this._processLateAnimationBindings();
  2297. }
  2298. /** @hidden */
  2299. public _registerTargetForLateAnimationBinding(runtimeAnimation: RuntimeAnimation): void {
  2300. let target = runtimeAnimation.target;
  2301. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  2302. if (!target._lateAnimationHolders) {
  2303. target._lateAnimationHolders = {};
  2304. }
  2305. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  2306. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  2307. totalWeight: 0,
  2308. animations: []
  2309. }
  2310. }
  2311. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  2312. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  2313. }
  2314. private _processLateAnimationBindingsForMatrices(holder: {
  2315. totalWeight: number,
  2316. animations: RuntimeAnimation[]
  2317. }, originalValue: Matrix): any {
  2318. let normalizer = 1.0;
  2319. let finalPosition = Tmp.Vector3[0];
  2320. let finalScaling = Tmp.Vector3[1];
  2321. let finalQuaternion = Tmp.Quaternion[0];
  2322. let startIndex = 0;
  2323. let originalAnimation = holder.animations[0];
  2324. var scale = 1;
  2325. if (holder.totalWeight < 1.0) {
  2326. // We need to mix the original value in
  2327. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  2328. scale = 1.0 - holder.totalWeight;
  2329. } else {
  2330. startIndex = 1;
  2331. // We need to normalize the weights
  2332. normalizer = holder.totalWeight;
  2333. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  2334. scale = originalAnimation.weight / normalizer;
  2335. if (scale == 1) {
  2336. return originalAnimation.currentValue;
  2337. }
  2338. }
  2339. finalScaling.scaleInPlace(scale);
  2340. finalPosition.scaleInPlace(scale);
  2341. finalQuaternion.scaleInPlace(scale);
  2342. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  2343. var runtimeAnimation = holder.animations[animIndex];
  2344. var scale = runtimeAnimation.weight / normalizer;
  2345. let currentPosition = Tmp.Vector3[2];
  2346. let currentScaling = Tmp.Vector3[3];
  2347. let currentQuaternion = Tmp.Quaternion[1];
  2348. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  2349. currentScaling.scaleAndAddToRef(scale, finalScaling);
  2350. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  2351. currentPosition.scaleAndAddToRef(scale, finalPosition);
  2352. }
  2353. Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  2354. return originalAnimation._workValue;
  2355. }
  2356. private _processLateAnimationBindings(): void {
  2357. if (!this._registeredForLateAnimationBindings.length) {
  2358. return;
  2359. }
  2360. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  2361. var target = this._registeredForLateAnimationBindings.data[index];
  2362. for (var path in target._lateAnimationHolders) {
  2363. var holder = target._lateAnimationHolders[path];
  2364. let originalAnimation = holder.animations[0];
  2365. let originalValue = originalAnimation.originalValue;
  2366. let finalTarget = originalAnimation.target;
  2367. let matrixDecomposeMode = Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  2368. let finalValue: any;
  2369. if (matrixDecomposeMode) {
  2370. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  2371. } else {
  2372. let startIndex = 0;
  2373. let normalizer = 1.0;
  2374. if (holder.totalWeight < 1.0) {
  2375. // We need to mix the original value in
  2376. if (originalValue.scale) {
  2377. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  2378. } else {
  2379. finalValue = originalValue * (1.0 - holder.totalWeight);
  2380. }
  2381. } else {
  2382. // We need to normalize the weights
  2383. normalizer = holder.totalWeight;
  2384. let scale = originalAnimation.weight / normalizer;
  2385. if (scale !== 1) {
  2386. if (originalAnimation.currentValue.scale) {
  2387. finalValue = originalAnimation.currentValue.scale(scale);
  2388. } else {
  2389. finalValue = originalAnimation.currentValue * scale;
  2390. }
  2391. } else {
  2392. finalValue = originalAnimation.currentValue;
  2393. }
  2394. startIndex = 1;
  2395. }
  2396. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  2397. var runtimeAnimation = holder.animations[animIndex];
  2398. var scale = runtimeAnimation.weight / normalizer;
  2399. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  2400. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  2401. } else {
  2402. finalValue += runtimeAnimation.currentValue * scale;
  2403. }
  2404. }
  2405. }
  2406. finalTarget[path] = finalValue;
  2407. }
  2408. target._lateAnimationHolders = {};
  2409. }
  2410. this._registeredForLateAnimationBindings.reset();
  2411. }
  2412. // Matrix
  2413. /** @hidden */
  2414. public _switchToAlternateCameraConfiguration(active: boolean): void {
  2415. this._useAlternateCameraConfiguration = active;
  2416. }
  2417. /**
  2418. * Gets the current view matrix
  2419. * @returns a Matrix
  2420. */
  2421. public getViewMatrix(): Matrix {
  2422. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  2423. }
  2424. /**
  2425. * Gets the current projection matrix
  2426. * @returns a Matrix
  2427. */
  2428. public getProjectionMatrix(): Matrix {
  2429. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  2430. }
  2431. /**
  2432. * Gets the current transform matrix
  2433. * @returns a Matrix made of View * Projection
  2434. */
  2435. public getTransformMatrix(): Matrix {
  2436. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  2437. }
  2438. /**
  2439. * Sets the current transform matrix
  2440. * @param view defines the View matrix to use
  2441. * @param projection defines the Projection matrix to use
  2442. */
  2443. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  2444. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  2445. return;
  2446. }
  2447. this._viewUpdateFlag = view.updateFlag;
  2448. this._projectionUpdateFlag = projection.updateFlag;
  2449. this._viewMatrix = view;
  2450. this._projectionMatrix = projection;
  2451. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  2452. // Update frustum
  2453. if (!this._frustumPlanes) {
  2454. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  2455. } else {
  2456. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  2457. }
  2458. if (this.activeCamera && this.activeCamera._alternateCamera) {
  2459. let otherCamera = this.activeCamera._alternateCamera;
  2460. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), Tmp.Matrix[0]);
  2461. Frustum.GetRightPlaneToRef(Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  2462. }
  2463. if (this._sceneUbo.useUbo) {
  2464. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  2465. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  2466. this._sceneUbo.update();
  2467. }
  2468. }
  2469. /** @hidden */
  2470. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  2471. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  2472. return;
  2473. }
  2474. this._alternateViewUpdateFlag = view.updateFlag;
  2475. this._alternateProjectionUpdateFlag = projection.updateFlag;
  2476. this._alternateViewMatrix = view;
  2477. this._alternateProjectionMatrix = projection;
  2478. if (!this._alternateTransformMatrix) {
  2479. this._alternateTransformMatrix = Matrix.Zero();
  2480. }
  2481. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  2482. if (!this._alternateSceneUbo) {
  2483. this._createAlternateUbo();
  2484. }
  2485. if (this._alternateSceneUbo.useUbo) {
  2486. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  2487. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  2488. this._alternateSceneUbo.update();
  2489. }
  2490. }
  2491. /**
  2492. * Gets the uniform buffer used to store scene data
  2493. * @returns a UniformBuffer
  2494. */
  2495. public getSceneUniformBuffer(): UniformBuffer {
  2496. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  2497. }
  2498. /**
  2499. * Gets an unique (relatively to the current scene) Id
  2500. * @returns an unique number for the scene
  2501. */
  2502. public getUniqueId() {
  2503. var result = Scene._uniqueIdCounter;
  2504. Scene._uniqueIdCounter++;
  2505. return result;
  2506. }
  2507. /**
  2508. * Add a mesh to the list of scene's meshes
  2509. * @param newMesh defines the mesh to add
  2510. */
  2511. public addMesh(newMesh: AbstractMesh) {
  2512. this.meshes.push(newMesh);
  2513. //notify the collision coordinator
  2514. if (this.collisionCoordinator) {
  2515. this.collisionCoordinator.onMeshAdded(newMesh);
  2516. }
  2517. newMesh._resyncLightSources();
  2518. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  2519. }
  2520. /**
  2521. * Remove a mesh for the list of scene's meshes
  2522. * @param toRemove defines the mesh to remove
  2523. * @returns the index where the mesh was in the mesh list
  2524. */
  2525. public removeMesh(toRemove: AbstractMesh): number {
  2526. var index = this.meshes.indexOf(toRemove);
  2527. if (index !== -1) {
  2528. // Remove from the scene if mesh found
  2529. this.meshes.splice(index, 1);
  2530. }
  2531. this.onMeshRemovedObservable.notifyObservers(toRemove);
  2532. return index;
  2533. }
  2534. /**
  2535. * Add a transform node to the list of scene's transform nodes
  2536. * @param newTransformNode defines the transform node to add
  2537. */
  2538. public addTransformNode(newTransformNode: TransformNode) {
  2539. this.transformNodes.push(newTransformNode);
  2540. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  2541. }
  2542. /**
  2543. * Remove a transform node for the list of scene's transform nodes
  2544. * @param toRemove defines the transform node to remove
  2545. * @returns the index where the transform node was in the transform node list
  2546. */
  2547. public removeTransformNode(toRemove: TransformNode): number {
  2548. var index = this.transformNodes.indexOf(toRemove);
  2549. if (index !== -1) {
  2550. // Remove from the scene if found
  2551. this.transformNodes.splice(index, 1);
  2552. }
  2553. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  2554. return index;
  2555. }
  2556. /**
  2557. * Remove a skeleton for the list of scene's skeletons
  2558. * @param toRemove defines the skeleton to remove
  2559. * @returns the index where the skeleton was in the skeleton list
  2560. */
  2561. public removeSkeleton(toRemove: Skeleton): number {
  2562. var index = this.skeletons.indexOf(toRemove);
  2563. if (index !== -1) {
  2564. // Remove from the scene if found
  2565. this.skeletons.splice(index, 1);
  2566. }
  2567. return index;
  2568. }
  2569. /**
  2570. * Remove a morph target for the list of scene's morph targets
  2571. * @param toRemove defines the morph target to remove
  2572. * @returns the index where the morph target was in the morph target list
  2573. */
  2574. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  2575. var index = this.morphTargetManagers.indexOf(toRemove);
  2576. if (index !== -1) {
  2577. // Remove from the scene if found
  2578. this.morphTargetManagers.splice(index, 1);
  2579. }
  2580. return index;
  2581. }
  2582. /**
  2583. * Remove a light for the list of scene's lights
  2584. * @param toRemove defines the light to remove
  2585. * @returns the index where the light was in the light list
  2586. */
  2587. public removeLight(toRemove: Light): number {
  2588. var index = this.lights.indexOf(toRemove);
  2589. if (index !== -1) {
  2590. // Remove from meshes
  2591. for (var mesh of this.meshes) {
  2592. mesh._removeLightSource(toRemove);
  2593. }
  2594. // Remove from the scene if mesh found
  2595. this.lights.splice(index, 1);
  2596. this.sortLightsByPriority();
  2597. }
  2598. this.onLightRemovedObservable.notifyObservers(toRemove);
  2599. return index;
  2600. }
  2601. /**
  2602. * Remove a camera for the list of scene's cameras
  2603. * @param toRemove defines the camera to remove
  2604. * @returns the index where the camera was in the camera list
  2605. */
  2606. public removeCamera(toRemove: Camera): number {
  2607. var index = this.cameras.indexOf(toRemove);
  2608. if (index !== -1) {
  2609. // Remove from the scene if mesh found
  2610. this.cameras.splice(index, 1);
  2611. }
  2612. // Remove from activeCameras
  2613. var index2 = this.activeCameras.indexOf(toRemove);
  2614. if (index2 !== -1) {
  2615. // Remove from the scene if mesh found
  2616. this.activeCameras.splice(index2, 1);
  2617. }
  2618. // Reset the activeCamera
  2619. if (this.activeCamera === toRemove) {
  2620. if (this.cameras.length > 0) {
  2621. this.activeCamera = this.cameras[0];
  2622. } else {
  2623. this.activeCamera = null;
  2624. }
  2625. }
  2626. this.onCameraRemovedObservable.notifyObservers(toRemove);
  2627. return index;
  2628. }
  2629. /**
  2630. * Remove a particle system for the list of scene's particle systems
  2631. * @param toRemove defines the particle system to remove
  2632. * @returns the index where the particle system was in the particle system list
  2633. */
  2634. public removeParticleSystem(toRemove: IParticleSystem): number {
  2635. var index = this.particleSystems.indexOf(toRemove);
  2636. if (index !== -1) {
  2637. this.particleSystems.splice(index, 1);
  2638. }
  2639. return index;
  2640. }
  2641. /**
  2642. * Remove a animation for the list of scene's animations
  2643. * @param toRemove defines the animation to remove
  2644. * @returns the index where the animation was in the animation list
  2645. */
  2646. public removeAnimation(toRemove: Animation): number {
  2647. var index = this.animations.indexOf(toRemove);
  2648. if (index !== -1) {
  2649. this.animations.splice(index, 1);
  2650. }
  2651. return index;
  2652. }
  2653. /**
  2654. * Removes the given animation group from this scene.
  2655. * @param toRemove The animation group to remove
  2656. * @returns The index of the removed animation group
  2657. */
  2658. public removeAnimationGroup(toRemove: AnimationGroup): number {
  2659. var index = this.animationGroups.indexOf(toRemove);
  2660. if (index !== -1) {
  2661. this.animationGroups.splice(index, 1);
  2662. }
  2663. return index;
  2664. }
  2665. /**
  2666. * Removes the given multi-material from this scene.
  2667. * @param toRemove The multi-material to remove
  2668. * @returns The index of the removed multi-material
  2669. */
  2670. public removeMultiMaterial(toRemove: MultiMaterial): number {
  2671. var index = this.multiMaterials.indexOf(toRemove);
  2672. if (index !== -1) {
  2673. this.multiMaterials.splice(index, 1);
  2674. }
  2675. return index;
  2676. }
  2677. /**
  2678. * Removes the given material from this scene.
  2679. * @param toRemove The material to remove
  2680. * @returns The index of the removed material
  2681. */
  2682. public removeMaterial(toRemove: Material): number {
  2683. var index = this.materials.indexOf(toRemove);
  2684. if (index !== -1) {
  2685. this.materials.splice(index, 1);
  2686. }
  2687. return index;
  2688. }
  2689. /**
  2690. * Removes the given lens flare system from this scene.
  2691. * @param toRemove The lens flare system to remove
  2692. * @returns The index of the removed lens flare system
  2693. */
  2694. public removeLensFlareSystem(toRemove: LensFlareSystem): number {
  2695. var index = this.lensFlareSystems.indexOf(toRemove);
  2696. if (index !== -1) {
  2697. this.lensFlareSystems.splice(index, 1);
  2698. }
  2699. return index;
  2700. }
  2701. /**
  2702. * Removes the given action manager from this scene.
  2703. * @param toRemove The action manager to remove
  2704. * @returns The index of the removed action manager
  2705. */
  2706. public removeActionManager(toRemove: ActionManager): number {
  2707. var index = this._actionManagers.indexOf(toRemove);
  2708. if (index !== -1) {
  2709. this._actionManagers.splice(index, 1);
  2710. }
  2711. return index;
  2712. }
  2713. /**
  2714. * Removes the given effect layer from this scene.
  2715. * @param toRemove defines the effect layer to remove
  2716. * @returns the index of the removed effect layer
  2717. */
  2718. public removeEffectLayer(toRemove: EffectLayer): number {
  2719. var index = this.effectLayers.indexOf(toRemove);
  2720. if (index !== -1) {
  2721. this.effectLayers.splice(index, 1);
  2722. }
  2723. return index;
  2724. }
  2725. /**
  2726. * Removes the given texture from this scene.
  2727. * @param toRemove The texture to remove
  2728. * @returns The index of the removed texture
  2729. */
  2730. public removeTexture(toRemove: BaseTexture): number {
  2731. var index = this.textures.indexOf(toRemove);
  2732. if (index !== -1) {
  2733. this.textures.splice(index, 1);
  2734. }
  2735. return index;
  2736. }
  2737. /**
  2738. * Adds the given light to this scene
  2739. * @param newLight The light to add
  2740. */
  2741. public addLight(newLight: Light): void {
  2742. this.lights.push(newLight);
  2743. this.sortLightsByPriority();
  2744. // Add light to all meshes (To support if the light is removed and then readded)
  2745. for (var mesh of this.meshes) {
  2746. if (mesh._lightSources.indexOf(newLight) === -1) {
  2747. mesh._lightSources.push(newLight);
  2748. mesh._resyncLightSources();
  2749. }
  2750. }
  2751. this.onNewLightAddedObservable.notifyObservers(newLight);
  2752. }
  2753. /**
  2754. * Sorts the list list based on light priorities
  2755. */
  2756. public sortLightsByPriority(): void {
  2757. if (this.requireLightSorting) {
  2758. this.lights.sort(Light.CompareLightsPriority);
  2759. }
  2760. }
  2761. /**
  2762. * Adds the given camera to this scene
  2763. * @param newCamera The camera to add
  2764. */
  2765. public addCamera(newCamera: Camera): void {
  2766. this.cameras.push(newCamera);
  2767. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  2768. }
  2769. /**
  2770. * Adds the given skeleton to this scene
  2771. * @param newSkeleton The skeleton to add
  2772. */
  2773. public addSkeleton(newSkeleton: Skeleton): void {
  2774. this.skeletons.push(newSkeleton);
  2775. }
  2776. /**
  2777. * Adds the given particle system to this scene
  2778. * @param newParticleSystem The particle system to add
  2779. */
  2780. public addParticleSystem(newParticleSystem: IParticleSystem): void {
  2781. this.particleSystems.push(newParticleSystem);
  2782. }
  2783. /**
  2784. * Adds the given animation to this scene
  2785. * @param newAnimation The animation to add
  2786. */
  2787. public addAnimation(newAnimation: Animation): void {
  2788. this.animations.push(newAnimation);
  2789. }
  2790. /**
  2791. * Adds the given animation group to this scene.
  2792. * @param newAnimationGroup The animation group to add
  2793. */
  2794. public addAnimationGroup(newAnimationGroup: AnimationGroup): void {
  2795. this.animationGroups.push(newAnimationGroup);
  2796. }
  2797. /**
  2798. * Adds the given multi-material to this scene
  2799. * @param newMultiMaterial The multi-material to add
  2800. */
  2801. public addMultiMaterial(newMultiMaterial: MultiMaterial): void {
  2802. this.multiMaterials.push(newMultiMaterial);
  2803. }
  2804. /**
  2805. * Adds the given material to this scene
  2806. * @param newMaterial The material to add
  2807. */
  2808. public addMaterial(newMaterial: Material): void {
  2809. this.materials.push(newMaterial);
  2810. }
  2811. /**
  2812. * Adds the given morph target to this scene
  2813. * @param newMorphTargetManager The morph target to add
  2814. */
  2815. public addMorphTargetManager(newMorphTargetManager: MorphTargetManager): void {
  2816. this.morphTargetManagers.push(newMorphTargetManager);
  2817. }
  2818. /**
  2819. * Adds the given geometry to this scene
  2820. * @param newGeometry The geometry to add
  2821. */
  2822. public addGeometry(newGeometry: Geometry): void {
  2823. this._geometries.push(newGeometry);
  2824. }
  2825. /**
  2826. * Adds the given lens flare system to this scene
  2827. * @param newLensFlareSystem The lens flare system to add
  2828. */
  2829. public addLensFlareSystem(newLensFlareSystem: LensFlareSystem): void {
  2830. this.lensFlareSystems.push(newLensFlareSystem);
  2831. }
  2832. /**
  2833. * Adds the given effect layer to this scene
  2834. * @param newEffectLayer defines the effect layer to add
  2835. */
  2836. public addEffectLayer(newEffectLayer: EffectLayer): void {
  2837. this.effectLayers.push(newEffectLayer);
  2838. }
  2839. /**
  2840. * Adds the given action manager to this scene
  2841. * @param newActionManager The action manager to add
  2842. */
  2843. public addActionManager(newActionManager: ActionManager): void {
  2844. this._actionManagers.push(newActionManager);
  2845. }
  2846. /**
  2847. * Adds the given texture to this scene.
  2848. * @param newTexture The texture to add
  2849. */
  2850. public addTexture(newTexture: BaseTexture): void {
  2851. this.textures.push(newTexture);
  2852. }
  2853. /**
  2854. * Switch active camera
  2855. * @param newCamera defines the new active camera
  2856. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  2857. */
  2858. public switchActiveCamera(newCamera: Camera, attachControl = true): void {
  2859. var canvas = this._engine.getRenderingCanvas();
  2860. if (!canvas) {
  2861. return;
  2862. }
  2863. if (this.activeCamera) {
  2864. this.activeCamera.detachControl(canvas);
  2865. }
  2866. this.activeCamera = newCamera;
  2867. if (attachControl) {
  2868. newCamera.attachControl(canvas);
  2869. }
  2870. }
  2871. /**
  2872. * sets the active camera of the scene using its ID
  2873. * @param id defines the camera's ID
  2874. * @return the new active camera or null if none found.
  2875. */
  2876. public setActiveCameraByID(id: string): Nullable<Camera> {
  2877. var camera = this.getCameraByID(id);
  2878. if (camera) {
  2879. this.activeCamera = camera;
  2880. return camera;
  2881. }
  2882. return null;
  2883. }
  2884. /**
  2885. * sets the active camera of the scene using its name
  2886. * @param name defines the camera's name
  2887. * @returns the new active camera or null if none found.
  2888. */
  2889. public setActiveCameraByName(name: string): Nullable<Camera> {
  2890. var camera = this.getCameraByName(name);
  2891. if (camera) {
  2892. this.activeCamera = camera;
  2893. return camera;
  2894. }
  2895. return null;
  2896. }
  2897. /**
  2898. * get an animation group using its name
  2899. * @param name defines the material's name
  2900. * @return the animation group or null if none found.
  2901. */
  2902. public getAnimationGroupByName(name: string): Nullable<AnimationGroup> {
  2903. for (var index = 0; index < this.animationGroups.length; index++) {
  2904. if (this.animationGroups[index].name === name) {
  2905. return this.animationGroups[index];
  2906. }
  2907. }
  2908. return null;
  2909. }
  2910. /**
  2911. * get a material using its id
  2912. * @param id defines the material's ID
  2913. * @return the material or null if none found.
  2914. */
  2915. public getMaterialByID(id: string): Nullable<Material> {
  2916. for (var index = 0; index < this.materials.length; index++) {
  2917. if (this.materials[index].id === id) {
  2918. return this.materials[index];
  2919. }
  2920. }
  2921. return null;
  2922. }
  2923. /**
  2924. * Gets a material using its name
  2925. * @param name defines the material's name
  2926. * @return the material or null if none found.
  2927. */
  2928. public getMaterialByName(name: string): Nullable<Material> {
  2929. for (var index = 0; index < this.materials.length; index++) {
  2930. if (this.materials[index].name === name) {
  2931. return this.materials[index];
  2932. }
  2933. }
  2934. return null;
  2935. }
  2936. /**
  2937. * Gets a lens flare system using its name
  2938. * @param name defines the name to look for
  2939. * @returns the lens flare system or null if not found
  2940. */
  2941. public getLensFlareSystemByName(name: string): Nullable<LensFlareSystem> {
  2942. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  2943. if (this.lensFlareSystems[index].name === name) {
  2944. return this.lensFlareSystems[index];
  2945. }
  2946. }
  2947. return null;
  2948. }
  2949. /**
  2950. * Gets a lens flare system using its id
  2951. * @param id defines the id to look for
  2952. * @returns the lens flare system or null if not found
  2953. */
  2954. public getLensFlareSystemByID(id: string): Nullable<LensFlareSystem> {
  2955. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  2956. if (this.lensFlareSystems[index].id === id) {
  2957. return this.lensFlareSystems[index];
  2958. }
  2959. }
  2960. return null;
  2961. }
  2962. /**
  2963. * Gets a camera using its id
  2964. * @param id defines the id to look for
  2965. * @returns the camera or null if not found
  2966. */
  2967. public getCameraByID(id: string): Nullable<Camera> {
  2968. for (var index = 0; index < this.cameras.length; index++) {
  2969. if (this.cameras[index].id === id) {
  2970. return this.cameras[index];
  2971. }
  2972. }
  2973. return null;
  2974. }
  2975. /**
  2976. * Gets a camera using its unique id
  2977. * @param uniqueId defines the unique id to look for
  2978. * @returns the camera or null if not found
  2979. */
  2980. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  2981. for (var index = 0; index < this.cameras.length; index++) {
  2982. if (this.cameras[index].uniqueId === uniqueId) {
  2983. return this.cameras[index];
  2984. }
  2985. }
  2986. return null;
  2987. }
  2988. /**
  2989. * Gets a camera using its name
  2990. * @param name defines the camera's name
  2991. * @return the camera or null if none found.
  2992. */
  2993. public getCameraByName(name: string): Nullable<Camera> {
  2994. for (var index = 0; index < this.cameras.length; index++) {
  2995. if (this.cameras[index].name === name) {
  2996. return this.cameras[index];
  2997. }
  2998. }
  2999. return null;
  3000. }
  3001. /**
  3002. * Gets a bone using its id
  3003. * @param id defines the bone's id
  3004. * @return the bone or null if not found
  3005. */
  3006. public getBoneByID(id: string): Nullable<Bone> {
  3007. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  3008. var skeleton = this.skeletons[skeletonIndex];
  3009. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  3010. if (skeleton.bones[boneIndex].id === id) {
  3011. return skeleton.bones[boneIndex];
  3012. }
  3013. }
  3014. }
  3015. return null;
  3016. }
  3017. /**
  3018. * Gets a bone using its id
  3019. * @param name defines the bone's name
  3020. * @return the bone or null if not found
  3021. */
  3022. public getBoneByName(name: string): Nullable<Bone> {
  3023. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  3024. var skeleton = this.skeletons[skeletonIndex];
  3025. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  3026. if (skeleton.bones[boneIndex].name === name) {
  3027. return skeleton.bones[boneIndex];
  3028. }
  3029. }
  3030. }
  3031. return null;
  3032. }
  3033. /**
  3034. * Gets a light node using its name
  3035. * @param name defines the the light's name
  3036. * @return the light or null if none found.
  3037. */
  3038. public getLightByName(name: string): Nullable<Light> {
  3039. for (var index = 0; index < this.lights.length; index++) {
  3040. if (this.lights[index].name === name) {
  3041. return this.lights[index];
  3042. }
  3043. }
  3044. return null;
  3045. }
  3046. /**
  3047. * Gets a light node using its id
  3048. * @param id defines the light's id
  3049. * @return the light or null if none found.
  3050. */
  3051. public getLightByID(id: string): Nullable<Light> {
  3052. for (var index = 0; index < this.lights.length; index++) {
  3053. if (this.lights[index].id === id) {
  3054. return this.lights[index];
  3055. }
  3056. }
  3057. return null;
  3058. }
  3059. /**
  3060. * Gets a light node using its scene-generated unique ID
  3061. * @param uniqueId defines the light's unique id
  3062. * @return the light or null if none found.
  3063. */
  3064. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  3065. for (var index = 0; index < this.lights.length; index++) {
  3066. if (this.lights[index].uniqueId === uniqueId) {
  3067. return this.lights[index];
  3068. }
  3069. }
  3070. return null;
  3071. }
  3072. /**
  3073. * Gets a particle system by id
  3074. * @param id defines the particle system id
  3075. * @return the corresponding system or null if none found
  3076. */
  3077. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  3078. for (var index = 0; index < this.particleSystems.length; index++) {
  3079. if (this.particleSystems[index].id === id) {
  3080. return this.particleSystems[index];
  3081. }
  3082. }
  3083. return null;
  3084. }
  3085. /**
  3086. * Gets a geometry using its ID
  3087. * @param id defines the geometry's id
  3088. * @return the geometry or null if none found.
  3089. */
  3090. public getGeometryByID(id: string): Nullable<Geometry> {
  3091. for (var index = 0; index < this._geometries.length; index++) {
  3092. if (this._geometries[index].id === id) {
  3093. return this._geometries[index];
  3094. }
  3095. }
  3096. return null;
  3097. }
  3098. /**
  3099. * Add a new geometry to this scene
  3100. * @param geometry defines the geometry to be added to the scene.
  3101. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  3102. * @return a boolean defining if the geometry was added or not
  3103. */
  3104. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  3105. if (!force && this.getGeometryByID(geometry.id)) {
  3106. return false;
  3107. }
  3108. this._geometries.push(geometry);
  3109. //notify the collision coordinator
  3110. if (this.collisionCoordinator) {
  3111. this.collisionCoordinator.onGeometryAdded(geometry);
  3112. }
  3113. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  3114. return true;
  3115. }
  3116. /**
  3117. * Removes an existing geometry
  3118. * @param geometry defines the geometry to be removed from the scene
  3119. * @return a boolean defining if the geometry was removed or not
  3120. */
  3121. public removeGeometry(geometry: Geometry): boolean {
  3122. var index = this._geometries.indexOf(geometry);
  3123. if (index > -1) {
  3124. this._geometries.splice(index, 1);
  3125. //notify the collision coordinator
  3126. if (this.collisionCoordinator) {
  3127. this.collisionCoordinator.onGeometryDeleted(geometry);
  3128. }
  3129. this.onGeometryRemovedObservable.notifyObservers(geometry);
  3130. return true;
  3131. }
  3132. return false;
  3133. }
  3134. /**
  3135. * Gets the list of geometries attached to the scene
  3136. * @returns an array of Geometry
  3137. */
  3138. public getGeometries(): Geometry[] {
  3139. return this._geometries;
  3140. }
  3141. /**
  3142. * Gets the first added mesh found of a given ID
  3143. * @param id defines the id to search for
  3144. * @return the mesh found or null if not found at all
  3145. */
  3146. public getMeshByID(id: string): Nullable<AbstractMesh> {
  3147. for (var index = 0; index < this.meshes.length; index++) {
  3148. if (this.meshes[index].id === id) {
  3149. return this.meshes[index];
  3150. }
  3151. }
  3152. return null;
  3153. }
  3154. /**
  3155. * Gets a list of meshes using their id
  3156. * @param id defines the id to search for
  3157. * @returns a list of meshes
  3158. */
  3159. public getMeshesByID(id: string): Array<AbstractMesh> {
  3160. return this.meshes.filter(function (m) {
  3161. return m.id === id;
  3162. })
  3163. }
  3164. /**
  3165. * Gets the first added transform node found of a given ID
  3166. * @param id defines the id to search for
  3167. * @return the found transform node or null if not found at all.
  3168. */
  3169. public getTransformNodeByID(id: string): Nullable<TransformNode> {
  3170. for (var index = 0; index < this.transformNodes.length; index++) {
  3171. if (this.transformNodes[index].id === id) {
  3172. return this.transformNodes[index];
  3173. }
  3174. }
  3175. return null;
  3176. }
  3177. /**
  3178. * Gets a list of transform nodes using their id
  3179. * @param id defines the id to search for
  3180. * @returns a list of transform nodes
  3181. */
  3182. public getTransformNodesByID(id: string): Array<TransformNode> {
  3183. return this.transformNodes.filter(function (m) {
  3184. return m.id === id;
  3185. })
  3186. }
  3187. /**
  3188. * Gets a mesh with its auto-generated unique id
  3189. * @param uniqueId defines the unique id to search for
  3190. * @return the found mesh or null if not found at all.
  3191. */
  3192. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  3193. for (var index = 0; index < this.meshes.length; index++) {
  3194. if (this.meshes[index].uniqueId === uniqueId) {
  3195. return this.meshes[index];
  3196. }
  3197. }
  3198. return null;
  3199. }
  3200. /**
  3201. * Gets a the last added mesh using a given id
  3202. * @param id defines the id to search for
  3203. * @return the found mesh or null if not found at all.
  3204. */
  3205. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  3206. for (var index = this.meshes.length - 1; index >= 0; index--) {
  3207. if (this.meshes[index].id === id) {
  3208. return this.meshes[index];
  3209. }
  3210. }
  3211. return null;
  3212. }
  3213. /**
  3214. * Gets a the last added node (Mesh, Camera, Light) using a given id
  3215. * @param id defines the id to search for
  3216. * @return the found node or null if not found at all
  3217. */
  3218. public getLastEntryByID(id: string): Nullable<Node> {
  3219. var index: number;
  3220. for (index = this.meshes.length - 1; index >= 0; index--) {
  3221. if (this.meshes[index].id === id) {
  3222. return this.meshes[index];
  3223. }
  3224. }
  3225. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  3226. if (this.transformNodes[index].id === id) {
  3227. return this.transformNodes[index];
  3228. }
  3229. }
  3230. for (index = this.cameras.length - 1; index >= 0; index--) {
  3231. if (this.cameras[index].id === id) {
  3232. return this.cameras[index];
  3233. }
  3234. }
  3235. for (index = this.lights.length - 1; index >= 0; index--) {
  3236. if (this.lights[index].id === id) {
  3237. return this.lights[index];
  3238. }
  3239. }
  3240. return null;
  3241. }
  3242. /**
  3243. * Gets a node (Mesh, Camera, Light) using a given id
  3244. * @param id defines the id to search for
  3245. * @return the found node or null if not found at all
  3246. */
  3247. public getNodeByID(id: string): Nullable<Node> {
  3248. var mesh = this.getMeshByID(id);
  3249. if (mesh) {
  3250. return mesh;
  3251. }
  3252. var light = this.getLightByID(id);
  3253. if (light) {
  3254. return light;
  3255. }
  3256. var camera = this.getCameraByID(id);
  3257. if (camera) {
  3258. return camera;
  3259. }
  3260. var bone = this.getBoneByID(id);
  3261. return bone;
  3262. }
  3263. /**
  3264. * Gets a node (Mesh, Camera, Light) using a given name
  3265. * @param name defines the name to search for
  3266. * @return the found node or null if not found at all.
  3267. */
  3268. public getNodeByName(name: string): Nullable<Node> {
  3269. var mesh = this.getMeshByName(name);
  3270. if (mesh) {
  3271. return mesh;
  3272. }
  3273. var light = this.getLightByName(name);
  3274. if (light) {
  3275. return light;
  3276. }
  3277. var camera = this.getCameraByName(name);
  3278. if (camera) {
  3279. return camera;
  3280. }
  3281. var bone = this.getBoneByName(name);
  3282. return bone;
  3283. }
  3284. /**
  3285. * Gets a mesh using a given name
  3286. * @param name defines the name to search for
  3287. * @return the found mesh or null if not found at all.
  3288. */
  3289. public getMeshByName(name: string): Nullable<AbstractMesh> {
  3290. for (var index = 0; index < this.meshes.length; index++) {
  3291. if (this.meshes[index].name === name) {
  3292. return this.meshes[index];
  3293. }
  3294. }
  3295. return null;
  3296. }
  3297. /**
  3298. * Gets a transform node using a given name
  3299. * @param name defines the name to search for
  3300. * @return the found transform node or null if not found at all.
  3301. */
  3302. public getTransformNodeByName(name: string): Nullable<TransformNode> {
  3303. for (var index = 0; index < this.transformNodes.length; index++) {
  3304. if (this.transformNodes[index].name === name) {
  3305. return this.transformNodes[index];
  3306. }
  3307. }
  3308. return null;
  3309. }
  3310. /**
  3311. * Gets a sound using a given name
  3312. * @param name defines the name to search for
  3313. * @return the found sound or null if not found at all.
  3314. */
  3315. public getSoundByName(name: string): Nullable<Sound> {
  3316. var index: number;
  3317. if (AudioEngine) {
  3318. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  3319. if (this.mainSoundTrack.soundCollection[index].name === name) {
  3320. return this.mainSoundTrack.soundCollection[index];
  3321. }
  3322. }
  3323. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  3324. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  3325. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  3326. return this.soundTracks[sdIndex].soundCollection[index];
  3327. }
  3328. }
  3329. }
  3330. }
  3331. return null;
  3332. }
  3333. /**
  3334. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  3335. * @param id defines the id to search for
  3336. * @return the found skeleton or null if not found at all.
  3337. */
  3338. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  3339. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  3340. if (this.skeletons[index].id === id) {
  3341. return this.skeletons[index];
  3342. }
  3343. }
  3344. return null;
  3345. }
  3346. /**
  3347. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  3348. * @param id defines the id to search for
  3349. * @return the found skeleton or null if not found at all.
  3350. */
  3351. public getSkeletonById(id: string): Nullable<Skeleton> {
  3352. for (var index = 0; index < this.skeletons.length; index++) {
  3353. if (this.skeletons[index].id === id) {
  3354. return this.skeletons[index];
  3355. }
  3356. }
  3357. return null;
  3358. }
  3359. /**
  3360. * Gets a skeleton using a given name
  3361. * @param name defines the name to search for
  3362. * @return the found skeleton or null if not found at all.
  3363. */
  3364. public getSkeletonByName(name: string): Nullable<Skeleton> {
  3365. for (var index = 0; index < this.skeletons.length; index++) {
  3366. if (this.skeletons[index].name === name) {
  3367. return this.skeletons[index];
  3368. }
  3369. }
  3370. return null;
  3371. }
  3372. /**
  3373. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  3374. * @param id defines the id to search for
  3375. * @return the found morph target manager or null if not found at all.
  3376. */
  3377. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  3378. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  3379. if (this.morphTargetManagers[index].uniqueId === id) {
  3380. return this.morphTargetManagers[index];
  3381. }
  3382. }
  3383. return null;
  3384. }
  3385. /**
  3386. * Gets a boolean indicating if the given mesh is active
  3387. * @param mesh defines the mesh to look for
  3388. * @returns true if the mesh is in the active list
  3389. */
  3390. public isActiveMesh(mesh: AbstractMesh): boolean {
  3391. return (this._activeMeshes.indexOf(mesh) !== -1);
  3392. }
  3393. /**
  3394. * Return a the first highlight layer of the scene with a given name.
  3395. * @param name The name of the highlight layer to look for.
  3396. * @return The highlight layer if found otherwise null.
  3397. */
  3398. public getHighlightLayerByName(name: string): Nullable<HighlightLayer> {
  3399. for (var index = 0; index < this.effectLayers.length; index++) {
  3400. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  3401. return (<any>this.effectLayers[index]) as HighlightLayer;
  3402. }
  3403. }
  3404. return null;
  3405. }
  3406. /**
  3407. * Return a the first highlight layer of the scene with a given name.
  3408. * @param name The name of the highlight layer to look for.
  3409. * @return The highlight layer if found otherwise null.
  3410. */
  3411. public getGlowLayerByName(name: string): Nullable<GlowLayer> {
  3412. for (var index = 0; index < this.effectLayers.length; index++) {
  3413. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  3414. return (<any>this.effectLayers[index]) as GlowLayer;
  3415. }
  3416. }
  3417. return null;
  3418. }
  3419. /**
  3420. * Return a unique id as a string which can serve as an identifier for the scene
  3421. */
  3422. public get uid(): string {
  3423. if (!this._uid) {
  3424. this._uid = Tools.RandomId();
  3425. }
  3426. return this._uid;
  3427. }
  3428. /**
  3429. * Add an externaly attached data from its key.
  3430. * This method call will fail and return false, if such key already exists.
  3431. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3432. * @param key the unique key that identifies the data
  3433. * @param data the data object to associate to the key for this Engine instance
  3434. * @return true if no such key were already present and the data was added successfully, false otherwise
  3435. */
  3436. public addExternalData<T>(key: string, data: T): boolean {
  3437. if (!this._externalData) {
  3438. this._externalData = new StringDictionary<Object>();
  3439. }
  3440. return this._externalData.add(key, data);
  3441. }
  3442. /**
  3443. * Get an externaly attached data from its key
  3444. * @param key the unique key that identifies the data
  3445. * @return the associated data, if present (can be null), or undefined if not present
  3446. */
  3447. public getExternalData<T>(key: string): Nullable<T> {
  3448. if (!this._externalData) {
  3449. return null;
  3450. }
  3451. return <T>this._externalData.get(key);
  3452. }
  3453. /**
  3454. * Get an externaly attached data from its key, create it using a factory if it's not already present
  3455. * @param key the unique key that identifies the data
  3456. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3457. * @return the associated data, can be null if the factory returned null.
  3458. */
  3459. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  3460. if (!this._externalData) {
  3461. this._externalData = new StringDictionary<Object>();
  3462. }
  3463. return <T>this._externalData.getOrAddWithFactory(key, factory);
  3464. }
  3465. /**
  3466. * Remove an externaly attached data from the Engine instance
  3467. * @param key the unique key that identifies the data
  3468. * @return true if the data was successfully removed, false if it doesn't exist
  3469. */
  3470. public removeExternalData(key: string): boolean {
  3471. return this._externalData.remove(key);
  3472. }
  3473. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  3474. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  3475. if (mesh.showSubMeshesBoundingBox) {
  3476. const boundingInfo = subMesh.getBoundingInfo();
  3477. if (boundingInfo !== null && boundingInfo !== undefined) {
  3478. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  3479. }
  3480. }
  3481. const material = subMesh.getMaterial();
  3482. if (material !== null && material !== undefined) {
  3483. // Render targets
  3484. if (material.getRenderTargetTextures !== undefined) {
  3485. if (this._processedMaterials.indexOf(material) === -1) {
  3486. this._processedMaterials.push(material);
  3487. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  3488. }
  3489. }
  3490. // Dispatch
  3491. this._activeIndices.addCount(subMesh.indexCount, false);
  3492. this._renderingManager.dispatch(subMesh, mesh, material);
  3493. }
  3494. }
  3495. }
  3496. /**
  3497. * Clear the processed materials smart array preventing retention point in material dispose.
  3498. */
  3499. public freeProcessedMaterials(): void {
  3500. this._processedMaterials.dispose();
  3501. }
  3502. /**
  3503. * Clear the active meshes smart array preventing retention point in mesh dispose.
  3504. */
  3505. public freeActiveMeshes(): void {
  3506. this._activeMeshes.dispose();
  3507. if (this.activeCamera && this.activeCamera._activeMeshes) {
  3508. this.activeCamera._activeMeshes.dispose();
  3509. }
  3510. if (this.activeCameras) {
  3511. for (let i = 0; i < this.activeCameras.length; i++) {
  3512. let activeCamera = this.activeCameras[i];
  3513. if (activeCamera && activeCamera._activeMeshes) {
  3514. activeCamera._activeMeshes.dispose();
  3515. }
  3516. }
  3517. }
  3518. }
  3519. /**
  3520. * Clear the info related to rendering groups preventing retention points during dispose.
  3521. */
  3522. public freeRenderingGroups(): void {
  3523. if (this._renderingManager) {
  3524. this._renderingManager.freeRenderingGroups();
  3525. }
  3526. if (this.textures) {
  3527. for (let i = 0; i < this.textures.length; i++) {
  3528. let texture = this.textures[i];
  3529. if (texture && (<RenderTargetTexture>texture).renderList) {
  3530. (<RenderTargetTexture>texture).freeRenderingGroups();
  3531. }
  3532. }
  3533. }
  3534. }
  3535. /** @hidden */
  3536. public _isInIntermediateRendering(): boolean {
  3537. return this._intermediateRendering
  3538. }
  3539. private _activeMeshCandidateProvider: IActiveMeshCandidateProvider;
  3540. /**
  3541. * Defines the current active mesh candidate provider
  3542. * @param provider defines the provider to use
  3543. */
  3544. public setActiveMeshCandidateProvider(provider: IActiveMeshCandidateProvider): void {
  3545. this._activeMeshCandidateProvider = provider;
  3546. }
  3547. /**
  3548. * Gets the current active mesh candidate provider
  3549. * @returns the current active mesh candidate provider
  3550. */
  3551. public getActiveMeshCandidateProvider(): IActiveMeshCandidateProvider {
  3552. return this._activeMeshCandidateProvider;
  3553. }
  3554. private _activeMeshesFrozen = false;
  3555. /**
  3556. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  3557. * @returns the current scene
  3558. */
  3559. public freezeActiveMeshes(): Scene {
  3560. if (!this.activeCamera) {
  3561. return this;
  3562. }
  3563. if (!this._frustumPlanes) {
  3564. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3565. }
  3566. this._evaluateActiveMeshes();
  3567. this._activeMeshesFrozen = true;
  3568. return this;
  3569. }
  3570. /**
  3571. * Use this function to restart evaluating active meshes on every frame
  3572. * @returns the current scene
  3573. */
  3574. public unfreezeActiveMeshes(): Scene {
  3575. this._activeMeshesFrozen = false;
  3576. return this;
  3577. }
  3578. private _evaluateActiveMeshes(): void {
  3579. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  3580. return;
  3581. }
  3582. if (!this.activeCamera) {
  3583. return;
  3584. }
  3585. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  3586. this.activeCamera._activeMeshes.reset();
  3587. this._activeMeshes.reset();
  3588. this._renderingManager.reset();
  3589. this._processedMaterials.reset();
  3590. this._activeParticleSystems.reset();
  3591. this._activeSkeletons.reset();
  3592. this._softwareSkinnedMeshes.reset();
  3593. if (this._boundingBoxRenderer) {
  3594. this._boundingBoxRenderer.reset();
  3595. }
  3596. // Meshes
  3597. var meshes: AbstractMesh[];
  3598. var len: number;
  3599. var checkIsEnabled = true;
  3600. // Determine mesh candidates
  3601. if (this._activeMeshCandidateProvider !== undefined) {
  3602. // Use _activeMeshCandidateProvider
  3603. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  3604. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  3605. if (meshes !== undefined) {
  3606. len = meshes.length;
  3607. } else {
  3608. len = 0;
  3609. }
  3610. } else if (this._selectionOctree !== undefined) {
  3611. // Octree
  3612. var selection = this._selectionOctree.select(this._frustumPlanes);
  3613. meshes = selection.data;
  3614. len = selection.length;
  3615. } else {
  3616. // Full scene traversal
  3617. len = this.meshes.length;
  3618. meshes = this.meshes;
  3619. }
  3620. // Check each mesh
  3621. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  3622. mesh = meshes[meshIndex];
  3623. if (mesh.isBlocked) {
  3624. continue;
  3625. }
  3626. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  3627. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  3628. continue;
  3629. }
  3630. mesh.computeWorldMatrix();
  3631. // Intersections
  3632. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  3633. this._meshesForIntersections.pushNoDuplicate(mesh);
  3634. }
  3635. // Switch to current LOD
  3636. meshLOD = mesh.getLOD(this.activeCamera);
  3637. if (meshLOD === undefined || meshLOD === null) {
  3638. continue;
  3639. }
  3640. mesh._preActivate();
  3641. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  3642. this._activeMeshes.push(mesh);
  3643. this.activeCamera._activeMeshes.push(mesh);
  3644. mesh._activate(this._renderId);
  3645. if (meshLOD !== mesh) {
  3646. meshLOD._activate(this._renderId);
  3647. }
  3648. this._activeMesh(mesh, meshLOD);
  3649. }
  3650. }
  3651. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  3652. // Particle systems
  3653. if (this.particlesEnabled) {
  3654. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  3655. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  3656. var particleSystem = this.particleSystems[particleIndex];
  3657. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  3658. continue;
  3659. }
  3660. let emitter = <any>particleSystem.emitter;
  3661. if (!emitter.position || emitter.isEnabled()) {
  3662. this._activeParticleSystems.push(particleSystem);
  3663. particleSystem.animate();
  3664. this._renderingManager.dispatchParticles(particleSystem);
  3665. }
  3666. }
  3667. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  3668. }
  3669. }
  3670. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  3671. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  3672. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  3673. mesh.skeleton.prepare();
  3674. }
  3675. if (!mesh.computeBonesUsingShaders) {
  3676. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  3677. }
  3678. }
  3679. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  3680. let boundingInfo = sourceMesh.getBoundingInfo();
  3681. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  3682. }
  3683. if (
  3684. mesh !== undefined && mesh !== null
  3685. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0
  3686. ) {
  3687. // Submeshes Octrees
  3688. var len: number;
  3689. var subMeshes: SubMesh[];
  3690. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  3691. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  3692. len = intersections.length;
  3693. subMeshes = intersections.data;
  3694. } else {
  3695. subMeshes = mesh.subMeshes;
  3696. len = subMeshes.length;
  3697. }
  3698. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  3699. subMesh = subMeshes[subIndex];
  3700. this._evaluateSubMesh(subMesh, mesh);
  3701. }
  3702. }
  3703. }
  3704. /**
  3705. * Update the transform matrix to update from the current active camera
  3706. * @param force defines a boolean used to force the update even if cache is up to date
  3707. */
  3708. public updateTransformMatrix(force?: boolean): void {
  3709. if (!this.activeCamera) {
  3710. return;
  3711. }
  3712. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  3713. }
  3714. /**
  3715. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  3716. * @param alternateCamera defines the camera to use
  3717. */
  3718. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  3719. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  3720. }
  3721. private _renderForCamera(camera: Camera, rigParent?: Camera): void {
  3722. if (camera && camera._skipRendering) {
  3723. return;
  3724. }
  3725. var engine = this._engine;
  3726. this.activeCamera = camera;
  3727. if (!this.activeCamera)
  3728. throw new Error("Active camera not set");
  3729. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  3730. // Viewport
  3731. engine.setViewport(this.activeCamera.viewport);
  3732. // Camera
  3733. this.resetCachedMaterial();
  3734. this._renderId++;
  3735. this.updateTransformMatrix();
  3736. if (camera._alternateCamera) {
  3737. this.updateAlternateTransformMatrix(camera._alternateCamera);
  3738. this._alternateRendering = true;
  3739. }
  3740. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  3741. // Meshes
  3742. this._evaluateActiveMeshes();
  3743. // Software skinning
  3744. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  3745. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  3746. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  3747. }
  3748. // Render targets
  3749. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3750. var needsRestoreFrameBuffer = false;
  3751. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  3752. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  3753. }
  3754. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  3755. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  3756. }
  3757. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  3758. this._intermediateRendering = true;
  3759. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3760. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  3761. let renderTarget = this._renderTargets.data[renderIndex];
  3762. if (renderTarget._shouldRender()) {
  3763. this._renderId++;
  3764. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  3765. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  3766. }
  3767. }
  3768. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3769. this._intermediateRendering = false;
  3770. this._renderId++;
  3771. needsRestoreFrameBuffer = true; // Restore back buffer
  3772. }
  3773. // Render EffecttLayer Texture
  3774. var stencilState = this._engine.getStencilBuffer();
  3775. var renderEffects = false;
  3776. var needStencil = false;
  3777. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  3778. this._intermediateRendering = true;
  3779. for (let i = 0; i < this.effectLayers.length; i++) {
  3780. let effectLayer = this.effectLayers[i];
  3781. if (effectLayer.shouldRender() &&
  3782. (!effectLayer.camera ||
  3783. (effectLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  3784. (effectLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  3785. renderEffects = true;
  3786. needStencil = needStencil || effectLayer.needStencil();
  3787. let renderTarget = (<RenderTargetTexture>(<any>effectLayer)._mainTexture);
  3788. if (renderTarget._shouldRender()) {
  3789. this._renderId++;
  3790. renderTarget.render(false, false);
  3791. needsRestoreFrameBuffer = true;
  3792. }
  3793. }
  3794. }
  3795. this._intermediateRendering = false;
  3796. this._renderId++;
  3797. }
  3798. if (needsRestoreFrameBuffer) {
  3799. engine.restoreDefaultFramebuffer(); // Restore back buffer
  3800. }
  3801. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  3802. // Prepare Frame
  3803. this.postProcessManager._prepareFrame();
  3804. // Backgrounds
  3805. var layerIndex;
  3806. var layer;
  3807. if (this.layers.length) {
  3808. engine.setDepthBuffer(false);
  3809. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  3810. layer = this.layers[layerIndex];
  3811. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  3812. layer.render();
  3813. }
  3814. }
  3815. engine.setDepthBuffer(true);
  3816. }
  3817. // Activate effect Layer stencil
  3818. if (needStencil) {
  3819. this._engine.setStencilBuffer(true);
  3820. }
  3821. // Render
  3822. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  3823. this._renderingManager.render(null, null, true, true);
  3824. this.onAfterDrawPhaseObservable.notifyObservers(this);
  3825. // Restore effect Layer stencil
  3826. if (needStencil) {
  3827. this._engine.setStencilBuffer(stencilState);
  3828. }
  3829. // Bounding boxes
  3830. if (this._boundingBoxRenderer) {
  3831. this._boundingBoxRenderer.render();
  3832. }
  3833. // Lens flares
  3834. if (this.lensFlaresEnabled) {
  3835. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  3836. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  3837. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  3838. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  3839. lensFlareSystem.render();
  3840. }
  3841. }
  3842. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  3843. }
  3844. // Effect Layer
  3845. if (renderEffects) {
  3846. engine.setDepthBuffer(false);
  3847. for (let i = 0; i < this.effectLayers.length; i++) {
  3848. if (this.effectLayers[i].shouldRender()) {
  3849. this.effectLayers[i].render();
  3850. }
  3851. }
  3852. engine.setDepthBuffer(true);
  3853. }
  3854. // Foregrounds
  3855. if (this.layers.length) {
  3856. engine.setDepthBuffer(false);
  3857. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  3858. layer = this.layers[layerIndex];
  3859. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  3860. layer.render();
  3861. }
  3862. }
  3863. engine.setDepthBuffer(true);
  3864. }
  3865. // Finalize frame
  3866. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  3867. // Reset some special arrays
  3868. this._renderTargets.reset();
  3869. this._alternateRendering = false;
  3870. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  3871. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  3872. }
  3873. private _processSubCameras(camera: Camera): void {
  3874. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  3875. this._renderForCamera(camera);
  3876. return;
  3877. }
  3878. // rig cameras
  3879. for (var index = 0; index < camera._rigCameras.length; index++) {
  3880. this._renderForCamera(camera._rigCameras[index], camera);
  3881. }
  3882. this.activeCamera = camera;
  3883. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3884. }
  3885. private _checkIntersections(): void {
  3886. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  3887. var sourceMesh = this._meshesForIntersections.data[index];
  3888. if (!sourceMesh.actionManager) {
  3889. continue;
  3890. }
  3891. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  3892. var action = sourceMesh.actionManager.actions[actionIndex];
  3893. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3894. var parameters = action.getTriggerParameter();
  3895. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  3896. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  3897. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  3898. if (areIntersecting && currentIntersectionInProgress === -1) {
  3899. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  3900. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3901. sourceMesh._intersectionsInProgress.push(otherMesh);
  3902. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3903. sourceMesh._intersectionsInProgress.push(otherMesh);
  3904. }
  3905. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  3906. //They intersected, and now they don't.
  3907. //is this trigger an exit trigger? execute an event.
  3908. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3909. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3910. }
  3911. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  3912. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger, parameter => {
  3913. var parameterMesh = parameter instanceof AbstractMesh ? parameter : parameter.mesh;
  3914. return otherMesh === parameterMesh;
  3915. }) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3916. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  3917. }
  3918. }
  3919. }
  3920. }
  3921. }
  3922. }
  3923. /**
  3924. * Render the scene
  3925. */
  3926. public render(): void {
  3927. if (this.isDisposed) {
  3928. return;
  3929. }
  3930. this._activeParticles.fetchNewFrame();
  3931. this._totalVertices.fetchNewFrame();
  3932. this._activeIndices.fetchNewFrame();
  3933. this._activeBones.fetchNewFrame();
  3934. this._meshesForIntersections.reset();
  3935. this.resetCachedMaterial();
  3936. this.onBeforeAnimationsObservable.notifyObservers(this);
  3937. // Actions
  3938. if (this.actionManager) {
  3939. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger);
  3940. }
  3941. //Simplification Queue
  3942. if (this.simplificationQueue && !this.simplificationQueue.running) {
  3943. this.simplificationQueue.executeNext();
  3944. }
  3945. if (this._engine.isDeterministicLockStep()) {
  3946. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  3947. var defaultFPS = (60.0 / 1000.0);
  3948. let defaultFrameTime = 1000 / 60; // frame time in MS
  3949. if (this._physicsEngine) {
  3950. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  3951. }
  3952. let stepsTaken = 0;
  3953. var maxSubSteps = this._engine.getLockstepMaxSteps();
  3954. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  3955. internalSteps = Math.min(internalSteps, maxSubSteps);
  3956. do {
  3957. this.onBeforeStepObservable.notifyObservers(this);
  3958. // Animations
  3959. this._animationRatio = defaultFrameTime * defaultFPS;
  3960. this._animate();
  3961. this.onAfterAnimationsObservable.notifyObservers(this);
  3962. // Physics
  3963. if (this._physicsEngine) {
  3964. this.onBeforePhysicsObservable.notifyObservers(this);
  3965. this._physicsEngine._step(defaultFrameTime / 1000);
  3966. this.onAfterPhysicsObservable.notifyObservers(this);
  3967. }
  3968. this.onAfterStepObservable.notifyObservers(this);
  3969. this._currentStepId++;
  3970. stepsTaken++;
  3971. deltaTime -= defaultFrameTime;
  3972. } while (deltaTime > 0 && stepsTaken < internalSteps);
  3973. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  3974. }
  3975. else {
  3976. // Animations
  3977. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  3978. this._animationRatio = deltaTime * (60.0 / 1000.0);
  3979. this._animate();
  3980. this.onAfterAnimationsObservable.notifyObservers(this);
  3981. // Physics
  3982. if (this._physicsEngine) {
  3983. this.onBeforePhysicsObservable.notifyObservers(this);
  3984. this._physicsEngine._step(deltaTime / 1000.0);
  3985. this.onAfterPhysicsObservable.notifyObservers(this);
  3986. }
  3987. }
  3988. // update gamepad manager
  3989. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  3990. this._gamepadManager._checkGamepadsStatus();
  3991. }
  3992. // Update Cameras
  3993. if (this.activeCameras.length > 0) {
  3994. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3995. let camera = this.activeCameras[cameraIndex];
  3996. camera.update();
  3997. if (camera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  3998. // rig cameras
  3999. for (var index = 0; index < camera._rigCameras.length; index++) {
  4000. camera._rigCameras[index].update();
  4001. }
  4002. }
  4003. }
  4004. } else if (this.activeCamera) {
  4005. this.activeCamera.update();
  4006. if (this.activeCamera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  4007. // rig cameras
  4008. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  4009. this.activeCamera._rigCameras[index].update();
  4010. }
  4011. }
  4012. }
  4013. // Before render
  4014. this.onBeforeRenderObservable.notifyObservers(this);
  4015. // Customs render targets
  4016. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  4017. var engine = this.getEngine();
  4018. var currentActiveCamera = this.activeCamera;
  4019. if (this.renderTargetsEnabled) {
  4020. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  4021. this._intermediateRendering = true;
  4022. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  4023. var renderTarget = this.customRenderTargets[customIndex];
  4024. if (renderTarget._shouldRender()) {
  4025. this._renderId++;
  4026. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  4027. if (!this.activeCamera)
  4028. throw new Error("Active camera not set");
  4029. // Viewport
  4030. engine.setViewport(this.activeCamera.viewport);
  4031. // Camera
  4032. this.updateTransformMatrix();
  4033. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  4034. }
  4035. }
  4036. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  4037. this._intermediateRendering = false;
  4038. this._renderId++;
  4039. }
  4040. // Restore back buffer
  4041. if (this.customRenderTargets.length > 0) {
  4042. engine.restoreDefaultFramebuffer();
  4043. }
  4044. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  4045. this.activeCamera = currentActiveCamera;
  4046. // Procedural textures
  4047. if (this.proceduralTexturesEnabled) {
  4048. Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  4049. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  4050. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  4051. if (proceduralTexture._shouldRender()) {
  4052. proceduralTexture.render();
  4053. }
  4054. }
  4055. Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  4056. }
  4057. // Clear
  4058. if (this.autoClearDepthAndStencil || this.autoClear) {
  4059. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  4060. }
  4061. // Shadows
  4062. if (this.shadowsEnabled) {
  4063. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  4064. var light = this.lights[lightIndex];
  4065. var shadowGenerator = light.getShadowGenerator();
  4066. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  4067. var shadowMap = <RenderTargetTexture>(shadowGenerator.getShadowMap());
  4068. if (this.textures.indexOf(shadowMap) !== -1) {
  4069. this._renderTargets.push(shadowMap);
  4070. }
  4071. }
  4072. }
  4073. }
  4074. // Depth renderer
  4075. for (var key in this._depthRenderer) {
  4076. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  4077. }
  4078. // Geometry renderer
  4079. if (this._geometryBufferRenderer) {
  4080. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  4081. }
  4082. // RenderPipeline
  4083. if (this._postProcessRenderPipelineManager) {
  4084. this._postProcessRenderPipelineManager.update();
  4085. }
  4086. // Multi-cameras?
  4087. if (this.activeCameras.length > 0) {
  4088. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  4089. if (cameraIndex > 0) {
  4090. this._engine.clear(null, false, true, true);
  4091. }
  4092. this._processSubCameras(this.activeCameras[cameraIndex]);
  4093. }
  4094. } else {
  4095. if (!this.activeCamera) {
  4096. throw new Error("No camera defined");
  4097. }
  4098. this._processSubCameras(this.activeCamera);
  4099. }
  4100. // Intersection checks
  4101. this._checkIntersections();
  4102. // Update the audio listener attached to the camera
  4103. if (AudioEngine) {
  4104. this._updateAudioParameters();
  4105. }
  4106. // After render
  4107. if (this.afterRender) {
  4108. this.afterRender();
  4109. }
  4110. this.onAfterRenderObservable.notifyObservers(this);
  4111. // Cleaning
  4112. for (var index = 0; index < this._toBeDisposed.length; index++) {
  4113. var data = this._toBeDisposed.data[index];
  4114. if (data) {
  4115. data.dispose();
  4116. }
  4117. this._toBeDisposed[index] = null;
  4118. }
  4119. this._toBeDisposed.reset();
  4120. if (this.dumpNextRenderTargets) {
  4121. this.dumpNextRenderTargets = false;
  4122. }
  4123. this._activeBones.addCount(0, true);
  4124. this._activeIndices.addCount(0, true);
  4125. this._activeParticles.addCount(0, true);
  4126. }
  4127. private _updateAudioParameters() {
  4128. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  4129. return;
  4130. }
  4131. var listeningCamera: Nullable<Camera>;
  4132. var audioEngine = Engine.audioEngine;
  4133. if (this.activeCameras.length > 0) {
  4134. listeningCamera = this.activeCameras[0];
  4135. } else {
  4136. listeningCamera = this.activeCamera;
  4137. }
  4138. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  4139. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  4140. // for VR cameras
  4141. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  4142. listeningCamera = listeningCamera.rigCameras[0];
  4143. }
  4144. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  4145. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  4146. cameraDirection.normalize();
  4147. // To avoid some errors on GearVR
  4148. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  4149. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  4150. }
  4151. var i: number;
  4152. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  4153. var sound = this.mainSoundTrack.soundCollection[i];
  4154. if (sound.useCustomAttenuation) {
  4155. sound.updateDistanceFromListener();
  4156. }
  4157. }
  4158. for (i = 0; i < this.soundTracks.length; i++) {
  4159. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  4160. sound = this.soundTracks[i].soundCollection[j];
  4161. if (sound.useCustomAttenuation) {
  4162. sound.updateDistanceFromListener();
  4163. }
  4164. }
  4165. }
  4166. }
  4167. }
  4168. // Audio
  4169. /**
  4170. * Gets or sets if audio support is enabled
  4171. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  4172. */
  4173. public get audioEnabled(): boolean {
  4174. return this._audioEnabled;
  4175. }
  4176. public set audioEnabled(value: boolean) {
  4177. this._audioEnabled = value;
  4178. if (AudioEngine) {
  4179. if (this._audioEnabled) {
  4180. this._enableAudio();
  4181. }
  4182. else {
  4183. this._disableAudio();
  4184. }
  4185. }
  4186. }
  4187. private _disableAudio() {
  4188. var i: number;
  4189. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  4190. this.mainSoundTrack.soundCollection[i].pause();
  4191. }
  4192. for (i = 0; i < this.soundTracks.length; i++) {
  4193. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  4194. this.soundTracks[i].soundCollection[j].pause();
  4195. }
  4196. }
  4197. }
  4198. private _enableAudio() {
  4199. var i: number;
  4200. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  4201. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  4202. this.mainSoundTrack.soundCollection[i].play();
  4203. }
  4204. }
  4205. for (i = 0; i < this.soundTracks.length; i++) {
  4206. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  4207. if (this.soundTracks[i].soundCollection[j].isPaused) {
  4208. this.soundTracks[i].soundCollection[j].play();
  4209. }
  4210. }
  4211. }
  4212. }
  4213. /**
  4214. * Gets or sets if audio will be output to headphones
  4215. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  4216. */
  4217. public get headphone(): boolean {
  4218. return this._headphone;
  4219. }
  4220. public set headphone(value: boolean) {
  4221. this._headphone = value;
  4222. if (AudioEngine) {
  4223. if (this._headphone) {
  4224. this._switchAudioModeForHeadphones();
  4225. }
  4226. else {
  4227. this._switchAudioModeForNormalSpeakers();
  4228. }
  4229. }
  4230. }
  4231. private _switchAudioModeForHeadphones() {
  4232. this.mainSoundTrack.switchPanningModelToHRTF();
  4233. for (var i = 0; i < this.soundTracks.length; i++) {
  4234. this.soundTracks[i].switchPanningModelToHRTF();
  4235. }
  4236. }
  4237. private _switchAudioModeForNormalSpeakers() {
  4238. this.mainSoundTrack.switchPanningModelToEqualPower();
  4239. for (var i = 0; i < this.soundTracks.length; i++) {
  4240. this.soundTracks[i].switchPanningModelToEqualPower();
  4241. }
  4242. }
  4243. /**
  4244. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  4245. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  4246. * @returns the created depth renderer
  4247. */
  4248. public enableDepthRenderer(camera?: Nullable<Camera>): DepthRenderer {
  4249. camera = camera || this.activeCamera;
  4250. if (!camera) {
  4251. throw "No camera available to enable depth renderer";
  4252. }
  4253. if (!this._depthRenderer[camera.id]) {
  4254. var textureType = 0;
  4255. if (this._engine.getCaps().textureHalfFloatRender) {
  4256. textureType = Engine.TEXTURETYPE_HALF_FLOAT;
  4257. }
  4258. else if (this._engine.getCaps().textureFloatRender) {
  4259. textureType = Engine.TEXTURETYPE_FLOAT;
  4260. } else {
  4261. throw "Depth renderer does not support int texture type";
  4262. }
  4263. this._depthRenderer[camera.id] = new DepthRenderer(this, textureType, camera);
  4264. }
  4265. return this._depthRenderer[camera.id];
  4266. }
  4267. /**
  4268. * Disables a depth renderer for a given camera
  4269. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  4270. */
  4271. public disableDepthRenderer(camera?: Nullable<Camera>): void {
  4272. camera = camera || this.activeCamera;
  4273. if (!camera || !this._depthRenderer[camera.id]) {
  4274. return;
  4275. }
  4276. this._depthRenderer[camera.id].dispose();
  4277. delete this._depthRenderer[camera.id];
  4278. }
  4279. /**
  4280. * Enables a GeometryBufferRender and associates it with the scene
  4281. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  4282. * @returns the GeometryBufferRenderer
  4283. */
  4284. public enableGeometryBufferRenderer(ratio: number = 1): Nullable<GeometryBufferRenderer> {
  4285. if (this._geometryBufferRenderer) {
  4286. return this._geometryBufferRenderer;
  4287. }
  4288. this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio);
  4289. if (!this._geometryBufferRenderer.isSupported) {
  4290. this._geometryBufferRenderer = null;
  4291. }
  4292. return this._geometryBufferRenderer;
  4293. }
  4294. /**
  4295. * Disables the GeometryBufferRender associated with the scene
  4296. */
  4297. public disableGeometryBufferRenderer(): void {
  4298. if (!this._geometryBufferRenderer) {
  4299. return;
  4300. }
  4301. this._geometryBufferRenderer.dispose();
  4302. this._geometryBufferRenderer = null;
  4303. }
  4304. /**
  4305. * Freeze all materials
  4306. * A frozen material will not be updatable but should be faster to render
  4307. */
  4308. public freezeMaterials(): void {
  4309. for (var i = 0; i < this.materials.length; i++) {
  4310. this.materials[i].freeze();
  4311. }
  4312. }
  4313. /**
  4314. * Unfreeze all materials
  4315. * A frozen material will not be updatable but should be faster to render
  4316. */
  4317. public unfreezeMaterials(): void {
  4318. for (var i = 0; i < this.materials.length; i++) {
  4319. this.materials[i].unfreeze();
  4320. }
  4321. }
  4322. /**
  4323. * Releases all held ressources
  4324. */
  4325. public dispose(): void {
  4326. this.beforeRender = null;
  4327. this.afterRender = null;
  4328. this.skeletons = [];
  4329. this.morphTargetManagers = [];
  4330. this.importedMeshesFiles = new Array<string>();
  4331. this.stopAllAnimations();
  4332. this.resetCachedMaterial();
  4333. for (var key in this._depthRenderer) {
  4334. this._depthRenderer[key].dispose();
  4335. }
  4336. if (this._gamepadManager) {
  4337. this._gamepadManager.dispose();
  4338. this._gamepadManager = null;
  4339. }
  4340. // Smart arrays
  4341. if (this.activeCamera) {
  4342. this.activeCamera._activeMeshes.dispose();
  4343. this.activeCamera = null;
  4344. }
  4345. this._activeMeshes.dispose();
  4346. this._renderingManager.dispose();
  4347. this._processedMaterials.dispose();
  4348. this._activeParticleSystems.dispose();
  4349. this._activeSkeletons.dispose();
  4350. this._softwareSkinnedMeshes.dispose();
  4351. this._renderTargets.dispose();
  4352. this._registeredForLateAnimationBindings.dispose();
  4353. if (this._boundingBoxRenderer) {
  4354. this._boundingBoxRenderer.dispose();
  4355. }
  4356. this._meshesForIntersections.dispose();
  4357. this._toBeDisposed.dispose();
  4358. // Abort active requests
  4359. for (let request of this._activeRequests) {
  4360. request.abort();
  4361. }
  4362. // Debug layer
  4363. if (this._debugLayer) {
  4364. this._debugLayer.hide();
  4365. }
  4366. // Events
  4367. this.onDisposeObservable.notifyObservers(this);
  4368. this.onDisposeObservable.clear();
  4369. this.onBeforeRenderObservable.clear();
  4370. this.onAfterRenderObservable.clear();
  4371. this.onBeforeRenderTargetsRenderObservable.clear();
  4372. this.onAfterRenderTargetsRenderObservable.clear();
  4373. this.onAfterStepObservable.clear();
  4374. this.onBeforeStepObservable.clear();
  4375. this.onBeforeActiveMeshesEvaluationObservable.clear();
  4376. this.onAfterActiveMeshesEvaluationObservable.clear();
  4377. this.onBeforeParticlesRenderingObservable.clear();
  4378. this.onAfterParticlesRenderingObservable.clear();
  4379. this.onBeforeSpritesRenderingObservable.clear();
  4380. this.onAfterSpritesRenderingObservable.clear();
  4381. this.onBeforeDrawPhaseObservable.clear();
  4382. this.onAfterDrawPhaseObservable.clear();
  4383. this.onBeforePhysicsObservable.clear();
  4384. this.onAfterPhysicsObservable.clear();
  4385. this.onBeforeAnimationsObservable.clear();
  4386. this.onAfterAnimationsObservable.clear();
  4387. this.onDataLoadedObservable.clear();
  4388. this.detachControl();
  4389. // Release sounds & sounds tracks
  4390. if (AudioEngine) {
  4391. this.disposeSounds();
  4392. }
  4393. // VR Helper
  4394. if (this.VRHelper) {
  4395. this.VRHelper.dispose();
  4396. }
  4397. // Detach cameras
  4398. var canvas = this._engine.getRenderingCanvas();
  4399. if (canvas) {
  4400. var index;
  4401. for (index = 0; index < this.cameras.length; index++) {
  4402. this.cameras[index].detachControl(canvas);
  4403. }
  4404. }
  4405. // Release animation groups
  4406. while (this.animationGroups.length) {
  4407. this.animationGroups[0].dispose();
  4408. }
  4409. // Release lights
  4410. while (this.lights.length) {
  4411. this.lights[0].dispose();
  4412. }
  4413. // Release meshes
  4414. while (this.meshes.length) {
  4415. this.meshes[0].dispose(true);
  4416. }
  4417. while (this.transformNodes.length) {
  4418. this.removeTransformNode(this.transformNodes[0]);
  4419. }
  4420. // Release cameras
  4421. while (this.cameras.length) {
  4422. this.cameras[0].dispose();
  4423. }
  4424. // Release materials
  4425. if (this.defaultMaterial) {
  4426. this.defaultMaterial.dispose()
  4427. }
  4428. while (this.multiMaterials.length) {
  4429. this.multiMaterials[0].dispose();
  4430. }
  4431. while (this.materials.length) {
  4432. this.materials[0].dispose();
  4433. }
  4434. // Release particles
  4435. while (this.particleSystems.length) {
  4436. this.particleSystems[0].dispose();
  4437. }
  4438. // Release sprites
  4439. while (this.spriteManagers.length) {
  4440. this.spriteManagers[0].dispose();
  4441. }
  4442. // Release postProcesses
  4443. while (this.postProcesses.length) {
  4444. this.postProcesses[0].dispose();
  4445. }
  4446. // Release layers
  4447. while (this.layers.length) {
  4448. this.layers[0].dispose();
  4449. }
  4450. while (this.effectLayers.length) {
  4451. this.effectLayers[0].dispose();
  4452. }
  4453. // Release textures
  4454. while (this.textures.length) {
  4455. this.textures[0].dispose();
  4456. }
  4457. // Release UBO
  4458. this._sceneUbo.dispose();
  4459. if (this._alternateSceneUbo) {
  4460. this._alternateSceneUbo.dispose();
  4461. }
  4462. // Post-processes
  4463. this.postProcessManager.dispose();
  4464. if (this._postProcessRenderPipelineManager) {
  4465. this._postProcessRenderPipelineManager.dispose();
  4466. }
  4467. // Physics
  4468. if (this._physicsEngine) {
  4469. this.disablePhysicsEngine();
  4470. }
  4471. // Remove from engine
  4472. index = this._engine.scenes.indexOf(this);
  4473. if (index > -1) {
  4474. this._engine.scenes.splice(index, 1);
  4475. }
  4476. this._engine.wipeCaches(true);
  4477. this._isDisposed = true;
  4478. }
  4479. /**
  4480. * Gets if the scene is already disposed
  4481. */
  4482. public get isDisposed(): boolean {
  4483. return this._isDisposed;
  4484. }
  4485. /**
  4486. * Releases sounds & soundtracks
  4487. */
  4488. public disposeSounds() {
  4489. if (!this._mainSoundTrack) {
  4490. return;
  4491. }
  4492. this.mainSoundTrack.dispose();
  4493. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  4494. this.soundTracks[scIndex].dispose();
  4495. }
  4496. }
  4497. // Octrees
  4498. /**
  4499. * Get the world extend vectors with an optional filter
  4500. *
  4501. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  4502. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  4503. */
  4504. public getWorldExtends(filterPredicate?: (mesh: AbstractMesh) => boolean): { min: Vector3; max: Vector3 } {
  4505. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4506. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4507. filterPredicate = filterPredicate || (() => true);
  4508. this.meshes.filter(filterPredicate).forEach(mesh => {
  4509. mesh.computeWorldMatrix(true);
  4510. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  4511. return;
  4512. }
  4513. let boundingInfo = mesh.getBoundingInfo();
  4514. var minBox = boundingInfo.boundingBox.minimumWorld;
  4515. var maxBox = boundingInfo.boundingBox.maximumWorld;
  4516. Tools.CheckExtends(minBox, min, max);
  4517. Tools.CheckExtends(maxBox, min, max);
  4518. })
  4519. return {
  4520. min: min,
  4521. max: max
  4522. };
  4523. }
  4524. /**
  4525. * Creates or updates the octree used to boost selection (picking)
  4526. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  4527. * @param maxCapacity defines the maximum capacity per leaf
  4528. * @param maxDepth defines the maximum depth of the octree
  4529. * @returns an octree of AbstractMesh
  4530. */
  4531. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  4532. if (!this._selectionOctree) {
  4533. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  4534. }
  4535. var worldExtends = this.getWorldExtends();
  4536. // Update octree
  4537. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  4538. return this._selectionOctree;
  4539. }
  4540. // Picking
  4541. /**
  4542. * Creates a ray that can be used to pick in the scene
  4543. * @param x defines the x coordinate of the origin (on-screen)
  4544. * @param y defines the y coordinate of the origin (on-screen)
  4545. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4546. * @param camera defines the camera to use for the picking
  4547. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4548. * @returns a Ray
  4549. */
  4550. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  4551. let result = Ray.Zero();
  4552. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  4553. return result;
  4554. }
  4555. /**
  4556. * Creates a ray that can be used to pick in the scene
  4557. * @param x defines the x coordinate of the origin (on-screen)
  4558. * @param y defines the y coordinate of the origin (on-screen)
  4559. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4560. * @param result defines the ray where to store the picking ray
  4561. * @param camera defines the camera to use for the picking
  4562. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4563. * @returns the current scene
  4564. */
  4565. public createPickingRayToRef(x: number, y: number, world: Matrix, result: Ray, camera: Nullable<Camera>, cameraViewSpace = false): Scene {
  4566. var engine = this._engine;
  4567. if (!camera) {
  4568. if (!this.activeCamera)
  4569. throw new Error("Active camera not set");
  4570. camera = this.activeCamera;
  4571. }
  4572. var cameraViewport = camera.viewport;
  4573. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4574. // Moving coordinates to local viewport world
  4575. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  4576. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  4577. result.update(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  4578. return this;
  4579. }
  4580. /**
  4581. * Creates a ray that can be used to pick in the scene
  4582. * @param x defines the x coordinate of the origin (on-screen)
  4583. * @param y defines the y coordinate of the origin (on-screen)
  4584. * @param camera defines the camera to use for the picking
  4585. * @returns a Ray
  4586. */
  4587. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Ray {
  4588. let result = Ray.Zero();
  4589. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  4590. return result;
  4591. }
  4592. /**
  4593. * Creates a ray that can be used to pick in the scene
  4594. * @param x defines the x coordinate of the origin (on-screen)
  4595. * @param y defines the y coordinate of the origin (on-screen)
  4596. * @param result defines the ray where to store the picking ray
  4597. * @param camera defines the camera to use for the picking
  4598. * @returns the current scene
  4599. */
  4600. public createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene {
  4601. if (!PickingInfo) {
  4602. return this;
  4603. }
  4604. var engine = this._engine;
  4605. if (!camera) {
  4606. if (!this.activeCamera)
  4607. throw new Error("Active camera not set");
  4608. camera = this.activeCamera;
  4609. }
  4610. var cameraViewport = camera.viewport;
  4611. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4612. var identity = Matrix.Identity();
  4613. // Moving coordinates to local viewport world
  4614. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  4615. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  4616. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  4617. return this;
  4618. }
  4619. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  4620. if (!PickingInfo) {
  4621. return null;
  4622. }
  4623. var pickingInfo = null;
  4624. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4625. var mesh = this.meshes[meshIndex];
  4626. if (predicate) {
  4627. if (!predicate(mesh)) {
  4628. continue;
  4629. }
  4630. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  4631. continue;
  4632. }
  4633. var world = mesh.getWorldMatrix();
  4634. var ray = rayFunction(world);
  4635. var result = mesh.intersects(ray, fastCheck);
  4636. if (!result || !result.hit)
  4637. continue;
  4638. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  4639. continue;
  4640. pickingInfo = result;
  4641. if (fastCheck) {
  4642. break;
  4643. }
  4644. }
  4645. return pickingInfo || new PickingInfo();
  4646. }
  4647. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  4648. if (!PickingInfo) {
  4649. return null;
  4650. }
  4651. var pickingInfos = new Array<PickingInfo>();
  4652. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4653. var mesh = this.meshes[meshIndex];
  4654. if (predicate) {
  4655. if (!predicate(mesh)) {
  4656. continue;
  4657. }
  4658. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  4659. continue;
  4660. }
  4661. var world = mesh.getWorldMatrix();
  4662. var ray = rayFunction(world);
  4663. var result = mesh.intersects(ray, false);
  4664. if (!result || !result.hit)
  4665. continue;
  4666. pickingInfos.push(result);
  4667. }
  4668. return pickingInfos;
  4669. }
  4670. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  4671. if (!PickingInfo) {
  4672. return null;
  4673. }
  4674. var pickingInfo = null;
  4675. if (!camera) {
  4676. if (!this.activeCamera) {
  4677. return null;
  4678. }
  4679. camera = this.activeCamera;
  4680. }
  4681. if (this.spriteManagers.length > 0) {
  4682. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  4683. var spriteManager = this.spriteManagers[spriteIndex];
  4684. if (!spriteManager.isPickable) {
  4685. continue;
  4686. }
  4687. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  4688. if (!result || !result.hit)
  4689. continue;
  4690. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  4691. continue;
  4692. pickingInfo = result;
  4693. if (fastCheck) {
  4694. break;
  4695. }
  4696. }
  4697. }
  4698. return pickingInfo || new PickingInfo();
  4699. }
  4700. private _tempPickingRay: Nullable<Ray> = Ray ? Ray.Zero() : null;
  4701. /** Launch a ray to try to pick a mesh in the scene
  4702. * @param x position on screen
  4703. * @param y position on screen
  4704. * @param 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
  4705. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  4706. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4707. * @returns a PickingInfo
  4708. */
  4709. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Nullable<Camera>): Nullable<PickingInfo> {
  4710. if (!PickingInfo) {
  4711. return null;
  4712. }
  4713. return this._internalPick(world => {
  4714. this.createPickingRayToRef(x, y, world, this._tempPickingRay!, camera || null);
  4715. return this._tempPickingRay!;
  4716. }, predicate, fastCheck);
  4717. }
  4718. /** Launch a ray to try to pick a sprite in the scene
  4719. * @param x position on screen
  4720. * @param y position on screen
  4721. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  4722. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  4723. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4724. * @returns a PickingInfo
  4725. */
  4726. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  4727. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay!, camera);
  4728. return this._internalPickSprites(this._tempPickingRay!, predicate, fastCheck, camera);
  4729. }
  4730. private _cachedRayForTransform: Ray;
  4731. /** Use the given ray to pick a mesh in the scene
  4732. * @param ray The ray to use to pick meshes
  4733. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  4734. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  4735. * @returns a PickingInfo
  4736. */
  4737. public pickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  4738. return this._internalPick(world => {
  4739. if (!this._pickWithRayInverseMatrix) {
  4740. this._pickWithRayInverseMatrix = Matrix.Identity();
  4741. }
  4742. world.invertToRef(this._pickWithRayInverseMatrix);
  4743. if (!this._cachedRayForTransform) {
  4744. this._cachedRayForTransform = Ray.Zero();
  4745. }
  4746. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  4747. return this._cachedRayForTransform;
  4748. }, predicate, fastCheck);
  4749. }
  4750. /**
  4751. * Launch a ray to try to pick a mesh in the scene
  4752. * @param x X position on screen
  4753. * @param y Y position on screen
  4754. * @param 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
  4755. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4756. * @returns an array of PickingInfo
  4757. */
  4758. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): Nullable<PickingInfo[]> {
  4759. return this._internalMultiPick(world => this.createPickingRay(x, y, world, camera || null), predicate);
  4760. }
  4761. /**
  4762. * Launch a ray to try to pick a mesh in the scene
  4763. * @param ray Ray to use
  4764. * @param 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
  4765. * @returns an array of PickingInfo
  4766. */
  4767. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  4768. return this._internalMultiPick(world => {
  4769. if (!this._pickWithRayInverseMatrix) {
  4770. this._pickWithRayInverseMatrix = Matrix.Identity();
  4771. }
  4772. world.invertToRef(this._pickWithRayInverseMatrix);
  4773. if (!this._cachedRayForTransform) {
  4774. this._cachedRayForTransform = Ray.Zero();
  4775. }
  4776. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  4777. return this._cachedRayForTransform;
  4778. }, predicate);
  4779. }
  4780. /**
  4781. * Force the value of meshUnderPointer
  4782. * @param mesh defines the mesh to use
  4783. */
  4784. public setPointerOverMesh(mesh: Nullable<AbstractMesh>): void {
  4785. if (this._pointerOverMesh === mesh) {
  4786. return;
  4787. }
  4788. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  4789. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4790. }
  4791. this._pointerOverMesh = mesh;
  4792. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  4793. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4794. }
  4795. }
  4796. /**
  4797. * Gets the mesh under the pointer
  4798. * @returns a Mesh or null if no mesh is under the pointer
  4799. */
  4800. public getPointerOverMesh(): Nullable<AbstractMesh> {
  4801. return this._pointerOverMesh;
  4802. }
  4803. /**
  4804. * Force the sprite under the pointer
  4805. * @param sprite defines the sprite to use
  4806. */
  4807. public setPointerOverSprite(sprite: Nullable<Sprite>): void {
  4808. if (this._pointerOverSprite === sprite) {
  4809. return;
  4810. }
  4811. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  4812. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  4813. }
  4814. this._pointerOverSprite = sprite;
  4815. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  4816. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  4817. }
  4818. }
  4819. /**
  4820. * Gets the sprite under the pointer
  4821. * @returns a Sprite or null if no sprite is under the pointer
  4822. */
  4823. public getPointerOverSprite(): Nullable<Sprite> {
  4824. return this._pointerOverSprite;
  4825. }
  4826. // Physics
  4827. /**
  4828. * Gets the current physics engine
  4829. * @returns a PhysicsEngine or null if none attached
  4830. */
  4831. public getPhysicsEngine(): Nullable<PhysicsEngine> {
  4832. return this._physicsEngine;
  4833. }
  4834. /**
  4835. * Enables physics to the current scene
  4836. * @param gravity defines the scene's gravity for the physics engine
  4837. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  4838. * @return a boolean indicating if the physics engine was initialized
  4839. */
  4840. public enablePhysics(gravity: Nullable<Vector3> = null, plugin?: IPhysicsEnginePlugin): boolean {
  4841. if (this._physicsEngine) {
  4842. return true;
  4843. }
  4844. try {
  4845. this._physicsEngine = new PhysicsEngine(gravity, plugin);
  4846. return true;
  4847. } catch (e) {
  4848. Tools.Error(e.message);
  4849. return false;
  4850. }
  4851. }
  4852. /**
  4853. * Disables and disposes the physics engine associated with the scene
  4854. */
  4855. public disablePhysicsEngine(): void {
  4856. if (!this._physicsEngine) {
  4857. return;
  4858. }
  4859. this._physicsEngine.dispose();
  4860. this._physicsEngine = null;
  4861. }
  4862. /**
  4863. * Gets a boolean indicating if there is an active physics engine
  4864. * @returns a boolean indicating if there is an active physics engine
  4865. */
  4866. public isPhysicsEnabled(): boolean {
  4867. return this._physicsEngine !== undefined;
  4868. }
  4869. /**
  4870. * Deletes a physics compound impostor
  4871. * @param compound defines the compound to delete
  4872. */
  4873. public deleteCompoundImpostor(compound: any): void {
  4874. var mesh: AbstractMesh = compound.parts[0].mesh;
  4875. if (mesh.physicsImpostor) {
  4876. mesh.physicsImpostor.dispose(/*true*/);
  4877. mesh.physicsImpostor = null;
  4878. }
  4879. }
  4880. // Misc.
  4881. /** @hidden */
  4882. public _rebuildGeometries(): void {
  4883. for (var geometry of this._geometries) {
  4884. geometry._rebuild();
  4885. }
  4886. for (var mesh of this.meshes) {
  4887. mesh._rebuild();
  4888. }
  4889. if (this.postProcessManager) {
  4890. this.postProcessManager._rebuild();
  4891. }
  4892. for (var layer of this.layers) {
  4893. layer._rebuild();
  4894. }
  4895. for (var effectLayer of this.effectLayers) {
  4896. effectLayer._rebuild();
  4897. }
  4898. if (this._boundingBoxRenderer) {
  4899. this._boundingBoxRenderer._rebuild();
  4900. }
  4901. for (var system of this.particleSystems) {
  4902. system.rebuild();
  4903. }
  4904. if (this._postProcessRenderPipelineManager) {
  4905. this._postProcessRenderPipelineManager._rebuild();
  4906. }
  4907. }
  4908. /** @hidden */
  4909. public _rebuildTextures(): void {
  4910. for (var texture of this.textures) {
  4911. texture._rebuild();
  4912. }
  4913. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  4914. }
  4915. /**
  4916. * Creates a default light for the scene.
  4917. * @param replace Whether to replace the existing lights in the scene.
  4918. */
  4919. public createDefaultLight(replace = false): void {
  4920. // Dispose existing light in replace mode.
  4921. if (replace) {
  4922. if (this.lights) {
  4923. for (var i = 0; i < this.lights.length; i++) {
  4924. this.lights[i].dispose();
  4925. }
  4926. }
  4927. }
  4928. // Light
  4929. if (this.lights.length === 0) {
  4930. new HemisphericLight("default light", Vector3.Up(), this);
  4931. }
  4932. }
  4933. /**
  4934. * Creates a default camera for the scene.
  4935. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  4936. * @param replace Whether to replace the existing active camera in the scene.
  4937. * @param attachCameraControls Whether to attach camera controls to the canvas.
  4938. */
  4939. public createDefaultCamera(createArcRotateCamera = false, replace = false, attachCameraControls = false): void {
  4940. // Dispose existing camera in replace mode.
  4941. if (replace) {
  4942. if (this.activeCamera) {
  4943. this.activeCamera.dispose();
  4944. this.activeCamera = null;
  4945. }
  4946. }
  4947. // Camera
  4948. if (!this.activeCamera) {
  4949. var worldExtends = this.getWorldExtends();
  4950. var worldSize = worldExtends.max.subtract(worldExtends.min);
  4951. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  4952. var camera: TargetCamera;
  4953. var radius = worldSize.length() * 1.5;
  4954. // empty scene scenario!
  4955. if (!isFinite(radius)) {
  4956. radius = 1;
  4957. worldCenter.copyFromFloats(0, 0, 0);
  4958. }
  4959. if (createArcRotateCamera) {
  4960. var arcRotateCamera = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  4961. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  4962. arcRotateCamera.wheelPrecision = 100 / radius;
  4963. camera = arcRotateCamera;
  4964. }
  4965. else {
  4966. var freeCamera = new FreeCamera("default camera", new Vector3(worldCenter.x, worldCenter.y, -radius), this);
  4967. freeCamera.setTarget(worldCenter);
  4968. camera = freeCamera;
  4969. }
  4970. camera.minZ = radius * 0.01;
  4971. camera.maxZ = radius * 1000;
  4972. camera.speed = radius * 0.2;
  4973. this.activeCamera = camera;
  4974. let canvas = this.getEngine().getRenderingCanvas();
  4975. if (attachCameraControls && canvas) {
  4976. camera.attachControl(canvas);
  4977. }
  4978. }
  4979. }
  4980. /**
  4981. * Creates a default camera and a default light
  4982. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  4983. * @param replace defines if the camera and/or light will replace the existing ones
  4984. * @param attachCameraControls defines if attachControl will be called on the new camera
  4985. */
  4986. public createDefaultCameraOrLight(createArcRotateCamera = false, replace = false, attachCameraControls = false): void {
  4987. this.createDefaultLight(replace);
  4988. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  4989. }
  4990. /**
  4991. * Creates a new sky box
  4992. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  4993. * @param environmentTexture defines the texture to use as environment texture
  4994. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  4995. * @param scale defines the overall scale of the skybox
  4996. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  4997. * @returns a new mesh holding the sky box
  4998. */
  4999. public createDefaultSkybox(environmentTexture?: BaseTexture, pbr = false, scale = 1000, blur = 0): Nullable<Mesh> {
  5000. if (environmentTexture) {
  5001. this.environmentTexture = environmentTexture;
  5002. }
  5003. if (!this.environmentTexture) {
  5004. Tools.Warn("Can not create default skybox without environment texture.");
  5005. return null;
  5006. }
  5007. // Skybox
  5008. var hdrSkybox = Mesh.CreateBox("hdrSkyBox", scale, this);
  5009. if (pbr) {
  5010. let hdrSkyboxMaterial = new PBRMaterial("skyBox", this);
  5011. hdrSkyboxMaterial.backFaceCulling = false;
  5012. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  5013. if (hdrSkyboxMaterial.reflectionTexture) {
  5014. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  5015. }
  5016. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  5017. hdrSkyboxMaterial.disableLighting = true;
  5018. hdrSkyboxMaterial.twoSidedLighting = true;
  5019. hdrSkybox.infiniteDistance = true;
  5020. hdrSkybox.material = hdrSkyboxMaterial;
  5021. }
  5022. else {
  5023. let skyboxMaterial = new StandardMaterial("skyBox", this);
  5024. skyboxMaterial.backFaceCulling = false;
  5025. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  5026. if (skyboxMaterial.reflectionTexture) {
  5027. skyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  5028. }
  5029. skyboxMaterial.disableLighting = true;
  5030. hdrSkybox.infiniteDistance = true;
  5031. hdrSkybox.material = skyboxMaterial;
  5032. }
  5033. return hdrSkybox;
  5034. }
  5035. /**
  5036. * Creates a new environment
  5037. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  5038. * @param options defines the options you can use to configure the environment
  5039. * @returns the new EnvironmentHelper
  5040. */
  5041. public createDefaultEnvironment(options: Partial<IEnvironmentHelperOptions>): Nullable<EnvironmentHelper> {
  5042. if (EnvironmentHelper) {
  5043. return new EnvironmentHelper(options, this);
  5044. }
  5045. return null;
  5046. }
  5047. /**
  5048. * Creates a new VREXperienceHelper
  5049. * @see http://doc.babylonjs.com/how_to/webvr_helper
  5050. * @param webVROptions defines the options used to create the new VREXperienceHelper
  5051. * @returns a new VREXperienceHelper
  5052. */
  5053. public createDefaultVRExperience(webVROptions: VRExperienceHelperOptions = {}): VRExperienceHelper {
  5054. return new VRExperienceHelper(this, webVROptions);
  5055. }
  5056. // Tags
  5057. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  5058. if (tagsQuery === undefined) {
  5059. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  5060. return list;
  5061. }
  5062. var listByTags = [];
  5063. forEach = forEach || ((item: any) => { return; });
  5064. for (var i in list) {
  5065. var item = list[i];
  5066. if (Tags && Tags.MatchesQuery(item, tagsQuery)) {
  5067. listByTags.push(item);
  5068. forEach(item);
  5069. }
  5070. }
  5071. return listByTags;
  5072. }
  5073. /**
  5074. * Get a list of meshes by tags
  5075. * @param tagsQuery defines the tags query to use
  5076. * @param forEach defines a predicate used to filter results
  5077. * @returns an array of Mesh
  5078. */
  5079. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  5080. return this._getByTags(this.meshes, tagsQuery, forEach);
  5081. }
  5082. /**
  5083. * Get a list of cameras by tags
  5084. * @param tagsQuery defines the tags query to use
  5085. * @param forEach defines a predicate used to filter results
  5086. * @returns an array of Camera
  5087. */
  5088. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  5089. return this._getByTags(this.cameras, tagsQuery, forEach);
  5090. }
  5091. /**
  5092. * Get a list of lights by tags
  5093. * @param tagsQuery defines the tags query to use
  5094. * @param forEach defines a predicate used to filter results
  5095. * @returns an array of Light
  5096. */
  5097. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  5098. return this._getByTags(this.lights, tagsQuery, forEach);
  5099. }
  5100. /**
  5101. * Get a list of materials by tags
  5102. * @param tagsQuery defines the tags query to use
  5103. * @param forEach defines a predicate used to filter results
  5104. * @returns an array of Material
  5105. */
  5106. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  5107. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  5108. }
  5109. /**
  5110. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  5111. * This allowed control for front to back rendering or reversly depending of the special needs.
  5112. *
  5113. * @param renderingGroupId The rendering group id corresponding to its index
  5114. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  5115. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  5116. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  5117. */
  5118. public setRenderingOrder(renderingGroupId: number,
  5119. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  5120. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  5121. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  5122. this._renderingManager.setRenderingOrder(renderingGroupId,
  5123. opaqueSortCompareFn,
  5124. alphaTestSortCompareFn,
  5125. transparentSortCompareFn);
  5126. }
  5127. /**
  5128. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  5129. *
  5130. * @param renderingGroupId The rendering group id corresponding to its index
  5131. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  5132. * @param depth Automatically clears depth between groups if true and autoClear is true.
  5133. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  5134. */
  5135. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  5136. depth = true,
  5137. stencil = true): void {
  5138. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  5139. }
  5140. /**
  5141. * Will flag all materials as dirty to trigger new shader compilation
  5142. * @param flag defines the flag used to specify which material part must be marked as dirty
  5143. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  5144. */
  5145. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  5146. for (var material of this.materials) {
  5147. if (predicate && !predicate(material)) {
  5148. continue;
  5149. }
  5150. material.markAsDirty(flag);
  5151. }
  5152. }
  5153. /** @hidden */
  5154. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, useDatabase?: boolean, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  5155. let request = Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  5156. this._activeRequests.push(request);
  5157. request.onCompleteObservable.add(request => {
  5158. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  5159. });
  5160. return request;
  5161. }
  5162. /** @hidden */
  5163. public _loadFileAsync(url: string, useDatabase?: boolean, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  5164. return new Promise((resolve, reject) => {
  5165. this._loadFile(url, (data) => {
  5166. resolve(data);
  5167. }, undefined, useDatabase, useArrayBuffer, (request, exception) => {
  5168. reject(exception);
  5169. })
  5170. });
  5171. }
  5172. }
  5173. }