babylon.scene.ts 168 KB

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