scene.ts 186 KB

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