Ejemplo n.º 1
0
 /// <summary>
 /// Harmony prefix to load Plop the Growables data on pre-update.
 /// Never pre-empts.
 /// </summary>
 /// <param name="mode">Loading manager load mode</param>
 public static void Prefix(SimulationManager.UpdateMode mode)
 {
     if (mode == SimulationManager.UpdateMode.LoadGame)
     {
         PlopTheGrowables.LoadData();
     }
 }
Ejemplo n.º 2
0
 void LoadingManager_LevelLoaded(SimulationManager.UpdateMode updateMode)
 {
     if (optionsWindow == null)
     {
         CreateOptionsWindow();
     }
 }
		private static void UpdateData(TreeManager tm, SimulationManager.UpdateMode mode)
		{
			Singleton<LoadingManager>.instance.m_loadingProfilerSimulation.BeginLoading("TreeManager.UpdateData");
            if (TreeUnlimiter.Mod.DEBUG_LOG_ON == true) { Debug.Log("[TreeUnlimiter::LimitTreeManager::UpdateData()] calling Ensure Init"); }
            LimitTreeManager.Helper.EnsureInit(3);
			for (int i = 1; i < LimitTreeManager.Helper.TreeLimit; i++)
			{
				if (tm.m_trees.m_buffer[i].m_flags != 0 && tm.m_trees.m_buffer[i].Info == null)
				{
					tm.ReleaseTree((uint)i);
				}
			}
			int num = PrefabCollection<TreeInfo>.PrefabCount();
			int num1 = 1;
			while (num1 * num1 < num)
			{
				num1++;
			}
			for (int j = 0; j < num; j++)
			{
				TreeInfo prefab = PrefabCollection<TreeInfo>.GetPrefab((uint)j);
				if (prefab != null)
				{
					prefab.SetRenderParameters(j, num1);
				}
			}
			ColossalFramework.Threading.ThreadHelper.dispatcher.Dispatch(() => {
				tm.GetType().GetField("m_lastShadowRotation", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(tm, new Quaternion());
				tm.GetType().GetField("m_lastCameraRotation", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(tm, new Quaternion());
			});
			tm.m_infoCount = num;
			Singleton<LoadingManager>.instance.m_loadingProfilerSimulation.EndLoading();
		}
Ejemplo n.º 4
0
        public static void SpecialInvoke(LevelLoadedHandler e, SimulationManager.UpdateMode mode)
        {
            if (e is null)
            {
                Log.Exception(new ArgumentNullException("e"));
                return;
            }

            Log.Info($"invoking LoadingManager.m_levelLoaded()", copyToGameLog: true);
            Log.Flush();
            sw_total.Reset();
            sw_total.Start();

            foreach (LevelLoadedHandler @delegate in e.GetInvocationList())
            {
                string name = @delegate.Method.FullDescription();
                Log.Info($"invoking " + name, copyToGameLog: true);
                sw.Reset();
                sw.Start();
                try {
                    @delegate(mode);
                    sw.Stop();
                    Log.Info($"{name} successful! " +
                             $"duration = {sw.ElapsedMilliseconds:#,0}ms", copyToGameLog: true);
                } catch (Exception ex) {
                    Log.Exception(ex);
                }
            }
            sw_total.Stop();
            Log.Info($"LoadingManager.m_levelLoaded() successful! " +
                     $"total duration = {sw_total.ElapsedMilliseconds:#,0}ms", copyToGameLog: true);
            Log.Flush();
        }
Ejemplo n.º 5
0
 void LoadingManager_LevelLoaded(SimulationManager.UpdateMode updateMode)
 {
     if (window == null)
     {
         CreateDebuggerWindow();
     }
 }
Ejemplo n.º 6
0
 public void OnLevelLoaded(SimulationManager.UpdateMode mode)
 {
     ProcessLoadingExtensions(mode, " OnLevelLoaded", (e, m) =>
     {
         e.OnLevelLoaded((LoadMode)m);
         return(true);
     });
 }
Ejemplo n.º 7
0
        [RedirectMethod(true)] // Detour reason: Load extra zone data before method is executed
        public static void UpdateData(TerrainManager _this, SimulationManager.UpdateMode mode)
        {
            DataExtension.instance.OnUpdateData();

            // Call original method
            UpdateDataRedirector.Revert();
            _this.UpdateData(mode);
            UpdateDataRedirector.Apply();
        }
Ejemplo n.º 8
0
        public override void UpdateData(SimulationManager.UpdateMode mode)
        {
            // Call
            EventUpdateDataPre?.Invoke(mode);
            EventUpdateData?.Invoke(mode);
            EventUpdateDataPost?.Invoke(mode);

            // Execute original method
            RedirectionHelper.RevertRedirect(_RenderManager_UpdateData_original, _RenderManager_UpdateData_state);
            RenderManager.instance.UpdateData(mode);
            RedirectionHelper.RedirectCalls(_RenderManager_UpdateData_original, _RenderManager_UpdateData_detour);
        }
Ejemplo n.º 9
0
        public void OnPreUpdateData(SimulationManager.UpdateMode mode)
        {
            _lightPropEnabler.OnPreUpdateData();

            ClearSkinData();

            var dataFound = LoadSkinData();

            if (!dataFound)
            {
                LoadLegacySkinData();
            }
        }
Ejemplo n.º 10
0
        public void OnLevelLoaded(SimulationManager.UpdateMode mode)
        {
            InitModTools(mode);

            var loadingManager = LoadingManager.instance;
            var wrapper        = loadingManager.m_LoadingWrapper;

            var loadingExtensions = Util.GetPrivate <List <ILoadingExtension> >(wrapper, "m_LoadingExtensions");

            for (int i = 0; i < loadingExtensions.Count; i++)
            {
                loadingExtensions[i].OnLevelLoaded((LoadMode)mode);
            }
        }
Ejemplo n.º 11
0
        private void OnLevelLoaded(SimulationManager.UpdateMode updateMode)
        {
            OnLevelUnloaded();

            if (updateMode != SimulationManager.UpdateMode.NewGameFromMap &&
                updateMode != SimulationManager.UpdateMode.NewGameFromScenario &&
                updateMode != SimulationManager.UpdateMode.LoadGame)
            {
                return;
            }

            mod.data.Setup();

            SetupUIBindings();
        }
Ejemplo n.º 12
0
        private static void InitModTools(SimulationManager.UpdateMode mode)
        {
            if (!IsModToolsActive())
            {
                return;
            }

            if (modToolsGameObject != null)
            {
                return;
            }

            modToolsGameObject = new GameObject("ModTools");
            modTools           = modToolsGameObject.AddComponent <ModTools>();
            modTools.Initialize(mode);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Like OnLevelLoaded, but executed earlier.
        /// </summary>
        /// <param name="mode"></param>
        public void OnUpdateData(SimulationManager.UpdateMode mode)
        {
            if (mode != SimulationManager.UpdateMode.LoadGame && mode != SimulationManager.UpdateMode.LoadMap)
            {
                return;
            }

            DeserializeSegmentDataMap();
            DeserializeActiveOptions();

            foreach (var segmentData in _usedSegmentData)
            {
                segmentData.UsedCount = SegmentToSegmentDataMap.Count(segmentData.Equals);
                segmentData.FindPrefabs(); // Find the prefabs for the loaded names
            }

            CleanupData();
        }
Ejemplo n.º 14
0
        private void ProcessLoadingExtensions(SimulationManager.UpdateMode mode, string methodName, Func <ILoadingExtension, SimulationManager.UpdateMode, bool> callback)
        {
            var loadingExtensions = (List <ILoadingExtension>)(typeof(LoadingWrapper).
                                                               GetField("m_LoadingExtensions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this));
            var exceptions = new List <Exception>();

            foreach (var loadingExtension in loadingExtensions)
            {
                try
                {
                    callback(loadingExtension, mode);
                }
                catch (Exception ex)
                {
                    UnityEngine.Debug.LogException(ex);
                    exceptions.Add(ex);
                }
            }
            if (exceptions.Count <= 0)
            {
                return;
            }
            var mergedTraces = "";
            var i            = 0;

            exceptions.ForEach((e) =>
            {
                if (e == null)
                {
                    mergedTraces += String.Format("\n---------------------------\n[{0}]: <null exception>", i);
                }
                else
                {
                    mergedTraces += String.Format("\n---------------------------\n[{0}]: {1}\n{2}", i, e.Message, e.StackTrace);
                }
                ++i;
            });
            UIView.ForwardException(new ModException(String.Format("{0} - Some mods caused errors:", mode),
                                                     new Exception(mergedTraces)));
        }
Ejemplo n.º 15
0
        public static void StartSession(string mapName, string playerMap, SimulationManager.UpdateMode mode, SimulationMetaData ngs)
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableStartSession))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("Start Session telemetry disabled.");
                    }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent("start_session", new Telemetry.Pair[]
                {
                    new Telemetry.Pair("type", playerMap),
                    new Telemetry.Pair("start_flag", mode.ToString()),
                    new Telemetry.Pair("map_name", Path.GetFileName(mapName))
                });
                if (ngs != null)
                {
                    telemetry.AddEvent("start_session", new Telemetry.Pair[]
                    {
                        new Telemetry.Pair("environment", ngs.m_environment),
                        new Telemetry.Pair("invert_traffic", ngs.m_invertTraffic),
                        new Telemetry.Pair("guid", ngs.m_gameInstanceIdentifier)
                    });
                }
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Ejemplo n.º 16
0
        public override void OnLevelLoaded(LoadMode mode)
        {
            SimulationManager.UpdateMode updateMode = SimulationManager.instance.m_metaData.m_updateMode;
            Log.Info($"OnLevelLoaded({mode}) called. updateMode={updateMode}");
            base.OnLevelLoaded(mode);

            Log._Debug("OnLevelLoaded Returned from base, calling custom code.");

            IsGameLoaded = false;
            switch (updateMode)
            {
            case SimulationManager.UpdateMode.NewGameFromMap:
            case SimulationManager.UpdateMode.NewGameFromScenario:
            case SimulationManager.UpdateMode.LoadGame:
                if (BuildConfig.applicationVersion != BuildConfig.VersionToString(TrafficManagerMod.GameVersion, false))
                {
                    string[] majorVersionElms = BuildConfig.applicationVersion.Split('-');
                    string[] versionElms      = majorVersionElms[0].Split('.');
                    uint     versionA         = Convert.ToUInt32(versionElms[0]);
                    uint     versionB         = Convert.ToUInt32(versionElms[1]);
                    uint     versionC         = Convert.ToUInt32(versionElms[2]);

                    Log.Info($"Detected game version v{BuildConfig.applicationVersion}");

                    bool isModTooOld = TrafficManagerMod.GameVersionA < versionA ||
                                       (TrafficManagerMod.GameVersionA == versionA && TrafficManagerMod.GameVersionB < versionB) /* ||
                                                                                                                                  * (TrafficManagerMod.GameVersionA == versionA && TrafficManagerMod.GameVersionB == versionB && TrafficManagerMod.GameVersionC < versionC)*/;

                    bool isModNewer = TrafficManagerMod.GameVersionA < versionA ||
                                      (TrafficManagerMod.GameVersionA == versionA && TrafficManagerMod.GameVersionB > versionB) /* ||
                                                                                                                                 * (TrafficManagerMod.GameVersionA == versionA && TrafficManagerMod.GameVersionB == versionB && TrafficManagerMod.GameVersionC > versionC)*/;

                    if (isModTooOld)
                    {
                        string msg = $"Traffic Manager: President Edition detected that you are running a newer game version ({BuildConfig.applicationVersion}) than TM:PE has been built for ({BuildConfig.VersionToString(TrafficManagerMod.GameVersion, false)}). Please be aware that TM:PE has not been updated for the newest game version yet and thus it is very likely it will not work as expected.";
                        Log.Error(msg);
                        Singleton <SimulationManager> .instance.m_ThreadingWrapper.QueueMainThread(() => {
                            UIView.library.ShowModal <ExceptionPanel>("ExceptionPanel").SetMessage("TM:PE has not been updated yet", msg, false);
                        });
                    }
                    else if (isModNewer)
                    {
                        string msg = $"Traffic Manager: President Edition has been built for game version {BuildConfig.VersionToString(TrafficManagerMod.GameVersion, false)}. You are running game version {BuildConfig.applicationVersion}. Some features of TM:PE will not work with older game versions. Please let Steam update your game.";
                        Log.Error(msg);
                        Singleton <SimulationManager> .instance.m_ThreadingWrapper.QueueMainThread(() => {
                            UIView.library.ShowModal <ExceptionPanel>("ExceptionPanel").SetMessage("Your game should be updated", msg, false);
                        });
                    }
                }
                IsGameLoaded = true;
                break;

            default:
                Log.Info($"OnLevelLoaded: Unsupported game mode {mode}");
                return;
            }

            if (!IsPathManagerReplaced)
            {
                try {
                    Log.Info("Pathfinder Compatible. Setting up CustomPathManager and SimManager.");
                    var pathManagerInstance = typeof(Singleton <PathManager>).GetField("sInstance", BindingFlags.Static | BindingFlags.NonPublic);

                    var stockPathManager = PathManager.instance;
                    Log._Debug($"Got stock PathManager instance {stockPathManager.GetName()}");

                    CustomPathManager = stockPathManager.gameObject.AddComponent <CustomPathManager>();
                    Log._Debug("Added CustomPathManager to gameObject List");

                    if (CustomPathManager == null)
                    {
                        Log.Error("CustomPathManager null. Error creating it.");
                        return;
                    }

                    CustomPathManager.UpdateWithPathManagerValues(stockPathManager);
                    Log._Debug("UpdateWithPathManagerValues success");

                    pathManagerInstance?.SetValue(null, CustomPathManager);

                    Log._Debug("Getting Current SimulationManager");
                    var simManager =
                        typeof(SimulationManager).GetField("m_managers", BindingFlags.Static | BindingFlags.NonPublic)?
                        .GetValue(null) as FastList <ISimulationManager>;

                    Log._Debug("Removing Stock PathManager");
                    simManager?.Remove(stockPathManager);

                    Log._Debug("Adding Custom PathManager");
                    simManager?.Add(CustomPathManager);

                    Object.Destroy(stockPathManager, 10f);

                    Log._Debug("Should be custom: " + Singleton <PathManager> .instance.GetType().ToString());

                    IsPathManagerReplaced = true;
                } catch (Exception ex) {
                    string error = "Traffic Manager: President Edition failed to load. You can continue playing but it's NOT recommended. Traffic Manager will not work as expected.";
                    Log.Error(error);
                    Log.Error($"Path manager replacement error: {ex.ToString()}");
                    Singleton <SimulationManager> .instance.m_ThreadingWrapper.QueueMainThread(() => {
                        UIView.library.ShowModal <ExceptionPanel>("ExceptionPanel").SetMessage("TM:PE failed to load", error, true);
                    });
                }
            }

            Log.Info("Adding Controls to UI.");
            if (BaseUI == null)
            {
                Log._Debug("Adding UIBase instance.");
                BaseUI = ToolsModifierControl.toolController.gameObject.AddComponent <UIBase>();
            }

            // Init transport demand UI
            if (TransportDemandUI == null)
            {
                var uiView = UIView.GetAView();
                TransportDemandUI = (UITransportDemand)uiView.AddUIComponent(typeof(UITransportDemand));
            }

            // add "remove vehicle" button
            UIView.GetAView().gameObject.AddComponent <RemoveVehicleButtonExtender>();

            // add "remove citizen instance" button
            UIView.GetAView().gameObject.AddComponent <RemoveCitizenInstanceButtonExtender>();

            initDetours();

            //Log.Info("Fixing non-created nodes with problems...");
            //FixNonCreatedNodeProblems();

            Log.Info("Notifying managers...");
            foreach (ICustomManager manager in RegisteredManagers)
            {
                Log.Info($"OnLevelLoading: {manager.GetType().Name}");
                manager.OnLevelLoading();
            }

            //InitTool();
            //Log._Debug($"Current tool: {ToolManager.instance.m_properties.CurrentTool}");

            Log.Info("OnLevelLoaded complete.");
        }
        public IEnumerator LoadLevelCoroutine(Package.Asset asset, string playerScene, string uiScene, SimulationMetaData ngs)
        {
            string scene;

            yield return(null);

            LoadingManager.instance.SetSceneProgress(0f);
            Util.InvokeVoid(LoadingManager.instance, "PreLoadLevel");
            AsyncTask task = Singleton <SimulationManager> .instance.AddAction("Loading", (IEnumerator)Util.Invoke(LoadingManager.instance, "LoadSimulationData", asset, ngs));

            LoadSaveStatus.activeTask = task;

            if (!LoadingManager.instance.LoadingAnimationComponent.AnimationLoaded)
            {
                LoadingManager.instance.m_loadingProfilerScenes.BeginLoading("LoadingAnimation");
                yield return(SceneManager.LoadSceneAsync("LoadingAnimation", LoadSceneMode.Additive));

                LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
            }

            if (LoadingManager.instance.m_loadedEnvironment == null) // loading from main menu
            {
                knownToFail.Clear();
                fastLoad = false;
            }
            else // loading from in-game (the pause menu)
            {
                while (!LoadingManager.instance.m_metaDataLoaded && !task.completedOrFailed) // IL_139
                {
                    yield return(null);
                }

                if (SimulationManager.instance.m_metaData == null)
                {
                    SimulationManager.instance.m_metaData = new SimulationMetaData();
                    SimulationManager.instance.m_metaData.m_environment = "Sunny";
                    SimulationManager.instance.m_metaData.Merge(ngs);
                }

                Util.InvokeVoid(LoadingManager.instance, "MetaDataLoaded");
                string mapThemeName = SimulationManager.instance.m_metaData.m_MapThemeMetaData?.name;
                fastLoad = SimulationManager.instance.m_metaData.m_environment == LoadingManager.instance.m_loadedEnvironment && mapThemeName == LoadingManager.instance.m_loadedMapTheme;

                // The game is nicely optimized when loading from the pause menu. We must specifically address the following situation:
                // - environment (biome) stays the same
                // - map theme stays the same
                // - 'load used assets' is enabled
                // - not all assets and prefabs used in the save being loaded are currently in memory.

                if (fastLoad)
                {
                    if (Settings.settings.loadUsed)
                    {
                        int startMillis = Profiling.Millis;

                        while (Profiling.Millis - startMillis < 5000 && !IsSaveDeserialized())
                        {
                            yield return(null);
                        }

                        fastLoad = !AnyMissingAssets();
                    }

                    if (fastLoad) // optimized load
                    {
                        LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "EssentialScenesLoaded"));
                        LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "RenderDataReady"));
                    }
                    else // fallback to full load
                    {
                        DestroyLoadedPrefabs();
                        LoadingManager.instance.m_loadedEnvironment = null;
                        LoadingManager.instance.m_loadedMapTheme    = null;
                    }
                }
                else // full load
                {
                    // Notice that there is a race condition in the base game at this point: DestroyAllPrefabs ruins the simulation
                    // if its deserialization has progressed far enough. Typically there is no problem.
                    Util.InvokeVoid(LoadingManager.instance, "DestroyAllPrefabs");
                    LoadingManager.instance.m_loadedEnvironment = null;
                    LoadingManager.instance.m_loadedMapTheme    = null;
                }
            }

            if (LoadingManager.instance.m_loadedEnvironment == null) // IL_27C
            {
                AsyncOperation op;

                if (!string.IsNullOrEmpty(playerScene))
                {
                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(playerScene);
                    op = SceneManager.LoadSceneAsync(playerScene, LoadSceneMode.Single);

                    while (!op.isDone) // IL_2FF
                    {
                        LoadingManager.instance.SetSceneProgress(op.progress * 0.1f);
                        yield return(null);
                    }

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                }

                while (!LoadingManager.instance.m_metaDataLoaded && !task.completedOrFailed) // IL_33C
                {
                    yield return(null);
                }

                if (SimulationManager.instance.m_metaData == null)
                {
                    SimulationManager.instance.m_metaData = new SimulationMetaData();
                    SimulationManager.instance.m_metaData.m_environment = "Sunny";
                    SimulationManager.instance.m_metaData.Merge(ngs);
                }

                Util.InvokeVoid(LoadingManager.instance, "MetaDataLoaded");
                KeyValuePair <string, float>[] levels = SetLevels();
                float currentProgress = 0.10f;

                for (int i = 0; i < levels.Length; i++)
                {
                    scene = levels[i].Key;

                    if (string.IsNullOrEmpty(scene)) // just a marker to stop prefab skipping
                    {
                        PrefabLoader.instance?.Revert();
                        continue;
                    }

                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(scene);
                    op = SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive);

                    while (!op.isDone)
                    {
                        LoadingManager.instance.SetSceneProgress(currentProgress + op.progress * (levels[i].Value - currentProgress));
                        yield return(null);
                    }

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                    currentProgress = levels[i].Value;
                }

                if (Settings.settings.SkipAny)
                {
                    yield return(null);

                    PrefabLoader.instance?.DestroySkipped();
                    yield return(null);

                    try
                    {
                        Resources.UnloadUnusedAssets();
                    }
                    catch (Exception e)
                    {
                        UnityEngine.Debug.LogException(e);
                    }

                    yield return(null);

                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    yield return(null);
                }

                // LoadingManager.instance.QueueLoadingAction((IEnumerator) Util.Invoke(LoadingManager.instance, "LoadCustomContent")); // IL_B65
                LoadingManager.instance.QueueLoadingAction(AssetLoader.instance.LoadCustomContent());
                RenderManager.Managers_CheckReferences();
                LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "EssentialScenesLoaded"));
                RenderManager.Managers_InitRenderData();
                LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "RenderDataReady"));
                simulationFailed = HasFailed(task);

                // Performance optimization: do not load scenes while custom assets are loading.
                while (!AssetLoader.instance.hasFinished)
                {
                    yield return(null);
                }

                scene = SimulationManager.instance.m_metaData.m_environment + "Properties";

                if (!string.IsNullOrEmpty(scene))
                {
                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(scene);
                    op = SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive);

                    while (!op.isDone) // IL_C47
                    {
                        LoadingManager.instance.SetSceneProgress(0.74f + op.progress * 0.05f);
                        yield return(null);
                    }

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                }

                if (!simulationFailed)
                {
                    simulationFailed = HasFailed(task);
                }

                if (!string.IsNullOrEmpty(uiScene)) // IL_C67
                {
                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(uiScene);
                    op = SceneManager.LoadSceneAsync(uiScene, LoadSceneMode.Additive);

                    while (!op.isDone) // IL_CDE
                    {
                        LoadingManager.instance.SetSceneProgress(0.79f + op.progress * 0.2f);
                        yield return(null);
                    }

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                }

                LoadingManager.instance.m_loadedEnvironment = SimulationManager.instance.m_metaData.m_environment; // IL_CFE
                LoadingManager.instance.m_loadedMapTheme    = SimulationManager.instance.m_metaData.m_MapThemeMetaData?.name;
            }
            else
            {
                scene = (string)Util.Invoke(LoadingManager.instance, "GetLoadingScene");

                if (!string.IsNullOrEmpty(scene))
                {
                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(scene);
                    yield return(SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive));

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                }
            }

            LoadingManager.instance.SetSceneProgress(1f); // IL_DBF

            if (!simulationFailed)
            {
                simulationFailed = HasFailed(task);
            }

            while (!task.completedOrFailed) // IL_DED
            {
                yield return(null);
            }

            LoadingManager.instance.m_simulationDataLoaded = LoadingManager.instance.m_metaDataLoaded;
            LoadingManager.SimulationDataReadyHandler SimDataReady = Util.Get(LoadingManager.instance, "m_simulationDataReady") as LoadingManager.SimulationDataReadyHandler;
            SimDataReady?.Invoke();
            SimulationManager.UpdateMode mode = SimulationManager.UpdateMode.Undefined;

            if (ngs != null)
            {
                mode = ngs.m_updateMode;
            }

            LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "LoadLevelComplete", mode));

            if (Singleton <TelemetryManager> .exists)
            {
                Singleton <TelemetryManager> .instance.StartSession(asset?.name, playerScene, mode, SimulationManager.instance.m_metaData);
            }

            PrefabLoader.instance?.Dispose();
        }
