babylon.scene.ts 206 KB

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