scene.ts 218 KB

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