예제 #1
0
        protected float GetAdjustedChancePercentage()
        {
            float additionalAmount = 0;

            if (m_eventData.m_incentives != null && m_eventIncentives != null)
            {
                List <CityEventXmlIncentive> xmlIncentives = m_eventIncentives.ToList();

                foreach (CityEventDataIncentives dataIncentive in m_eventData.m_incentives)
                {
                    CityEventXmlIncentive foundIncentive = xmlIncentives.Find(incentive => incentive._name == dataIncentive.name);

                    if (foundIncentive != null)
                    {
                        if (dataIncentive.boughtItems < dataIncentive.itemCount || (!m_eventData.m_userEvent && foundIncentive._activeWhenRandomEvent))
                        {
                            additionalAmount += foundIncentive._positiveEffect;
                        }
                        else
                        {
                            additionalAmount -= foundIncentive._negativeEffect;
                        }
                    }
                }
            }

            LoggingWrapper.Log("Adjusting percentage for event. Adjusting by " + additionalAmount.ToString());

            return(additionalAmount);
        }
예제 #2
0
        private static Localisation LoadLocalisation(string potentialLocalisation)
        {
            LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Message, $"Attempting to load localisation from {potentialLocalisation}...");

            try
            {
                var localisationFileContents = File.ReadAllText(potentialLocalisation);
                var serialiser = Serialiser;

                using (var textReader = new StringReader(localisationFileContents))
                {
                    if (serialiser.Deserialize(textReader) is Localisation localisation)
                    {
                        _localisations.Add(localisation);

                        LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Message, $"Loaded!");

                        return(localisation);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Error, $"Failed to load localisation at {potentialLocalisation}!");
                LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, ex);
            }

            return(null);
        }
예제 #3
0
        private void LoadLegacyTimeData()
        {
            CityEventManager eventManager = CityEventManager.instance;

            CimTools.CimToolsHandler.LegacyCimToolBase.SaveFileOptions.LoadData(serializableDataManager);

            CimTools.CimToolsHandler.LegacyCimToolBase.SaveFileOptions.Data.GetValue("CityTimeDay", ref Data.CityTime.day);
            CimTools.CimToolsHandler.LegacyCimToolBase.SaveFileOptions.Data.GetValue("CityTimeMonth", ref Data.CityTime.month);
            CimTools.CimToolsHandler.LegacyCimToolBase.SaveFileOptions.Data.GetValue("CityTimeYear", ref Data.CityTime.year);

            bool loaded = Data.CityTime.day != 0 && Data.CityTime.month != 0 && Data.CityTime.year != 0;

            if (loaded)
            {
                eventManager.UpdateTime();
                LoggingWrapper.Log("Loaded legacy date data. Time: " + Data.CityTime.day + "/" + Data.CityTime.month + "/" + Data.CityTime.year);
            }
            else
            {
                Data.CityTime.year  = CityEventManager.CITY_TIME.Year;
                Data.CityTime.month = CityEventManager.CITY_TIME.Month;
                Data.CityTime.day   = CityEventManager.CITY_TIME.Day;

                LoggingWrapper.Log("Initially setting up time: " + Data.CityTime.day + "/" + Data.CityTime.month + "/" + Data.CityTime.year);
            }
        }
예제 #4
0
        public void PrintMonuments()
        {
            BuildingManager _buildingManager = Singleton <BuildingManager> .instance;

            if (_buildingManager != null)
            {
                FastList <ushort> monuments = _buildingManager.GetServiceBuildings(ItemClass.Service.Monument);

                if (ExperimentsToggle.PrintAllMonuments)
                {
                    Debug.Log("Available monuments:");

                    for (int index = 0; index < monuments.m_size; ++index)
                    {
                        Building monument = _buildingManager.m_buildings.m_buffer[monuments.m_buffer[index]];

                        if ((monument.m_flags & Building.Flags.Created) != Building.Flags.None)
                        {
                            Debug.Log(monument.Info.name);
                            LoggingWrapper.Log(monument.Info.name);
                        }
                    }
                }
            }
        }
