scene.ts 174 KB

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