< Summary

Class:DCL.SceneController
Assembly:DCL.Runtime
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/SceneController.cs
Covered lines:173
Uncovered lines:175
Coverable lines:348
Total lines:871
Line coverage:49.7% (173 of 348)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
SceneController()0%110100%
Initialize()0%22093.33%
SetupDeferredRunners()0%110100%
PrewarmSceneMessagesPool()0%20400%
OnDebugModeSet(...)0%3.713057.14%
Dispose()0%220100%
Update()0%440100%
LateUpdate()0%220100%
ProcessMessage(...)0%1101000%
ProcessMessage(...)0%22564700%
ParseQuery(...)0%12300%
SendSceneMessage(...)0%6200%
Decode(...)0%20400%
DeferredDecodingAndEnqueue()0%7.777075%
EnqueueChunk(...)0%12300%
WatchForNewChunksToDecode()0%30500%
ThreadedDecodeAndEnqueue(...)0%20400%
EnqueueSceneMessage(...)0%2100%
SendSceneReady(...)0%220100%
ActivateBuilderInWorldEditScene()0%110100%
DeactivateBuilderInWorldEditScene()0%110100%
SetPositionDirty(...)0%4.054085.71%
SortScenesByDistance()0%440100%
OnCurrentSceneIdChange(...)0%64050%
LoadParcelScenesExecute(...)0%14.213080.77%
UpdateParcelScenesExecute(...)0%20400%
UpdateParcelScenesExecute(...)0%6.396077.78%
UnloadScene(...)0%220100%
UnloadParcelSceneExecute(...)0%6.356078.57%
UnloadAllScenes(...)0%440100%
LoadParcelScenes(...)0%3.043083.33%
UpdateParcelScenes(...)0%6200%
UnloadAllScenesQueued()0%6200%
CreateGlobalScene(...)0%10.8910079.31%
IsolateScene(...)0%330100%
ReIntegrateIsolatedScene()0%220100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/SceneController.cs