예제 #5
0
        public static bool PatchAll()
        {
            var patchSuccess = false;

            LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"Patching...");

            try
            {
                LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"Patching {PatchAssembly.GetName().Name}...");

                patchSuccess = Patcher.PatchAll();

                LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, "Done!");
            }
            catch (Exception ex)
            {
                LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Error, $"Couldn't patch the required methods!");
                LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, ex, true);
            }

            if (!patchSuccess)
            {
                MessageBoxWrapper.Show(MessageBoxWrapper.MessageType.Warning,
                                       $"{Details.ModName} couldn't start", $"{Details.ModName} couldn't fully start due to an issue overriding parts of the game.\n\n" +
                                       $"This is likely due to a recent update to Cities, and in order to prevent potential compatibility issues {Details.BaseModName} has disabled some functionality by reverting changes until a solution is found. This will result in most mod functionaity being disabled.\n\n" +
                                       $"If this has not previously been reported please do so, otherwise an update to the mod is required to fix the incompatibilites.");

                UnPatchAll();
            }

            return(patchSuccess);
        }
예제 #6
0
        public static bool UnPatchAll()
        {
            var unpatchSuccess = false;

            try
            {
                LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"Removing patching for {PatchAssembly.GetName().Name}...");

                var patchedMethods = HarmonyInstanceHolder.Instance.GetPatchedMethods();
                foreach (var patchedMethod in patchedMethods)
                {
                    HarmonyInstanceHolder.Instance.Unpatch(patchedMethod, Harmony.HarmonyPatchType.All, HarmonyInstanceHolder.Instance.Id);
                }

                LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, "Done!");

                unpatchSuccess = true;
            }
            catch (Exception ex)
            {
                LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Error, $"Couldn't unpatch everything!");
                LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, ex, true);
            }

            return(unpatchSuccess);
        }
예제 #7
0
        public void SetUp(LabelOptionItem selectedData, ushort buildingID)
        {
            _linkedEvent = selectedData.linkedEvent;

            if (_linkedEvent != null && buildingID != 0 && _ticketSlider != null)
            {
                List <CityEventXmlIncentive> incentives = _linkedEvent.GetIncentives();

                title = _linkedEvent.GetReadableName();

                _ticketSlider.maxValue = _linkedEvent.GetCapacity();
                _ticketSlider.minValue = Mathf.Min(_linkedEvent.GetCapacity(), 100);
                _ticketSlider.value    = _ticketSlider.minValue;

                _incentiveList.rowsData.Clear();

                foreach (CityEventXmlIncentive incentive in incentives)
                {
                    IncentiveOptionItem optionItem = new IncentiveOptionItem()
                    {
                        cost           = incentive._cost,
                        description    = incentive._description,
                        negativeEffect = incentive._negativeEffect,
                        positiveEffect = incentive._positiveEffect,
                        returnCost     = incentive._returnCost,
                        title          = incentive._name,
                        ticketCount    = _ticketSlider.value
                    };
                    optionItem.OnOptionItemChanged += OptionItem_OnOptionItemChanged;

                    _incentiveList.rowsData.Add(optionItem);
                }

                try
                {
                    _incentiveList.DisplayAt(0);
                    _incentiveList.selectedIndex = 0;
                    _incentiveList.Show();
                }
                catch
                {
                    LoggingWrapper.LogError("IncentiveList DisplayAt hit an error. Probably too few items in the list.");
                }

                _incentiveList.Refresh();

                CalculateTotal();
                TranslateInfoString();
                PerformLayout();

                LoggingWrapper.Log("Event capacity is " + _linkedEvent.GetCapacity().ToString() + ".");
                LoggingWrapper.Log("Successfully set up the UserEventCreationWindow.");
            }
            else
            {
                LoggingWrapper.LogError("Linked event was invalid, or the building was 0!");
            }

            relativePosition = Vector3.zero;
        }
예제 #8
0
        private static void UpdateEventSelection(UIComponent component)
        {
            UIFastList list = component as UIFastList;

            if (list != null)
            {
                LabelOptionItem selectedOption = list.selectedItem as LabelOptionItem;

                if (selectedOption != null && eventCreationWindow != null)
                {
                    eventCreationWindow.Show();
                    eventCreationWindow.SetUp(selectedOption, lastInstanceID.Value.Building);
                    eventCreationWindow.relativePosition = list.relativePosition + new Vector3(-(list.width / 2f), list.height);

                    LoggingWrapper.Log("Selected " + list.selectedIndex);
                }
                else
                {
                    LoggingWrapper.LogError("Couldn't find the option that has been selected for an event!");
                }
            }
            else
            {
                LoggingWrapper.LogError("Couldn't find the list that the selection was made on!");
            }
        }