Ejemplo n.º 18
0
 public void UpdateData(SimulationManager.UpdateMode mode)
 {
     // we -only- want this. ffs.
     Base.mode = mode;
 }
Ejemplo n.º 19
0
 void ISimulationManager.UpdateData(SimulationManager.UpdateMode mode)
 {
 }
Ejemplo n.º 20
0
        public void UpdateData(SimulationManager.UpdateMode mode)
        {
            try
            {
                lightPropsDefParseErrors = new HashSet <string>();
                var checkedPaths = new List <string>();

                for (uint i = 0; i < PrefabCollection <PropInfo> .LoadedCount(); i++)
                {
                    var prefab = PrefabCollection <PropInfo> .GetLoaded(i);

                    if (prefab == null)
                    {
                        continue;
                    }

                    // search for LightPropDefinition.xml
                    var asset = PackageManager.FindAssetByName(prefab.name);

                    var crpPath = asset?.package?.packagePath;
                    if (crpPath == null)
                    {
                        continue;
                    }

                    var lightPropsDefPath = Path.Combine(Path.GetDirectoryName(crpPath) ?? "",
                                                         "LightPropsDefinition.xml");

                    // skip files which were already parsed
                    if (checkedPaths.Contains(lightPropsDefPath))
                    {
                        continue;
                    }
                    checkedPaths.Add(lightPropsDefPath);

                    if (!File.Exists(lightPropsDefPath))
                    {
                        continue;
                    }

                    LightPropsDefinition lightPropsDef = null;

                    var xmlSerializer = new XmlSerializer(typeof(LightPropsDefinition));
                    try
                    {
                        using (var streamReader = new System.IO.StreamReader(lightPropsDefPath))
                        {
                            lightPropsDef = xmlSerializer.Deserialize(streamReader) as LightPropsDefinition;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                        lightPropsDefParseErrors.Add(asset.package.packageName + " - " + e.Message);
                        continue;
                    }

                    if (lightPropsDef?.Props == null || lightPropsDef.Props.Count == 0)
                    {
                        lightPropsDefParseErrors.Add(asset.package.packageName + " - lightPropDef is null or empty.");
                        continue;
                    }

                    foreach (var propDef in lightPropsDef.Props)
                    {
                        if (propDef?.Name == null)
                        {
                            lightPropsDefParseErrors.Add(asset.package.packageName + " - Prop name missing.");
                            continue;
                        }

                        var propDefPrefab = FindProp(propDef.Name, asset.package.packageName);

                        if (propDefPrefab == null)
                        {
                            lightPropsDefParseErrors.Add(asset.package.packageName + " - Prop with name " + propDef.Name +
                                                         " not loaded.");
                            continue;
                        }

                        if (propDef.Effects == null || propDef.Effects.Count == 0)
                        {
                            lightPropsDefParseErrors.Add(asset.package.packageName + " - No effects specified for " +
                                                         propDef.Name + ".");
                            continue;
                        }

                        var effects = new List <PropInfo.Effect>();

                        foreach (var effectDef in propDef.Effects)
                        {
                            if (effectDef?.Name == null)
                            {
                                lightPropsDefParseErrors.Add(propDef.Name + " - Effect name missing.");
                                continue;
                            }

                            var effectPrefab = EffectCollection.FindEffect(effectDef.Name);

                            if (effectPrefab == null)
                            {
                                lightPropsDefParseErrors.Add(propDef.Name + " - Effect with name " + effectDef.Name +
                                                             " not loaded.");
                                continue;
                            }

                            if (effectDef.Position == null)
                            {
                                lightPropsDefParseErrors.Add(propDef.Name + " - Effect position not set.");
                                continue;
                            }

                            if (effectDef.Direction == null)
                            {
                                lightPropsDefParseErrors.Add(propDef.Name + " - Effect direction not set.");
                                continue;
                            }

                            var effect = new PropInfo.Effect
                            {
                                m_effect    = effectPrefab,
                                m_position  = effectDef.Position.ToUnityVector(),
                                m_direction = effectDef.Direction.ToUnityVector().normalized
                            };

                            effects.Add(effect);
                        }

                        if (effects.Count == 0)
                        {
                            lightPropsDefParseErrors.Add("No effects specified for " + propDef.Name + ".");
                            continue;
                        }

                        propDefPrefab.m_effects = effects.ToArray();

                        // taken from PropInfo.InitializePrefab
                        if (propDefPrefab.m_effects != null)
                        {
                            propDefPrefab.m_hasEffects = (propDefPrefab.m_effects.Length != 0);
                            for (var j = 0; j < propDefPrefab.m_effects.Length; j++)
                            {
                                if (propDefPrefab.m_effects[j].m_effect == null)
                                {
                                    continue;
                                }

                                propDefPrefab.m_effects[j].m_effect.InitializeEffect();
                                var layer = propDefPrefab.m_effects[j].m_effect.GroupLayer();
                                if (layer != -1)
                                {
                                    propDefPrefab.m_effectLayer = layer;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
        }
Ejemplo n.º 21
0
 public void LateUpdateData(SimulationManager.UpdateMode mode)
 {
     // This is where RefreshMilestones is called, in another manager.
 }
Ejemplo n.º 22
0
 private void OnLevelLoaded(SimulationManager.UpdateMode mode)
 {
     UnityEngine.Debug.Log("Lalala");
 }
Ejemplo n.º 23
0
        public IEnumerator LoadLevelCoroutine(Package.Asset asset, string playerScene, string uiScene, SimulationMetaData ngs)
        {
            string scene;
            int    i;

            yield return(null);

            Util.InvokeVoid(LoadingManager.instance, "PreLoadLevel");

            if (!LoadingManager.instance.LoadingAnimationComponent.AnimationLoaded)
            {
                LoadingManager.instance.m_loadingProfilerScenes.BeginLoading("LoadingAnimation");
                yield return(SceneManager.LoadSceneAsync("LoadingAnimation", LoadSceneMode.Additive));

                LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
            }

            AsyncTask task = Singleton <SimulationManager> .instance.AddAction("Loading", (IEnumerator)Util.Invoke(LoadingManager.instance, "LoadSimulationData", asset, ngs));

            LoadSaveStatus.activeTask = task;

            if (LoadingManager.instance.m_loadedEnvironment == null) // loading from main menu
            {
                knownFailedAssets.Clear();
                fastLoad = false;
            }
            else // loading from in-game (the pause menu)
            {
                while (!LoadingManager.instance.m_metaDataLoaded && !task.completedOrFailed) // IL_139
                {
                    yield return(null);
                }

                if (SimulationManager.instance.m_metaData == null)
                {
                    SimulationManager.instance.m_metaData = new SimulationMetaData();
                    SimulationManager.instance.m_metaData.m_environment = "Sunny";
                    SimulationManager.instance.m_metaData.Merge(ngs);
                }

                Util.InvokeVoid(LoadingManager.instance, "MetaDataLoaded"); // No OnCreated
                string mapThemeName = SimulationManager.instance.m_metaData.m_MapThemeMetaData?.name;
                fastLoad = SimulationManager.instance.m_metaData.m_environment == LoadingManager.instance.m_loadedEnvironment && mapThemeName == LoadingManager.instance.m_loadedMapTheme;

                // The game is nicely optimized when loading from the pause menu. We must specifically address the following situation:
                // - environment (biome) stays the same
                // - map theme stays the same
                // - 'load used assets' is enabled
                // - not all assets used in the save being loaded are currently in memory.

                if (fastLoad)
                {
                    if (Settings.settings.loadUsed && !IsKnownFastLoad(asset))
                    {
                        i = Profiling.Millis;

                        while (Profiling.Millis - i < 5000 && !IsSaveDeserialized())
                        {
                            yield return(null);
                        }

                        fastLoad = AllAssetsAvailable();
                    }

                    if (fastLoad) // optimized load
                    {
                        LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "EssentialScenesLoaded"));
                        LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "RenderDataReady"));
                        Util.DebugPrint("fast load at", Profiling.Millis);
                    }
                    else // fallback to full load
                    {
                        DestroyLoadedPrefabs();
                        LoadingManager.instance.m_loadedEnvironment = null;
                        LoadingManager.instance.m_loadedMapTheme    = null;
                        Util.DebugPrint("not fast load at", Profiling.Millis);
                    }
                }
                else // full load
                {
                    // Notice that there is a race condition in the base game at this point: DestroyAllPrefabs ruins the simulation
                    // if its deserialization has progressed far enough. Typically there is no problem.
                    Util.InvokeVoid(LoadingManager.instance, "DestroyAllPrefabs");
                    LoadingManager.instance.m_loadedEnvironment = null;
                    LoadingManager.instance.m_loadedMapTheme    = null;
                    Util.DebugPrint("full load at", Profiling.Millis);
                }
            }

            if (LoadingManager.instance.m_loadedEnvironment == null) // IL_27C
            {
                AsyncOperation op;
                knownFastLoads.Clear();
                fullLoadTime = DateTime.Now;
                loadingLock  = Util.Get(LoadingManager.instance, "m_loadingLock");

                if (!string.IsNullOrEmpty(playerScene))
                {
                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(playerScene);
                    op = SceneManager.LoadSceneAsync(playerScene, LoadSceneMode.Single);

                    while (!op.isDone) // IL_2FF
                    {
                        LoadingManager.instance.SetSceneProgress(op.progress * 0.01f);
                        yield return(null);
                    }

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                }

                while (!LoadingManager.instance.m_metaDataLoaded && !task.completedOrFailed) // IL_33C
                {
                    yield return(null);
                }

                if (SimulationManager.instance.m_metaData == null)
                {
                    SimulationManager.instance.m_metaData = new SimulationMetaData();
                    SimulationManager.instance.m_metaData.m_environment = "Sunny";
                    SimulationManager.instance.m_metaData.Merge(ngs);
                }

                Util.InvokeVoid(LoadingManager.instance, "MetaDataLoaded"); // OnCreated if loading from the main manu
                KeyValuePair <string, float>[] levels = SetLevels();
                float currentProgress = 0.10f;

                for (i = 0; i < levels.Length; i++)
                {
                    scene = levels[i].Key;
                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(scene);
                    op = SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive);

                    while (!op.isDone)
                    {
                        LoadingManager.instance.SetSceneProgress(currentProgress + op.progress * (levels[i].Value - currentProgress));
                        yield return(null);
                    }

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                    currentProgress = levels[i].Value;
                }

                Queue <IEnumerator> mainThreadQueue;

                // Some major mods (Network Extensions 1 & 2, Single Train Track, Metro Overhaul) have a race condition issue
                // in their NetInfo Installer. Everything goes fine if LoadCustomContent() below is NOT queued before the
                // said Installers have finished. This is just a workaround for the issue. The actual fix should be in
                // the Installers. Notice that the built-in loader of the game is also affected.

                do
                {
                    yield return(null);

                    yield return(null);

                    lock (loadingLock)
                    {
                        mainThreadQueue = (Queue <IEnumerator>)queueField.GetValue(LoadingManager.instance);
                        i = mainThreadQueue.Count;
                    }
                }while (i > 0);

                LoadingManager.instance.QueueLoadingAction(AssetLoader.instance.LoadCustomContent());
                RenderManager.Managers_CheckReferences();
                LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "EssentialScenesLoaded"));
                RenderManager.Managers_InitRenderData();
                LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "RenderDataReady"));
                simulationFailed = HasFailed(task);

                // Performance optimization: do not load scenes while custom assets are loading.
                while (!AssetLoader.instance.hasFinished)
                {
                    yield return(null);
                }

                scene = SimulationManager.instance.m_metaData.m_environment + "Properties";

                if (!string.IsNullOrEmpty(scene))
                {
                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(scene);
                    op = SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive);

                    while (!op.isDone) // IL_C47
                    {
                        LoadingManager.instance.SetSceneProgress(0.85f + op.progress * 0.05f);
                        yield return(null);
                    }

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                }

                if (!simulationFailed)
                {
                    simulationFailed = HasFailed(task);
                }

                if (!string.IsNullOrEmpty(uiScene)) // IL_C67
                {
                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(uiScene);
                    op = SceneManager.LoadSceneAsync(uiScene, LoadSceneMode.Additive);

                    while (!op.isDone) // IL_CDE
                    {
                        LoadingManager.instance.SetSceneProgress(0.90f + op.progress * 0.08f);
                        yield return(null);
                    }

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                }

                LoadingManager.instance.m_loadedEnvironment = SimulationManager.instance.m_metaData.m_environment; // IL_CFE
                LoadingManager.instance.m_loadedMapTheme    = SimulationManager.instance.m_metaData.m_MapThemeMetaData?.name;
            }
            else
            {
                scene = (string)Util.Invoke(LoadingManager.instance, "GetLoadingScene");

                if (!string.IsNullOrEmpty(scene))
                {
                    LoadingManager.instance.m_loadingProfilerScenes.BeginLoading(scene);
                    yield return(SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive));

                    LoadingManager.instance.m_loadingProfilerScenes.EndLoading();
                }
            }

            LoadingManager.instance.SetSceneProgress(1f); // IL_DBF

            if (!simulationFailed)
            {
                simulationFailed = HasFailed(task);
            }

            while (!task.completedOrFailed) // IL_DED
            {
                yield return(null);
            }

            LoadingManager.instance.m_simulationDataLoaded = LoadingManager.instance.m_metaDataLoaded;
            LoadingManager.SimulationDataReadyHandler SimDataReady = Util.Get(LoadingManager.instance, "m_simulationDataReady") as LoadingManager.SimulationDataReadyHandler;
            SimDataReady?.Invoke();
            SimulationManager.UpdateMode mode = SimulationManager.UpdateMode.Undefined;

            if (ngs != null)
            {
                mode = ngs.m_updateMode;
            }

            LoadingManager.instance.QueueLoadingAction((IEnumerator)Util.Invoke(LoadingManager.instance, "LoadLevelComplete", mode));  // OnLevelLoaded

            if (Singleton <TelemetryManager> .exists)
            {
                Singleton <TelemetryManager> .instance.StartSession(asset?.name, playerScene, mode, SimulationManager.instance.m_metaData);
            }

            LoadingManager.instance.QueueLoadingAction(LoadingComplete());
            knownFastLoads.Add(asset.fullName);
            AssetLoader.instance.PrintMem();
        }
        public override void OnLevelLoaded(LoadMode mode)
        {
            SimulationManager.UpdateMode updateMode = SimulationManager.instance.m_metaData.m_updateMode;
            string scene = SceneManager.GetActiveScene().name;

            Log.Info($"OnLevelLoaded({mode}) called. updateMode={updateMode}, scene={scene}");

            if (scene == "ThemeEditor")
            {
                return;
            }

            IsGameLoaded = false;

            if (BuildConfig.applicationVersion != BuildConfig.VersionToString(
                    TrafficManagerMod.GAME_VERSION,
                    false))
            {
                string[] majorVersionElms = BuildConfig.applicationVersion.Split('-');
                string[] versionElms      = majorVersionElms[0].Split('.');
                uint     versionA         = Convert.ToUInt32(versionElms[0]);
                uint     versionB         = Convert.ToUInt32(versionElms[1]);
                uint     versionC         = Convert.ToUInt32(versionElms[2]);

                Log.Info($"Detected game version v{BuildConfig.applicationVersion}");

                bool isModTooOld = TrafficManagerMod.GAME_VERSION_A < versionA ||
                                   (TrafficManagerMod.GAME_VERSION_A == versionA &&
                                    TrafficManagerMod.GAME_VERSION_B < versionB);
                // || (TrafficManagerMod.GameVersionA == versionA
                // && TrafficManagerMod.GameVersionB == versionB
                // && TrafficManagerMod.GameVersionC < versionC);

                bool isModNewer = TrafficManagerMod.GAME_VERSION_A < versionA ||
                                  (TrafficManagerMod.GAME_VERSION_A == versionA &&
                                   TrafficManagerMod.GAME_VERSION_B > versionB);
                // || (TrafficManagerMod.GameVersionA == versionA
                // && TrafficManagerMod.GameVersionB == versionB
                // && TrafficManagerMod.GameVersionC > versionC);

                if (isModTooOld)
                {
                    string msg = string.Format(
                        "Traffic Manager: President Edition detected that you are running " +
                        "a newer game version ({0}) than TM:PE has been built for ({1}). " +
                        "Please be aware that TM:PE has not been updated for the newest game " +
                        "version yet and thus it is very likely it will not work as expected.",
                        BuildConfig.applicationVersion,
                        BuildConfig.VersionToString(TrafficManagerMod.GAME_VERSION, false));

                    Log.Error(msg);
                    Singleton <SimulationManager> .instance.m_ThreadingWrapper.QueueMainThread(
                        () => {
                        UIView.library
                        .ShowModal <ExceptionPanel>("ExceptionPanel")
                        .SetMessage(
                            "TM:PE has not been updated yet",
                            msg,
                            false);
                    });
                }
                else if (isModNewer)
                {
                    string msg = string.Format(
                        "Traffic Manager: President Edition has been built for game version {0}. " +
                        "You are running game version {1}. Some features of TM:PE will not " +
                        "work with older game versions. Please let Steam update your game.",
                        BuildConfig.VersionToString(TrafficManagerMod.GAME_VERSION, false),
                        BuildConfig.applicationVersion);

                    Log.Error(msg);
                    Singleton <SimulationManager>
                    .instance.m_ThreadingWrapper.QueueMainThread(
                        () => {
                        UIView.library
                        .ShowModal <ExceptionPanel>("ExceptionPanel")
                        .SetMessage(
                            "Your game should be updated",
                            msg,
                            false);
                    });
                }
            }

            IsGameLoaded = true;

            //it will replace stock PathManager or already Replaced before HotReload
            if (!IsPathManagerReplaced || TrafficManagerMod.Instance.InGameHotReload)
            {
                try {
                    Log.Info("Pathfinder Compatible. Setting up CustomPathManager and SimManager.");
                    FieldInfo pathManagerInstance = typeof(Singleton <PathManager>).GetField(
                        "sInstance",
                        BindingFlags.Static | BindingFlags.NonPublic);
                    if (pathManagerInstance == null)
                    {
                        throw new Exception("pathManagerInstance is null");
                    }


                    PathManager stockPathManager = PathManager.instance;
                    if (stockPathManager == null)
                    {
                        throw new Exception("stockPathManager is null");
                    }

                    Log._Debug($"Got stock PathManager instance {stockPathManager?.GetName()}");

                    CustomPathManager =
                        stockPathManager.gameObject.AddComponent <CustomPathManager>();
                    Log._Debug("Added CustomPathManager to gameObject List");

                    if (CustomPathManager == null)
                    {
                        Log.Error("CustomPathManager null. Error creating it.");
                        return;
                    }

                    CustomPathManager.UpdateWithPathManagerValues(stockPathManager);
                    Log._Debug("UpdateWithPathManagerValues success");

                    pathManagerInstance.SetValue(null, CustomPathManager);

                    Log._Debug("Getting Current SimulationManager");
                    var simManager = this.simManager;
                    if (simManager == null)
                    {
                        throw new Exception("simManager is null");
                    }

                    Log._Debug("Removing Stock PathManager");
                    simManager.Remove(stockPathManager);

                    Log._Debug("Adding Custom PathManager");
                    simManager.Add(CustomPathManager);

                    Object.Destroy(stockPathManager, 10f);

                    Log._Debug("Should be custom: " + Singleton <PathManager> .instance.GetType());

                    IsPathManagerReplaced = true;
                }
                catch (Exception ex) {
                    string error =
                        "Traffic Manager: President Edition failed to load. You can continue " +
                        "playing but it's NOT recommended. Traffic Manager will not work as expected.";
                    Log.Error(error);
                    Log.Error($"Path manager replacement error: {ex}");

                    Singleton <SimulationManager> .instance.m_ThreadingWrapper.QueueMainThread(
                        () => {
                        UIView.library
                        .ShowModal <ExceptionPanel>(
                            "ExceptionPanel")
                        .SetMessage(
                            "TM:PE failed to load",
                            error,
                            true);
                    });
                }
            }

            ModUI.OnLevelLoaded();
            if (PlayMode)
            {
                // Init transport demand UI
                if (TransportDemandUI == null)
                {
                    UIView uiView = UIView.GetAView();
                    TransportDemandUI = (UITransportDemand)uiView.AddUIComponent(typeof(UITransportDemand));
                }

                // add "remove vehicle" button
                UIView.GetAView().gameObject.AddComponent <RemoveVehicleButtonExtender>();

                // add "remove citizen instance" button
                UIView.GetAView().gameObject.AddComponent <RemoveCitizenInstanceButtonExtender>();

                UIView.GetAView().gameObject.AddComponent <RoadSelectionPanels>();
            }

            Patcher.Create().Install();

            // Log.Info("Fixing non-created nodes with problems...");
            // FixNonCreatedNodeProblems();
            Log.Info("Notifying managers...");
            foreach (ICustomManager manager in RegisteredManagers)
            {
                Log.Info($"OnLevelLoading: {manager.GetType().Name}");
                manager.OnLevelLoading();
            }

            // InitTool();
            // Log._Debug($"Current tool: {ToolManager.instance.m_properties.CurrentTool}");
            Log.Info("OnLevelLoaded complete.");
        }
			private static void Deserialize(TreeManager.Data data, DataSerializer s)
			{
				short num;
				short num1;
                if (TreeUnlimiter.Mod.DEBUG_LOG_ON == true) { Debug.Log("[TreeUnlimiter::LimitTreeManager::Data:Deserialize()] calling Ensure Init"); }
                LimitTreeManager.Helper.EnsureInit(1);
				Singleton<LoadingManager>.instance.m_loadingProfilerSimulation.BeginDeserialize(s, "TreeManager");
				TreeManager treeManager = Singleton<TreeManager>.instance;
				TreeInstance[] mBuffer = treeManager.m_trees.m_buffer;
                if(TreeUnlimiter.Mod.DEBUG_LOG_ON == true) { Debug.Log("[TreeUnlimiter::LimitTreeManager::Data:Deserialize()] mbuffersize=" + mBuffer.Length.ToString()); }
                uint[] mTreeGrid = treeManager.m_treeGrid;
				int num2 = 262144;
				int length = (int)mTreeGrid.Length;
				treeManager.m_trees.ClearUnused();
				SimulationManager.UpdateMode mUpdateMode = Singleton<SimulationManager>.instance.m_metaData.m_updateMode;
                if (TreeUnlimiter.Mod.DEBUG_LOG_ON == true) { Debug.LogFormat("[TreeUnlimiter:LimitTreeManager::Data::Deserialize()] mUpdatemode" + mUpdateMode.ToString()); }
                bool flag = (mUpdateMode == SimulationManager.UpdateMode.NewAsset ? true : mUpdateMode == SimulationManager.UpdateMode.LoadAsset);

                for (int i = 0; i < length; i++)
				{
					mTreeGrid[i] = 0;
				}
				EncodedArray.UShort num3 = EncodedArray.UShort.BeginRead(s);
				for (int j = 1; j < num2; j++)
				{
					mBuffer[j].m_flags = num3.Read();
				}
				num3.EndRead();
				PrefabCollection<TreeInfo>.BeginDeserialize(s);
				for (int k = 1; k < num2; k++)
				{
					if (mBuffer[k].m_flags != 0)
					{
						mBuffer[k].m_infoIndex = (ushort)PrefabCollection<TreeInfo>.Deserialize();
					}
				}
				PrefabCollection<TreeInfo>.EndDeserialize(s);
				EncodedArray.Short num4 = EncodedArray.Short.BeginRead(s);
				for (int l = 1; l < num2; l++)
				{
					if (mBuffer[l].m_flags == 0)
					{
						num = 0;
					}
					else
					{
						num = num4.Read();
					}
					mBuffer[l].m_posX = num;
				}
				num4.EndRead();
				EncodedArray.Short num5 = EncodedArray.Short.BeginRead(s);
				for (int m = 1; m < num2; m++)
				{
					if (mBuffer[m].m_flags == 0)
					{
						num1 = 0;
					}
					else
					{
						num1 = num5.Read();
					}
					mBuffer[m].m_posZ = num1;
				}
				num5.EndRead();
				for (int n = 1; n < num2; n++)
				{
					mBuffer[n].m_nextGridTree = 0;
					mBuffer[n].m_posY = 0;
				}
				if (LimitTreeManager.Helper.UseModifiedTreeCap)
				{
                    if (TreeUnlimiter.Mod.DEBUG_LOG_ON == true) { Debug.LogFormat("[TreeUnlimiter::LimitTreeManager::Data:Deserialize()] Using ModifiedTreeCap - Calling Custom Deserializer."); }
					LimitTreeManager.CustomSerializer.Deserialize();
				}
				treeManager.m_trees.ClearUnused();
				for (int o = 0; o < LimitTreeManager.Helper.TreeLimit; o++)
				{
					if (mBuffer[o].m_flags == 0)
					{
						treeManager.m_trees.ReleaseItem((uint)o);
					}
					else
					{
						LimitTreeManager.InitializeTree(treeManager, (uint)o, ref mBuffer[o], flag);
					}
				}
				Singleton<LoadingManager>.instance.m_loadingProfilerSimulation.EndDeserialize(s, "TreeManager");
			}
 private void OnLevelLoaded(SimulationManager.UpdateMode mode)
 {
     this.ResetUndoBuffer();
 }
