scene.ts 170 KB

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