예제 #9
0
        public virtual string GetCitizenMessageInitialised()
        {
            string chosenMessage = "";

            if (m_eventInitialisedMessages.Count > 0)
            {
                if (m_eventInitialisedMessages.Count < 4)
                {
                    LoggingWrapper.LogWarning("Event " + m_eventData.m_eventName + " has less than 4 messages for the initialisation. This could get boring.");
                }

                int   days                  = (m_eventData.m_eventStartTime - CityEventManager.CITY_TIME).Days;
                float eventLength           = (float)GetEventLength();
                int   roundedEventLength    = Mathf.FloorToInt(eventLength);
                float eventLengthDifference = eventLength - roundedEventLength;

                string dayString         = days < 1 ? "less than a day" : days + " day" + (days > 1 ? "s" : "");
                string ticketString      = GetCapacity() + " tickets";
                string eventLengthString = (eventLengthDifference > 0.1 ? "more than " : "") + roundedEventLength + " hour" + (roundedEventLength > 1 ? "s" : "") + " long";

                int randomIndex = Singleton <SimulationManager> .instance.m_randomizer.Int32(1, m_eventInitialisedMessages.Count) - 1;

                chosenMessage = string.Format(m_eventInitialisedMessages[randomIndex], dayString, ticketString, eventLengthString);
            }

            LoggingWrapper.Log("Event chirped initialised \"" + chosenMessage + "\"");
            return(chosenMessage);
        }
예제 #10
0
        public static string GetTranslationFor(string text, string toIsoCode, string fromIsoCode = "en-gb")
        {
            LoggingWrapper.Log(LoggingWrapper.LogArea.File, LoggingWrapper.LogType.Message, $"Translating {text} into {toIsoCode} from {fromIsoCode}...");

            try
            {
                var safeText = WWW.EscapeURL(text);
                var request  = new Request("get", $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={fromIsoCode}&tl={toIsoCode}&dt=t&q={safeText}");
                request.AddHeader("Accept-Language", "en");
                request.acceptGzip = false;

                request.Send();

                var timeout = DateTime.Now + TimeSpan.FromSeconds(5);

                while (!request.isDone || DateTime.Now > timeout)
                {
                    Thread.Sleep(10);
                }

                if (request.response != null)
                {
                    return(GetTranslation(request.response));
                }
            }
            catch (Exception ex)
            {
                LoggingWrapper.Log(LoggingWrapper.LogArea.File, LoggingWrapper.LogType.Error, "There was an issue trying to get an automatic translation from Google Translate");
                LoggingWrapper.Log(LoggingWrapper.LogArea.File, ex);
            }

            return(null);
        }
예제 #11
0
        public static bool Load()
        {
            LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Message, $"Attempting to load settings from {SaveFilePath}");

            var success = false;

            try
            {
                if (File.Exists(SaveFilePath))
                {
                    using (var saveFile = File.OpenRead(SaveFilePath))
                    {
                        var serialiser = Serialiser;
                        _settingsHolder = serialiser.Deserialize(saveFile) as UserModSettingsHolder;

                        LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Message, $"Loaded settings from {SaveFilePath}");
                    }

                    success = true;
                }

                CheckIfModHasUpdated();
            }
            catch (Exception ex)
            {
                LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Error, $"Unable to load settings from {SaveFilePath}");
                LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, ex);
            }

            return(success);
        }
예제 #12
0
        public CityEvent GetEventForBuilding(ref Building thisBuilding, List <CityEventXml> xmlEvents)
        {
            CityEvent _buildingEvent = null;
            List <CityEventXmlContainer> _validEvents       = new List <CityEventXmlContainer>();
            SimulationManager            _simulationManager = Singleton <SimulationManager> .instance;

            foreach (CityEventXml xmlEvent in xmlEvents)
            {
                foreach (CityEventXmlContainer containedEvent in xmlEvent._containedEvents)
                {
                    if (containedEvent._eventBuildingClassName == thisBuilding.Info.name && containedEvent._supportsRandomEvents)
                    {
                        _validEvents.Add(containedEvent);
                    }
                }
            }

            if (_validEvents.Count > 0)
            {
                CityEventXmlContainer pickedEvent = _validEvents[_simulationManager.m_randomizer.Int32((uint)_validEvents.Count)];

                if (pickedEvent != null)
                {
                    _buildingEvent = new XmlEvent(pickedEvent);
                }
            }
            else
            {
                LoggingWrapper.Log("Couldn't find any events for " + thisBuilding.Info.name);
            }

            return(_buildingEvent);
        }