Ejemplo n.º 27
0
 private static void OnLevelLoaded(SimulationManager.UpdateMode updateMode)
 {
     LoadingManager.instance.m_introLoaded -= OnIntroLoaded;
     LoadingManager.instance.m_levelLoaded -= OnLevelLoaded;
     Show();
 }
 public virtual void UpdateData(SimulationManager.UpdateMode mode)
 {
 }
Ejemplo n.º 29
0
 public void LateUpdateData(SimulationManager.UpdateMode mode)
 {
 }
Ejemplo n.º 30
0
        public void Initialize(SimulationManager.UpdateMode _updateMode)
        {
            updateMode = _updateMode;

            if (!loggingInitialized)
            {
                Application.logMessageReceived += (condition, trace, type) =>
                {
                    if (!logExceptionsToConsole)
                    {
                        return;
                    }

                    if (Instance.console != null)
                    {
                        Instance.console.AddMessage(String.Format("{0} ({1})", condition, trace), type, true);
                        return;
                    }

                    if (type == LogType.Error || type == LogType.Exception || type == LogType.Assert)
                    {
                        Log.Error(condition);
                    }
                    else if (type == LogType.Warning)
                    {
                        Log.Warning(condition);
                    }
                    else
                    {
                        Log.Message(condition);
                    }
                };

                loggingInitialized = true;
            }

            sceneExplorer = gameObject.AddComponent<SceneExplorer>();
            watches = gameObject.AddComponent<Watches>();
            colorPicker = gameObject.AddComponent<ColorPicker>();

            sceneExplorerColorConfig = gameObject.AddComponent<SceneExplorerColorConfig>();

            LoadConfig();

            if (extendGamePanels && (updateMode == SimulationManager.UpdateMode.NewGame || updateMode == SimulationManager.UpdateMode.LoadGame))
            {
                panelExtender = gameObject.AddComponent<GamePanelExtender>();
            }

            if (useModToolsConsole)
            {
                console = gameObject.AddComponent<Console>();
            }

            if (config.hookUnityLogging)
            {
                UnityLoggingHook.EnableHook();
            }

            if (updateMode == SimulationManager.UpdateMode.Undefined && config.improvedWorkshopIntegration)
            {
                ImprovedWorkshopIntegration.Bootstrap();
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Like OnLevelLoaded, but executed earlier.
        /// </summary>
        /// <param name="mode"></param>
        public void OnUpdateData(SimulationManager.UpdateMode mode)
        {
            if (mode != SimulationManager.UpdateMode.LoadMap && mode != SimulationManager.UpdateMode.NewMap &&
                mode != SimulationManager.UpdateMode.LoadGame && mode != SimulationManager.UpdateMode.NewGameFromMap &&
                mode != SimulationManager.UpdateMode.NewGameFromScenario)
            {
                return;
            }

            // no trees
            _availableTrees.Add(null);

            for (uint i = 0; i < PrefabCollection <TreeInfo> .LoadedCount(); i++)
            {
                var prefab = PrefabCollection <TreeInfo> .GetLoaded(i);

                if (prefab == null)
                {
                    continue;
                }

                _availableTrees.Add(prefab);
            }

            // no street lights
            _availableStreetLights.Add(null);

            for (uint i = 0; i < PrefabCollection <PropInfo> .LoadedCount(); i++)
            {
                var prefab = PrefabCollection <PropInfo> .GetLoaded(i);

                if (prefab == null)
                {
                    continue;
                }
                if (prefab.m_class.m_service == ItemClass.Service.Road ||
                    prefab.m_class.m_subService == ItemClass.SubService.PublicTransportPlane ||
                    prefab.name.ToLower().Contains("streetlamp") || prefab.name.ToLower().Contains("streetlight") || prefab.name.ToLower().Contains("lantern"))
                {
                    if (prefab.m_effects != null && prefab.m_effects.Length > 0)
                    {
                        if (prefab.name.ToLower().Contains("taxiway"))
                        {
                            continue;
                        }
                        if (prefab.name.ToLower().Contains("runway"))
                        {
                            continue;
                        }

                        if (prefab.m_effects.Where(effect => effect.m_effect != null).Any(effect => effect.m_effect is LightEffect))
                        {
                            _availableStreetLights.Add(prefab);
                        }
                    }
                }
            }

            // compile list of data indices for fast check if a prefab is a street light:
            StreetLightPrefabDataIndices = _availableStreetLights.Where(prop => prop != null).Select(prop => prop.m_prefabDataIndex).ToArray();
        }