scene.ts 163 KB

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