예제 #13
0
        public static void WriteLog(LoggingWrapper.LogArea logArea)
        {
            if (UserModSettings.Settings.Log_Citizen_Status)
            {
                lock (_logLockObject)
                {
                    var activityValues     = Enum.GetValues(typeof(Activity));
                    var output             = new List <string>();
                    var citizenManager     = CitizenManager.instance;
                    var vehicleCount       = VehicleManager.instance.m_vehicleCount;
                    var citizenCount       = CitizenManager.instance.m_instanceCount;
                    var percentageVehicles = (vehicleCount / (double)VehicleManager.MAX_VEHICLE_COUNT) * 100d;
                    var percentageCitizens = (citizenCount / (double)CitizenManager.MAX_CITIZEN_COUNT) * 100d;

                    foreach (Activity activity in activityValues)
                    {
                        var citizensForActivity = _activitiesLog.Where(citizenLog => citizenLog.Value == activity);
                        var agesForActivity     = citizensForActivity.GroupBy(citizenLog => Citizen.GetAgeGroup(citizenManager.m_citizens.m_buffer[citizenLog.Key].Age));
                        var ageOutput           = new List <string>();
                        var total = 0;

                        foreach (var ageForActivity in agesForActivity)
                        {
                            ageOutput.Add($"[{ageForActivity.Count()} {ageForActivity.Key}]");

                            total += ageForActivity.Count();
                        }

                        output.Add($"{activity.ToString()}: {string.Join(" ", ageOutput.ToArray())} (total: {total})");
                    }

                    LoggingWrapper.Log(logArea, LoggingWrapper.LogType.Message, $"Current activities: \n{string.Join("\n", output.ToArray())}\nCitizen instances: {percentageCitizens}%, Vehicle instances: {percentageVehicles}%");
                }
            }
        }
예제 #14
0
        public CityEvent GetXmlEventFromData(CityEventData data)
        {
            CityEvent dataEvent = null;

            if (data.m_eventName != "")
            {
                foreach (CityEventXml xmlEvent in CityEventManager.instance.m_xmlEvents)
                {
                    foreach (CityEventXmlContainer containedEvent in xmlEvent._containedEvents)
                    {
                        if ("XMLEvent-" + containedEvent._name == data.m_eventName)
                        {
                            dataEvent             = new XmlEvent(containedEvent);
                            dataEvent.m_eventData = data;
                            LoggingWrapper.Log("Created an XML event: " + data.m_eventName);
                            break;
                        }
                    }

                    if (dataEvent != null)
                    {
                        break;
                    }
                }
            }

            return(dataEvent);
        }
예제 #15
0
        public void AddEvent(CityEvent eventToAdd)
        {
            if (eventToAdd != null)
            {
                BuildingManager buildingManager = Singleton <BuildingManager> .instance;
                Building        monument        = buildingManager.m_buildings.m_buffer[eventToAdd.m_eventData.m_eventBuilding];

                if ((monument.m_flags & Building.Flags.Active) != Building.Flags.None && (monument.m_flags & Building.Flags.Created) != Building.Flags.None)
                {
                    m_nextEvents.Add(eventToAdd);

                    string message = eventToAdd.GetCitizenMessageInitialised();

                    if (message != "")
                    {
                        MessageManager _messageManager = Singleton <MessageManager> .instance;
                        _messageManager.QueueMessage(new CitizenCustomMessage(_messageManager.GetRandomResidentID(), message));
                    }

                    LoggingWrapper.Log("Event created at " + monument.Info.name + " for " + eventToAdd.m_eventData.m_eventStartTime.ToShortDateString() + ". Current date: " + CITY_TIME.ToShortDateString());

                    Debug.Log("Event starting at " + eventToAdd.m_eventData.m_eventStartTime.ToLongTimeString() + ", " + eventToAdd.m_eventData.m_eventStartTime.ToShortDateString());
                    Debug.Log("Event building is " + monument.Info.name);
                    Debug.Log("Current date: " + CITY_TIME.ToLongTimeString() + ", " + CITY_TIME.ToShortDateString());
                }
                else
                {
                    LoggingWrapper.LogError("Couldn't create an event, as the building is inactive or not created!");
                }
            }
            else
            {
                LoggingWrapper.LogError("Couldn't create an event, as it was null!");
            }
        }