#LineLine coverage
 1using DCL.Controllers;
 2using DCL.Helpers;
 3using DCL.Interface;
 4using DCL.Models;
 5using DCL.Configuration;
 6using System;
 7using System.Collections;
 8using System.Collections.Concurrent;
 9using System.ComponentModel;
 10using System.Linq;
 11using System.Threading;
 12using Cysharp.Threading.Tasks;
 13using DCL.Components;
 14using DCL.CRDT;
 15using UnityEngine;
 16using Debug = UnityEngine.Debug;
 17
 18namespace DCL
 19{
 20    public class SceneController : ISceneController
 21    {
 22        public static bool VERBOSE = false;
 23        const int SCENE_MESSAGES_PREWARM_COUNT = 100000;
 24
 71425        public bool enabled { get; set; } = true;
 226        internal BaseVariable<Transform> isPexViewerInitialized => DataStore.i.experiencesViewer.isInitialized;
 27
 28        //TODO(Brian): Move to WorldRuntimePlugin later
 29        private LoadingFeedbackController loadingFeedbackController;
 30        private Coroutine deferredDecodingCoroutine;
 31
 32        private CancellationTokenSource tokenSource;
 90433        private IMessagingControllersManager messagingControllersManager => Environment.i.messaging.manager;
 34
 72335        public EntityIdHelper entityIdHelper { get; } = new EntityIdHelper();
 36
 37        public void Initialize()
 38        {
 69039            tokenSource = new CancellationTokenSource();
 69040            sceneSortDirty = true;
 69041            positionDirty = true;
 69042            lastSortFrame = 0;
 69043            enabled = true;
 44
 69045            loadingFeedbackController = new LoadingFeedbackController();
 46
 69047            DataStore.i.debugConfig.isDebugMode.OnChange += OnDebugModeSet;
 48
 69049            SetupDeferredRunners();
 50
 69051            DataStore.i.player.playerGridPosition.OnChange += SetPositionDirty;
 69052            CommonScriptableObjects.sceneID.OnChange += OnCurrentSceneIdChange;
 53
 54            // TODO(Brian): Move this later to Main.cs
 69055            if ( !EnvironmentSettings.RUNNING_TESTS )
 56            {
 057                PrewarmSceneMessagesPool();
 58            }
 59
 69060            Environment.i.platform.updateEventHandler.AddListener(IUpdateEventHandler.EventType.Update, Update);
 69061            Environment.i.platform.updateEventHandler.AddListener(IUpdateEventHandler.EventType.LateUpdate, LateUpdate);
 69062        }
 63        private void SetupDeferredRunners()
 64        {
 65#if UNITY_WEBGL
 69066            deferredDecodingCoroutine = CoroutineStarter.Start(DeferredDecodingAndEnqueue());
 67#else
 68            CancellationToken tokenSourceToken = tokenSource.Token;
 69            TaskUtils.Run(async () => await WatchForNewChunksToDecode(tokenSourceToken), cancellationToken: tokenSourceT
 70#endif
 69071        }
 72
 73        private void PrewarmSceneMessagesPool()
 74        {
 075            if (prewarmSceneMessagesPool)
 76            {
 077                for (int i = 0; i < SCENE_MESSAGES_PREWARM_COUNT; i++)
 78                {
 079                    sceneMessagesPool.Enqueue(new QueuedSceneMessage_Scene());
 80                }
 81            }
 82
 083            if (prewarmEntitiesPool)
 84            {
 085                PoolManagerFactory.EnsureEntityPool(prewarmEntitiesPool);
 86            }
 087        }
 88
 89        private void OnDebugModeSet(bool current, bool previous)
 90        {
 2991            if (current == previous)
 092                return;
 93
 2994            if (current)
 95            {
 2996                Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new SceneBoundsFeedbackStyle_RedBox());
 2997            }
 98            else
 99            {
 0100                Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new SceneBoundsFeedbackStyle_Simple());
 101            }
 0102        }
 103
 104        public void Dispose()
 105        {
 690106            tokenSource.Cancel();
 690107            tokenSource.Dispose();
 690108            loadingFeedbackController.Dispose();
 109
 690110            Environment.i.platform.updateEventHandler.RemoveListener(IUpdateEventHandler.EventType.Update, Update);
 690111            Environment.i.platform.updateEventHandler.RemoveListener(IUpdateEventHandler.EventType.LateUpdate, LateUpdat
 112
 690113            PoolManager.i.OnGet -= Environment.i.platform.physicsSyncController.MarkDirty;
 690114            PoolManager.i.OnGet -= Environment.i.platform.cullingController.objectsTracker.MarkDirty;
 115
 690116            DataStore.i.player.playerGridPosition.OnChange -= SetPositionDirty;
 690117            DataStore.i.debugConfig.isDebugMode.OnChange -= OnDebugModeSet;
 118
 690119            CommonScriptableObjects.sceneID.OnChange -= OnCurrentSceneIdChange;
 120
 690121            UnloadAllScenes(includePersistent: true);
 122
 690123            if (deferredDecodingCoroutine != null)
 690124                CoroutineStarter.Stop(deferredDecodingCoroutine);
 690125        }
 126
 127        public void Update()
 128        {
 7042129            if (!enabled)
 429130                return;
 131
 6613132            if (lastSortFrame != Time.frameCount && sceneSortDirty)
 133            {
 688134                lastSortFrame = Time.frameCount;
 688135                sceneSortDirty = false;
 688136                SortScenesByDistance();
 137            }
 6613138        }
 139
 140        public void LateUpdate()
 141        {
 7042142            if (!enabled)
 429143                return;
 144
 6613145            Environment.i.platform.physicsSyncController.Sync();
 6613146        }
 147
 148        //======================================================================
 149
 150        #region MESSAGES_HANDLING
 151
 152        //======================================================================
 153
 154#if UNITY_EDITOR
 155        public delegate void ProcessDelegate(string sceneId, string method);
 156
 157        public event ProcessDelegate OnMessageProcessInfoStart;
 158        public event ProcessDelegate OnMessageProcessInfoEnds;
 159#endif
 0160        public bool deferredMessagesDecoding { get; set; } = false;
 161
 690162        readonly ConcurrentQueue<string> chunksToDecode = new ConcurrentQueue<string>();
 690163        private readonly ConcurrentQueue<QueuedSceneMessage_Scene> messagesToProcess = new ConcurrentQueue<QueuedSceneMe
 164
 165        const float MAX_TIME_FOR_DECODE = 0.005f;
 166
 167        public bool ProcessMessage(QueuedSceneMessage_Scene msgObject, out CustomYieldInstruction yieldInstruction)
 168        {
 0169            string sceneId = msgObject.sceneId;
 0170            string method = msgObject.method;
 171
 0172            yieldInstruction = null;
 173
 174            IParcelScene scene;
 0175            bool res = false;
 0176            IWorldState worldState = Environment.i.world.state;
 0177            DebugConfig debugConfig = DataStore.i.debugConfig;
 178
 0179            if (worldState.TryGetScene(sceneId, out scene))
 180            {
 181#if UNITY_EDITOR
 0182                if (debugConfig.soloScene && scene is GlobalScene && debugConfig.ignoreGlobalScenes)
 183                {
 0184                    return false;
 185                }
 186#endif
 0187                if (!scene.GetSceneTransform().gameObject.activeInHierarchy)
 188                {
 0189                    return true;
 190                }
 191
 192#if UNITY_EDITOR
 0193                OnMessageProcessInfoStart?.Invoke(sceneId, method);
 194#endif
 0195                ProfilingEvents.OnMessageProcessStart?.Invoke(method);
 196
 0197                ProcessMessage(scene as ParcelScene, method, msgObject.payload, out yieldInstruction);
 198
 0199                ProfilingEvents.OnMessageProcessEnds?.Invoke(method);
 200
 201#if UNITY_EDITOR
 0202                OnMessageProcessInfoEnds?.Invoke(sceneId, method);
 203#endif
 204
 0205                res = true;
 0206            }
 207
 208            else
 209            {
 0210                res = false;
 211            }
 212
 0213            sceneMessagesPool.Enqueue(msgObject);
 214
 0215            return res;
 216        }
 217
 218        private void ProcessMessage(ParcelScene scene, string method, object msgPayload,
 219            out CustomYieldInstruction yieldInstruction)
 220        {
 0221            yieldInstruction = null;
 0222            IDelayedComponent delayedComponent = null;
 223
 224            try
 225            {
 226                switch (method)
 227                {
 228                    case MessagingTypes.ENTITY_CREATE:
 229                        {
 0230                            if (msgPayload is Protocol.CreateEntity payload)
 0231                                scene.CreateEntity(entityIdHelper.EntityFromLegacyEntityString(payload.entityId));
 232
 0233                            break;
 234                        }
 235                    case MessagingTypes.ENTITY_REPARENT:
 236                        {
 0237                            if (msgPayload is Protocol.SetEntityParent payload)
 0238                                scene.SetEntityParent(entityIdHelper.EntityFromLegacyEntityString(payload.entityId),
 239                                    entityIdHelper.EntityFromLegacyEntityString(payload.parentId));
 240
 0241                            break;
 242                        }
 243
 244                    case MessagingTypes.ENTITY_COMPONENT_CREATE_OR_UPDATE:
 245                        {
 0246                            if (msgPayload is Protocol.EntityComponentCreateOrUpdate payload)
 247                            {
 0248                                delayedComponent = scene.componentsManagerLegacy.EntityComponentCreateOrUpdate(
 249                                    entityIdHelper.EntityFromLegacyEntityString(payload.entityId),
 250                                    (CLASS_ID_COMPONENT) payload.classId, payload.json) as IDelayedComponent;
 251                            }
 252
 0253                            break;
 254                        }
 255
 256                    case MessagingTypes.ENTITY_COMPONENT_DESTROY:
 257                        {
 0258                            if (msgPayload is Protocol.EntityComponentDestroy payload)
 0259                                scene.componentsManagerLegacy.EntityComponentRemove(
 260                                    entityIdHelper.EntityFromLegacyEntityString(payload.entityId), payload.name);
 261
 0262                            break;
 263                        }
 264
 265                    case MessagingTypes.SHARED_COMPONENT_ATTACH:
 266                        {
 0267                            if (msgPayload is Protocol.SharedComponentAttach payload)
 0268                                scene.componentsManagerLegacy.SceneSharedComponentAttach(
 269                                    entityIdHelper.EntityFromLegacyEntityString(payload.entityId), payload.id);
 270
 0271                            break;
 272                        }
 273
 274                    case MessagingTypes.SHARED_COMPONENT_CREATE:
 275                        {
 0276                            if (msgPayload is Protocol.SharedComponentCreate payload)
 0277                                scene.componentsManagerLegacy.SceneSharedComponentCreate(payload.id, payload.classId);
 278
 0279                            break;
 280                        }
 281
 282                    case MessagingTypes.SHARED_COMPONENT_DISPOSE:
 283                        {
 0284                            if (msgPayload is Protocol.SharedComponentDispose payload)
 0285                                scene.componentsManagerLegacy.SceneSharedComponentDispose(payload.id);
 286
 0287                            break;
 288                        }
 289
 290                    case MessagingTypes.SHARED_COMPONENT_UPDATE:
 291                        {
 0292                            if (msgPayload is Protocol.SharedComponentUpdate payload)
 0293                                delayedComponent = scene.componentsManagerLegacy.SceneSharedComponentUpdate(payload.comp
 294
 0295                            break;
 296                        }
 297
 298                    case MessagingTypes.ENTITY_DESTROY:
 299                        {
 0300                            if (msgPayload is Protocol.RemoveEntity payload)
 0301                                scene.RemoveEntity(entityIdHelper.EntityFromLegacyEntityString(payload.entityId));
 302
 0303                            break;
 304                        }
 305
 306                    case MessagingTypes.INIT_DONE:
 307                        {
 0308                            scene.sceneLifecycleHandler.SetInitMessagesDone();
 309
 0310                            break;
 311                        }
 312
 313                    case MessagingTypes.QUERY:
 314                        {
 0315                            if (msgPayload is QueryMessage queryMessage)
 0316                                ParseQuery(queryMessage.payload, scene.sceneData.id);
 317
 0318                            break;
 319                        }
 320
 321                    case MessagingTypes.OPEN_EXTERNAL_URL:
 322                        {
 0323                            if (msgPayload is Protocol.OpenExternalUrl payload)
 0324                                OnOpenExternalUrlRequest?.Invoke(scene, payload.url);
 325
 0326                            break;
 327                        }
 328
 329                    case MessagingTypes.OPEN_NFT_DIALOG:
 330                        {
 0331                            if (msgPayload is Protocol.OpenNftDialog payload)
 0332                                DataStore.i.common.onOpenNFTPrompt.Set(new NFTPromptModel(payload.contactAddress, payloa
 333                                    payload.comment), true);
 334
 0335                            break;
 336                        }
 337
 338                    default:
 0339                        Debug.LogError($"Unknown method {method}");
 340
 341                        break;
 342                }
 0343            }
 344            catch (Exception e)
 345            {
 0346                Debug.LogException(e);
 0347                Debug.LogError($"Scene message error. scene: {scene.sceneData.id} method: {method} payload: {JsonUtility
 0348            }
 349
 0350            if (delayedComponent != null)
 351            {
 0352                if (delayedComponent.isRoutineRunning)
 0353                    yieldInstruction = delayedComponent.yieldInstruction;
 354            }
 0355        }
 356
 357        public void ParseQuery(object payload, string sceneId)
 358        {
 0359            if (!Environment.i.world.state.TryGetScene(sceneId, out var scene)) return;
 360
 0361            if (!(payload is RaycastQuery raycastQuery))
 0362                return;
 363
 0364            Vector3 worldOrigin = raycastQuery.ray.origin + Utils.GridToWorldPosition(scene.sceneData.basePosition.x, sc
 365
 0366            raycastQuery.ray.unityOrigin = PositionUtils.WorldToUnityPosition(worldOrigin);
 0367            raycastQuery.sceneId = sceneId;
 0368            PhysicsCast.i.Query(raycastQuery, entityIdHelper);
 0369        }
 370
 371        public void SendSceneMessage(string chunk)
 372        {
 0373            var renderer = CommonScriptableObjects.rendererState.Get();
 374
 0375            if (!renderer)
 376            {
 0377                EnqueueChunk(chunk);
 0378            }
 379            else
 380            {
 0381                chunksToDecode.Enqueue(chunk);
 382            }
 0383        }
 384
 385        private QueuedSceneMessage_Scene Decode(string payload, QueuedSceneMessage_Scene queuedMessage)
 386        {
 0387            ProfilingEvents.OnMessageDecodeStart?.Invoke("Misc");
 388
 0389            if (!MessageDecoder.DecodePayloadChunk(payload,
 390                    out string sceneId,
 391                    out string message,
 392                    out string messageTag,
 393                    out PB_SendSceneMessage sendSceneMessage))
 394            {
 0395                return null;
 396            }
 397
 0398            MessageDecoder.DecodeSceneMessage(sceneId, message, messageTag, sendSceneMessage, ref queuedMessage);
 399
 0400            ProfilingEvents.OnMessageDecodeEnds?.Invoke("Misc");
 401
 0402            return queuedMessage;
 403        }
 404
 405        private IEnumerator DeferredDecodingAndEnqueue()
 406        {
 690407            float start = Time.realtimeSinceStartup;
 408            float maxTimeForDecode;
 409
 7234410            while (true)
 411            {
 7924412                maxTimeForDecode = CommonScriptableObjects.rendererState.Get() ? MAX_TIME_FOR_DECODE : float.MaxValue;
 413
 7924414                if (chunksToDecode.TryDequeue(out string chunk))
 415                {
 0416                    EnqueueChunk(chunk);
 417
 0418                    if (Time.realtimeSinceStartup - start < maxTimeForDecode)
 419                        continue;
 420                }
 421
 7924422                yield return null;
 423
 7234424                start = Time.unscaledTime;
 425            }
 426        }
 427        private void EnqueueChunk(string chunk)
 428        {
 0429            string[] payloads = chunk.Split(new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
 0430            var count = payloads.Length;
 431
 0432            for (int i = 0; i < count; i++)
 433            {
 0434                bool availableMessage = sceneMessagesPool.TryDequeue(out QueuedSceneMessage_Scene freeMessage);
 435
 0436                if (availableMessage)
 437                {
 0438                    EnqueueSceneMessage(Decode(payloads[i], freeMessage));
 0439                }
 440                else
 441                {
 0442                    EnqueueSceneMessage(Decode(payloads[i], new QueuedSceneMessage_Scene()));
 443                }
 444            }
 0445        }
 446        private async UniTask WatchForNewChunksToDecode(CancellationToken cancellationToken)
 447        {
 0448            while (!cancellationToken.IsCancellationRequested)
 449            {
 450                try
 451                {
 0452                    if (chunksToDecode.Count > 0)
 453                    {
 0454                        ThreadedDecodeAndEnqueue(cancellationToken);
 455                    }
 0456                }
 457                catch (Exception e)
 458                {
 0459                    Debug.LogException(e);
 0460                }
 461
 0462                await UniTask.Yield();
 463            }
 0464        }
 465        private void ThreadedDecodeAndEnqueue(CancellationToken cancellationToken)
 466        {
 0467            while (chunksToDecode.TryDequeue(out string chunk))
 468            {
 0469                cancellationToken.ThrowIfCancellationRequested();
 470
 0471                string[] payloads = chunk.Split(new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
 0472                var count = payloads.Length;
 473
 0474                for (int i = 0; i < count; i++)
 475                {
 0476                    var payload = payloads[i];
 0477                    bool availableMessage = sceneMessagesPool.TryDequeue(out QueuedSceneMessage_Scene freeMessage);
 478
 0479                    if (availableMessage)
 480                    {
 0481                        EnqueueSceneMessage(Decode(payload, freeMessage));
 0482                    }
 483                    else
 484                    {
 0485                        EnqueueSceneMessage(Decode(payload, new QueuedSceneMessage_Scene()));
 486                    }
 487                }
 0488            }
 0489        }
 490
 491        public void EnqueueSceneMessage(QueuedSceneMessage_Scene message)
 492        {
 0493            bool isGlobalScene = WorldStateUtils.IsGlobalScene(message.sceneId);
 0494            messagingControllersManager.AddControllerIfNotExists(this, message.sceneId);
 0495            messagingControllersManager.Enqueue(isGlobalScene, message);
 0496        }
 497
 498        //======================================================================
 499
 500        #endregion
 501
 502        //======================================================================
 503
 504        //======================================================================
 505
 506        #region SCENES_MANAGEMENT
 507
 508        //======================================================================
 509        public event Action<string> OnReadyScene;
 510
 511        public void SendSceneReady(string sceneId)
 512        {
 415513            messagingControllersManager.SetSceneReady(sceneId);
 514
 415515            WebInterface.ReportControlEvent(new WebInterface.SceneReady(sceneId));
 415516            WebInterface.ReportCameraChanged(CommonScriptableObjects.cameraMode.Get(), sceneId);
 517
 415518            Environment.i.world.blockersController.SetupWorldBlockers();
 519
 415520            OnReadyScene?.Invoke(sceneId);
 2521        }
 522
 10523        public void ActivateBuilderInWorldEditScene() { Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new Scen
 524
 2525        public void DeactivateBuilderInWorldEditScene() { Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new Sc
 526
 527        private void SetPositionDirty(Vector2Int gridPosition, Vector2Int previous)
 528        {
 14529            positionDirty = gridPosition.x != currentGridSceneCoordinate.x || gridPosition.y != currentGridSceneCoordina
 530
 14531            if (positionDirty)
 532            {
 14533                sceneSortDirty = true;
 14534                currentGridSceneCoordinate = gridPosition;
 535
 536                // Since the first position for the character is not sent from Kernel until just-before calling
 537                // the rendering activation from Kernel, we need to sort the scenes to get the current scene id
 538                // to lock the rendering accordingly...
 14539                if (!CommonScriptableObjects.rendererState.Get())
 540                {
 0541                    SortScenesByDistance();
 542                }
 543            }
 14544        }
 545
 546        public void SortScenesByDistance()
 547        {
 548            // if (DCLCharacterController.i == null)
 549            //     return;
 550
 688551            IWorldState worldState = Environment.i.world.state;
 552
 688553            worldState.SortScenesByDistance(currentGridSceneCoordinate);
 554
 688555            string currentSceneId = worldState.GetCurrentSceneId();
 556
 688557            if (!DataStore.i.debugConfig.isDebugMode.Get() && string.IsNullOrEmpty(currentSceneId))
 558            {
 559                // When we don't know the current scene yet, we must lock the rendering from enabling until it is set
 666560                CommonScriptableObjects.rendererState.AddLock(this);
 666561            }
 562            else
 563            {
 564                // 1. Set current scene id
 22565                CommonScriptableObjects.sceneID.Set(currentSceneId);
 566
 567                // 2. Attempt to remove SceneController's lock on rendering
 22568                CommonScriptableObjects.rendererState.RemoveLock(this);
 569            }
 570
 688571            OnSortScenes?.Invoke();
 688572        }
 573
 574        private void OnCurrentSceneIdChange(string newSceneId, string prevSceneId)
 575        {
 79576            if (Environment.i.world.state.TryGetScene(newSceneId, out IParcelScene newCurrentScene)
 577                && !(newCurrentScene as ParcelScene).sceneLifecycleHandler.isReady)
 578            {
 0579                CommonScriptableObjects.rendererState.AddLock(newCurrentScene);
 580
 0581                (newCurrentScene as ParcelScene).sceneLifecycleHandler.OnSceneReady += (readyScene) => { CommonScriptabl
 582            }
 79583        }
 584
 585        public void LoadParcelScenesExecute(string scenePayload)
 586        {
 587            LoadParcelScenesMessage.UnityParcelScene scene;
 588
 28589            ProfilingEvents.OnMessageDecodeStart?.Invoke(MessagingTypes.SCENE_LOAD);
 28590            scene = Utils.SafeFromJson<LoadParcelScenesMessage.UnityParcelScene>(scenePayload);
 28591            ProfilingEvents.OnMessageDecodeEnds?.Invoke(MessagingTypes.SCENE_LOAD);
 592
 28593            if (scene == null || scene.id == null)
 0594                return;
 595
 28596            var sceneToLoad = scene;
 597
 28598            DebugConfig debugConfig = DataStore.i.debugConfig;
 599#if UNITY_EDITOR
 28600            if (debugConfig.soloScene && sceneToLoad.basePosition.ToString() != debugConfig.soloSceneCoords.ToString())
 601            {
 0602                SendSceneReady(sceneToLoad.id);
 603
 0604                return;
 605            }
 606#endif
 607
 28608            ProfilingEvents.OnMessageProcessStart?.Invoke(MessagingTypes.SCENE_LOAD);
 609
 28610            IWorldState worldState = Environment.i.world.state;
 611
 28612            if (!worldState.ContainsScene(sceneToLoad.id))
 613            {
 28614                var newGameObject = new GameObject("New Scene");
 615
 28616                var newScene = newGameObject.AddComponent<ParcelScene>();
 28617                newScene.SetData(sceneToLoad);
 618
 28619                if (debugConfig.isDebugMode.Get())
 620                {
 28621                    newScene.InitializeDebugPlane();
 622                }
 623
 28624                worldState.AddScene(sceneToLoad.id, newScene);
 625
 28626                sceneSortDirty = true;
 627
 28628                OnNewSceneAdded?.Invoke(newScene);
 629
 28630                messagingControllersManager.AddControllerIfNotExists(this, newScene.sceneData.id);
 631
 28632                if (VERBOSE)
 0633                    Debug.Log($"{Time.frameCount}: Load parcel scene (id: {newScene.sceneData.id})");
 634            }
 635
 28636            ProfilingEvents.OnMessageProcessEnds?.Invoke(MessagingTypes.SCENE_LOAD);
 0637        }
 638
 639        public void UpdateParcelScenesExecute(string sceneId)
 640        {
 641            LoadParcelScenesMessage.UnityParcelScene sceneData;
 642
 0643            ProfilingEvents.OnMessageDecodeStart?.Invoke(MessagingTypes.SCENE_UPDATE);
 0644            sceneData = Utils.SafeFromJson<LoadParcelScenesMessage.UnityParcelScene>(sceneId);
 0645            ProfilingEvents.OnMessageDecodeEnds?.Invoke(MessagingTypes.SCENE_UPDATE);
 646
 0647            IWorldState worldState = Environment.i.world.state;
 648
 0649            if (worldState.TryGetScene(sceneData.id, out IParcelScene sceneInterface))
 650            {
 0651                ParcelScene scene = sceneInterface as ParcelScene;
 0652                scene.SetUpdateData(sceneData);
 0653            }
 654            else
 655            {
 0656                LoadParcelScenesExecute(sceneId);
 657            }
 0658        }
 659
 660        public void UpdateParcelScenesExecute(LoadParcelScenesMessage.UnityParcelScene scene)
 661        {
 15662            if (scene == null || scene.id == null)
 0663                return;
 664
 15665            var sceneToLoad = scene;
 666
 15667            ProfilingEvents.OnMessageProcessStart?.Invoke(MessagingTypes.SCENE_UPDATE);
 668
 15669            ParcelScene parcelScene = Environment.i.world.state.GetScene(sceneToLoad.id) as ParcelScene;
 670
 15671            if (parcelScene != null)
 15672                parcelScene.SetUpdateData(sceneToLoad);
 673
 15674            ProfilingEvents.OnMessageProcessEnds?.Invoke(MessagingTypes.SCENE_UPDATE);
 0675        }
 676
 677        public void UnloadScene(string sceneKey)
 678        {
 2679            var queuedMessage = new QueuedSceneMessage()
 680                { type = QueuedSceneMessage.Type.UNLOAD_PARCEL, message = sceneKey };
 681
 2682            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_DESTROY);
 683
 2684            messagingControllersManager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 2685            messagingControllersManager.RemoveController(sceneKey);
 2686        }
 687
 688        public void UnloadParcelSceneExecute(string sceneId)
 689        {
 424690            ProfilingEvents.OnMessageProcessStart?.Invoke(MessagingTypes.SCENE_DESTROY);
 691
 424692            IWorldState worldState = Environment.i.world.state;
 693
 424694            if (!worldState.TryGetScene(sceneId, out ParcelScene scene))
 0695                return;
 696
 424697            worldState.RemoveScene(sceneId);
 698
 424699            DataStore.i.world.portableExperienceIds.Remove(sceneId);
 700
 701            // Remove messaging controller for unloaded scene
 424702            messagingControllersManager.RemoveController(sceneId);
 703
 424704            scene.Cleanup(!CommonScriptableObjects.rendererState.Get());
 705
 424706            if (VERBOSE)
 707            {
 0708                Debug.Log($"{Time.frameCount} : Destroying scene {scene.sceneData.basePosition}");
 709            }
 710
 424711            Environment.i.world.blockersController.SetupWorldBlockers();
 712
 424713            ProfilingEvents.OnMessageProcessEnds?.Invoke(MessagingTypes.SCENE_DESTROY);
 424714            OnSceneRemoved?.Invoke(scene);
 0715        }
 716
 717        public void UnloadAllScenes(bool includePersistent = false)
 718        {
 692719            var worldState = Environment.i.world.state;
 720
 721            // since the list was changing by this foreach, we make a copy
 692722            var list = worldState.GetLoadedScenes().ToArray();
 723
 2222724            foreach (var kvp in list)
 725            {
 419726                if (kvp.Value.isPersistent && !includePersistent)
 727                    continue;
 728
 419729                UnloadParcelSceneExecute(kvp.Key);
 730            }
 692731        }
 732
 733        public void LoadParcelScenes(string decentralandSceneJSON)
 734        {
 28735            var queuedMessage = new QueuedSceneMessage()
 736            {
 737                type = QueuedSceneMessage.Type.LOAD_PARCEL,
 738                message = decentralandSceneJSON
 739            };
 740
 28741            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_LOAD);
 742
 28743            messagingControllersManager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 744
 28745            if (VERBOSE)
 0746                Debug.Log($"{Time.frameCount} : Load parcel scene queue {decentralandSceneJSON}");
 28747        }
 748
 749        public void UpdateParcelScenes(string decentralandSceneJSON)
 750        {
 0751            var queuedMessage = new QueuedSceneMessage()
 752                { type = QueuedSceneMessage.Type.UPDATE_PARCEL, message = decentralandSceneJSON };
 753
 0754            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_UPDATE);
 755
 0756            messagingControllersManager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 0757        }
 758
 759        public void UnloadAllScenesQueued()
 760        {
 0761            var queuedMessage = new QueuedSceneMessage() { type = QueuedSceneMessage.Type.UNLOAD_SCENES };
 762
 0763            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_DESTROY);
 764
 0765            Environment.i.messaging.manager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 0766        }
 767
 768        public void CreateGlobalScene(string json)
 769        {
 770#if UNITY_EDITOR
 5771            DebugConfig debugConfig = DataStore.i.debugConfig;
 772
 5773            if (debugConfig.soloScene && debugConfig.ignoreGlobalScenes)
 0774                return;
 775#endif
 5776            CreateGlobalSceneMessage globalScene = Utils.SafeFromJson<CreateGlobalSceneMessage>(json);
 777
 778            // NOTE(Brian): We should remove this line. SceneController is a runtime core class.
 779            //              It should never have references to UI systems or higher level systems.
 5780            if (globalScene.isPortableExperience && !isPexViewerInitialized.Get())
 781            {
 0782                Debug.LogError(
 783                    "Portable experiences are trying to be added before the system is initialized!. SceneID: " +
 784                    globalScene.id);
 0785                return;
 786            }
 787
 5788            string newGlobalSceneId = globalScene.id;
 789
 5790            IWorldState worldState = Environment.i.world.state;
 791
 5792            if (worldState.ContainsScene(newGlobalSceneId))
 0793                return;
 794
 5795            var newGameObject = new GameObject("Global Scene - " + newGlobalSceneId);
 796
 5797            var newScene = newGameObject.AddComponent<GlobalScene>();
 5798            newScene.unloadWithDistance = false;
 5799            newScene.isPersistent = true;
 5800            newScene.sceneName = globalScene.name;
 5801            newScene.isPortableExperience = globalScene.isPortableExperience;
 802
 5803            LoadParcelScenesMessage.UnityParcelScene data = new LoadParcelScenesMessage.UnityParcelScene
 804            {
 805                id = newGlobalSceneId,
 806                basePosition = new Vector2Int(0, 0),
 807                baseUrl = globalScene.baseUrl,
 808                contents = globalScene.contents
 809            };
 810
 5811            newScene.SetData(data);
 812
 5813            if (!string.IsNullOrEmpty(globalScene.icon))
 814            {
 0815                newScene.iconUrl = newScene.contentProvider.GetContentsUrl(globalScene.icon);
 816            }
 817
 5818            worldState.AddGlobalScene(newGlobalSceneId, newScene);
 5819            OnNewSceneAdded?.Invoke(newScene);
 820
 5821            if (newScene.isPortableExperience)
 822            {
 2823                DataStore.i.world.portableExperienceIds.Add(newGlobalSceneId);
 824            }
 825
 5826            messagingControllersManager.AddControllerIfNotExists(this, newGlobalSceneId, isGlobal: true);
 827
 5828            if (VERBOSE)
 0829                Debug.Log($"Creating Global scene {newGlobalSceneId}");
 5830        }
 831
 832        public void IsolateScene(IParcelScene sceneToActive)
 833        {
 156834            foreach (IParcelScene scene in Environment.i.world.state.GetScenesSortedByDistance())
 835            {
 39836                if (scene != sceneToActive)
 5837                    scene.GetSceneTransform().gameObject.SetActive(false);
 838            }
 39839        }
 840
 841        public void ReIntegrateIsolatedScene()
 842        {
 20843            foreach (IParcelScene scene in Environment.i.world.state.GetScenesSortedByDistance())
 844            {
 5845                scene.GetSceneTransform().gameObject.SetActive(true);
 846            }
 5847        }
 848
 849        //======================================================================
 850
 851        #endregion
 852
 853        //======================================================================
 854
 690855        public ConcurrentQueue<QueuedSceneMessage_Scene> sceneMessagesPool { get; } = new ConcurrentQueue<QueuedSceneMes
 856
 690857        public bool prewarmSceneMessagesPool { get; set; } = true;
 690858        public bool prewarmEntitiesPool { get; set; } = true;
 859
 860        private bool sceneSortDirty = false;
 690861        private bool positionDirty = true;
 862        private int lastSortFrame = 0;
 863
 864        public event Action OnSortScenes;
 865        public event Action<IParcelScene, string> OnOpenExternalUrlRequest;
 866        public event Action<IParcelScene> OnNewSceneAdded;
 867        public event Action<IParcelScene> OnSceneRemoved;
 868
 690869        private Vector2Int currentGridSceneCoordinate = new Vector2Int(EnvironmentSettings.MORDOR_SCALAR, EnvironmentSet
 870    }
 871}

Methods/Properties

enabled()
enabled(System.Boolean)
SceneController()
isPexViewerInitialized()
messagingControllersManager()
entityIdHelper()
Initialize()
SetupDeferredRunners()
PrewarmSceneMessagesPool()
OnDebugModeSet(System.Boolean, System.Boolean)
Dispose()
Update()
LateUpdate()
deferredMessagesDecoding()
deferredMessagesDecoding(System.Boolean)
ProcessMessage(DCL.QueuedSceneMessage_Scene, UnityEngine.CustomYieldInstruction&)
ProcessMessage(DCL.Controllers.ParcelScene, System.String, System.Object, UnityEngine.CustomYieldInstruction&)
ParseQuery(System.Object, System.String)
SendSceneMessage(System.String)
Decode(System.String, DCL.QueuedSceneMessage_Scene)
DeferredDecodingAndEnqueue()
EnqueueChunk(System.String)
WatchForNewChunksToDecode()
ThreadedDecodeAndEnqueue(System.Threading.CancellationToken)
EnqueueSceneMessage(DCL.QueuedSceneMessage_Scene)
SendSceneReady(System.String)
ActivateBuilderInWorldEditScene()
DeactivateBuilderInWorldEditScene()
SetPositionDirty(UnityEngine.Vector2Int, UnityEngine.Vector2Int)
SortScenesByDistance()
OnCurrentSceneIdChange(System.String, System.String)
LoadParcelScenesExecute(System.String)
UpdateParcelScenesExecute(System.String)
UpdateParcelScenesExecute(DCL.Models.LoadParcelScenesMessage/UnityParcelScene)
UnloadScene(System.String)
UnloadParcelSceneExecute(System.String)
UnloadAllScenes(System.Boolean)
LoadParcelScenes(System.String)
UpdateParcelScenes(System.String)
UnloadAllScenesQueued()
CreateGlobalScene(System.String)
IsolateScene(DCL.Controllers.IParcelScene)
ReIntegrateIsolatedScene()
sceneMessagesPool()
prewarmSceneMessagesPool()
prewarmSceneMessagesPool(System.Boolean)
prewarmEntitiesPool()
prewarmEntitiesPool(System.Boolean)