babylon.scene.ts 172 KB

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