예제 #16
0
        /// <summary>
        /// <para>Call [[CimToolsRushHour.CimToolsHandler.CimToolBase.XMLFileOptions.Data.GetValue]], reporting any errors to [[DebugOutputPanel]].</para>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns>Whether the value was retrieved</returns>
        private static bool safelyGetValue <T>(string name, ref T value, bool legacy)
        {
            bool success = false;

            if (legacy)
            {
                success = CimTools.CimToolsHandler.LegacyCimToolBase.XMLFileOptions.Data.GetValue(name, ref value, "IngameOptions", true) == CimToolsRushHour.Legacy.File.ExportOptionBase.OptionError.NoError;
                CimTools.CimToolsHandler.CimToolBase.ModPanelOptions.SetOptionValue(name, value);
                CimTools.CimToolsHandler.CimToolBase.ModPanelOptions.SaveOptions();
            }
            else
            {
                success = CimTools.CimToolsHandler.CimToolBase.ModPanelOptions.GetOptionValue(name, ref value);
            }

            if (!success)
            {
                LoggingWrapper.LogError(string.Format("An error occurred trying to fetch '{0}'.", name));
            }
            else
            {
                LoggingWrapper.Log("Option \"" + name + "\" is " + value);
            }

            return(success);
        }
예제 #17
0
        public void OnSettingsUI(UIHelperBase helper)
        {
            LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"{Name} is creating settings.");

            _settingsHelper = helper;

            LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"{Name} has created settings.");
        }
예제 #18
0
        public static bool SaveDefault()
        {
            LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Message, $"Updating default en-gb localisation.");

            var defaultLocalisation = new Localisation();
            var exampleFilePath     = Path.Combine(LocalisationFilePath, "en-gb.xml");

            return(Save(defaultLocalisation, exampleFilePath));
        }
예제 #19
0
 private static void BuildCreationWindow(UIComponent parent)
 {
     if (eventCreationWindow == null)
     {
         eventCreationWindow      = parent.AddUIComponent <UserEventCreationWindow>();
         eventCreationWindow.name = "EventCreator";
         LoggingWrapper.Log("Creating a new UserEventCreationWindow");
         eventCreationWindow.Hide();
     }
 }
예제 #20
0
        public void OnDisabled()
        {
            LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"{Name} has been disabled.");

            PatchManager.UnPatchAll();

            LoadingManager.instance.m_introLoaded -= OnIntroLoaded;

            LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"{Name} has finished disabling.");
        }
예제 #21
0
        public static void OnSetTarget(BuildingWorldInfoPanel thisPanel)
        {
            FieldInfo m_TimeInfo = typeof(BuildingWorldInfoPanel).GetField("m_Time", BindingFlags.NonPublic | BindingFlags.Instance);
            float?    m_Time     = m_TimeInfo.GetValue(thisPanel) as float?;

            if (m_Time != null)
            {
                m_NameField = thisPanel.Find <UITextField>("BuildingName");

                if (m_NameField != null)
                {
                    if (originalNameWidth == -1)
                    {
                        originalNameWidth = m_NameField.width;
                    }

                    m_NameField.text = GetName(thisPanel);
                    m_Time           = 0.0f;

                    CityServiceWorldInfoPanel servicePanel = thisPanel as CityServiceWorldInfoPanel;

                    if (servicePanel != null)
                    {
                        LoggingWrapper.Log("Adding event UI to service panel.");
                        AddEventUI(servicePanel);

                        if (!translationSetUp)
                        {
                            translationSetUp = true;

                            CimTools.CimToolsHandler.CimToolBase.Translation.OnLanguageChanged += delegate(string languageIdentifier)
                            {
                                UIButton createEventButton = null;

                                try { createEventButton = servicePanel.Find <UIButton>("CreateEventButton"); } catch { }

                                if (createEventButton != null)
                                {
                                    createEventButton.tooltip = CimTools.CimToolsHandler.CimToolBase.Translation.GetTranslation("Event_CreateUserEvent");
                                    createEventButton.RefreshTooltip();
                                }
                            };
                        }
                    }
                }
                else
                {
                    Debug.LogError("Couldn't set the m_NameField parameter of the BuildingWorldInfoPanel");
                }
            }
            else
            {
                Debug.LogError("Couldn't set the m_Time parameter of the BuildingWorldInfoPanel");
            }
        }
