babylon.scene.ts 194 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854
  1. module BABYLON {
  2. export interface IDisposable {
  3. dispose(): void;
  4. }
  5. export interface IActiveMeshCandidateProvider {
  6. getMeshes(scene: Scene): AbstractMesh[];
  7. readonly checksIsEnabled: boolean; // Indicates if the meshes have been checked to make sure they are isEnabled().
  8. }
  9. class ClickInfo {
  10. private _singleClick = false;
  11. private _doubleClick = false;
  12. private _hasSwiped = false;
  13. private _ignore = false;
  14. public get singleClick(): boolean {
  15. return this._singleClick;
  16. }
  17. public get doubleClick(): boolean {
  18. return this._doubleClick;
  19. }
  20. public get hasSwiped(): boolean {
  21. return this._hasSwiped;
  22. }
  23. public get ignore(): boolean {
  24. return this._ignore;
  25. }
  26. public set singleClick(b: boolean) {
  27. this._singleClick = b;
  28. }
  29. public set doubleClick(b: boolean) {
  30. this._doubleClick = b;
  31. }
  32. public set hasSwiped(b: boolean) {
  33. this._hasSwiped = b;
  34. }
  35. public set ignore(b: boolean) {
  36. this._ignore = b;
  37. }
  38. }
  39. /**
  40. * This class is used by the onRenderingGroupObservable
  41. */
  42. export class RenderingGroupInfo {
  43. /**
  44. * The Scene that being rendered
  45. */
  46. scene: Scene;
  47. /**
  48. * The camera currently used for the rendering pass
  49. */
  50. camera: Nullable<Camera>;
  51. /**
  52. * The ID of the renderingGroup being processed
  53. */
  54. renderingGroupId: number;
  55. /**
  56. * The rendering stage, can be either STAGE_PRECLEAR, STAGE_PREOPAQUE, STAGE_PRETRANSPARENT, STAGE_POSTTRANSPARENT
  57. */
  58. renderStage: number;
  59. /**
  60. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  61. * This stage will be fired no matter what
  62. */
  63. static STAGE_PRECLEAR = 1;
  64. /**
  65. * Called before opaque object are rendered.
  66. * This stage will be fired only if there's 3D Opaque content to render
  67. */
  68. static STAGE_PREOPAQUE = 2;
  69. /**
  70. * Called after the opaque objects are rendered and before the transparent ones
  71. * This stage will be fired only if there's 3D transparent content to render
  72. */
  73. static STAGE_PRETRANSPARENT = 3;
  74. /**
  75. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  76. * This stage will be fired no matter what
  77. */
  78. static STAGE_POSTTRANSPARENT = 4;
  79. }
  80. /**
  81. * Represents a scene to be rendered by the engine.
  82. * @see http://doc.babylonjs.com/page.php?p=21911
  83. */
  84. export class Scene implements IAnimatable {
  85. // Statics
  86. private static _FOGMODE_NONE = 0;
  87. private static _FOGMODE_EXP = 1;
  88. private static _FOGMODE_EXP2 = 2;
  89. private static _FOGMODE_LINEAR = 3;
  90. private static _uniqueIdCounter = 0;
  91. public static MinDeltaTime = 1.0;
  92. public static MaxDeltaTime = 1000.0;
  93. /** The fog is deactivated */
  94. public static get FOGMODE_NONE(): number {
  95. return Scene._FOGMODE_NONE;
  96. }
  97. /** The fog density is following an exponential function */
  98. public static get FOGMODE_EXP(): number {
  99. return Scene._FOGMODE_EXP;
  100. }
  101. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  102. public static get FOGMODE_EXP2(): number {
  103. return Scene._FOGMODE_EXP2;
  104. }
  105. /** The fog density is following a linear function. */
  106. public static get FOGMODE_LINEAR(): number {
  107. return Scene._FOGMODE_LINEAR;
  108. }
  109. // Members
  110. public autoClear = true;
  111. public autoClearDepthAndStencil = true;
  112. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  113. public ambientColor = new Color3(0, 0, 0);
  114. public _environmentBRDFTexture: BaseTexture;
  115. protected _environmentTexture: BaseTexture;
  116. /**
  117. * Texture used in all pbr material as the reflection texture.
  118. * As in the majority of the scene they are the same (exception for multi room and so on),
  119. * this is easier to reference from here than from all the materials.
  120. */
  121. public get environmentTexture(): BaseTexture {
  122. return this._environmentTexture;
  123. }
  124. /**
  125. * Texture used in all pbr material as the reflection texture.
  126. * As in the majority of the scene they are the same (exception for multi room and so on),
  127. * this is easier to set here than in all the materials.
  128. */
  129. public set environmentTexture(value: BaseTexture) {
  130. if (this._environmentTexture === value) {
  131. return;
  132. }
  133. this._environmentTexture = value;
  134. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  135. }
  136. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  137. /**
  138. * Default image processing configuration used either in the rendering
  139. * Forward main pass or through the imageProcessingPostProcess if present.
  140. * As in the majority of the scene they are the same (exception for multi camera),
  141. * this is easier to reference from here than from all the materials and post process.
  142. *
  143. * No setter as we it is a shared configuration, you can set the values instead.
  144. */
  145. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  146. return this._imageProcessingConfiguration;
  147. }
  148. public forceWireframe = false;
  149. private _forcePointsCloud = false;
  150. public set forcePointsCloud(value: boolean) {
  151. if (this._forcePointsCloud === value) {
  152. return;
  153. }
  154. this._forcePointsCloud = value;
  155. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  156. }
  157. public get forcePointsCloud(): boolean {
  158. return this._forcePointsCloud;
  159. }
  160. public forceShowBoundingBoxes = false;
  161. public clipPlane: Nullable<Plane>;
  162. public animationsEnabled = true;
  163. public useConstantAnimationDeltaTime = false;
  164. public constantlyUpdateMeshUnderPointer = false;
  165. public hoverCursor = "pointer";
  166. public defaultCursor: string = "";
  167. /**
  168. * This is used to call preventDefault() on pointer down
  169. * in order to block unwanted artifacts like system double clicks
  170. */
  171. public preventDefaultOnPointerDown = true;
  172. // Metadata
  173. public metadata: any = null;
  174. public loadingPluginName: string;
  175. // Events
  176. private _spritePredicate: (sprite: Sprite) => boolean;
  177. /**
  178. * An event triggered when the scene is disposed.
  179. * @type {BABYLON.Observable}
  180. */
  181. public onDisposeObservable = new Observable<Scene>();
  182. private _onDisposeObserver: Nullable<Observer<Scene>>;
  183. /** A function to be executed when this scene is disposed. */
  184. public set onDispose(callback: () => void) {
  185. if (this._onDisposeObserver) {
  186. this.onDisposeObservable.remove(this._onDisposeObserver);
  187. }
  188. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  189. }
  190. /**
  191. * An event triggered before rendering the scene (right after animations and physics)
  192. * @type {BABYLON.Observable}
  193. */
  194. public onBeforeRenderObservable = new Observable<Scene>();
  195. private _onBeforeRenderObserver: Nullable<Observer<Scene>>;
  196. /** A function to be executed before rendering this scene */
  197. public set beforeRender(callback: Nullable<() => void>) {
  198. if (this._onBeforeRenderObserver) {
  199. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  200. }
  201. if (callback) {
  202. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  203. }
  204. }
  205. /**
  206. * An event triggered after rendering the scene
  207. * @type {BABYLON.Observable}
  208. */
  209. public onAfterRenderObservable = new Observable<Scene>();
  210. private _onAfterRenderObserver: Nullable<Observer<Scene>>;
  211. /** A function to be executed after rendering this scene */
  212. public set afterRender(callback: Nullable<() => void>) {
  213. if (this._onAfterRenderObserver) {
  214. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  215. }
  216. if (callback) {
  217. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  218. }
  219. }
  220. /**
  221. * An event triggered before animating the scene
  222. * @type {BABYLON.Observable}
  223. */
  224. public onBeforeAnimationsObservable = new Observable<Scene>();
  225. /**
  226. * An event triggered after animations processing
  227. * @type {BABYLON.Observable}
  228. */
  229. public onAfterAnimationsObservable = new Observable<Scene>();
  230. /**
  231. * An event triggered before draw calls are ready to be sent
  232. * @type {BABYLON.Observable}
  233. */
  234. public onBeforeDrawPhaseObservable = new Observable<Scene>();
  235. /**
  236. * An event triggered after draw calls have been sent
  237. * @type {BABYLON.Observable}
  238. */
  239. public onAfterDrawPhaseObservable = new Observable<Scene>();
  240. /**
  241. * An event triggered when physic simulation is about to be run
  242. * @type {BABYLON.Observable}
  243. */
  244. public onBeforePhysicsObservable = new Observable<Scene>();
  245. /**
  246. * An event triggered when physic simulation has been done
  247. * @type {BABYLON.Observable}
  248. */
  249. public onAfterPhysicsObservable = new Observable<Scene>();
  250. /**
  251. * An event triggered when the scene is ready
  252. * @type {BABYLON.Observable}
  253. */
  254. public onReadyObservable = new Observable<Scene>();
  255. /**
  256. * An event triggered before rendering a camera
  257. * @type {BABYLON.Observable}
  258. */
  259. public onBeforeCameraRenderObservable = new Observable<Camera>();
  260. private _onBeforeCameraRenderObserver: Nullable<Observer<Camera>>;
  261. public set beforeCameraRender(callback: () => void) {
  262. if (this._onBeforeCameraRenderObserver) {
  263. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  264. }
  265. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  266. }
  267. /**
  268. * An event triggered after rendering a camera
  269. * @type {BABYLON.Observable}
  270. */
  271. public onAfterCameraRenderObservable = new Observable<Camera>();
  272. private _onAfterCameraRenderObserver: Nullable<Observer<Camera>>;
  273. public set afterCameraRender(callback: () => void) {
  274. if (this._onAfterCameraRenderObserver) {
  275. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  276. }
  277. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  278. }
  279. /**
  280. * An event triggered when active meshes evaluation is about to start
  281. * @type {BABYLON.Observable}
  282. */
  283. public onBeforeActiveMeshesEvaluationObservable = new Observable<Scene>();
  284. /**
  285. * An event triggered when active meshes evaluation is done
  286. * @type {BABYLON.Observable}
  287. */
  288. public onAfterActiveMeshesEvaluationObservable = new Observable<Scene>();
  289. /**
  290. * An event triggered when particles rendering is about to start
  291. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  292. * @type {BABYLON.Observable}
  293. */
  294. public onBeforeParticlesRenderingObservable = new Observable<Scene>();
  295. /**
  296. * An event triggered when particles rendering is done
  297. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  298. * @type {BABYLON.Observable}
  299. */
  300. public onAfterParticlesRenderingObservable = new Observable<Scene>();
  301. /**
  302. * An event triggered when sprites rendering is about to start
  303. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  304. * @type {BABYLON.Observable}
  305. */
  306. public onBeforeSpritesRenderingObservable = new Observable<Scene>();
  307. /**
  308. * An event triggered when sprites rendering is done
  309. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  310. * @type {BABYLON.Observable}
  311. */
  312. public onAfterSpritesRenderingObservable = new Observable<Scene>();
  313. /**
  314. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  315. * @type {BABYLON.Observable}
  316. */
  317. public onDataLoadedObservable = new Observable<Scene>();
  318. /**
  319. * An event triggered when a camera is created
  320. * @type {BABYLON.Observable}
  321. */
  322. public onNewCameraAddedObservable = new Observable<Camera>();
  323. /**
  324. * An event triggered when a camera is removed
  325. * @type {BABYLON.Observable}
  326. */
  327. public onCameraRemovedObservable = new Observable<Camera>();
  328. /**
  329. * An event triggered when a light is created
  330. * @type {BABYLON.Observable}
  331. */
  332. public onNewLightAddedObservable = new Observable<Light>();
  333. /**
  334. * An event triggered when a light is removed
  335. * @type {BABYLON.Observable}
  336. */
  337. public onLightRemovedObservable = new Observable<Light>();
  338. /**
  339. * An event triggered when a geometry is created
  340. * @type {BABYLON.Observable}
  341. */
  342. public onNewGeometryAddedObservable = new Observable<Geometry>();
  343. /**
  344. * An event triggered when a geometry is removed
  345. * @type {BABYLON.Observable}
  346. */
  347. public onGeometryRemovedObservable = new Observable<Geometry>();
  348. /**
  349. * An event triggered when a transform node is created
  350. * @type {BABYLON.Observable}
  351. */
  352. public onNewTransformNodeAddedObservable = new Observable<TransformNode>();
  353. /**
  354. * An event triggered when a transform node is removed
  355. * @type {BABYLON.Observable}
  356. */
  357. public onTransformNodeRemovedObservable = new Observable<TransformNode>();
  358. /**
  359. * An event triggered when a mesh is created
  360. * @type {BABYLON.Observable}
  361. */
  362. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  363. /**
  364. * An event triggered when a mesh is removed
  365. * @type {BABYLON.Observable}
  366. */
  367. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  368. /**
  369. * An event triggered when render targets are about to be rendered
  370. * Can happen multiple times per frame.
  371. * @type {BABYLON.Observable}
  372. */
  373. public OnBeforeRenderTargetsRenderObservable = new Observable<Scene>();
  374. /**
  375. * An event triggered when render targets were rendered.
  376. * Can happen multiple times per frame.
  377. * @type {BABYLON.Observable}
  378. */
  379. public OnAfterRenderTargetsRenderObservable = new Observable<Scene>();
  380. /**
  381. * An event triggered before calculating deterministic simulation step
  382. * @type {BABYLON.Observable}
  383. */
  384. public onBeforeStepObservable = new Observable<Scene>();
  385. /**
  386. * An event triggered after calculating deterministic simulation step
  387. * @type {BABYLON.Observable}
  388. */
  389. public onAfterStepObservable = new Observable<Scene>();
  390. /**
  391. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  392. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  393. * 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)
  394. */
  395. public onRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  396. // Animations
  397. public animations: Animation[] = [];
  398. // Pointers
  399. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  400. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  401. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  402. private _onPointerMove: (evt: PointerEvent) => void;
  403. private _onPointerDown: (evt: PointerEvent) => void;
  404. private _onPointerUp: (evt: PointerEvent) => void;
  405. /** Deprecated. Use onPointerObservable instead */
  406. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  407. /** Deprecated. Use onPointerObservable instead */
  408. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  409. /** Deprecated. Use onPointerObservable instead */
  410. public onPointerUp: (evt: PointerEvent, pickInfo: Nullable<PickingInfo>) => void;
  411. /** Deprecated. Use onPointerObservable instead */
  412. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  413. // Gamepads
  414. private _gamepadManager: Nullable<GamepadManager>;
  415. public get gamepadManager(): GamepadManager {
  416. if (!this._gamepadManager) {
  417. this._gamepadManager = new GamepadManager(this);
  418. }
  419. return this._gamepadManager;
  420. }
  421. /**
  422. * 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).
  423. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  424. */
  425. public onPrePointerObservable = new Observable<PointerInfoPre>();
  426. /**
  427. * Observable event triggered each time an input event is received from the rendering canvas
  428. */
  429. public onPointerObservable = new Observable<PointerInfo>();
  430. public get unTranslatedPointer(): Vector2 {
  431. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  432. }
  433. /** The distance in pixel that you have to move to prevent some events */
  434. public static DragMovementThreshold = 10; // in pixels
  435. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  436. public static LongPressDelay = 500; // in milliseconds
  437. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  438. public static DoubleClickDelay = 300; // in milliseconds
  439. /** If you need to check double click without raising a single click at first click, enable this flag */
  440. public static ExclusiveDoubleClickMode = false;
  441. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  442. private _initActionManager: (act: Nullable<ActionManager>, clickInfo: ClickInfo) => Nullable<ActionManager>;
  443. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  444. private _delayedSimpleClickTimeout: number;
  445. private _previousDelayedSimpleClickTimeout: number;
  446. private _meshPickProceed = false;
  447. private _previousButtonPressed: number;
  448. private _currentPickResult: Nullable<PickingInfo> = null;
  449. private _previousPickResult: Nullable<PickingInfo> = null;
  450. private _totalPointersPressed = 0;
  451. private _doubleClickOccured = false;
  452. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  453. public cameraToUseForPointers: Nullable<Camera> = null;
  454. private _pointerX: number;
  455. private _pointerY: number;
  456. private _unTranslatedPointerX: number;
  457. private _unTranslatedPointerY: number;
  458. private _startingPointerPosition = new Vector2(0, 0);
  459. private _previousStartingPointerPosition = new Vector2(0, 0);
  460. private _startingPointerTime = 0;
  461. private _previousStartingPointerTime = 0;
  462. // Deterministic lockstep
  463. private _timeAccumulator: number = 0;
  464. private _currentStepId: number = 0;
  465. private _currentInternalStep: number = 0;
  466. // Mirror
  467. public _mirroredCameraPosition: Nullable<Vector3>;
  468. // Keyboard
  469. /**
  470. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  471. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  472. */
  473. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  474. /**
  475. * Observable event triggered each time an keyboard event is received from the hosting window
  476. */
  477. public onKeyboardObservable = new Observable<KeyboardInfo>();
  478. private _onKeyDown: (evt: KeyboardEvent) => void;
  479. private _onKeyUp: (evt: KeyboardEvent) => void;
  480. private _onCanvasFocusObserver: Nullable<Observer<Engine>>;
  481. private _onCanvasBlurObserver: Nullable<Observer<Engine>>;
  482. // Coordinate system
  483. /**
  484. * use right-handed coordinate system on this scene.
  485. * @type {boolean}
  486. */
  487. private _useRightHandedSystem = false;
  488. public set useRightHandedSystem(value: boolean) {
  489. if (this._useRightHandedSystem === value) {
  490. return;
  491. }
  492. this._useRightHandedSystem = value;
  493. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  494. }
  495. public get useRightHandedSystem(): boolean {
  496. return this._useRightHandedSystem;
  497. }
  498. public setStepId(newStepId: number): void {
  499. this._currentStepId = newStepId;
  500. };
  501. public getStepId(): number {
  502. return this._currentStepId;
  503. };
  504. public getInternalStep(): number {
  505. return this._currentInternalStep;
  506. };
  507. // Fog
  508. private _fogEnabled = true;
  509. /**
  510. * is fog enabled on this scene.
  511. */
  512. public set fogEnabled(value: boolean) {
  513. if (this._fogEnabled === value) {
  514. return;
  515. }
  516. this._fogEnabled = value;
  517. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  518. }
  519. public get fogEnabled(): boolean {
  520. return this._fogEnabled;
  521. }
  522. private _fogMode = Scene.FOGMODE_NONE;
  523. public set fogMode(value: number) {
  524. if (this._fogMode === value) {
  525. return;
  526. }
  527. this._fogMode = value;
  528. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  529. }
  530. public get fogMode(): number {
  531. return this._fogMode;
  532. }
  533. public fogColor = new Color3(0.2, 0.2, 0.3);
  534. public fogDensity = 0.1;
  535. public fogStart = 0;
  536. public fogEnd = 1000.0;
  537. // Lights
  538. /**
  539. * is shadow enabled on this scene.
  540. * @type {boolean}
  541. */
  542. private _shadowsEnabled = true;
  543. public set shadowsEnabled(value: boolean) {
  544. if (this._shadowsEnabled === value) {
  545. return;
  546. }
  547. this._shadowsEnabled = value;
  548. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  549. }
  550. public get shadowsEnabled(): boolean {
  551. return this._shadowsEnabled;
  552. }
  553. /**
  554. * is light enabled on this scene.
  555. * @type {boolean}
  556. */
  557. private _lightsEnabled = true;
  558. public set lightsEnabled(value: boolean) {
  559. if (this._lightsEnabled === value) {
  560. return;
  561. }
  562. this._lightsEnabled = value;
  563. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  564. }
  565. public get lightsEnabled(): boolean {
  566. return this._lightsEnabled;
  567. }
  568. /**
  569. * All of the lights added to this scene.
  570. * @see BABYLON.Light
  571. * @type {BABYLON.Light[]}
  572. */
  573. public lights = new Array<Light>();
  574. // Cameras
  575. /** All of the cameras added to this scene. */
  576. public cameras = new Array<Camera>();
  577. /** All of the active cameras added to this scene. */
  578. public activeCameras = new Array<Camera>();
  579. /** The current active camera */
  580. public activeCamera: Nullable<Camera>;
  581. // Meshes
  582. /**
  583. * All of the tranform nodes added to this scene.
  584. * @see BABYLON.TransformNode
  585. * @type {BABYLON.TransformNode[]}
  586. */
  587. public transformNodes = new Array<TransformNode>();
  588. /**
  589. * All of the (abstract) meshes added to this scene.
  590. * @see BABYLON.AbstractMesh
  591. * @type {BABYLON.AbstractMesh[]}
  592. */
  593. public meshes = new Array<AbstractMesh>();
  594. /**
  595. * All of the animation groups added to this scene.
  596. * @see BABYLON.AnimationGroup
  597. * @type {BABYLON.AnimationGroup[]}
  598. */
  599. public animationGroups = new Array<AnimationGroup>();
  600. // Geometries
  601. private _geometries = new Array<Geometry>();
  602. public materials = new Array<Material>();
  603. public multiMaterials = new Array<MultiMaterial>();
  604. private _defaultMaterial: Material;
  605. /** The default material used on meshes when no material is affected */
  606. public get defaultMaterial(): Material {
  607. if (!this._defaultMaterial) {
  608. this._defaultMaterial = new StandardMaterial("default material", this);
  609. }
  610. return this._defaultMaterial;
  611. }
  612. /** The default material used on meshes when no material is affected */
  613. public set defaultMaterial(value: Material) {
  614. this._defaultMaterial = value;
  615. }
  616. // Textures
  617. private _texturesEnabled = true;
  618. public set texturesEnabled(value: boolean) {
  619. if (this._texturesEnabled === value) {
  620. return;
  621. }
  622. this._texturesEnabled = value;
  623. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  624. }
  625. public get texturesEnabled(): boolean {
  626. return this._texturesEnabled;
  627. }
  628. public textures = new Array<BaseTexture>();
  629. // Particles
  630. public particlesEnabled = true;
  631. public particleSystems = new Array<IParticleSystem>();
  632. // Sprites
  633. public spritesEnabled = true;
  634. public spriteManagers = new Array<SpriteManager>();
  635. // Layers
  636. public layers = new Array<Layer>();
  637. public highlightLayers = new Array<HighlightLayer>();
  638. // Skeletons
  639. private _skeletonsEnabled = true;
  640. public set skeletonsEnabled(value: boolean) {
  641. if (this._skeletonsEnabled === value) {
  642. return;
  643. }
  644. this._skeletonsEnabled = value;
  645. this.markAllMaterialsAsDirty(Material.AttributesDirtyFlag);
  646. }
  647. public get skeletonsEnabled(): boolean {
  648. return this._skeletonsEnabled;
  649. }
  650. public skeletons = new Array<Skeleton>();
  651. // Morph targets
  652. public morphTargetManagers = new Array<MorphTargetManager>();
  653. // Lens flares
  654. public lensFlaresEnabled = true;
  655. public lensFlareSystems = new Array<LensFlareSystem>();
  656. // Collisions
  657. public collisionsEnabled = true;
  658. private _workerCollisions: boolean;
  659. public collisionCoordinator: ICollisionCoordinator;
  660. /** Defines the gravity applied to this scene */
  661. public gravity = new Vector3(0, -9.807, 0);
  662. // Postprocesses
  663. public postProcesses = new Array<PostProcess>();
  664. public postProcessesEnabled = true;
  665. public postProcessManager: PostProcessManager;
  666. private _postProcessRenderPipelineManager: PostProcessRenderPipelineManager
  667. public get postProcessRenderPipelineManager(): PostProcessRenderPipelineManager {
  668. if (!this._postProcessRenderPipelineManager) {
  669. this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  670. }
  671. return this._postProcessRenderPipelineManager;
  672. }
  673. // Customs render targets
  674. public renderTargetsEnabled = true;
  675. public dumpNextRenderTargets = false;
  676. public customRenderTargets = new Array<RenderTargetTexture>();
  677. // Delay loading
  678. public useDelayedTextureLoading: boolean;
  679. // Imported meshes
  680. public importedMeshesFiles = new Array<String>();
  681. // Probes
  682. public probesEnabled = true;
  683. public reflectionProbes = new Array<ReflectionProbe>();
  684. // Database
  685. public database: Database;
  686. /**
  687. * This scene's action manager
  688. * @type {BABYLON.ActionManager}
  689. */
  690. public actionManager: ActionManager;
  691. public _actionManagers = new Array<ActionManager>();
  692. private _meshesForIntersections = new SmartArrayNoDuplicate<AbstractMesh>(256);
  693. // Procedural textures
  694. public proceduralTexturesEnabled = true;
  695. public _proceduralTextures = new Array<ProceduralTexture>();
  696. // Sound Tracks
  697. private _mainSoundTrack: SoundTrack;
  698. public soundTracks = new Array<SoundTrack>();
  699. private _audioEnabled = true;
  700. private _headphone = false;
  701. public get mainSoundTrack(): SoundTrack {
  702. if (!this._mainSoundTrack) {
  703. this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  704. }
  705. return this._mainSoundTrack;
  706. }
  707. // VR Helper
  708. public VRHelper: VRExperienceHelper;
  709. //Simplification Queue
  710. public simplificationQueue: SimplificationQueue;
  711. // Private
  712. private _engine: Engine;
  713. // Performance counters
  714. private _totalVertices = new PerfCounter();
  715. public _activeIndices = new PerfCounter();
  716. public _activeParticles = new PerfCounter();
  717. public _activeBones = new PerfCounter();
  718. private _animationRatio: number;
  719. private _animationTimeLast: number;
  720. private _animationTime: number = 0;
  721. public animationTimeScale: number = 1;
  722. public _cachedMaterial: Nullable<Material>;
  723. public _cachedEffect: Nullable<Effect>;
  724. public _cachedVisibility: Nullable<number>;
  725. private _renderId = 0;
  726. private _executeWhenReadyTimeoutId = -1;
  727. private _intermediateRendering = false;
  728. private _viewUpdateFlag = -1;
  729. private _projectionUpdateFlag = -1;
  730. private _alternateViewUpdateFlag = -1;
  731. private _alternateProjectionUpdateFlag = -1;
  732. public _toBeDisposed = new SmartArray<Nullable<IDisposable>>(256);
  733. private _activeRequests = new Array<IFileRequest>();
  734. private _pendingData = new Array();
  735. private _isDisposed = false;
  736. public dispatchAllSubMeshesOfActiveMeshes: boolean = false;
  737. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  738. private _processedMaterials = new SmartArray<Material>(256);
  739. private _renderTargets = new SmartArrayNoDuplicate<RenderTargetTexture>(256);
  740. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  741. private _activeSkeletons = new SmartArrayNoDuplicate<Skeleton>(32);
  742. private _softwareSkinnedMeshes = new SmartArrayNoDuplicate<Mesh>(32);
  743. private _renderingManager: RenderingManager;
  744. private _physicsEngine: Nullable<PhysicsEngine>;
  745. public _activeAnimatables = new Array<Animatable>();
  746. private _transformMatrix = Matrix.Zero();
  747. private _sceneUbo: UniformBuffer;
  748. private _alternateSceneUbo: UniformBuffer;
  749. private _pickWithRayInverseMatrix: Matrix;
  750. private _boundingBoxRenderer: BoundingBoxRenderer;
  751. private _outlineRenderer: OutlineRenderer;
  752. private _viewMatrix: Matrix;
  753. private _projectionMatrix: Matrix;
  754. private _alternateViewMatrix: Matrix;
  755. private _alternateProjectionMatrix: Matrix;
  756. private _alternateTransformMatrix: Matrix;
  757. private _useAlternateCameraConfiguration = false;
  758. private _alternateRendering = false;
  759. public _forcedViewPosition: Nullable<Vector3>;
  760. public get _isAlternateRenderingEnabled(): boolean {
  761. return this._alternateRendering;
  762. }
  763. private _frustumPlanes: Plane[];
  764. public get frustumPlanes(): Plane[] {
  765. return this._frustumPlanes;
  766. }
  767. public requireLightSorting = false;
  768. private _selectionOctree: Octree<AbstractMesh>;
  769. private _pointerOverMesh: Nullable<AbstractMesh>;
  770. private _pointerOverSprite: Nullable<Sprite>;
  771. private _debugLayer: DebugLayer;
  772. private _depthRenderer: Nullable<DepthRenderer>;
  773. private _geometryBufferRenderer: Nullable<GeometryBufferRenderer>;
  774. /**
  775. * Gets the current geometry buffer associated to the scene.
  776. */
  777. public get geometryBufferRenderer(): Nullable<GeometryBufferRenderer> {
  778. return this._geometryBufferRenderer;
  779. }
  780. /**
  781. * Sets the current geometry buffer for the scene.
  782. */
  783. public set geometryBufferRenderer(geometryBufferRenderer: Nullable<GeometryBufferRenderer>) {
  784. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  785. this._geometryBufferRenderer = geometryBufferRenderer;
  786. }
  787. }
  788. private _pickedDownMesh: Nullable<AbstractMesh>;
  789. private _pickedUpMesh: Nullable<AbstractMesh>;
  790. private _pickedDownSprite: Nullable<Sprite>;
  791. private _externalData: StringDictionary<Object>;
  792. private _uid: Nullable<string>;
  793. /**
  794. * @constructor
  795. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  796. */
  797. constructor(engine: Engine) {
  798. this._engine = engine || Engine.LastCreatedEngine;
  799. this._engine.scenes.push(this);
  800. this._uid = null;
  801. this._renderingManager = new RenderingManager(this);
  802. this.postProcessManager = new PostProcessManager(this);
  803. if (OutlineRenderer) {
  804. this._outlineRenderer = new OutlineRenderer(this);
  805. }
  806. if (Tools.IsWindowObjectExist()) {
  807. this.attachControl();
  808. }
  809. //simplification queue
  810. if (SimplificationQueue) {
  811. this.simplificationQueue = new SimplificationQueue();
  812. }
  813. //collision coordinator initialization. For now legacy per default.
  814. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  815. // Uniform Buffer
  816. this._createUbo();
  817. // Default Image processing definition.
  818. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  819. }
  820. // Properties
  821. public get debugLayer(): DebugLayer {
  822. if (!this._debugLayer) {
  823. this._debugLayer = new DebugLayer(this);
  824. }
  825. return this._debugLayer;
  826. }
  827. public set workerCollisions(enabled: boolean) {
  828. if (!CollisionCoordinatorLegacy) {
  829. return;
  830. }
  831. enabled = (enabled && !!Worker);
  832. this._workerCollisions = enabled;
  833. if (this.collisionCoordinator) {
  834. this.collisionCoordinator.destroy();
  835. }
  836. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  837. this.collisionCoordinator.init(this);
  838. }
  839. public get workerCollisions(): boolean {
  840. return this._workerCollisions;
  841. }
  842. public get selectionOctree(): Octree<AbstractMesh> {
  843. return this._selectionOctree;
  844. }
  845. /**
  846. * The mesh that is currently under the pointer.
  847. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  848. */
  849. public get meshUnderPointer(): Nullable<AbstractMesh> {
  850. return this._pointerOverMesh;
  851. }
  852. /**
  853. * Current on-screen X position of the pointer
  854. * @return {number} X position of the pointer
  855. */
  856. public get pointerX(): number {
  857. return this._pointerX;
  858. }
  859. /**
  860. * Current on-screen Y position of the pointer
  861. * @return {number} Y position of the pointer
  862. */
  863. public get pointerY(): number {
  864. return this._pointerY;
  865. }
  866. public getCachedMaterial(): Nullable<Material> {
  867. return this._cachedMaterial;
  868. }
  869. public getCachedEffect(): Nullable<Effect> {
  870. return this._cachedEffect;
  871. }
  872. public getCachedVisibility(): Nullable<number> {
  873. return this._cachedVisibility;
  874. }
  875. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  876. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  877. }
  878. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  879. if (!this._boundingBoxRenderer) {
  880. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  881. }
  882. return this._boundingBoxRenderer;
  883. }
  884. public getOutlineRenderer(): OutlineRenderer {
  885. return this._outlineRenderer;
  886. }
  887. public getEngine(): Engine {
  888. return this._engine;
  889. }
  890. public getTotalVertices(): number {
  891. return this._totalVertices.current;
  892. }
  893. public get totalVerticesPerfCounter(): PerfCounter {
  894. return this._totalVertices;
  895. }
  896. public getActiveIndices(): number {
  897. return this._activeIndices.current;
  898. }
  899. public get totalActiveIndicesPerfCounter(): PerfCounter {
  900. return this._activeIndices;
  901. }
  902. public getActiveParticles(): number {
  903. return this._activeParticles.current;
  904. }
  905. public get activeParticlesPerfCounter(): PerfCounter {
  906. return this._activeParticles;
  907. }
  908. public getActiveBones(): number {
  909. return this._activeBones.current;
  910. }
  911. public get activeBonesPerfCounter(): PerfCounter {
  912. return this._activeBones;
  913. }
  914. // Stats
  915. public getInterFramePerfCounter(): number {
  916. Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  917. return 0;
  918. }
  919. public get interFramePerfCounter(): Nullable<PerfCounter> {
  920. Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  921. return null;
  922. }
  923. public getLastFrameDuration(): number {
  924. Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  925. return 0;
  926. }
  927. public get lastFramePerfCounter(): Nullable<PerfCounter> {
  928. Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  929. return null;
  930. }
  931. public getEvaluateActiveMeshesDuration(): number {
  932. Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  933. return 0;
  934. }
  935. public get evaluateActiveMeshesDurationPerfCounter(): Nullable<PerfCounter> {
  936. Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  937. return null;
  938. }
  939. public getActiveMeshes(): SmartArray<AbstractMesh> {
  940. return this._activeMeshes;
  941. }
  942. public getRenderTargetsDuration(): number {
  943. Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  944. return 0;
  945. }
  946. public getRenderDuration(): number {
  947. Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  948. return 0;
  949. }
  950. public get renderDurationPerfCounter(): Nullable<PerfCounter> {
  951. Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  952. return null;
  953. }
  954. public getParticlesDuration(): number {
  955. Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  956. return 0;
  957. }
  958. public get particlesDurationPerfCounter(): Nullable<PerfCounter> {
  959. Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  960. return null;
  961. }
  962. public getSpritesDuration(): number {
  963. Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  964. return 0;
  965. }
  966. public get spriteDuractionPerfCounter(): Nullable<PerfCounter> {
  967. Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  968. return null;
  969. }
  970. public getAnimationRatio(): number {
  971. return this._animationRatio;
  972. }
  973. public getRenderId(): number {
  974. return this._renderId;
  975. }
  976. public incrementRenderId(): void {
  977. this._renderId++;
  978. }
  979. private _updatePointerPosition(evt: PointerEvent): void {
  980. var canvasRect = this._engine.getRenderingCanvasClientRect();
  981. if (!canvasRect) {
  982. return;
  983. }
  984. this._pointerX = evt.clientX - canvasRect.left;
  985. this._pointerY = evt.clientY - canvasRect.top;
  986. this._unTranslatedPointerX = this._pointerX;
  987. this._unTranslatedPointerY = this._pointerY;
  988. }
  989. private _createUbo(): void {
  990. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  991. this._sceneUbo.addUniform("viewProjection", 16);
  992. this._sceneUbo.addUniform("view", 16);
  993. }
  994. private _createAlternateUbo(): void {
  995. this._alternateSceneUbo = new UniformBuffer(this._engine, undefined, true);
  996. this._alternateSceneUbo.addUniform("viewProjection", 16);
  997. this._alternateSceneUbo.addUniform("view", 16);
  998. }
  999. // Pointers handling
  1000. /**
  1001. * Use this method to simulate a pointer move on a mesh
  1002. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1003. */
  1004. public simulatePointerMove(pickResult: PickingInfo): Scene {
  1005. let evt = new PointerEvent("pointermove");
  1006. return this._processPointerMove(pickResult, evt);
  1007. }
  1008. private _processPointerMove(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1009. var canvas = this._engine.getRenderingCanvas();
  1010. if (!canvas) {
  1011. return this;
  1012. }
  1013. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1014. this.setPointerOverSprite(null);
  1015. this.setPointerOverMesh(pickResult.pickedMesh);
  1016. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  1017. if (this._pointerOverMesh.actionManager.hoverCursor) {
  1018. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  1019. } else {
  1020. canvas.style.cursor = this.hoverCursor;
  1021. }
  1022. } else {
  1023. canvas.style.cursor = this.defaultCursor;
  1024. }
  1025. } else {
  1026. this.setPointerOverMesh(null);
  1027. // Sprites
  1028. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1029. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1030. this.setPointerOverSprite(pickResult.pickedSprite);
  1031. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  1032. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  1033. } else {
  1034. canvas.style.cursor = this.hoverCursor;
  1035. }
  1036. } else {
  1037. this.setPointerOverSprite(null);
  1038. // Restore pointer
  1039. canvas.style.cursor = this.defaultCursor;
  1040. }
  1041. }
  1042. if (pickResult) {
  1043. if (this.onPointerMove) {
  1044. this.onPointerMove(evt, pickResult);
  1045. }
  1046. if (this.onPointerObservable.hasObservers()) {
  1047. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1048. let pi = new PointerInfo(type, evt, pickResult);
  1049. this.onPointerObservable.notifyObservers(pi, type);
  1050. }
  1051. }
  1052. return this;
  1053. }
  1054. /**
  1055. * Use this method to simulate a pointer down on a mesh
  1056. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1057. */
  1058. public simulatePointerDown(pickResult: PickingInfo): Scene {
  1059. let evt = new PointerEvent("pointerdown");
  1060. return this._processPointerDown(pickResult, evt);
  1061. }
  1062. private _processPointerDown(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1063. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1064. this._pickedDownMesh = pickResult.pickedMesh;
  1065. var actionManager = pickResult.pickedMesh.actionManager;
  1066. if (actionManager) {
  1067. if (actionManager.hasPickTriggers) {
  1068. actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1069. switch (evt.button) {
  1070. case 0:
  1071. actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1072. break;
  1073. case 1:
  1074. actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1075. break;
  1076. case 2:
  1077. actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1078. break;
  1079. }
  1080. }
  1081. if (actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  1082. window.setTimeout(() => {
  1083. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  1084. (mesh: AbstractMesh): boolean => (<boolean>(mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger) && mesh == this._pickedDownMesh)),
  1085. false, this.cameraToUseForPointers);
  1086. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  1087. if (this._totalPointersPressed !== 0 &&
  1088. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  1089. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  1090. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  1091. this._startingPointerTime = 0;
  1092. actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1093. }
  1094. }
  1095. }, Scene.LongPressDelay);
  1096. }
  1097. }
  1098. }
  1099. if (pickResult) {
  1100. if (this.onPointerDown) {
  1101. this.onPointerDown(evt, pickResult);
  1102. }
  1103. if (this.onPointerObservable.hasObservers()) {
  1104. let type = PointerEventTypes.POINTERDOWN;
  1105. let pi = new PointerInfo(type, evt, pickResult);
  1106. this.onPointerObservable.notifyObservers(pi, type);
  1107. }
  1108. }
  1109. return this;
  1110. }
  1111. /**
  1112. * Use this method to simulate a pointer up on a mesh
  1113. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1114. */
  1115. public simulatePointerUp(pickResult: PickingInfo): Scene {
  1116. let evt = new PointerEvent("pointerup");
  1117. let clickInfo = new ClickInfo();
  1118. clickInfo.singleClick = true;
  1119. clickInfo.ignore = true;
  1120. return this._processPointerUp(pickResult, evt, clickInfo);
  1121. }
  1122. private _processPointerUp(pickResult: Nullable<PickingInfo>, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  1123. if (pickResult && pickResult && pickResult.pickedMesh) {
  1124. this._pickedUpMesh = pickResult.pickedMesh;
  1125. if (this._pickedDownMesh === this._pickedUpMesh) {
  1126. if (this.onPointerPick) {
  1127. this.onPointerPick(evt, pickResult);
  1128. }
  1129. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1130. let type = PointerEventTypes.POINTERPICK;
  1131. let pi = new PointerInfo(type, evt, pickResult);
  1132. this.onPointerObservable.notifyObservers(pi, type);
  1133. }
  1134. }
  1135. if (pickResult.pickedMesh.actionManager) {
  1136. if (clickInfo.ignore) {
  1137. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1138. }
  1139. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  1140. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1141. }
  1142. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1143. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1144. }
  1145. }
  1146. }
  1147. if (this._pickedDownMesh &&
  1148. this._pickedDownMesh.actionManager &&
  1149. this._pickedDownMesh.actionManager.hasSpecificTrigger(ActionManager.OnPickOutTrigger) &&
  1150. this._pickedDownMesh !== this._pickedUpMesh) {
  1151. this._pickedDownMesh.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1152. }
  1153. if (this.onPointerUp) {
  1154. this.onPointerUp(evt, pickResult);
  1155. }
  1156. if (this.onPointerObservable.hasObservers()) {
  1157. if (!clickInfo.ignore) {
  1158. if (!clickInfo.hasSwiped) {
  1159. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1160. let type = PointerEventTypes.POINTERTAP;
  1161. let pi = new PointerInfo(type, evt, pickResult);
  1162. this.onPointerObservable.notifyObservers(pi, type);
  1163. }
  1164. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1165. let type = PointerEventTypes.POINTERDOUBLETAP;
  1166. let pi = new PointerInfo(type, evt, pickResult);
  1167. this.onPointerObservable.notifyObservers(pi, type);
  1168. }
  1169. }
  1170. }
  1171. else {
  1172. let type = PointerEventTypes.POINTERUP;
  1173. let pi = new PointerInfo(type, evt, pickResult);
  1174. this.onPointerObservable.notifyObservers(pi, type);
  1175. }
  1176. }
  1177. return this;
  1178. }
  1179. /**
  1180. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1181. * @param attachUp defines if you want to attach events to pointerup
  1182. * @param attachDown defines if you want to attach events to pointerdown
  1183. * @param attachMove defines if you want to attach events to pointermove
  1184. */
  1185. public attachControl(attachUp = true, attachDown = true, attachMove = true) {
  1186. this._initActionManager = (act: Nullable<ActionManager>, clickInfo: ClickInfo): Nullable<ActionManager> => {
  1187. if (!this._meshPickProceed) {
  1188. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1189. this._currentPickResult = pickResult;
  1190. if (pickResult) {
  1191. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1192. }
  1193. this._meshPickProceed = true;
  1194. }
  1195. return act;
  1196. };
  1197. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => {
  1198. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1199. if ((new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1200. btn !== this._previousButtonPressed) {
  1201. this._doubleClickOccured = false;
  1202. clickInfo.singleClick = true;
  1203. clickInfo.ignore = false;
  1204. cb(clickInfo, this._currentPickResult);
  1205. }
  1206. }
  1207. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void): void => {
  1208. let clickInfo = new ClickInfo();
  1209. this._currentPickResult = null;
  1210. let act: Nullable<ActionManager> = null;
  1211. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1212. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1213. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1214. if (!checkPicking && ActionManager && ActionManager.HasPickTriggers) {
  1215. act = this._initActionManager(act, clickInfo);
  1216. if (act)
  1217. checkPicking = act.hasPickTriggers;
  1218. }
  1219. if (checkPicking) {
  1220. let btn = evt.button;
  1221. clickInfo.hasSwiped = Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1222. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1223. if (!clickInfo.hasSwiped) {
  1224. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1225. if (!checkSingleClickImmediately) {
  1226. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1227. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1228. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1229. act = this._initActionManager(act, clickInfo);
  1230. if (act)
  1231. checkSingleClickImmediately = !act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1232. }
  1233. }
  1234. if (checkSingleClickImmediately) {
  1235. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1236. if (new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1237. btn !== this._previousButtonPressed) {
  1238. clickInfo.singleClick = true;
  1239. cb(clickInfo, this._currentPickResult);
  1240. }
  1241. }
  1242. // at least one double click is required to be check and exclusive double click is enabled
  1243. else {
  1244. // wait that no double click has been raised during the double click delay
  1245. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1246. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1247. }
  1248. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1249. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1250. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1251. act = this._initActionManager(act, clickInfo);
  1252. if (act)
  1253. checkDoubleClick = act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1254. }
  1255. if (checkDoubleClick) {
  1256. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1257. if (btn === this._previousButtonPressed &&
  1258. new Date().getTime() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1259. !this._doubleClickOccured
  1260. ) {
  1261. // pointer has not moved for 2 clicks, it's a double click
  1262. if (!clickInfo.hasSwiped &&
  1263. Math.abs(this._previousStartingPointerPosition.x - this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  1264. Math.abs(this._previousStartingPointerPosition.y - this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  1265. this._previousStartingPointerTime = 0;
  1266. this._doubleClickOccured = true;
  1267. clickInfo.doubleClick = true;
  1268. clickInfo.ignore = false;
  1269. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout) {
  1270. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1271. }
  1272. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1273. cb(clickInfo, this._currentPickResult);
  1274. }
  1275. // if the two successive clicks are too far, it's just two simple clicks
  1276. else {
  1277. this._doubleClickOccured = false;
  1278. this._previousStartingPointerTime = this._startingPointerTime;
  1279. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1280. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1281. this._previousButtonPressed = btn;
  1282. if (Scene.ExclusiveDoubleClickMode) {
  1283. if (this._previousDelayedSimpleClickTimeout) {
  1284. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1285. }
  1286. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1287. cb(clickInfo, this._previousPickResult);
  1288. }
  1289. else {
  1290. cb(clickInfo, this._currentPickResult);
  1291. }
  1292. }
  1293. }
  1294. // just the first click of the double has been raised
  1295. else {
  1296. this._doubleClickOccured = false;
  1297. this._previousStartingPointerTime = this._startingPointerTime;
  1298. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1299. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1300. this._previousButtonPressed = btn;
  1301. }
  1302. }
  1303. }
  1304. }
  1305. clickInfo.ignore = true;
  1306. cb(clickInfo, this._currentPickResult);
  1307. };
  1308. this._spritePredicate = (sprite: Sprite): boolean => {
  1309. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  1310. };
  1311. this._onPointerMove = (evt: PointerEvent) => {
  1312. this._updatePointerPosition(evt);
  1313. // PreObservable support
  1314. if (this.onPrePointerObservable.hasObservers()) {
  1315. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1316. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1317. this.onPrePointerObservable.notifyObservers(pi, type);
  1318. if (pi.skipOnPointerObservable) {
  1319. return;
  1320. }
  1321. }
  1322. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1323. return;
  1324. }
  1325. if (!this.pointerMovePredicate) {
  1326. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  1327. }
  1328. // Meshes
  1329. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1330. this._processPointerMove(pickResult, evt);
  1331. };
  1332. this._onPointerDown = (evt: PointerEvent) => {
  1333. this._totalPointersPressed++;
  1334. this._pickedDownMesh = null;
  1335. this._meshPickProceed = false;
  1336. this._updatePointerPosition(evt);
  1337. if (this.preventDefaultOnPointerDown && canvas) {
  1338. evt.preventDefault();
  1339. canvas.focus();
  1340. }
  1341. // PreObservable support
  1342. if (this.onPrePointerObservable.hasObservers()) {
  1343. let type = PointerEventTypes.POINTERDOWN;
  1344. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1345. this.onPrePointerObservable.notifyObservers(pi, type);
  1346. if (pi.skipOnPointerObservable) {
  1347. return;
  1348. }
  1349. }
  1350. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1351. return;
  1352. }
  1353. this._startingPointerPosition.x = this._pointerX;
  1354. this._startingPointerPosition.y = this._pointerY;
  1355. this._startingPointerTime = new Date().getTime();
  1356. if (!this.pointerDownPredicate) {
  1357. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1358. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1359. };
  1360. }
  1361. // Meshes
  1362. this._pickedDownMesh = null;
  1363. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1364. this._processPointerDown(pickResult, evt);
  1365. // Sprites
  1366. this._pickedDownSprite = null;
  1367. if (this.spriteManagers.length > 0) {
  1368. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1369. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1370. if (pickResult.pickedSprite.actionManager) {
  1371. this._pickedDownSprite = pickResult.pickedSprite;
  1372. switch (evt.button) {
  1373. case 0:
  1374. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1375. break;
  1376. case 1:
  1377. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1378. break;
  1379. case 2:
  1380. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1381. break;
  1382. }
  1383. if (pickResult.pickedSprite.actionManager) {
  1384. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1385. }
  1386. }
  1387. }
  1388. }
  1389. };
  1390. this._onPointerUp = (evt: PointerEvent) => {
  1391. if (this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  1392. return; // So we need to test it the pointer down was pressed before.
  1393. }
  1394. this._totalPointersPressed--;
  1395. this._pickedUpMesh = null;
  1396. this._meshPickProceed = false;
  1397. this._updatePointerPosition(evt);
  1398. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => {
  1399. // PreObservable support
  1400. if (this.onPrePointerObservable.hasObservers()) {
  1401. if (!clickInfo.ignore) {
  1402. if (!clickInfo.hasSwiped) {
  1403. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1404. let type = PointerEventTypes.POINTERTAP;
  1405. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1406. this.onPrePointerObservable.notifyObservers(pi, type);
  1407. if (pi.skipOnPointerObservable) {
  1408. return;
  1409. }
  1410. }
  1411. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1412. let type = PointerEventTypes.POINTERDOUBLETAP;
  1413. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1414. this.onPrePointerObservable.notifyObservers(pi, type);
  1415. if (pi.skipOnPointerObservable) {
  1416. return;
  1417. }
  1418. }
  1419. }
  1420. }
  1421. else {
  1422. let type = PointerEventTypes.POINTERUP;
  1423. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1424. this.onPrePointerObservable.notifyObservers(pi, type);
  1425. if (pi.skipOnPointerObservable) {
  1426. return;
  1427. }
  1428. }
  1429. }
  1430. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1431. return;
  1432. }
  1433. if (!this.pointerUpPredicate) {
  1434. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1435. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1436. };
  1437. }
  1438. // Meshes
  1439. if (!this._meshPickProceed && (ActionManager && ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1440. this._initActionManager(null, clickInfo);
  1441. }
  1442. if (!pickResult) {
  1443. pickResult = this._currentPickResult;
  1444. }
  1445. this._processPointerUp(pickResult, evt, clickInfo);
  1446. // Sprites
  1447. if (this.spriteManagers.length > 0) {
  1448. let spritePickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1449. if (spritePickResult) {
  1450. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  1451. if (spritePickResult.pickedSprite.actionManager) {
  1452. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1453. if (spritePickResult.pickedSprite.actionManager) {
  1454. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  1455. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1456. }
  1457. }
  1458. }
  1459. }
  1460. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== spritePickResult.pickedSprite) {
  1461. this._pickedDownSprite.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  1462. }
  1463. }
  1464. }
  1465. this._previousPickResult = this._currentPickResult;
  1466. });
  1467. };
  1468. this._onKeyDown = (evt: KeyboardEvent) => {
  1469. let type = KeyboardEventTypes.KEYDOWN;
  1470. if (this.onPreKeyboardObservable.hasObservers()) {
  1471. let pi = new KeyboardInfoPre(type, evt);
  1472. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1473. if (pi.skipOnPointerObservable) {
  1474. return;
  1475. }
  1476. }
  1477. if (this.onKeyboardObservable.hasObservers()) {
  1478. let pi = new KeyboardInfo(type, evt);
  1479. this.onKeyboardObservable.notifyObservers(pi, type);
  1480. }
  1481. if (this.actionManager) {
  1482. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1483. }
  1484. };
  1485. this._onKeyUp = (evt: KeyboardEvent) => {
  1486. let type = KeyboardEventTypes.KEYUP;
  1487. if (this.onPreKeyboardObservable.hasObservers()) {
  1488. let pi = new KeyboardInfoPre(type, evt);
  1489. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1490. if (pi.skipOnPointerObservable) {
  1491. return;
  1492. }
  1493. }
  1494. if (this.onKeyboardObservable.hasObservers()) {
  1495. let pi = new KeyboardInfo(type, evt);
  1496. this.onKeyboardObservable.notifyObservers(pi, type);
  1497. }
  1498. if (this.actionManager) {
  1499. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1500. }
  1501. };
  1502. let engine = this.getEngine();
  1503. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(() => {
  1504. if (!canvas) {
  1505. return;
  1506. }
  1507. canvas.addEventListener("keydown", this._onKeyDown, false);
  1508. canvas.addEventListener("keyup", this._onKeyUp, false);
  1509. });
  1510. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(() => {
  1511. if (!canvas) {
  1512. return;
  1513. }
  1514. canvas.removeEventListener("keydown", this._onKeyDown);
  1515. canvas.removeEventListener("keyup", this._onKeyUp);
  1516. });
  1517. var eventPrefix = Tools.GetPointerPrefix();
  1518. var canvas = this._engine.getRenderingCanvas();
  1519. if (!canvas) {
  1520. return;
  1521. }
  1522. if (attachMove) {
  1523. canvas.addEventListener(eventPrefix + "move", <any>this._onPointerMove, false);
  1524. // Wheel
  1525. canvas.addEventListener('mousewheel', <any>this._onPointerMove, false);
  1526. canvas.addEventListener('DOMMouseScroll', <any>this._onPointerMove, false);
  1527. }
  1528. if (attachDown) {
  1529. canvas.addEventListener(eventPrefix + "down", <any>this._onPointerDown, false);
  1530. }
  1531. if (attachUp) {
  1532. window.addEventListener(eventPrefix + "up", <any>this._onPointerUp, false);
  1533. }
  1534. canvas.tabIndex = 1;
  1535. }
  1536. public detachControl() {
  1537. let engine = this.getEngine();
  1538. var eventPrefix = Tools.GetPointerPrefix();
  1539. var canvas = engine.getRenderingCanvas();
  1540. if (!canvas) {
  1541. return;
  1542. }
  1543. canvas.removeEventListener(eventPrefix + "move", <any>this._onPointerMove);
  1544. canvas.removeEventListener(eventPrefix + "down", <any>this._onPointerDown);
  1545. window.removeEventListener(eventPrefix + "up", <any>this._onPointerUp);
  1546. if (this._onCanvasBlurObserver) {
  1547. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1548. }
  1549. if (this._onCanvasFocusObserver) {
  1550. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1551. }
  1552. // Wheel
  1553. canvas.removeEventListener('mousewheel', <any>this._onPointerMove);
  1554. canvas.removeEventListener('DOMMouseScroll', <any>this._onPointerMove);
  1555. // Keyboard
  1556. canvas.removeEventListener("keydown", this._onKeyDown);
  1557. canvas.removeEventListener("keyup", this._onKeyUp);
  1558. // Observables
  1559. this.onKeyboardObservable.clear();
  1560. this.onPreKeyboardObservable.clear();
  1561. this.onPointerObservable.clear();
  1562. this.onPrePointerObservable.clear();
  1563. }
  1564. /**
  1565. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  1566. * Delay loaded resources are not taking in account
  1567. * @return true if all required resources are ready
  1568. */
  1569. public isReady(): boolean {
  1570. if (this._isDisposed) {
  1571. return false;
  1572. }
  1573. if (this._pendingData.length > 0) {
  1574. return false;
  1575. }
  1576. let index: number;
  1577. let engine = this.getEngine();
  1578. // Geometries
  1579. for (index = 0; index < this._geometries.length; index++) {
  1580. var geometry = this._geometries[index];
  1581. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1582. return false;
  1583. }
  1584. }
  1585. // Meshes
  1586. for (index = 0; index < this.meshes.length; index++) {
  1587. var mesh = this.meshes[index];
  1588. if (!mesh.isEnabled()) {
  1589. continue;
  1590. }
  1591. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1592. continue;
  1593. }
  1594. if (!mesh.isReady()) {
  1595. return false;
  1596. }
  1597. // Highlight layers
  1598. let hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && (<Mesh>mesh).instances.length > 0;
  1599. for (var layer of this.highlightLayers) {
  1600. if (!layer.hasMesh(mesh)) {
  1601. continue;
  1602. }
  1603. for (var subMesh of mesh.subMeshes) {
  1604. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  1605. return false;
  1606. }
  1607. }
  1608. }
  1609. }
  1610. return true;
  1611. }
  1612. public resetCachedMaterial(): void {
  1613. this._cachedMaterial = null;
  1614. this._cachedEffect = null;
  1615. this._cachedVisibility = null;
  1616. }
  1617. public registerBeforeRender(func: () => void): void {
  1618. this.onBeforeRenderObservable.add(func);
  1619. }
  1620. public unregisterBeforeRender(func: () => void): void {
  1621. this.onBeforeRenderObservable.removeCallback(func);
  1622. }
  1623. public registerAfterRender(func: () => void): void {
  1624. this.onAfterRenderObservable.add(func);
  1625. }
  1626. public unregisterAfterRender(func: () => void): void {
  1627. this.onAfterRenderObservable.removeCallback(func);
  1628. }
  1629. private _executeOnceBeforeRender(func: () => void): void {
  1630. let execFunc = () => {
  1631. func();
  1632. setTimeout(() => {
  1633. this.unregisterBeforeRender(execFunc);
  1634. });
  1635. }
  1636. this.registerBeforeRender(execFunc);
  1637. }
  1638. /**
  1639. * The provided function will run before render once and will be disposed afterwards.
  1640. * A timeout delay can be provided so that the function will be executed in N ms.
  1641. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  1642. * @param func The function to be executed.
  1643. * @param timeout optional delay in ms
  1644. */
  1645. public executeOnceBeforeRender(func: () => void, timeout?: number): void {
  1646. if (timeout !== undefined) {
  1647. setTimeout(() => {
  1648. this._executeOnceBeforeRender(func);
  1649. }, timeout);
  1650. } else {
  1651. this._executeOnceBeforeRender(func);
  1652. }
  1653. }
  1654. public _addPendingData(data: any): void {
  1655. this._pendingData.push(data);
  1656. }
  1657. public _removePendingData(data: any): void {
  1658. var wasLoading = this.isLoading;
  1659. var index = this._pendingData.indexOf(data);
  1660. if (index !== -1) {
  1661. this._pendingData.splice(index, 1);
  1662. }
  1663. if (wasLoading && !this.isLoading) {
  1664. this.onDataLoadedObservable.notifyObservers(this);
  1665. }
  1666. }
  1667. public getWaitingItemsCount(): number {
  1668. return this._pendingData.length;
  1669. }
  1670. public get isLoading(): boolean {
  1671. return this._pendingData.length > 0;
  1672. }
  1673. /**
  1674. * Registers a function to be executed when the scene is ready.
  1675. * @param {Function} func - the function to be executed.
  1676. */
  1677. public executeWhenReady(func: () => void): void {
  1678. this.onReadyObservable.add(func);
  1679. if (this._executeWhenReadyTimeoutId !== -1) {
  1680. return;
  1681. }
  1682. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1683. this._checkIsReady();
  1684. }, 150);
  1685. }
  1686. public _checkIsReady() {
  1687. if (this.isReady()) {
  1688. this.onReadyObservable.notifyObservers(this);
  1689. this.onReadyObservable.clear();
  1690. this._executeWhenReadyTimeoutId = -1;
  1691. return;
  1692. }
  1693. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1694. this._checkIsReady();
  1695. }, 150);
  1696. }
  1697. // Animations
  1698. /**
  1699. * Will start the animation sequence of a given target
  1700. * @param target - the target
  1701. * @param {number} from - from which frame should animation start
  1702. * @param {number} to - till which frame should animation run.
  1703. * @param {boolean} [loop] - should the animation loop
  1704. * @param {number} [speedRatio] - the speed in which to run the animation
  1705. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  1706. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  1707. * Returns {BABYLON.Animatable} the animatable object created for this animation
  1708. * See BABYLON.Animatable
  1709. */
  1710. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  1711. if (from > to && speedRatio > 0) {
  1712. speedRatio *= -1;
  1713. }
  1714. this.stopAnimation(target);
  1715. if (!animatable) {
  1716. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  1717. }
  1718. // Local animations
  1719. if (target.animations) {
  1720. animatable.appendAnimations(target, target.animations);
  1721. }
  1722. // Children animations
  1723. if (target.getAnimatables) {
  1724. var animatables = target.getAnimatables();
  1725. for (var index = 0; index < animatables.length; index++) {
  1726. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  1727. }
  1728. }
  1729. animatable.reset();
  1730. return animatable;
  1731. }
  1732. /**
  1733. * Begin a new animation on a given node
  1734. * @param {BABYLON.Node} node defines the root node where the animation will take place
  1735. * @param {BABYLON.Animation[]} defines the list of animations to start
  1736. * @param {number} from defines the initial value
  1737. * @param {number} to defines the final value
  1738. * @param {boolean} loop defines if you want animation to loop (off by default)
  1739. * @param {number} speedRatio defines the speed ratio to apply to all animations
  1740. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  1741. * @returns the list of created animatables
  1742. */
  1743. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  1744. if (speedRatio === undefined) {
  1745. speedRatio = 1.0;
  1746. }
  1747. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  1748. return animatable;
  1749. }
  1750. /**
  1751. * Begin a new animation on a given node and its hierarchy
  1752. * @param {BABYLON.Node} node defines the root node where the animation will take place
  1753. * @param {boolean} 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.
  1754. * @param {BABYLON.Animation[]} defines the list of animations to start
  1755. * @param {number} from defines the initial value
  1756. * @param {number} to defines the final value
  1757. * @param {boolean} loop defines if you want animation to loop (off by default)
  1758. * @param {number} speedRatio defines the speed ratio to apply to all animations
  1759. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  1760. * @returns the list of animatables created for all nodes
  1761. */
  1762. public beginDirectHierarchyAnimation(target: Node, directDescendantsOnly: boolean, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable[] {
  1763. let children = target.getDescendants(directDescendantsOnly);
  1764. let result = [];
  1765. for (var child of children) {
  1766. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  1767. }
  1768. return result;
  1769. }
  1770. public getAnimatableByTarget(target: any): Nullable<Animatable> {
  1771. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1772. if (this._activeAnimatables[index].target === target) {
  1773. return this._activeAnimatables[index];
  1774. }
  1775. }
  1776. return null;
  1777. }
  1778. public get animatables(): Animatable[] {
  1779. return this._activeAnimatables;
  1780. }
  1781. /**
  1782. * Will stop the animation of the given target
  1783. * @param target - the target
  1784. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  1785. * @see beginAnimation
  1786. */
  1787. public stopAnimation(target: any, animationName?: string): void {
  1788. var animatable = this.getAnimatableByTarget(target);
  1789. if (animatable) {
  1790. animatable.stop(animationName);
  1791. }
  1792. }
  1793. /**
  1794. * Stops and removes all animations that have been applied to the scene
  1795. */
  1796. public stopAllAnimations(): void {
  1797. if (this._activeAnimatables) {
  1798. for (let i = 0; i < this._activeAnimatables.length; i++) {
  1799. this._activeAnimatables[i].stop();
  1800. }
  1801. this._activeAnimatables = [];
  1802. }
  1803. }
  1804. private _animate(): void {
  1805. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  1806. return;
  1807. }
  1808. // Getting time
  1809. var now = Tools.Now;
  1810. if (!this._animationTimeLast) {
  1811. if (this._pendingData.length > 0) {
  1812. return;
  1813. }
  1814. this._animationTimeLast = now;
  1815. }
  1816. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  1817. this._animationTime += deltaTime;
  1818. this._animationTimeLast = now;
  1819. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1820. this._activeAnimatables[index]._animate(this._animationTime);
  1821. }
  1822. }
  1823. // Matrix
  1824. public _switchToAlternateCameraConfiguration(active: boolean): void {
  1825. this._useAlternateCameraConfiguration = active;
  1826. }
  1827. public getViewMatrix(): Matrix {
  1828. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  1829. }
  1830. public getProjectionMatrix(): Matrix {
  1831. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  1832. }
  1833. public getTransformMatrix(): Matrix {
  1834. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  1835. }
  1836. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  1837. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  1838. return;
  1839. }
  1840. this._viewUpdateFlag = view.updateFlag;
  1841. this._projectionUpdateFlag = projection.updateFlag;
  1842. this._viewMatrix = view;
  1843. this._projectionMatrix = projection;
  1844. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1845. // Update frustum
  1846. if (!this._frustumPlanes) {
  1847. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  1848. } else {
  1849. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1850. }
  1851. if (this.activeCamera && this.activeCamera._alternateCamera) {
  1852. let otherCamera = this.activeCamera._alternateCamera;
  1853. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), Tmp.Matrix[0]);
  1854. Frustum.GetRightPlaneToRef(Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  1855. }
  1856. if (this._sceneUbo.useUbo) {
  1857. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  1858. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  1859. this._sceneUbo.update();
  1860. }
  1861. }
  1862. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  1863. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  1864. return;
  1865. }
  1866. this._alternateViewUpdateFlag = view.updateFlag;
  1867. this._alternateProjectionUpdateFlag = projection.updateFlag;
  1868. this._alternateViewMatrix = view;
  1869. this._alternateProjectionMatrix = projection;
  1870. if (!this._alternateTransformMatrix) {
  1871. this._alternateTransformMatrix = Matrix.Zero();
  1872. }
  1873. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  1874. if (!this._alternateSceneUbo) {
  1875. this._createAlternateUbo();
  1876. }
  1877. if (this._alternateSceneUbo.useUbo) {
  1878. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  1879. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  1880. this._alternateSceneUbo.update();
  1881. }
  1882. }
  1883. public getSceneUniformBuffer(): UniformBuffer {
  1884. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  1885. }
  1886. // Methods
  1887. public getUniqueId() {
  1888. var result = Scene._uniqueIdCounter;
  1889. Scene._uniqueIdCounter++;
  1890. return result;
  1891. }
  1892. public addMesh(newMesh: AbstractMesh) {
  1893. this.meshes.push(newMesh);
  1894. //notify the collision coordinator
  1895. if (this.collisionCoordinator) {
  1896. this.collisionCoordinator.onMeshAdded(newMesh);
  1897. }
  1898. newMesh._resyncLightSources();
  1899. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  1900. }
  1901. public removeMesh(toRemove: AbstractMesh): number {
  1902. var index = this.meshes.indexOf(toRemove);
  1903. if (index !== -1) {
  1904. // Remove from the scene if mesh found
  1905. this.meshes.splice(index, 1);
  1906. }
  1907. this.onMeshRemovedObservable.notifyObservers(toRemove);
  1908. return index;
  1909. }
  1910. public addTransformNode(newTransformNode: TransformNode) {
  1911. this.transformNodes.push(newTransformNode);
  1912. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  1913. }
  1914. public removeTransformNode(toRemove: TransformNode): number {
  1915. var index = this.transformNodes.indexOf(toRemove);
  1916. if (index !== -1) {
  1917. // Remove from the scene if found
  1918. this.transformNodes.splice(index, 1);
  1919. }
  1920. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  1921. return index;
  1922. }
  1923. public removeSkeleton(toRemove: Skeleton): number {
  1924. var index = this.skeletons.indexOf(toRemove);
  1925. if (index !== -1) {
  1926. // Remove from the scene if found
  1927. this.skeletons.splice(index, 1);
  1928. }
  1929. return index;
  1930. }
  1931. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  1932. var index = this.morphTargetManagers.indexOf(toRemove);
  1933. if (index !== -1) {
  1934. // Remove from the scene if found
  1935. this.morphTargetManagers.splice(index, 1);
  1936. }
  1937. return index;
  1938. }
  1939. public removeLight(toRemove: Light): number {
  1940. var index = this.lights.indexOf(toRemove);
  1941. if (index !== -1) {
  1942. // Remove from meshes
  1943. for (var mesh of this.meshes) {
  1944. mesh._removeLightSource(toRemove);
  1945. }
  1946. // Remove from the scene if mesh found
  1947. this.lights.splice(index, 1);
  1948. this.sortLightsByPriority();
  1949. }
  1950. this.onLightRemovedObservable.notifyObservers(toRemove);
  1951. return index;
  1952. }
  1953. public removeCamera(toRemove: Camera): number {
  1954. var index = this.cameras.indexOf(toRemove);
  1955. if (index !== -1) {
  1956. // Remove from the scene if mesh found
  1957. this.cameras.splice(index, 1);
  1958. }
  1959. // Remove from activeCameras
  1960. var index2 = this.activeCameras.indexOf(toRemove);
  1961. if (index2 !== -1) {
  1962. // Remove from the scene if mesh found
  1963. this.activeCameras.splice(index2, 1);
  1964. }
  1965. // Reset the activeCamera
  1966. if (this.activeCamera === toRemove) {
  1967. if (this.cameras.length > 0) {
  1968. this.activeCamera = this.cameras[0];
  1969. } else {
  1970. this.activeCamera = null;
  1971. }
  1972. }
  1973. this.onCameraRemovedObservable.notifyObservers(toRemove);
  1974. return index;
  1975. }
  1976. public removeParticleSystem(toRemove: ParticleSystem): number {
  1977. var index = this.particleSystems.indexOf(toRemove);
  1978. if (index !== -1) {
  1979. this.particleSystems.splice(index, 1);
  1980. }
  1981. return index;
  1982. };
  1983. public removeAnimation(toRemove: Animation): number {
  1984. var index = this.animations.indexOf(toRemove);
  1985. if (index !== -1) {
  1986. this.animations.splice(index, 1);
  1987. }
  1988. return index;
  1989. };
  1990. public removeMultiMaterial(toRemove: MultiMaterial): number {
  1991. var index = this.multiMaterials.indexOf(toRemove);
  1992. if (index !== -1) {
  1993. this.multiMaterials.splice(index, 1);
  1994. }
  1995. return index;
  1996. };
  1997. public removeMaterial(toRemove: Material): number {
  1998. var index = this.materials.indexOf(toRemove);
  1999. if (index !== -1) {
  2000. this.materials.splice(index, 1);
  2001. }
  2002. return index;
  2003. };
  2004. public removeLensFlareSystem(toRemove: LensFlareSystem) {
  2005. var index = this.lensFlareSystems.indexOf(toRemove);
  2006. if (index !== -1) {
  2007. this.lensFlareSystems.splice(index, 1);
  2008. }
  2009. return index;
  2010. };
  2011. public removeActionManager(toRemove: ActionManager) {
  2012. var index = this._actionManagers.indexOf(toRemove);
  2013. if (index !== -1) {
  2014. this._actionManagers.splice(index, 1);
  2015. }
  2016. return index;
  2017. };
  2018. public addLight(newLight: Light) {
  2019. this.lights.push(newLight);
  2020. this.sortLightsByPriority();
  2021. // Add light to all meshes (To support if the light is removed and then readded)
  2022. for (var mesh of this.meshes) {
  2023. if (mesh._lightSources.indexOf(newLight) === -1) {
  2024. mesh._lightSources.push(newLight);
  2025. mesh._resyncLightSources();
  2026. }
  2027. }
  2028. this.onNewLightAddedObservable.notifyObservers(newLight);
  2029. }
  2030. public sortLightsByPriority(): void {
  2031. if (this.requireLightSorting) {
  2032. this.lights.sort(Light.CompareLightsPriority);
  2033. }
  2034. }
  2035. public addCamera(newCamera: Camera) {
  2036. this.cameras.push(newCamera);
  2037. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  2038. }
  2039. public addSkeleton(newSkeleton: Skeleton) {
  2040. this.skeletons.push(newSkeleton)
  2041. }
  2042. public addParticleSystem(newParticleSystem: ParticleSystem) {
  2043. this.particleSystems.push(newParticleSystem)
  2044. }
  2045. public addAnimation(newAnimation: Animation) {
  2046. this.animations.push(newAnimation)
  2047. }
  2048. public addMultiMaterial(newMultiMaterial: MultiMaterial) {
  2049. this.multiMaterials.push(newMultiMaterial)
  2050. }
  2051. public addMaterial(newMaterial: Material) {
  2052. this.materials.push(newMaterial)
  2053. }
  2054. public addMorphTargetManager(newMorphTargetManager: MorphTargetManager) {
  2055. this.morphTargetManagers.push(newMorphTargetManager)
  2056. }
  2057. public addGeometry(newGeometrie: Geometry) {
  2058. this._geometries.push(newGeometrie)
  2059. }
  2060. public addLensFlareSystem(newLensFlareSystem: LensFlareSystem) {
  2061. this.lensFlareSystems.push(newLensFlareSystem)
  2062. }
  2063. public addActionManager(newActionManager: ActionManager) {
  2064. this._actionManagers.push(newActionManager)
  2065. }
  2066. /**
  2067. * Switch active camera
  2068. * @param {Camera} newCamera - new active camera
  2069. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  2070. */
  2071. public switchActiveCamera(newCamera: Camera, attachControl = true) {
  2072. var canvas = this._engine.getRenderingCanvas();
  2073. if (!canvas) {
  2074. return;
  2075. }
  2076. if (this.activeCamera) {
  2077. this.activeCamera.detachControl(canvas);
  2078. }
  2079. this.activeCamera = newCamera;
  2080. if (attachControl) {
  2081. newCamera.attachControl(canvas);
  2082. }
  2083. }
  2084. /**
  2085. * sets the active camera of the scene using its ID
  2086. * @param {string} id - the camera's ID
  2087. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  2088. * @see activeCamera
  2089. */
  2090. public setActiveCameraByID(id: string): Nullable<Camera> {
  2091. var camera = this.getCameraByID(id);
  2092. if (camera) {
  2093. this.activeCamera = camera;
  2094. return camera;
  2095. }
  2096. return null;
  2097. }
  2098. /**
  2099. * sets the active camera of the scene using its name
  2100. * @param {string} name - the camera's name
  2101. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  2102. * @see activeCamera
  2103. */
  2104. public setActiveCameraByName(name: string): Nullable<Camera> {
  2105. var camera = this.getCameraByName(name);
  2106. if (camera) {
  2107. this.activeCamera = camera;
  2108. return camera;
  2109. }
  2110. return null;
  2111. }
  2112. /**
  2113. * get an animation group using its name
  2114. * @param {string} the material's name
  2115. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  2116. */
  2117. public getAnimationGroupByName(name: string): Nullable<AnimationGroup> {
  2118. for (var index = 0; index < this.animationGroups.length; index++) {
  2119. if (this.animationGroups[index].name === name) {
  2120. return this.animationGroups[index];
  2121. }
  2122. }
  2123. return null;
  2124. }
  2125. /**
  2126. * get a material using its id
  2127. * @param {string} the material's ID
  2128. * @return {BABYLON.Material|null} the material or null if none found.
  2129. */
  2130. public getMaterialByID(id: string): Nullable<Material> {
  2131. for (var index = 0; index < this.materials.length; index++) {
  2132. if (this.materials[index].id === id) {
  2133. return this.materials[index];
  2134. }
  2135. }
  2136. return null;
  2137. }
  2138. /**
  2139. * get a material using its name
  2140. * @param {string} the material's name
  2141. * @return {BABYLON.Material|null} the material or null if none found.
  2142. */
  2143. public getMaterialByName(name: string): Nullable<Material> {
  2144. for (var index = 0; index < this.materials.length; index++) {
  2145. if (this.materials[index].name === name) {
  2146. return this.materials[index];
  2147. }
  2148. }
  2149. return null;
  2150. }
  2151. public getLensFlareSystemByName(name: string): Nullable<LensFlareSystem> {
  2152. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  2153. if (this.lensFlareSystems[index].name === name) {
  2154. return this.lensFlareSystems[index];
  2155. }
  2156. }
  2157. return null;
  2158. }
  2159. public getLensFlareSystemByID(id: string): Nullable<LensFlareSystem> {
  2160. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  2161. if (this.lensFlareSystems[index].id === id) {
  2162. return this.lensFlareSystems[index];
  2163. }
  2164. }
  2165. return null;
  2166. }
  2167. public getCameraByID(id: string): Nullable<Camera> {
  2168. for (var index = 0; index < this.cameras.length; index++) {
  2169. if (this.cameras[index].id === id) {
  2170. return this.cameras[index];
  2171. }
  2172. }
  2173. return null;
  2174. }
  2175. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  2176. for (var index = 0; index < this.cameras.length; index++) {
  2177. if (this.cameras[index].uniqueId === uniqueId) {
  2178. return this.cameras[index];
  2179. }
  2180. }
  2181. return null;
  2182. }
  2183. /**
  2184. * get a camera using its name
  2185. * @param {string} the camera's name
  2186. * @return {BABYLON.Camera|null} the camera or null if none found.
  2187. */
  2188. public getCameraByName(name: string): Nullable<Camera> {
  2189. for (var index = 0; index < this.cameras.length; index++) {
  2190. if (this.cameras[index].name === name) {
  2191. return this.cameras[index];
  2192. }
  2193. }
  2194. return null;
  2195. }
  2196. /**
  2197. * get a bone using its id
  2198. * @param {string} the bone's id
  2199. * @return {BABYLON.Bone|null} the bone or null if not found
  2200. */
  2201. public getBoneByID(id: string): Nullable<Bone> {
  2202. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2203. var skeleton = this.skeletons[skeletonIndex];
  2204. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2205. if (skeleton.bones[boneIndex].id === id) {
  2206. return skeleton.bones[boneIndex];
  2207. }
  2208. }
  2209. }
  2210. return null;
  2211. }
  2212. /**
  2213. * get a bone using its id
  2214. * @param {string} the bone's name
  2215. * @return {BABYLON.Bone|null} the bone or null if not found
  2216. */
  2217. public getBoneByName(name: string): Nullable<Bone> {
  2218. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2219. var skeleton = this.skeletons[skeletonIndex];
  2220. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2221. if (skeleton.bones[boneIndex].name === name) {
  2222. return skeleton.bones[boneIndex];
  2223. }
  2224. }
  2225. }
  2226. return null;
  2227. }
  2228. /**
  2229. * get a light node using its name
  2230. * @param {string} the light's name
  2231. * @return {BABYLON.Light|null} the light or null if none found.
  2232. */
  2233. public getLightByName(name: string): Nullable<Light> {
  2234. for (var index = 0; index < this.lights.length; index++) {
  2235. if (this.lights[index].name === name) {
  2236. return this.lights[index];
  2237. }
  2238. }
  2239. return null;
  2240. }
  2241. /**
  2242. * get a light node using its ID
  2243. * @param {string} the light's id
  2244. * @return {BABYLON.Light|null} the light or null if none found.
  2245. */
  2246. public getLightByID(id: string): Nullable<Light> {
  2247. for (var index = 0; index < this.lights.length; index++) {
  2248. if (this.lights[index].id === id) {
  2249. return this.lights[index];
  2250. }
  2251. }
  2252. return null;
  2253. }
  2254. /**
  2255. * get a light node using its scene-generated unique ID
  2256. * @param {number} the light's unique id
  2257. * @return {BABYLON.Light|null} the light or null if none found.
  2258. */
  2259. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  2260. for (var index = 0; index < this.lights.length; index++) {
  2261. if (this.lights[index].uniqueId === uniqueId) {
  2262. return this.lights[index];
  2263. }
  2264. }
  2265. return null;
  2266. }
  2267. /**
  2268. * get a particle system by id
  2269. * @param id {number} the particle system id
  2270. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  2271. */
  2272. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  2273. for (var index = 0; index < this.particleSystems.length; index++) {
  2274. if (this.particleSystems[index].id === id) {
  2275. return this.particleSystems[index];
  2276. }
  2277. }
  2278. return null;
  2279. }
  2280. /**
  2281. * get a geometry using its ID
  2282. * @param {string} the geometry's id
  2283. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  2284. */
  2285. public getGeometryByID(id: string): Nullable<Geometry> {
  2286. for (var index = 0; index < this._geometries.length; index++) {
  2287. if (this._geometries[index].id === id) {
  2288. return this._geometries[index];
  2289. }
  2290. }
  2291. return null;
  2292. }
  2293. /**
  2294. * add a new geometry to this scene.
  2295. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  2296. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  2297. * @return {boolean} was the geometry added or not
  2298. */
  2299. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  2300. if (!force && this.getGeometryByID(geometry.id)) {
  2301. return false;
  2302. }
  2303. this._geometries.push(geometry);
  2304. //notify the collision coordinator
  2305. if (this.collisionCoordinator) {
  2306. this.collisionCoordinator.onGeometryAdded(geometry);
  2307. }
  2308. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  2309. return true;
  2310. }
  2311. /**
  2312. * Removes an existing geometry
  2313. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  2314. * @return {boolean} was the geometry removed or not
  2315. */
  2316. public removeGeometry(geometry: Geometry): boolean {
  2317. var index = this._geometries.indexOf(geometry);
  2318. if (index > -1) {
  2319. this._geometries.splice(index, 1);
  2320. //notify the collision coordinator
  2321. if (this.collisionCoordinator) {
  2322. this.collisionCoordinator.onGeometryDeleted(geometry);
  2323. }
  2324. this.onGeometryRemovedObservable.notifyObservers(geometry);
  2325. return true;
  2326. }
  2327. return false;
  2328. }
  2329. public getGeometries(): Geometry[] {
  2330. return this._geometries;
  2331. }
  2332. /**
  2333. * Get the first added mesh found of a given ID
  2334. * @param {string} id - the id to search for
  2335. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2336. */
  2337. public getMeshByID(id: string): Nullable<AbstractMesh> {
  2338. for (var index = 0; index < this.meshes.length; index++) {
  2339. if (this.meshes[index].id === id) {
  2340. return this.meshes[index];
  2341. }
  2342. }
  2343. return null;
  2344. }
  2345. public getMeshesByID(id: string): Array<AbstractMesh> {
  2346. return this.meshes.filter(function (m) {
  2347. return m.id === id;
  2348. })
  2349. }
  2350. /**
  2351. * Get the first added transform node found of a given ID
  2352. * @param {string} id - the id to search for
  2353. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  2354. */
  2355. public getTransformNodeByID(id: string): Nullable<TransformNode> {
  2356. for (var index = 0; index < this.transformNodes.length; index++) {
  2357. if (this.transformNodes[index].id === id) {
  2358. return this.transformNodes[index];
  2359. }
  2360. }
  2361. return null;
  2362. }
  2363. public getTransformNodesByID(id: string): Array<TransformNode> {
  2364. return this.transformNodes.filter(function (m) {
  2365. return m.id === id;
  2366. })
  2367. }
  2368. /**
  2369. * Get a mesh with its auto-generated unique id
  2370. * @param {number} uniqueId - the unique id to search for
  2371. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2372. */
  2373. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  2374. for (var index = 0; index < this.meshes.length; index++) {
  2375. if (this.meshes[index].uniqueId === uniqueId) {
  2376. return this.meshes[index];
  2377. }
  2378. }
  2379. return null;
  2380. }
  2381. /**
  2382. * Get a the last added mesh found of a given ID
  2383. * @param {string} id - the id to search for
  2384. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2385. */
  2386. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  2387. for (var index = this.meshes.length - 1; index >= 0; index--) {
  2388. if (this.meshes[index].id === id) {
  2389. return this.meshes[index];
  2390. }
  2391. }
  2392. return null;
  2393. }
  2394. /**
  2395. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  2396. * @param {string} id - the id to search for
  2397. * @return {BABYLON.Node|null} the node found or null if not found at all.
  2398. */
  2399. public getLastEntryByID(id: string): Nullable<Node> {
  2400. var index: number;
  2401. for (index = this.meshes.length - 1; index >= 0; index--) {
  2402. if (this.meshes[index].id === id) {
  2403. return this.meshes[index];
  2404. }
  2405. }
  2406. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  2407. if (this.transformNodes[index].id === id) {
  2408. return this.transformNodes[index];
  2409. }
  2410. }
  2411. for (index = this.cameras.length - 1; index >= 0; index--) {
  2412. if (this.cameras[index].id === id) {
  2413. return this.cameras[index];
  2414. }
  2415. }
  2416. for (index = this.lights.length - 1; index >= 0; index--) {
  2417. if (this.lights[index].id === id) {
  2418. return this.lights[index];
  2419. }
  2420. }
  2421. return null;
  2422. }
  2423. public getNodeByID(id: string): Nullable<Node> {
  2424. var mesh = this.getMeshByID(id);
  2425. if (mesh) {
  2426. return mesh;
  2427. }
  2428. var light = this.getLightByID(id);
  2429. if (light) {
  2430. return light;
  2431. }
  2432. var camera = this.getCameraByID(id);
  2433. if (camera) {
  2434. return camera;
  2435. }
  2436. var bone = this.getBoneByID(id);
  2437. return bone;
  2438. }
  2439. public getNodeByName(name: string): Nullable<Node> {
  2440. var mesh = this.getMeshByName(name);
  2441. if (mesh) {
  2442. return mesh;
  2443. }
  2444. var light = this.getLightByName(name);
  2445. if (light) {
  2446. return light;
  2447. }
  2448. var camera = this.getCameraByName(name);
  2449. if (camera) {
  2450. return camera;
  2451. }
  2452. var bone = this.getBoneByName(name);
  2453. return bone;
  2454. }
  2455. public getMeshByName(name: string): Nullable<AbstractMesh> {
  2456. for (var index = 0; index < this.meshes.length; index++) {
  2457. if (this.meshes[index].name === name) {
  2458. return this.meshes[index];
  2459. }
  2460. }
  2461. return null;
  2462. }
  2463. public getTransformNodeByName(name: string): Nullable<TransformNode> {
  2464. for (var index = 0; index < this.transformNodes.length; index++) {
  2465. if (this.transformNodes[index].name === name) {
  2466. return this.transformNodes[index];
  2467. }
  2468. }
  2469. return null;
  2470. }
  2471. public getSoundByName(name: string): Nullable<Sound> {
  2472. var index: number;
  2473. if (AudioEngine) {
  2474. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  2475. if (this.mainSoundTrack.soundCollection[index].name === name) {
  2476. return this.mainSoundTrack.soundCollection[index];
  2477. }
  2478. }
  2479. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  2480. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  2481. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  2482. return this.soundTracks[sdIndex].soundCollection[index];
  2483. }
  2484. }
  2485. }
  2486. }
  2487. return null;
  2488. }
  2489. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  2490. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  2491. if (this.skeletons[index].id === id) {
  2492. return this.skeletons[index];
  2493. }
  2494. }
  2495. return null;
  2496. }
  2497. public getSkeletonById(id: string): Nullable<Skeleton> {
  2498. for (var index = 0; index < this.skeletons.length; index++) {
  2499. if (this.skeletons[index].id === id) {
  2500. return this.skeletons[index];
  2501. }
  2502. }
  2503. return null;
  2504. }
  2505. public getSkeletonByName(name: string): Nullable<Skeleton> {
  2506. for (var index = 0; index < this.skeletons.length; index++) {
  2507. if (this.skeletons[index].name === name) {
  2508. return this.skeletons[index];
  2509. }
  2510. }
  2511. return null;
  2512. }
  2513. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  2514. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  2515. if (this.morphTargetManagers[index].uniqueId === id) {
  2516. return this.morphTargetManagers[index];
  2517. }
  2518. }
  2519. return null;
  2520. }
  2521. public isActiveMesh(mesh: AbstractMesh): boolean {
  2522. return (this._activeMeshes.indexOf(mesh) !== -1);
  2523. }
  2524. /**
  2525. * Return a the first highlight layer of the scene with a given name.
  2526. * @param name The name of the highlight layer to look for.
  2527. * @return The highlight layer if found otherwise null.
  2528. */
  2529. public getHighlightLayerByName(name: string): Nullable<HighlightLayer> {
  2530. for (var index = 0; index < this.highlightLayers.length; index++) {
  2531. if (this.highlightLayers[index].name === name) {
  2532. return this.highlightLayers[index];
  2533. }
  2534. }
  2535. return null;
  2536. }
  2537. /**
  2538. * Return a unique id as a string which can serve as an identifier for the scene
  2539. */
  2540. public get uid(): string {
  2541. if (!this._uid) {
  2542. this._uid = Tools.RandomId();
  2543. }
  2544. return this._uid;
  2545. }
  2546. /**
  2547. * Add an externaly attached data from its key.
  2548. * This method call will fail and return false, if such key already exists.
  2549. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2550. * @param key the unique key that identifies the data
  2551. * @param data the data object to associate to the key for this Engine instance
  2552. * @return true if no such key were already present and the data was added successfully, false otherwise
  2553. */
  2554. public addExternalData<T>(key: string, data: T): boolean {
  2555. if (!this._externalData) {
  2556. this._externalData = new StringDictionary<Object>();
  2557. }
  2558. return this._externalData.add(key, data);
  2559. }
  2560. /**
  2561. * Get an externaly attached data from its key
  2562. * @param key the unique key that identifies the data
  2563. * @return the associated data, if present (can be null), or undefined if not present
  2564. */
  2565. public getExternalData<T>(key: string): Nullable<T> {
  2566. if (!this._externalData) {
  2567. return null;
  2568. }
  2569. return <T>this._externalData.get(key);
  2570. }
  2571. /**
  2572. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2573. * @param key the unique key that identifies the data
  2574. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2575. * @return the associated data, can be null if the factory returned null.
  2576. */
  2577. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2578. if (!this._externalData) {
  2579. this._externalData = new StringDictionary<Object>();
  2580. }
  2581. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2582. }
  2583. /**
  2584. * Remove an externaly attached data from the Engine instance
  2585. * @param key the unique key that identifies the data
  2586. * @return true if the data was successfully removed, false if it doesn't exist
  2587. */
  2588. public removeExternalData(key: string): boolean {
  2589. return this._externalData.remove(key);
  2590. }
  2591. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  2592. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  2593. if (mesh.showSubMeshesBoundingBox) {
  2594. const boundingInfo = subMesh.getBoundingInfo();
  2595. if (boundingInfo !== null && boundingInfo !== undefined) {
  2596. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  2597. }
  2598. }
  2599. const material = subMesh.getMaterial();
  2600. if (material !== null && material !== undefined) {
  2601. // Render targets
  2602. if (material.getRenderTargetTextures !== undefined) {
  2603. if (this._processedMaterials.indexOf(material) === -1) {
  2604. this._processedMaterials.push(material);
  2605. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  2606. }
  2607. }
  2608. // Dispatch
  2609. this._activeIndices.addCount(subMesh.indexCount, false);
  2610. this._renderingManager.dispatch(subMesh, mesh, material);
  2611. }
  2612. }
  2613. }
  2614. public _isInIntermediateRendering(): boolean {
  2615. return this._intermediateRendering
  2616. }
  2617. private _activeMeshCandidateProvider: IActiveMeshCandidateProvider;
  2618. public setActiveMeshCandidateProvider(provider: IActiveMeshCandidateProvider): void {
  2619. this._activeMeshCandidateProvider = provider;
  2620. }
  2621. public getActiveMeshCandidateProvider(): IActiveMeshCandidateProvider {
  2622. return this._activeMeshCandidateProvider;
  2623. }
  2624. private _activeMeshesFrozen = false;
  2625. /**
  2626. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  2627. */
  2628. public freezeActiveMeshes(): Scene {
  2629. this._evaluateActiveMeshes();
  2630. this._activeMeshesFrozen = true;
  2631. return this;
  2632. }
  2633. /**
  2634. * Use this function to restart evaluating active meshes on every frame
  2635. */
  2636. public unfreezeActiveMeshes() {
  2637. this._activeMeshesFrozen = false;
  2638. return this;
  2639. }
  2640. private _evaluateActiveMeshes(): void {
  2641. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  2642. return;
  2643. }
  2644. if (!this.activeCamera) {
  2645. return;
  2646. }
  2647. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  2648. this.activeCamera._activeMeshes.reset();
  2649. this._activeMeshes.reset();
  2650. this._renderingManager.reset();
  2651. this._processedMaterials.reset();
  2652. this._activeParticleSystems.reset();
  2653. this._activeSkeletons.reset();
  2654. this._softwareSkinnedMeshes.reset();
  2655. if (this._boundingBoxRenderer) {
  2656. this._boundingBoxRenderer.reset();
  2657. }
  2658. // Meshes
  2659. var meshes: AbstractMesh[];
  2660. var len: number;
  2661. var checkIsEnabled = true;
  2662. // Determine mesh candidates
  2663. if (this._activeMeshCandidateProvider !== undefined) {
  2664. // Use _activeMeshCandidateProvider
  2665. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  2666. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  2667. if (meshes !== undefined) {
  2668. len = meshes.length;
  2669. } else {
  2670. len = 0;
  2671. }
  2672. } else if (this._selectionOctree !== undefined) {
  2673. // Octree
  2674. var selection = this._selectionOctree.select(this._frustumPlanes);
  2675. meshes = selection.data;
  2676. len = selection.length;
  2677. } else {
  2678. // Full scene traversal
  2679. len = this.meshes.length;
  2680. meshes = this.meshes;
  2681. }
  2682. // Check each mesh
  2683. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  2684. mesh = meshes[meshIndex];
  2685. if (mesh.isBlocked) {
  2686. continue;
  2687. }
  2688. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  2689. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  2690. continue;
  2691. }
  2692. mesh.computeWorldMatrix();
  2693. // Intersections
  2694. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  2695. this._meshesForIntersections.pushNoDuplicate(mesh);
  2696. }
  2697. // Switch to current LOD
  2698. meshLOD = mesh.getLOD(this.activeCamera);
  2699. if (meshLOD === undefined || meshLOD === null) {
  2700. continue;
  2701. }
  2702. mesh._preActivate();
  2703. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  2704. this._activeMeshes.push(mesh);
  2705. this.activeCamera._activeMeshes.push(mesh);
  2706. mesh._activate(this._renderId);
  2707. if (meshLOD !== mesh) {
  2708. meshLOD._activate(this._renderId);
  2709. }
  2710. this._activeMesh(mesh, meshLOD);
  2711. }
  2712. }
  2713. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  2714. // Particle systems
  2715. if (this.particlesEnabled) {
  2716. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  2717. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  2718. var particleSystem = this.particleSystems[particleIndex];
  2719. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  2720. continue;
  2721. }
  2722. let emitter = <any>particleSystem.emitter;
  2723. if (!emitter.position || emitter.isEnabled()) {
  2724. this._activeParticleSystems.push(particleSystem);
  2725. particleSystem.animate();
  2726. this._renderingManager.dispatchParticles(particleSystem);
  2727. }
  2728. }
  2729. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  2730. }
  2731. }
  2732. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  2733. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  2734. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  2735. mesh.skeleton.prepare();
  2736. }
  2737. if (!mesh.computeBonesUsingShaders) {
  2738. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  2739. }
  2740. }
  2741. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  2742. let boundingInfo = sourceMesh.getBoundingInfo();
  2743. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  2744. }
  2745. if (
  2746. mesh !== undefined && mesh !== null
  2747. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0
  2748. ) {
  2749. // Submeshes Octrees
  2750. var len: number;
  2751. var subMeshes: SubMesh[];
  2752. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  2753. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  2754. len = intersections.length;
  2755. subMeshes = intersections.data;
  2756. } else {
  2757. subMeshes = mesh.subMeshes;
  2758. len = subMeshes.length;
  2759. }
  2760. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  2761. subMesh = subMeshes[subIndex];
  2762. this._evaluateSubMesh(subMesh, mesh);
  2763. }
  2764. }
  2765. }
  2766. public updateTransformMatrix(force?: boolean): void {
  2767. if (!this.activeCamera) {
  2768. return;
  2769. }
  2770. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  2771. }
  2772. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  2773. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  2774. }
  2775. private _renderForCamera(camera: Camera): void {
  2776. if (camera && camera._skipRendering) {
  2777. return;
  2778. }
  2779. var engine = this._engine;
  2780. this.activeCamera = camera;
  2781. if (!this.activeCamera)
  2782. throw new Error("Active camera not set");
  2783. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2784. // Viewport
  2785. engine.setViewport(this.activeCamera.viewport);
  2786. // Camera
  2787. this.resetCachedMaterial();
  2788. this._renderId++;
  2789. this.activeCamera.update();
  2790. this.updateTransformMatrix();
  2791. if (camera._alternateCamera) {
  2792. this.updateAlternateTransformMatrix(camera._alternateCamera);
  2793. this._alternateRendering = true;
  2794. }
  2795. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  2796. // Meshes
  2797. this._evaluateActiveMeshes();
  2798. // Software skinning
  2799. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  2800. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  2801. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  2802. }
  2803. // Render targets
  2804. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  2805. var needsRestoreFrameBuffer = false;
  2806. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  2807. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  2808. }
  2809. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  2810. this._intermediateRendering = true;
  2811. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2812. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  2813. let renderTarget = this._renderTargets.data[renderIndex];
  2814. if (renderTarget._shouldRender()) {
  2815. this._renderId++;
  2816. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  2817. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  2818. }
  2819. }
  2820. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2821. this._intermediateRendering = false;
  2822. this._renderId++;
  2823. needsRestoreFrameBuffer = true; // Restore back buffer
  2824. }
  2825. // Render HighlightLayer Texture
  2826. var stencilState = this._engine.getStencilBuffer();
  2827. var renderhighlights = false;
  2828. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  2829. this._intermediateRendering = true;
  2830. for (let i = 0; i < this.highlightLayers.length; i++) {
  2831. let highlightLayer = this.highlightLayers[i];
  2832. if (highlightLayer.shouldRender() &&
  2833. (!highlightLayer.camera ||
  2834. (highlightLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  2835. (highlightLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  2836. renderhighlights = true;
  2837. let renderTarget = (<RenderTargetTexture>(<any>highlightLayer)._mainTexture);
  2838. if (renderTarget._shouldRender()) {
  2839. this._renderId++;
  2840. renderTarget.render(false, false);
  2841. needsRestoreFrameBuffer = true;
  2842. }
  2843. }
  2844. }
  2845. this._intermediateRendering = false;
  2846. this._renderId++;
  2847. }
  2848. if (needsRestoreFrameBuffer) {
  2849. engine.restoreDefaultFramebuffer(); // Restore back buffer
  2850. }
  2851. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  2852. // Prepare Frame
  2853. this.postProcessManager._prepareFrame();
  2854. // Backgrounds
  2855. var layerIndex;
  2856. var layer;
  2857. if (this.layers.length) {
  2858. engine.setDepthBuffer(false);
  2859. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2860. layer = this.layers[layerIndex];
  2861. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2862. layer.render();
  2863. }
  2864. }
  2865. engine.setDepthBuffer(true);
  2866. }
  2867. // Activate HighlightLayer stencil
  2868. if (renderhighlights) {
  2869. this._engine.setStencilBuffer(true);
  2870. }
  2871. // Render
  2872. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  2873. this._renderingManager.render(null, null, true, true);
  2874. this.onAfterDrawPhaseObservable.notifyObservers(this);
  2875. // Restore HighlightLayer stencil
  2876. if (renderhighlights) {
  2877. this._engine.setStencilBuffer(stencilState);
  2878. }
  2879. // Bounding boxes
  2880. if (this._boundingBoxRenderer) {
  2881. this._boundingBoxRenderer.render();
  2882. }
  2883. // Lens flares
  2884. if (this.lensFlaresEnabled) {
  2885. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2886. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  2887. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  2888. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  2889. lensFlareSystem.render();
  2890. }
  2891. }
  2892. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2893. }
  2894. // Foregrounds
  2895. if (this.layers.length) {
  2896. engine.setDepthBuffer(false);
  2897. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2898. layer = this.layers[layerIndex];
  2899. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2900. layer.render();
  2901. }
  2902. }
  2903. engine.setDepthBuffer(true);
  2904. }
  2905. // Highlight Layer
  2906. if (renderhighlights) {
  2907. engine.setDepthBuffer(false);
  2908. for (let i = 0; i < this.highlightLayers.length; i++) {
  2909. if (this.highlightLayers[i].shouldRender()) {
  2910. this.highlightLayers[i].render();
  2911. }
  2912. }
  2913. engine.setDepthBuffer(true);
  2914. }
  2915. // Finalize frame
  2916. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  2917. // Reset some special arrays
  2918. this._renderTargets.reset();
  2919. this._alternateRendering = false;
  2920. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  2921. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2922. }
  2923. private _processSubCameras(camera: Camera): void {
  2924. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  2925. this._renderForCamera(camera);
  2926. return;
  2927. }
  2928. // Update camera
  2929. if (this.activeCamera) {
  2930. this.activeCamera.update();
  2931. }
  2932. // rig cameras
  2933. for (var index = 0; index < camera._rigCameras.length; index++) {
  2934. this._renderForCamera(camera._rigCameras[index]);
  2935. }
  2936. this.activeCamera = camera;
  2937. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  2938. }
  2939. private _checkIntersections(): void {
  2940. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  2941. var sourceMesh = this._meshesForIntersections.data[index];
  2942. if (!sourceMesh.actionManager) {
  2943. continue;
  2944. }
  2945. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  2946. var action = sourceMesh.actionManager.actions[actionIndex];
  2947. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2948. var parameters = action.getTriggerParameter();
  2949. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  2950. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  2951. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  2952. if (areIntersecting && currentIntersectionInProgress === -1) {
  2953. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  2954. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  2955. sourceMesh._intersectionsInProgress.push(otherMesh);
  2956. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2957. sourceMesh._intersectionsInProgress.push(otherMesh);
  2958. }
  2959. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  2960. //They intersected, and now they don't.
  2961. //is this trigger an exit trigger? execute an event.
  2962. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2963. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  2964. }
  2965. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  2966. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2967. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  2968. }
  2969. }
  2970. }
  2971. }
  2972. }
  2973. }
  2974. public render(): void {
  2975. if (this.isDisposed) {
  2976. return;
  2977. }
  2978. this._activeParticles.fetchNewFrame();
  2979. this._totalVertices.fetchNewFrame();
  2980. this._activeIndices.fetchNewFrame();
  2981. this._activeBones.fetchNewFrame();
  2982. this._meshesForIntersections.reset();
  2983. this.resetCachedMaterial();
  2984. this.onBeforeAnimationsObservable.notifyObservers(this);
  2985. // Actions
  2986. if (this.actionManager) {
  2987. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger);
  2988. }
  2989. //Simplification Queue
  2990. if (this.simplificationQueue && !this.simplificationQueue.running) {
  2991. this.simplificationQueue.executeNext();
  2992. }
  2993. if (this._engine.isDeterministicLockStep()) {
  2994. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  2995. var defaultFPS = (60.0 / 1000.0);
  2996. let defaultFrameTime = 1000 / 60; // frame time in MS
  2997. if (this._physicsEngine) {
  2998. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  2999. }
  3000. let stepsTaken = 0;
  3001. var maxSubSteps = this._engine.getLockstepMaxSteps();
  3002. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  3003. internalSteps = Math.min(internalSteps, maxSubSteps);
  3004. do {
  3005. this.onBeforeStepObservable.notifyObservers(this);
  3006. // Animations
  3007. this._animationRatio = defaultFrameTime * defaultFPS;
  3008. this._animate();
  3009. this.onAfterAnimationsObservable.notifyObservers(this);
  3010. // Physics
  3011. if (this._physicsEngine) {
  3012. this.onBeforePhysicsObservable.notifyObservers(this);
  3013. this._physicsEngine._step(defaultFrameTime / 1000);
  3014. this.onAfterPhysicsObservable.notifyObservers(this);
  3015. }
  3016. this.onAfterStepObservable.notifyObservers(this);
  3017. this._currentStepId++;
  3018. stepsTaken++;
  3019. deltaTime -= defaultFrameTime;
  3020. } while (deltaTime > 0 && stepsTaken < internalSteps);
  3021. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  3022. }
  3023. else {
  3024. // Animations
  3025. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  3026. this._animationRatio = deltaTime * (60.0 / 1000.0);
  3027. this._animate();
  3028. this.onAfterAnimationsObservable.notifyObservers(this);
  3029. // Physics
  3030. if (this._physicsEngine) {
  3031. this.onBeforePhysicsObservable.notifyObservers(this);
  3032. this._physicsEngine._step(deltaTime / 1000.0);
  3033. this.onAfterPhysicsObservable.notifyObservers(this);
  3034. }
  3035. }
  3036. // update gamepad manager
  3037. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  3038. this._gamepadManager._checkGamepadsStatus();
  3039. }
  3040. // Before render
  3041. this.onBeforeRenderObservable.notifyObservers(this);
  3042. // Customs render targets
  3043. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3044. var engine = this.getEngine();
  3045. var currentActiveCamera = this.activeCamera;
  3046. if (this.renderTargetsEnabled) {
  3047. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3048. this._intermediateRendering = true;
  3049. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  3050. var renderTarget = this.customRenderTargets[customIndex];
  3051. if (renderTarget._shouldRender()) {
  3052. this._renderId++;
  3053. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  3054. if (!this.activeCamera)
  3055. throw new Error("Active camera not set");
  3056. // Viewport
  3057. engine.setViewport(this.activeCamera.viewport);
  3058. // Camera
  3059. this.updateTransformMatrix();
  3060. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  3061. }
  3062. }
  3063. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3064. this._intermediateRendering = false;
  3065. this._renderId++;
  3066. }
  3067. // Restore back buffer
  3068. if (this.customRenderTargets.length > 0) {
  3069. engine.restoreDefaultFramebuffer();
  3070. }
  3071. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  3072. this.activeCamera = currentActiveCamera;
  3073. // Procedural textures
  3074. if (this.proceduralTexturesEnabled) {
  3075. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  3076. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  3077. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  3078. if (proceduralTexture._shouldRender()) {
  3079. proceduralTexture.render();
  3080. }
  3081. }
  3082. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  3083. }
  3084. // Clear
  3085. if (this.autoClearDepthAndStencil || this.autoClear) {
  3086. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  3087. }
  3088. // Shadows
  3089. if (this.shadowsEnabled) {
  3090. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  3091. var light = this.lights[lightIndex];
  3092. var shadowGenerator = light.getShadowGenerator();
  3093. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  3094. var shadowMap = <RenderTargetTexture>(shadowGenerator.getShadowMap());
  3095. if (this.textures.indexOf(shadowMap) !== -1) {
  3096. this._renderTargets.push(shadowMap);
  3097. }
  3098. }
  3099. }
  3100. }
  3101. // Depth renderer
  3102. if (this._depthRenderer) {
  3103. this._renderTargets.push(this._depthRenderer.getDepthMap());
  3104. }
  3105. // Geometry renderer
  3106. if (this._geometryBufferRenderer) {
  3107. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  3108. }
  3109. // RenderPipeline
  3110. if (this._postProcessRenderPipelineManager) {
  3111. this._postProcessRenderPipelineManager.update();
  3112. }
  3113. // Multi-cameras?
  3114. if (this.activeCameras.length > 0) {
  3115. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3116. if (cameraIndex > 0) {
  3117. this._engine.clear(null, false, true, true);
  3118. }
  3119. this._processSubCameras(this.activeCameras[cameraIndex]);
  3120. }
  3121. } else {
  3122. if (!this.activeCamera) {
  3123. throw new Error("No camera defined");
  3124. }
  3125. this._processSubCameras(this.activeCamera);
  3126. }
  3127. // Intersection checks
  3128. this._checkIntersections();
  3129. // Update the audio listener attached to the camera
  3130. if (AudioEngine) {
  3131. this._updateAudioParameters();
  3132. }
  3133. // After render
  3134. if (this.afterRender) {
  3135. this.afterRender();
  3136. }
  3137. this.onAfterRenderObservable.notifyObservers(this);
  3138. // Cleaning
  3139. for (var index = 0; index < this._toBeDisposed.length; index++) {
  3140. var data = this._toBeDisposed.data[index];
  3141. if (data) {
  3142. data.dispose();
  3143. }
  3144. this._toBeDisposed[index] = null;
  3145. }
  3146. this._toBeDisposed.reset();
  3147. if (this.dumpNextRenderTargets) {
  3148. this.dumpNextRenderTargets = false;
  3149. }
  3150. this._activeBones.addCount(0, true);
  3151. this._activeIndices.addCount(0, true);
  3152. this._activeParticles.addCount(0, true);
  3153. }
  3154. private _updateAudioParameters() {
  3155. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  3156. return;
  3157. }
  3158. var listeningCamera: Nullable<Camera>;
  3159. var audioEngine = Engine.audioEngine;
  3160. if (this.activeCameras.length > 0) {
  3161. listeningCamera = this.activeCameras[0];
  3162. } else {
  3163. listeningCamera = this.activeCamera;
  3164. }
  3165. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  3166. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  3167. // for VR cameras
  3168. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  3169. listeningCamera = listeningCamera.rigCameras[0];
  3170. }
  3171. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  3172. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  3173. cameraDirection.normalize();
  3174. // To avoid some errors on GearVR
  3175. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  3176. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  3177. }
  3178. var i: number;
  3179. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  3180. var sound = this.mainSoundTrack.soundCollection[i];
  3181. if (sound.useCustomAttenuation) {
  3182. sound.updateDistanceFromListener();
  3183. }
  3184. }
  3185. for (i = 0; i < this.soundTracks.length; i++) {
  3186. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  3187. sound = this.soundTracks[i].soundCollection[j];
  3188. if (sound.useCustomAttenuation) {
  3189. sound.updateDistanceFromListener();
  3190. }
  3191. }
  3192. }
  3193. }
  3194. }
  3195. // Audio
  3196. public get audioEnabled(): boolean {
  3197. return this._audioEnabled;
  3198. }
  3199. public set audioEnabled(value: boolean) {
  3200. this._audioEnabled = value;
  3201. if (AudioEngine) {
  3202. if (this._audioEnabled) {
  3203. this._enableAudio();
  3204. }
  3205. else {
  3206. this._disableAudio();
  3207. }
  3208. }
  3209. }
  3210. private _disableAudio() {
  3211. var i: number;
  3212. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  3213. this.mainSoundTrack.soundCollection[i].pause();
  3214. }
  3215. for (i = 0; i < this.soundTracks.length; i++) {
  3216. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  3217. this.soundTracks[i].soundCollection[j].pause();
  3218. }
  3219. }
  3220. }
  3221. private _enableAudio() {
  3222. var i: number;
  3223. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  3224. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  3225. this.mainSoundTrack.soundCollection[i].play();
  3226. }
  3227. }
  3228. for (i = 0; i < this.soundTracks.length; i++) {
  3229. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  3230. if (this.soundTracks[i].soundCollection[j].isPaused) {
  3231. this.soundTracks[i].soundCollection[j].play();
  3232. }
  3233. }
  3234. }
  3235. }
  3236. public get headphone(): boolean {
  3237. return this._headphone;
  3238. }
  3239. public set headphone(value: boolean) {
  3240. this._headphone = value;
  3241. if (AudioEngine) {
  3242. if (this._headphone) {
  3243. this._switchAudioModeForHeadphones();
  3244. }
  3245. else {
  3246. this._switchAudioModeForNormalSpeakers();
  3247. }
  3248. }
  3249. }
  3250. private _switchAudioModeForHeadphones() {
  3251. this.mainSoundTrack.switchPanningModelToHRTF();
  3252. for (var i = 0; i < this.soundTracks.length; i++) {
  3253. this.soundTracks[i].switchPanningModelToHRTF();
  3254. }
  3255. }
  3256. private _switchAudioModeForNormalSpeakers() {
  3257. this.mainSoundTrack.switchPanningModelToEqualPower();
  3258. for (var i = 0; i < this.soundTracks.length; i++) {
  3259. this.soundTracks[i].switchPanningModelToEqualPower();
  3260. }
  3261. }
  3262. public enableDepthRenderer(): DepthRenderer {
  3263. if (this._depthRenderer) {
  3264. return this._depthRenderer;
  3265. }
  3266. this._depthRenderer = new DepthRenderer(this);
  3267. return this._depthRenderer;
  3268. }
  3269. public disableDepthRenderer(): void {
  3270. if (!this._depthRenderer) {
  3271. return;
  3272. }
  3273. this._depthRenderer.dispose();
  3274. this._depthRenderer = null;
  3275. }
  3276. public enableGeometryBufferRenderer(ratio: number = 1): Nullable<GeometryBufferRenderer> {
  3277. if (this._geometryBufferRenderer) {
  3278. return this._geometryBufferRenderer;
  3279. }
  3280. this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio);
  3281. if (!this._geometryBufferRenderer.isSupported) {
  3282. this._geometryBufferRenderer = null;
  3283. }
  3284. return this._geometryBufferRenderer;
  3285. }
  3286. public disableGeometryBufferRenderer(): void {
  3287. if (!this._geometryBufferRenderer) {
  3288. return;
  3289. }
  3290. this._geometryBufferRenderer.dispose();
  3291. this._geometryBufferRenderer = null;
  3292. }
  3293. public freezeMaterials(): void {
  3294. for (var i = 0; i < this.materials.length; i++) {
  3295. this.materials[i].freeze();
  3296. }
  3297. }
  3298. public unfreezeMaterials(): void {
  3299. for (var i = 0; i < this.materials.length; i++) {
  3300. this.materials[i].unfreeze();
  3301. }
  3302. }
  3303. public dispose(): void {
  3304. this.beforeRender = null;
  3305. this.afterRender = null;
  3306. this.skeletons = [];
  3307. this.morphTargetManagers = [];
  3308. this.importedMeshesFiles = new Array<string>();
  3309. this.stopAllAnimations();
  3310. this.resetCachedMaterial();
  3311. if (this._depthRenderer) {
  3312. this._depthRenderer.dispose();
  3313. }
  3314. if (this._gamepadManager) {
  3315. this._gamepadManager.dispose();
  3316. this._gamepadManager = null;
  3317. }
  3318. // Smart arrays
  3319. if (this.activeCamera) {
  3320. this.activeCamera._activeMeshes.dispose();
  3321. this.activeCamera = null;
  3322. }
  3323. this._activeMeshes.dispose();
  3324. this._renderingManager.dispose();
  3325. this._processedMaterials.dispose();
  3326. this._activeParticleSystems.dispose();
  3327. this._activeSkeletons.dispose();
  3328. this._softwareSkinnedMeshes.dispose();
  3329. this._renderTargets.dispose();
  3330. if (this._boundingBoxRenderer) {
  3331. this._boundingBoxRenderer.dispose();
  3332. }
  3333. this._meshesForIntersections.dispose();
  3334. this._toBeDisposed.dispose();
  3335. // Abort active requests
  3336. for (let request of this._activeRequests) {
  3337. request.abort();
  3338. }
  3339. // Debug layer
  3340. if (this._debugLayer) {
  3341. this._debugLayer.hide();
  3342. }
  3343. // Events
  3344. this.onDisposeObservable.notifyObservers(this);
  3345. this.onDisposeObservable.clear();
  3346. this.onBeforeRenderObservable.clear();
  3347. this.onAfterRenderObservable.clear();
  3348. this.OnBeforeRenderTargetsRenderObservable.clear();
  3349. this.OnAfterRenderTargetsRenderObservable.clear();
  3350. this.onAfterStepObservable.clear();
  3351. this.onBeforeStepObservable.clear();
  3352. this.onBeforeActiveMeshesEvaluationObservable.clear();
  3353. this.onAfterActiveMeshesEvaluationObservable.clear();
  3354. this.onBeforeParticlesRenderingObservable.clear();
  3355. this.onAfterParticlesRenderingObservable.clear();
  3356. this.onBeforeSpritesRenderingObservable.clear();
  3357. this.onAfterSpritesRenderingObservable.clear();
  3358. this.onBeforeDrawPhaseObservable.clear();
  3359. this.onAfterDrawPhaseObservable.clear();
  3360. this.onBeforePhysicsObservable.clear();
  3361. this.onAfterPhysicsObservable.clear();
  3362. this.onBeforeAnimationsObservable.clear();
  3363. this.onAfterAnimationsObservable.clear();
  3364. this.onDataLoadedObservable.clear();
  3365. this.detachControl();
  3366. // Release sounds & sounds tracks
  3367. if (AudioEngine) {
  3368. this.disposeSounds();
  3369. }
  3370. // VR Helper
  3371. if (this.VRHelper) {
  3372. this.VRHelper.dispose();
  3373. }
  3374. // Detach cameras
  3375. var canvas = this._engine.getRenderingCanvas();
  3376. if (canvas) {
  3377. var index;
  3378. for (index = 0; index < this.cameras.length; index++) {
  3379. this.cameras[index].detachControl(canvas);
  3380. }
  3381. }
  3382. // Release animation groups
  3383. while (this.animationGroups.length) {
  3384. this.animationGroups[0].dispose();
  3385. }
  3386. // Release lights
  3387. while (this.lights.length) {
  3388. this.lights[0].dispose();
  3389. }
  3390. // Release meshes
  3391. while (this.meshes.length) {
  3392. this.meshes[0].dispose(true);
  3393. }
  3394. while (this.transformNodes.length) {
  3395. this.removeTransformNode(this.transformNodes[0]);
  3396. }
  3397. // Release cameras
  3398. while (this.cameras.length) {
  3399. this.cameras[0].dispose();
  3400. }
  3401. // Release materials
  3402. if (this.defaultMaterial) {
  3403. this.defaultMaterial.dispose()
  3404. }
  3405. while (this.multiMaterials.length) {
  3406. this.multiMaterials[0].dispose();
  3407. }
  3408. while (this.materials.length) {
  3409. this.materials[0].dispose();
  3410. }
  3411. // Release particles
  3412. while (this.particleSystems.length) {
  3413. this.particleSystems[0].dispose();
  3414. }
  3415. // Release sprites
  3416. while (this.spriteManagers.length) {
  3417. this.spriteManagers[0].dispose();
  3418. }
  3419. // Release postProcesses
  3420. while (this.postProcesses.length) {
  3421. this.postProcesses[0].dispose();
  3422. }
  3423. // Release layers
  3424. while (this.layers.length) {
  3425. this.layers[0].dispose();
  3426. }
  3427. while (this.highlightLayers.length) {
  3428. this.highlightLayers[0].dispose();
  3429. }
  3430. // Release textures
  3431. while (this.textures.length) {
  3432. this.textures[0].dispose();
  3433. }
  3434. // Release UBO
  3435. this._sceneUbo.dispose();
  3436. if (this._alternateSceneUbo) {
  3437. this._alternateSceneUbo.dispose();
  3438. }
  3439. // Post-processes
  3440. this.postProcessManager.dispose();
  3441. if (this._postProcessRenderPipelineManager) {
  3442. this._postProcessRenderPipelineManager.dispose();
  3443. }
  3444. // Physics
  3445. if (this._physicsEngine) {
  3446. this.disablePhysicsEngine();
  3447. }
  3448. // Remove from engine
  3449. index = this._engine.scenes.indexOf(this);
  3450. if (index > -1) {
  3451. this._engine.scenes.splice(index, 1);
  3452. }
  3453. this._engine.wipeCaches(true);
  3454. this._isDisposed = true;
  3455. }
  3456. public get isDisposed(): boolean {
  3457. return this._isDisposed;
  3458. }
  3459. // Release sounds & sounds tracks
  3460. public disposeSounds() {
  3461. if (!this._mainSoundTrack) {
  3462. return;
  3463. }
  3464. this.mainSoundTrack.dispose();
  3465. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  3466. this.soundTracks[scIndex].dispose();
  3467. }
  3468. }
  3469. // Octrees
  3470. public getWorldExtends(): { min: Vector3; max: Vector3 } {
  3471. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3472. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3473. for (var index = 0; index < this.meshes.length; index++) {
  3474. var mesh = this.meshes[index];
  3475. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  3476. continue;
  3477. }
  3478. mesh.computeWorldMatrix(true);
  3479. let boundingInfo = mesh.getBoundingInfo();
  3480. var minBox = boundingInfo.boundingBox.minimumWorld;
  3481. var maxBox = boundingInfo.boundingBox.maximumWorld;
  3482. Tools.CheckExtends(minBox, min, max);
  3483. Tools.CheckExtends(maxBox, min, max);
  3484. }
  3485. return {
  3486. min: min,
  3487. max: max
  3488. };
  3489. }
  3490. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  3491. if (!this._selectionOctree) {
  3492. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  3493. }
  3494. var worldExtends = this.getWorldExtends();
  3495. // Update octree
  3496. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  3497. return this._selectionOctree;
  3498. }
  3499. // Picking
  3500. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  3501. let result = Ray.Zero();
  3502. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  3503. return result;
  3504. }
  3505. public createPickingRayToRef(x: number, y: number, world: Matrix, result: Ray, camera: Nullable<Camera>, cameraViewSpace = false): Scene {
  3506. var engine = this._engine;
  3507. if (!camera) {
  3508. if (!this.activeCamera)
  3509. throw new Error("Active camera not set");
  3510. camera = this.activeCamera;
  3511. }
  3512. var cameraViewport = camera.viewport;
  3513. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3514. // Moving coordinates to local viewport world
  3515. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3516. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3517. result.update(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  3518. return this;
  3519. }
  3520. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Ray {
  3521. let result = Ray.Zero();
  3522. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  3523. return result;
  3524. }
  3525. public createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene {
  3526. if (!PickingInfo) {
  3527. return this;
  3528. }
  3529. var engine = this._engine;
  3530. if (!camera) {
  3531. if (!this.activeCamera)
  3532. throw new Error("Active camera not set");
  3533. camera = this.activeCamera;
  3534. }
  3535. var cameraViewport = camera.viewport;
  3536. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3537. var identity = Matrix.Identity();
  3538. // Moving coordinates to local viewport world
  3539. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3540. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3541. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  3542. return this;
  3543. }
  3544. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  3545. if (!PickingInfo) {
  3546. return null;
  3547. }
  3548. var pickingInfo = null;
  3549. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3550. var mesh = this.meshes[meshIndex];
  3551. if (predicate) {
  3552. if (!predicate(mesh)) {
  3553. continue;
  3554. }
  3555. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3556. continue;
  3557. }
  3558. var world = mesh.getWorldMatrix();
  3559. var ray = rayFunction(world);
  3560. var result = mesh.intersects(ray, fastCheck);
  3561. if (!result || !result.hit)
  3562. continue;
  3563. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3564. continue;
  3565. pickingInfo = result;
  3566. if (fastCheck) {
  3567. break;
  3568. }
  3569. }
  3570. return pickingInfo || new PickingInfo();
  3571. }
  3572. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  3573. if (!PickingInfo) {
  3574. return null;
  3575. }
  3576. var pickingInfos = new Array<PickingInfo>();
  3577. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3578. var mesh = this.meshes[meshIndex];
  3579. if (predicate) {
  3580. if (!predicate(mesh)) {
  3581. continue;
  3582. }
  3583. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3584. continue;
  3585. }
  3586. var world = mesh.getWorldMatrix();
  3587. var ray = rayFunction(world);
  3588. var result = mesh.intersects(ray, false);
  3589. if (!result || !result.hit)
  3590. continue;
  3591. pickingInfos.push(result);
  3592. }
  3593. return pickingInfos;
  3594. }
  3595. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  3596. if (!PickingInfo) {
  3597. return null;
  3598. }
  3599. var pickingInfo = null;
  3600. if (!camera) {
  3601. if (!this.activeCamera) {
  3602. return null;
  3603. }
  3604. camera = this.activeCamera;
  3605. }
  3606. if (this.spriteManagers.length > 0) {
  3607. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  3608. var spriteManager = this.spriteManagers[spriteIndex];
  3609. if (!spriteManager.isPickable) {
  3610. continue;
  3611. }
  3612. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  3613. if (!result || !result.hit)
  3614. continue;
  3615. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3616. continue;
  3617. pickingInfo = result;
  3618. if (fastCheck) {
  3619. break;
  3620. }
  3621. }
  3622. }
  3623. return pickingInfo || new PickingInfo();
  3624. }
  3625. private _tempPickingRay: Nullable<Ray> = Ray ? Ray.Zero() : null;
  3626. /** Launch a ray to try to pick a mesh in the scene
  3627. * @param x position on screen
  3628. * @param y position on screen
  3629. * @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
  3630. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3631. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3632. */
  3633. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Nullable<Camera>): Nullable<PickingInfo> {
  3634. if (!PickingInfo) {
  3635. return null;
  3636. }
  3637. return this._internalPick(world => {
  3638. this.createPickingRayToRef(x, y, world, this._tempPickingRay!, camera || null);
  3639. return this._tempPickingRay!;
  3640. }, predicate, fastCheck);
  3641. }
  3642. /** Launch a ray to try to pick a sprite in the scene
  3643. * @param x position on screen
  3644. * @param y position on screen
  3645. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  3646. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3647. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3648. */
  3649. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  3650. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay!, camera);
  3651. return this._internalPickSprites(this._tempPickingRay!, predicate, fastCheck, camera);
  3652. }
  3653. private _cachedRayForTransform: Ray;
  3654. /** Use the given ray to pick a mesh in the scene
  3655. * @param ray The ray to use to pick meshes
  3656. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  3657. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3658. */
  3659. public pickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  3660. return this._internalPick(world => {
  3661. if (!this._pickWithRayInverseMatrix) {
  3662. this._pickWithRayInverseMatrix = Matrix.Identity();
  3663. }
  3664. world.invertToRef(this._pickWithRayInverseMatrix);
  3665. if (!this._cachedRayForTransform) {
  3666. this._cachedRayForTransform = Ray.Zero();
  3667. }
  3668. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  3669. return this._cachedRayForTransform;
  3670. }, predicate, fastCheck);
  3671. }
  3672. /**
  3673. * Launch a ray to try to pick a mesh in the scene
  3674. * @param x X position on screen
  3675. * @param y Y position on screen
  3676. * @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
  3677. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3678. */
  3679. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): Nullable<PickingInfo[]> {
  3680. return this._internalMultiPick(world => this.createPickingRay(x, y, world, camera || null), predicate);
  3681. }
  3682. /**
  3683. * Launch a ray to try to pick a mesh in the scene
  3684. * @param ray Ray to use
  3685. * @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
  3686. */
  3687. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  3688. return this._internalMultiPick(world => {
  3689. if (!this._pickWithRayInverseMatrix) {
  3690. this._pickWithRayInverseMatrix = Matrix.Identity();
  3691. }
  3692. world.invertToRef(this._pickWithRayInverseMatrix);
  3693. if (!this._cachedRayForTransform) {
  3694. this._cachedRayForTransform = Ray.Zero();
  3695. }
  3696. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  3697. return this._cachedRayForTransform;
  3698. }, predicate);
  3699. }
  3700. public setPointerOverMesh(mesh: Nullable<AbstractMesh>): void {
  3701. if (this._pointerOverMesh === mesh) {
  3702. return;
  3703. }
  3704. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3705. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3706. }
  3707. this._pointerOverMesh = mesh;
  3708. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3709. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3710. }
  3711. }
  3712. public getPointerOverMesh(): Nullable<AbstractMesh> {
  3713. return this._pointerOverMesh;
  3714. }
  3715. public setPointerOverSprite(sprite: Nullable<Sprite>): void {
  3716. if (this._pointerOverSprite === sprite) {
  3717. return;
  3718. }
  3719. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3720. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3721. }
  3722. this._pointerOverSprite = sprite;
  3723. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3724. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3725. }
  3726. }
  3727. public getPointerOverSprite(): Nullable<Sprite> {
  3728. return this._pointerOverSprite;
  3729. }
  3730. // Physics
  3731. public getPhysicsEngine(): Nullable<PhysicsEngine> {
  3732. return this._physicsEngine;
  3733. }
  3734. /**
  3735. * Enables physics to the current scene
  3736. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  3737. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  3738. * @return {boolean} was the physics engine initialized
  3739. */
  3740. public enablePhysics(gravity: Nullable<Vector3> = null, plugin?: IPhysicsEnginePlugin): boolean {
  3741. if (this._physicsEngine) {
  3742. return true;
  3743. }
  3744. try {
  3745. this._physicsEngine = new PhysicsEngine(gravity, plugin);
  3746. return true;
  3747. } catch (e) {
  3748. Tools.Error(e.message);
  3749. return false;
  3750. }
  3751. }
  3752. public disablePhysicsEngine(): void {
  3753. if (!this._physicsEngine) {
  3754. return;
  3755. }
  3756. this._physicsEngine.dispose();
  3757. this._physicsEngine = null;
  3758. }
  3759. public isPhysicsEnabled(): boolean {
  3760. return this._physicsEngine !== undefined;
  3761. }
  3762. public deleteCompoundImpostor(compound: any): void {
  3763. var mesh: AbstractMesh = compound.parts[0].mesh;
  3764. if (mesh.physicsImpostor) {
  3765. mesh.physicsImpostor.dispose(/*true*/);
  3766. mesh.physicsImpostor = null;
  3767. }
  3768. }
  3769. // Misc.
  3770. public _rebuildGeometries(): void {
  3771. for (var geometry of this._geometries) {
  3772. geometry._rebuild();
  3773. }
  3774. for (var mesh of this.meshes) {
  3775. mesh._rebuild();
  3776. }
  3777. if (this.postProcessManager) {
  3778. this.postProcessManager._rebuild();
  3779. }
  3780. for (var layer of this.layers) {
  3781. layer._rebuild();
  3782. }
  3783. for (var highlightLayer of this.highlightLayers) {
  3784. highlightLayer._rebuild();
  3785. }
  3786. if (this._boundingBoxRenderer) {
  3787. this._boundingBoxRenderer._rebuild();
  3788. }
  3789. for (var system of this.particleSystems) {
  3790. system.rebuild();
  3791. }
  3792. if (this._postProcessRenderPipelineManager) {
  3793. this._postProcessRenderPipelineManager._rebuild();
  3794. }
  3795. }
  3796. public _rebuildTextures(): void {
  3797. for (var texture of this.textures) {
  3798. texture._rebuild();
  3799. }
  3800. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  3801. }
  3802. /**
  3803. * Creates a default light for the scene.
  3804. * @param replace Whether to replace the existing lights in the scene.
  3805. */
  3806. public createDefaultLight(replace = false): void {
  3807. // Dispose existing light in replace mode.
  3808. if (replace) {
  3809. if (this.lights) {
  3810. for (var i = 0; i < this.lights.length; i++) {
  3811. this.lights[i].dispose();
  3812. }
  3813. }
  3814. }
  3815. // Light
  3816. if (this.lights.length === 0) {
  3817. new HemisphericLight("default light", Vector3.Up(), this);
  3818. }
  3819. }
  3820. /**
  3821. * Creates a default camera for the scene.
  3822. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  3823. * @param replace Whether to replace the existing active camera in the scene.
  3824. * @param attachCameraControls Whether to attach camera controls to the canvas.
  3825. */
  3826. public createDefaultCamera(createArcRotateCamera = false, replace = false, attachCameraControls = false): void {
  3827. // Dispose existing camera in replace mode.
  3828. if (replace) {
  3829. if (this.activeCamera) {
  3830. this.activeCamera.dispose();
  3831. this.activeCamera = null;
  3832. }
  3833. }
  3834. // Camera
  3835. if (!this.activeCamera) {
  3836. var worldExtends = this.getWorldExtends();
  3837. var worldSize = worldExtends.max.subtract(worldExtends.min);
  3838. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  3839. var camera: TargetCamera;
  3840. var radius = worldSize.length() * 1.5;
  3841. // empty scene scenario!
  3842. if (!isFinite(radius)) {
  3843. radius = 1;
  3844. worldCenter.copyFromFloats(0, 0, 0);
  3845. }
  3846. if (createArcRotateCamera) {
  3847. var arcRotateCamera = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  3848. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  3849. arcRotateCamera.wheelPrecision = 100 / radius;
  3850. camera = arcRotateCamera;
  3851. }
  3852. else {
  3853. var freeCamera = new FreeCamera("default camera", new Vector3(worldCenter.x, worldCenter.y, -radius), this);
  3854. freeCamera.setTarget(worldCenter);
  3855. camera = freeCamera;
  3856. }
  3857. camera.minZ = radius * 0.01;
  3858. camera.maxZ = radius * 1000;
  3859. camera.speed = radius * 0.2;
  3860. this.activeCamera = camera;
  3861. let canvas = this.getEngine().getRenderingCanvas();
  3862. if (attachCameraControls && canvas) {
  3863. camera.attachControl(canvas);
  3864. }
  3865. }
  3866. }
  3867. public createDefaultCameraOrLight(createArcRotateCamera = false, replace = false, attachCameraControls = false): void {
  3868. this.createDefaultLight(replace);
  3869. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  3870. }
  3871. public createDefaultSkybox(environmentTexture?: BaseTexture, pbr = false, scale = 1000, blur = 0): Nullable<Mesh> {
  3872. if (environmentTexture) {
  3873. this.environmentTexture = environmentTexture;
  3874. }
  3875. if (!this.environmentTexture) {
  3876. Tools.Warn("Can not create default skybox without environment texture.");
  3877. return null;
  3878. }
  3879. // Skybox
  3880. var hdrSkybox = Mesh.CreateBox("hdrSkyBox", scale, this);
  3881. if (pbr) {
  3882. let hdrSkyboxMaterial = new PBRMaterial("skyBox", this);
  3883. hdrSkyboxMaterial.backFaceCulling = false;
  3884. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  3885. if (hdrSkyboxMaterial.reflectionTexture) {
  3886. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  3887. }
  3888. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  3889. hdrSkyboxMaterial.disableLighting = true;
  3890. hdrSkyboxMaterial.twoSidedLighting = true;
  3891. hdrSkybox.infiniteDistance = true;
  3892. hdrSkybox.material = hdrSkyboxMaterial;
  3893. }
  3894. else {
  3895. let skyboxMaterial = new StandardMaterial("skyBox", this);
  3896. skyboxMaterial.backFaceCulling = false;
  3897. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  3898. if (skyboxMaterial.reflectionTexture) {
  3899. skyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  3900. }
  3901. skyboxMaterial.disableLighting = true;
  3902. hdrSkybox.infiniteDistance = true;
  3903. hdrSkybox.material = skyboxMaterial;
  3904. }
  3905. return hdrSkybox;
  3906. }
  3907. public createDefaultEnvironment(options: Partial<IEnvironmentHelperOptions>): Nullable<EnvironmentHelper> {
  3908. if (EnvironmentHelper) {
  3909. return new EnvironmentHelper(options, this);
  3910. }
  3911. return null;
  3912. }
  3913. public createDefaultVRExperience(webVROptions: VRExperienceHelperOptions = {}): VRExperienceHelper {
  3914. return new VRExperienceHelper(this, webVROptions);
  3915. }
  3916. // Tags
  3917. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  3918. if (tagsQuery === undefined) {
  3919. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  3920. return list;
  3921. }
  3922. var listByTags = [];
  3923. forEach = forEach || ((item: any) => { return; });
  3924. for (var i in list) {
  3925. var item = list[i];
  3926. if (Tags && Tags.MatchesQuery(item, tagsQuery)) {
  3927. listByTags.push(item);
  3928. forEach(item);
  3929. }
  3930. }
  3931. return listByTags;
  3932. }
  3933. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  3934. return this._getByTags(this.meshes, tagsQuery, forEach);
  3935. }
  3936. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  3937. return this._getByTags(this.cameras, tagsQuery, forEach);
  3938. }
  3939. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  3940. return this._getByTags(this.lights, tagsQuery, forEach);
  3941. }
  3942. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  3943. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  3944. }
  3945. /**
  3946. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  3947. * This allowed control for front to back rendering or reversly depending of the special needs.
  3948. *
  3949. * @param renderingGroupId The rendering group id corresponding to its index
  3950. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  3951. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  3952. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  3953. */
  3954. public setRenderingOrder(renderingGroupId: number,
  3955. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  3956. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  3957. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  3958. this._renderingManager.setRenderingOrder(renderingGroupId,
  3959. opaqueSortCompareFn,
  3960. alphaTestSortCompareFn,
  3961. transparentSortCompareFn);
  3962. }
  3963. /**
  3964. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  3965. *
  3966. * @param renderingGroupId The rendering group id corresponding to its index
  3967. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  3968. * @param depth Automatically clears depth between groups if true and autoClear is true.
  3969. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  3970. */
  3971. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  3972. depth = true,
  3973. stencil = true): void {
  3974. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  3975. }
  3976. /**
  3977. * Will flag all materials as dirty to trigger new shader compilation
  3978. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  3979. */
  3980. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  3981. for (var material of this.materials) {
  3982. if (predicate && !predicate(material)) {
  3983. continue;
  3984. }
  3985. material.markAsDirty(flag);
  3986. }
  3987. }
  3988. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, useDatabase?: boolean, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  3989. let request = Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  3990. this._activeRequests.push(request);
  3991. request.onCompleteObservable.add(request => {
  3992. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  3993. });
  3994. return request;
  3995. }
  3996. /** @ignore */
  3997. public _loadFileAsync(url: string, useDatabase?: boolean, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  3998. return new Promise((resolve, reject) => {
  3999. this._loadFile(url, (data) => {
  4000. resolve(data);
  4001. }, undefined, useDatabase, useArrayBuffer, (request, exception) => {
  4002. reject(exception);
  4003. })
  4004. });
  4005. }
  4006. }
  4007. }