scene.js 179 KB

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