예제 #22
0
        public static bool Patch(IPatchable patchable)
        {
            var patchableName = patchable?.GetType()?.Name;
            var repatchTries  = 1;

            while (repatchTries <= REPATCH_TRY_TIMES)
            {
                try
                {
                    var original = patchable.BaseMethod;
                    var prefix   = patchable.Prefix;
                    var postfix  = patchable.Postfix;

                    try
                    {
                        if (original != null && (prefix != null || postfix != null))
                        {
                            var originalInstanceString = $"{original.Name}({string.Join(", ", original.GetParameters().Select(parameter => parameter.ParameterType.Name).ToArray())})";
                            var prefixInstanceString   = prefix != null ? $"{prefix.Name}({string.Join(", ", prefix.GetParameters().Select(parameter => parameter.ParameterType.Name).ToArray())})" : "";
                            var postfixInstanceString  = postfix != null ? $"{postfix.Name}({string.Join(", ", postfix.GetParameters().Select(parameter => parameter.ParameterType.Name).ToArray())})" : "";

                            LoggingWrapper.Log(LoggingWrapper.LogArea.File, LoggingWrapper.LogType.Message, $"Attempting to patch {originalInstanceString} to prefix: {prefixInstanceString} or postfix: {postfixInstanceString} (try {repatchTries})");

                            HarmonyInstanceHolder.Instance.Patch(original, new HarmonyMethod(prefix), new HarmonyMethod(postfix));

                            LoggingWrapper.Log(LoggingWrapper.LogArea.File, LoggingWrapper.LogType.Message, $"Patched {originalInstanceString}");

                            return(true);
                        }
                        else
                        {
                            LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Error, $"Couldn't patch {patchableName} onto {original?.Name ?? "null"}!");
                        }
                    }
                    catch (Exception ex)
                    {
                        LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Error, $"Couldn't patch {patchableName} onto {original?.Name ?? "null"}!");
                        LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, ex);
                    }
                }
                catch (Exception ex)
                {
                    LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Error, $"Patchable {patchableName ?? "unknown"} is invalid!");
                    LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, ex);
                }

                ++repatchTries;

                Thread.Sleep(REPATCH_WAIT_TIME);
            }

            return(false);
        }
예제 #23
0
        public void OnEnabled()
        {
            LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"{Name} has been enabled.");

            LoadingManager.instance.m_introLoaded += OnIntroLoaded;

            LocalisationHolder.Load();
            UserModSettings.Load();
            LocalisationHolder.ChangeLocalisationFromName(UserModSettings.Settings.Language);

            LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"{Name} has finished enabling.");
        }
예제 #24
0
        private void Initialise()
        {
            if (_panel == null)
            {
                UIView view = UIView.GetAView();

                LoggingWrapper.Log("Creating event popup panel");
                _panel = LoadingExtension._mainUIGameObject.AddComponent <EventPopupPanel>();
                _panel.transform.parent = view.transform;
                _panel.Hide();
            }
        }
예제 #25
0
        public bool CreateUserEvent(int ticketsAvailable, float entryCost, List <IncentiveOptionItem> incentives, DateTime startTime)
        {
            bool created = false;

            if (!CityEventManager.instance.EventStartsBetween(startTime, startTime.AddHours(GetEventLength()) - startTime))
            {
                LoggingWrapper.Log("Creating user event");

                m_eventData.m_eventStartTime  = startTime;
                m_eventData.m_eventFinishTime = startTime.AddHours(GetEventLength());
                m_eventData.m_entryCost       = entryCost;
                m_eventData.m_userTickets     = ticketsAvailable;
                m_eventData.m_userEvent       = true;

                LoggingWrapper.Log("Adding incentives");

                if (m_eventData.m_incentives != null)
                {
                    foreach (CityEventDataIncentives dataIncentive in m_eventData.m_incentives)
                    {
                        LoggingWrapper.Log("Adding incentive " + dataIncentive.name);

                        IncentiveOptionItem foundIncentive = incentives.Find(match => match.title == dataIncentive.name);

                        if (foundIncentive != null)
                        {
                            LoggingWrapper.Log("Setting up incentive " + dataIncentive.name);
                            dataIncentive.itemCount  = Mathf.RoundToInt(foundIncentive.sliderValue);
                            dataIncentive.returnCost = foundIncentive.returnCost;
                        }
                        else
                        {
                            LoggingWrapper.LogWarning("Couldn't find the IncentiveOptionItem that matches " + dataIncentive.name);
                        }
                    }

                    TakeInitialAmount();

                    created = true;
                }
                else
                {
                    LoggingWrapper.LogWarning("There are no incentives for " + m_eventData.m_eventName + ". Skipping");
                }
            }
            else
            {
                LoggingWrapper.LogWarning("Event clashes with another event.");
            }

            return(created);
        }
