scene.ts 169 KB

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