scene.ts 174 KB

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