예제 #26
0
        public static void CheckIfModHasUpdated()
        {
            var lastVersion    = Settings.LastVersion;
            var currentVersion = Details.Version;

            LoggingWrapper.Log(LoggingWrapper.LogArea.Hidden, LoggingWrapper.LogType.Message, $"Checking whether mod has updated ({lastVersion} vs {currentVersion}).");

            _justUpdated = _justUpdated || Settings.LastVersion != Details.Version;

            Settings.LastVersion = Details.Version;

            Save();
        }
예제 #27
0
        private void OnIntroLoaded()
        {
            LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"{Name} is loading post intro.");

            CheckForExperimentalVersion();
            CheckForIncompatibilities();

            PatchManager.PatchAll();
            SimulationManager.RegisterSimulationManager(new SimulationExtension());
            UpdateText.DisplayIfRequired();

            LoggingWrapper.Log(LoggingWrapper.LogArea.All, LoggingWrapper.LogType.Message, $"{Name} has loaded post intro.");
        }
예제 #28
0
        public static TimeSpan EstimateTravelTime(Vector3 startPosition, Vector3 endPosition)
        {
            var simulationManager           = SimulationManager.instance;
            var difference                  = (startPosition - endPosition).magnitude;
            var estimatedTimeToTravelInGame = TimeSpan.FromMinutes(difference / ESTIMATED_DISTANCE_PER_MINUTE);

            if (estimatedTimeToTravelInGame.TotalHours >= MAXIMUM_TRAVEL_HOURS)
            {
                LoggingWrapper.Log(LoggingWrapper.LogArea.File, LoggingWrapper.LogType.Warning, $"Estimated travel time for a citizen was over {MAXIMUM_TRAVEL_HOURS} hours ({estimatedTimeToTravelInGame.TotalHours} estimated hours) with a distance of {difference}. This isn't good, so it's been reduced.");
                estimatedTimeToTravelInGame = TimeSpan.FromHours(MAXIMUM_TRAVEL_HOURS);
            }

            return(estimatedTimeToTravelInGame);
        }
예제 #29
0
        public EventPopupPanel Show(string title, string description, InstanceID instance)
        {
            Initialise();

            _panel.title         = title;
            _panel.worldInstance = instance;
            _panel.description   = description;
            _panel.PerformLayout();
            _panel.Show();
            _panel.Update();

            LoggingWrapper.Log("Showing event popup: " + title + " - " + description);

            return(_panel);
        }
예제 #30
0
        private static void CreateEventButton_eventClicked(UIComponent component, UIMouseEventParameter eventParam)
        {
            UIFastList eventSelection = component.parent.Find <UIFastList>("EventSelectionList");
            ushort     buildingID     = lastInstanceID.Value.Building;

            if (lastInstanceID != null && buildingID != 0)
            {
                BuildingManager _buildingManager = Singleton <BuildingManager> .instance;
                Building        _currentBuilding = _buildingManager.m_buildings.m_buffer[buildingID];

                if ((_currentBuilding.m_flags & Building.Flags.Active) != Building.Flags.None)
                {
                    List <CityEvent> userEvents = CityEventBuildings.instance.GetUserEventsForBuilding(ref _currentBuilding);

                    BuildDropdownList(component);

                    if (eventSelection.isVisible)
                    {
                        eventSelection.Hide();
                    }
                    else
                    {
                        eventSelection.selectedIndex = -1;
                        eventSelection.Show();
                        eventSelection.rowsData.Clear();

                        foreach (CityEvent userEvent in userEvents)
                        {
                            XmlEvent xmlUserEvent = userEvent as XmlEvent;

                            if (xmlUserEvent != null)
                            {
                                xmlUserEvent.SetUp(ref buildingID);
                                LabelOptionItem eventToInsert = new LabelOptionItem()
                                {
                                    linkedEvent = xmlUserEvent, readableLabel = xmlUserEvent.GetReadableName()
                                };
                                eventSelection.rowsData.Add(eventToInsert);

                                LoggingWrapper.Log(xmlUserEvent.GetReadableName());
                            }
                        }

                        eventSelection.DisplayAt(0);
                    }
                }
            }
        }