private static void SubmitConfig(On.RoR2.UI.BaseSettingsControl.orig_SubmitSettingInternal orig, BaseSettingsControl self, string newValue) { if (self.gameObject.name.Contains("VRModSetting")) { ModConfig.ConfigSetting setting; if (ModConfig.settings.TryGetValue(self.settingName, out setting)) { ConfigEntryBase entry = setting.entry; if (entry.SettingType == typeof(bool)) { (entry as ConfigEntry <bool>).Value = newValue == "1"; } else if (entry.SettingType == typeof(int)) { float parsedValue = float.Parse(newValue); (entry as ConfigEntry <int>).Value = (int)parsedValue; } else if (entry.SettingType == typeof(float)) { float parsedValue = float.Parse(newValue, System.Globalization.CultureInfo.InvariantCulture); (entry as ConfigEntry <float>).Value = parsedValue; } else if (entry.SettingType == typeof(string)) { (entry as ConfigEntry <string>).Value = newValue; } } RoR2.RoR2Application.onNextUpdate += self.OnUpdateControls; return; } orig(self, newValue); }
internal static void Draw(ConfigEntryBase entry) { var self = (ToggleableFloat)entry.BoxedValue; if (self.enabled = GUILayout.Toggle(self.enabled, self.enabled ? "Overwrite" : "Disabled")) { var str = GUILayout.TextField(self.value.ToString("f2", CultureInfo.InvariantCulture)); if (string.IsNullOrEmpty(str)) { self.value = 0; } else { if (float.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out var num)) { self.value = num; } else { self.value = 0; } } } entry.BoxedValue = self; }
internal void OnSettingChanged(object sender, ConfigEntryBase changedEntryBase) { if (changedEntryBase == null) { throw new ArgumentNullException(nameof(changedEntryBase)); } if (SaveOnConfigSet) { Save(); } var settingChanged = SettingChanged; if (settingChanged == null) { return; } var args = new SettingChangedEventArgs(changedEntryBase); foreach (var callback in settingChanged.GetInvocationList().Cast <EventHandler <SettingChangedEventArgs> >()) { try { callback(sender, args); } catch (Exception e) { Logger.Log(LogLevel.Error, e); } } }
private void CardButtonDrawer(ConfigEntryBase configEntry) { if (GUILayout.Button($"Browse for {CardName} Replacement", GUILayout.ExpandWidth(true))) { GetCard(); } }
public ConfigSettingEntry(ConfigEntryBase entry, BaseUnityPlugin owner) { Entry = entry; DispName = entry.Definition.Key; Category = entry.Definition.Section; Description = entry.Description?.Description; var converter = TomlTypeConverter.GetConverter(entry.SettingType); if (converter != null) { ObjToStr = o => converter.ConvertToString(o, entry.SettingType); StrToObj = s => converter.ConvertToObject(s, entry.SettingType); } var values = entry.Description?.AcceptableValues; if (values != null) { GetAcceptableValues(values); } DefaultValue = entry.DefaultValue; SetFromAttributes(entry.Description?.Tags, owner); }
private void FramerateLimitDrawer(ConfigEntryBase configEntry) { var toggle = GUILayout.Toggle(framerateToggle, "Enabled", GUILayout.Width(70)); if (toggle != framerateToggle) { if (framerateToggle = toggle) { var refreshRate = Screen.currentResolution.refreshRate; FramerateLimit.Value = refreshRate; Application.targetFrameRate = refreshRate; } else { FramerateLimit.Value = -1; Application.targetFrameRate = -1; } } var slider = (int)GUILayout.HorizontalSlider(FramerateLimit.Value, 30, 200, GUILayout.ExpandWidth(true)); if (slider != FramerateLimit.Value && framerateToggle) { FramerateLimit.Value = Application.targetFrameRate = slider; if (!framerateToggle) { framerateToggle = true; } } GUILayout.Space(5); GUILayout.TextField(FramerateLimit.Value.ToString(), GUILayout.Width(40)); }
private static IConfigField ProcessConfigRow(ConfigEntryBase configEntry) { if (configEntry.BoxedValue is bool) { return(CreateBooleanConfigField(configEntry as ConfigEntry <bool>)); } if (configEntry.BoxedValue is Enum) { return(CreateEnumConfigField(configEntry)); } if (configEntry.BoxedValue is int) { return(CreateIntConfigField(configEntry as ConfigEntry <int>)); } if (configEntry.BoxedValue is float) { return(CreateFloatConfigField(configEntry as ConfigEntry <float>)); } if (configEntry.BoxedValue is string) { return(CreateStringConfigField(configEntry as ConfigEntry <string>)); } if (configEntry.BoxedValue is Color) { return(CreateColorConfigField(configEntry as ConfigEntry <Color>)); } return(null); }
/// <summary> /// Set the local value of an admin config /// </summary> /// <param name="configurationEntry"></param> /// <param name="value"></param> /// <returns></returns> internal static void SetLocalValue(this ConfigEntryBase configurationEntry, object value) { var cma = configurationEntry.Description.Tags.FirstOrDefault(x => x is ConfigurationManagerAttributes) as ConfigurationManagerAttributes; if (cma != null) { cma.LocalValue = value; } }
static void Draw(ConfigEntryBase entry) { var saveGameUser = SaveGameManager.instance.saveGameUser; GUILayout.BeginVertical(); if (GUILayout.Button("Unlock all levels")) { MiSingletonNoMono <SaveGameManager> .instance.saveGameUser.unlockAllLevels(); MiSingletonNoMono <SaveGameManager> .instance.saveGameUser.unlockAllHeadHunters(); MiSingletonNoMono <SaveGameManager> .instance.saveSaveGameUser(); } if (GUILayout.Button("Badges")) { showBadges = !showBadges; showAchievements = false; } if (showBadges) { GUILayout.BeginVertical("box"); DrawBadges(saveGameUser); GUILayout.EndVertical(); } if (GUILayout.Button("Achievements")) { showAchievements = !showAchievements; showBadges = false; } if (showAchievements) { GUILayout.BeginVertical("box"); try { DrawAchievements(); } catch (Exception e) { StaticLogger.LogError(e); message = "Error:\n" + e.ToString(); } GUILayout.EndVertical(); } if (!string.IsNullOrWhiteSpace(message)) { GUILayout.Label(message); } GUILayout.EndVertical(); }
/// <summary> /// Get the local value of an admin config /// </summary> /// <param name="configurationEntry"></param> /// <returns></returns> internal static object GetLocalValue(this ConfigEntryBase configurationEntry) { var cma = configurationEntry.Description.Tags.FirstOrDefault(x => x is ConfigurationManagerAttributes) as ConfigurationManagerAttributes; if (cma != null) { return(cma.LocalValue); } return(null); }
/// <summary> /// Check, if this config entry is "writable" /// </summary> /// <param name="configurationEntry"></param> /// <returns></returns> internal static bool IsWritable(this ConfigEntryBase configurationEntry) { var cma = configurationEntry.Description.Tags.FirstOrDefault(x => x is ConfigurationManagerAttributes) as ConfigurationManagerAttributes; if (cma != null) { return(!cma.IsAdminOnly || (cma.IsAdminOnly && cma.IsUnlocked)); } return(true); }
/// <summary> /// Check, if this config entry is "syncable" /// </summary> /// <param name="configurationEntry"></param> /// <returns></returns> internal static bool IsSyncable(this ConfigEntryBase configurationEntry) { var cma = configurationEntry.Description.Tags.FirstOrDefault(x => x is ConfigurationManagerAttributes) as ConfigurationManagerAttributes; if (cma != null) { return(cma.IsAdminOnly); } return(false); }
/// <summary> /// Check, if this config entry is "visible" /// </summary> /// <param name="configurationEntry"></param> /// <returns></returns> internal static bool IsVisible(this ConfigEntryBase configurationEntry) { var cma = configurationEntry.Description.Tags.FirstOrDefault(x => x is ConfigurationManagerAttributes) as ConfigurationManagerAttributes; if (cma != null) { return(cma.Browsable != false); } return(true); }
internal ConfigSetting(ConfigEntryBase entry, SettingUpdate settingUpdate, EventHandler onChangedCallback = null) { this.entry = entry; this.settingUpdate = settingUpdate; if (onChangedCallback == null) { return; } AddCallback(onChangedCallback); }
private static EnumConfigField CreateEnumConfigField(ConfigEntryBase configEntry) { return(new EnumConfigField(configEntry.SettingType, configEntry.Definition.Key, configEntry.Description.Description, ValueAccessor, OnEndEdit)); Enum ValueAccessor() { return((Enum)configEntry.BoxedValue); } void OnEndEdit(Enum newValue) { configEntry.BoxedValue = newValue; } }
private void ResolutionDrawer(ConfigEntryBase configEntry) { string resX = GUILayout.TextField(resolutionX, GUILayout.Width(80)); string resY = GUILayout.TextField(resolutionY, GUILayout.Width(80)); if (resX != resolutionX && int.TryParse(resX, out _)) { resolutionX = resX; } if (resY != resolutionY && int.TryParse(resY, out _)) { resolutionY = resY; } if (GUILayout.Button("Apply", GUILayout.ExpandWidth(true))) { int x = int.Parse(resolutionX); int y = int.Parse(resolutionY); if (Screen.width != x || Screen.height != y) { StartCoroutine(SetResolution(x, y)); } } GUILayout.Space(5); if (GUILayout.Button("Reset", GUILayout.ExpandWidth(false))) { var display = Display.displays[SelectedMonitor.Value]; if (Screen.width != display.renderingWidth || Screen.height != display.renderingHeight) { StartCoroutine(SetResolution(display.renderingWidth, display.renderingHeight)); } } IEnumerator SetResolution(int width, int height) { Screen.SetResolution(width, height, Screen.fullScreen); yield return(null); UpdateConfigManagerSize(); resolutionX = Screen.width.ToString(); resolutionY = Screen.height.ToString(); if (DisplayMode.Value == SettingEnum.DisplayMode.BorderlessFullscreen) { StartCoroutine(RemoveBorder()); } } }
/// <summary> /// Get bound button config /// </summary> /// <param name="configurationEntry"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> internal static ButtonConfig GetButtonConfig(this ConfigEntryBase configurationEntry) { if (configurationEntry == null) { throw new ArgumentNullException(nameof(configurationEntry)); } if (configurationEntry.SettingType != typeof(KeyCode) && configurationEntry.SettingType != typeof(KeyboardShortcut) && configurationEntry.SettingType != typeof(InputManager.GamepadButton)) { return(null); } InputManager.ButtonToConfigDict.TryGetValue(configurationEntry, out var buttonConfig); return(buttonConfig); }
private static void HsvDrawer(ConfigEntryBase entry) { var vec = (Vector3)entry.BoxedValue; if (!_colorCache.TryGetValue(entry, out var cacheEntry)) { cacheEntry = new ColorCacheEntry { Tex = new Texture2D(40, 60, TextureFormat.ARGB32, false), Last = vec }; cacheEntry.Tex.FillTexture(Color.HSVToRGB(vec.x, vec.y, vec.z)); _colorCache[entry] = cacheEntry; } GUILayout.BeginVertical(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.Label("H", GUILayout.ExpandWidth(false)); vec.x = Mathf.Round(100.0f * GUILayout.HorizontalSlider(vec.x, 0f, 1f, GUILayout.ExpandWidth(true))) / 100.0f; GUILayout.Label($"{vec.x:F2}", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.Label("S", GUILayout.ExpandWidth(false)); vec.y = Mathf.Round(100.0f * GUILayout.HorizontalSlider(vec.y, 0f, 1f, GUILayout.ExpandWidth(true))) / 100.0f; GUILayout.Label($"{vec.y:F2}", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.Label("V", GUILayout.ExpandWidth(false)); vec.z = Mathf.Round(100.0f * GUILayout.HorizontalSlider(vec.z, 0f, 1f, GUILayout.ExpandWidth(true))) / 100.0f; GUILayout.Label($"{vec.z:F2}", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.EndVertical(); if (vec != cacheEntry.Last) { entry.BoxedValue = vec; cacheEntry.Tex.FillTexture(Color.HSVToRGB(vec.x, vec.y, vec.z)); cacheEntry.Last = vec; } GUILayout.Label(cacheEntry.Tex, GUILayout.ExpandWidth(false)); }
void DrawOverrides(ConfigEntryBase _) { GUILayout.BeginVertical(); if (GUILayout.Button(show ? "Hide" : "Show")) { show = !show; } if (!show) { GUILayout.EndVertical(); return; } GUILayout.BeginVertical("box"); GUILayout.BeginHorizontal(); configEnabled.Value = GUILayout.Toggle(configEnabled.Value, "Apply overrides on startup"); GUILayout.FlexibleSpace(); if (GUILayout.Button("Reset all overrides", GUILayout.Width(200))) { CharacterOverrides.ForEach(o => o.Reset()); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Reload overrides.json")) { Load(); Apply(); } if (GUILayout.Button("Apply changes and Save to overrides.json")) { Apply(); Store(); } GUILayout.EndHorizontal(); CharacterOverrides.ForEach(o => o.Draw(ref charToShow)); GUILayout.EndVertical(); GUILayout.EndVertical(); }
/// <summary> /// Get bound button's name /// </summary> /// <param name="configurationEntry"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> internal static string GetBoundButtonName(this ConfigEntryBase configurationEntry) { if (configurationEntry == null) { throw new ArgumentNullException(nameof(configurationEntry)); } if (configurationEntry.SettingType != typeof(KeyCode) && configurationEntry.SettingType != typeof(KeyboardShortcut) && configurationEntry.SettingType != typeof(InputManager.GamepadButton)) { return(null); } return(InputManager.ButtonToConfigDict.TryGetValue(configurationEntry, out var buttonConfig) ? buttonConfig.Name : null); //return configurationEntry.Definition.Key; }
private static string GetVRSettingValue(On.RoR2.UI.BaseSettingsControl.orig_GetCurrentValue orig, BaseSettingsControl self) { if (self.gameObject.name.Contains("VRModSetting")) { ModConfig.ConfigSetting setting; if (ModConfig.settings.TryGetValue(self.settingName, out setting)) { ConfigEntryBase entry = setting.entry; if (entry.SettingType == typeof(bool)) { return((entry as ConfigEntry <bool>).Value ? "1" : "0"); } else if (entry.SettingType == typeof(int)) { return(TextSerialization.ToStringInvariant((entry as ConfigEntry <int>).Value)); } else if (entry.SettingType == typeof(float)) { return(TextSerialization.ToStringInvariant((entry as ConfigEntry <float>).Value)); } else if (entry.SettingType == typeof(string)) { string value = (entry as ConfigEntry <string>).Value; if (Array.Exists((self as CarouselController).choices, x => x.convarValue == value)) { return(value); } else { return("#FFFFFF"); } } } else { return("0"); } } return(orig(self)); }
private void CardButtonDrawer(ConfigEntryBase configEntry) { string text; if (configEntry.Definition.Key.StartsWith(CardNameDefaultF)) { text = CardNameDefaultF; } else if (configEntry.Definition.Key.StartsWith(CardNameDefaultM)) { text = CardNameDefaultM; } else { text = CardNameOther; } if (GUILayout.Button($"Browse for {text} Replacement", GUILayout.ExpandWidth(true))) { GetCard(configEntry.Definition.Key); } }
static void DrawList(ConfigEntryBase entry) { try { var achievement = GetBountyHunterAchievement(); if (achievement.m_eCompletedState == MiCoreServices.AchievementBase.CompleteState.Completed) { GUILayout.Label("Achievement completed. You killed all the devs!", GUILayout.ExpandWidth(true)); } else if (achievement.m_eCompletedState == MiCoreServices.AchievementBase.CompleteState.CompletingAwaitingApiCall) { GUILayout.Label("Achievement completed. You killed all the devs! (The achievement is still in the process of being registered)", GUILayout.ExpandWidth(true)); } else { var done = achievement.m_lGUIDsTriggered.Count; var total = Dev.DEVS.Length; GUILayout.BeginVertical(); GUILayout.Label("You found " + done + "/" + total + " devs. " + (total - done) + " are still missing:", GUILayout.ExpandWidth(true)); foreach (var dev in Dev.DEVS) { if (!achievement.m_lGUIDsTriggered.Contains(dev.guid)) { GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.Label(Dev.LEVEL_NAMES[dev.level], GUILayout.Width(200)); GUILayout.Label(dev.nick); GUILayout.EndHorizontal(); } } GUILayout.Label("Check https://www.trueachievements.com/a298714/veteran-bounty-hunter-achievement for the exact locations.", GUILayout.ExpandWidth(true)); GUILayout.EndVertical(); } } catch (Exception e) { GUILayout.Label("Error: " + e.Message, GUILayout.ExpandWidth(true)); } }
public static bool MyWriteDescription(ref ConfigEntryBase __instance, ref StreamWriter writer) { if (__instance.ConfigFile == configFile) { if (!typeStr.TryGetValue(__instance.SettingType, out string TypeName)) { TypeName = __instance.SettingType.Name; } string TypeDescription = TypeName + ", default: " + TomlTypeConverter.ConvertToString(__instance.DefaultValue, __instance.SettingType); if (!string.IsNullOrEmpty(__instance.Description.Description)) { writer.WriteLine("# " + __instance.Description.Description.Replace("\n", "\n# ") + " (" + TypeDescription + ")"); } else { writer.WriteLine("# " + TypeDescription); } if (__instance.Description.AcceptableValues != null) { writer.WriteLine(__instance.Description.AcceptableValues.ToDescriptionString()); } else if (__instance.SettingType.IsEnum) { writer.WriteLine("# Acceptable values: " + string.Join(", ", Enum.GetNames(__instance.SettingType))); if (__instance.SettingType.GetCustomAttributes(typeof(FlagsAttribute), inherit: true).Any()) { writer.WriteLine("# Multiple values can be set at the same time by separating them with , (e.g. Debug, Warning)"); } } return(false); } else { return(true); } }
/// <inheritdoc /> public SettingChangedEventArgs(ConfigEntryBase changedSetting) => ChangedSetting = changedSetting;
static void DrawCommands(ConfigEntryBase entry) { var gameInput = MiGameInput.instance; if (gameInput == null) { GUILayout.BeginVertical("box"); GUILayout.Label("Enter a level to show available commands"); GUILayout.EndVertical(); return; } GUILayout.BeginVertical(); if (GUILayout.Button(show ? "Hide" : "Show")) { show = !show; } if (!show) { GUILayout.EndVertical(); return; } GUILayout.BeginVertical("box"); var difficultySettings = (MissionSetupSettings.DifficultySettings)fieldMissionSetupSettings_s_difficultySettings.GetValue(null); var showdownPauseOld = difficultySettings.m_bFocusModePause; difficultySettings.m_bFocusModePause = GUILayout.Toggle(difficultySettings.m_bFocusModePause, "Pausing Showdownmode"); if (showdownPauseOld != difficultySettings.m_bFocusModePause) { fieldMissionSetupSettings_s_difficultySettings.SetValue(null, difficultySettings); } if (SceneStatistics.instance != null && GUILayout.Button("Reset Level Statistics")) { var stats = SceneStatistics.instance; var statsType = typeof(SceneStatistics); ((IDictionary)AccessTools.Field(statsType, "m_dictNPCsKilledBy").GetValue(stats)).Clear(); ((IDictionary)AccessTools.Field(statsType, "m_dictSkillsUsed").GetValue(stats)).Clear(); AccessTools.Field(statsType, "m_iAlarmCount").SetValue(stats, 0); AccessTools.Field(statsType, "m_iBodiesHidden").SetValue(stats, 0); AccessTools.Field(statsType, "m_iCritterKilled").SetValue(stats, 0); AccessTools.Field(statsType, "m_iDeadBodiesFound").SetValue(stats, 0); AccessTools.Field(statsType, "m_iEnemiesKilled").SetValue(stats, 0); AccessTools.Field(statsType, "m_iEnemiesKilledWithTorches").SetValue(stats, 0); AccessTools.Field(statsType, "m_iEnemiesShotPlayer").SetValue(stats, 0); AccessTools.Field(statsType, "m_iDeadBodiesFound").SetValue(stats, 0); AccessTools.Field(statsType, "m_iEnemiesSpared").SetValue(stats, 0); AccessTools.Field(statsType, "m_iEnemiesTiedUp").SetValue(stats, 0); AccessTools.Field(statsType, "m_iDeadBodiesFound").SetValue(stats, 0); AccessTools.Field(statsType, "m_iNPCsKilled").SetValue(stats, 0); AccessTools.Field(statsType, "m_iPlayerDetected").SetValue(stats, 0); AccessTools.Field(statsType, "m_iSamuraiKilled").SetValue(stats, 0); var statsData = stats.persistentSaveData; statsData.fPlaytime = 0; statsData.iFrameCount = 0; statsData.iLoadCount = 0; statsData.iSaveCount = 0; statsData.iTotalHealthLost = 0; statsData.lPlayerDeathCount.Clear(); statsData.lPlayerStateDurations.Clear(); var statsNoSaveData = SceneStatisticsNoSave.instance.persistentSaveData; statsNoSaveData.fPlaytime = 0; statsNoSaveData.iFrameCount = 0; statsNoSaveData.iLoadCount = 0; statsNoSaveData.iSaveCount = 0; statsNoSaveData.iTotalHealthLost = 0; statsNoSaveData.lPlayerDeathCount.Clear(); statsNoSaveData.lPlayerStateDurations.Clear(); } #if DEBUG if (GUILayout.Button("Dump Skill Data")) { var content = ""; foreach (var data in Resources.FindObjectsOfTypeAll <PlayerSkillData>()) { content += data.name + "\n"; } File.WriteAllText(Path.Combine(Paths.ConfigPath, "skills.toml"), content); } #endif if (gameInput.iPlayerCharacterCount != charCount) { charToShow = -1; charCount = gameInput.iPlayerCharacterCount; } else { for (int i = 0; i < gameInput.iPlayerCharacterCount; i++) { MiCharacter character = gameInput.lPlayerCharacter[i]; var uiData = character.uiData; if (string.IsNullOrWhiteSpace(uiData.lstrName.strText)) { continue; } GUILayout.BeginHorizontal(); GUILayout.Label(uiData.lstrName.strText, Main.SkinBold, GUILayout.Width(200)); var enabled = GUILayout.Toggle(character.enabled, character.enabled ? "Enabled" : "Disabled", GUILayout.Width(100)); if (!enabled) { if (character.enabled) { AccessTools.Method(typeof(MiCharacter), "disable").Invoke(gameInput.lPlayerCharacter[i], new object[] { false, false, false }); if (charToShow == i) { charToShow = -1; } } GUILayout.EndHorizontal(); continue; } if (!character.enabled) { AccessTools.Method(typeof(MiCharacter), "enable").Invoke(gameInput.lPlayerCharacter[i], new object[] { true, false, false, true }); } GUILayout.Label($"Health: {character.m_charHealth.iHealth}", GUILayout.Width(80)); if (GUILayout.Button("-", GUILayout.Width(50))) { character.m_charHealth.iHealth--; } if (GUILayout.Button("+", GUILayout.Width(50))) { character.m_charHealth.iHealth++; } if (GUILayout.Button(charToShow == i ? "Hide" : "Show")) { if (charToShow == i) { charToShow = -1; } else { charToShow = i; } } GUILayout.EndHorizontal(); if (charToShow != i) { continue; } GUILayout.BeginVertical("box"); foreach (var skill in character.controller.lSkills) { DrawCharacterSkill(character, skill); } GUILayout.EndVertical(); } } GUILayout.EndVertical(); GUILayout.EndVertical(); }
//Turns string code into actual values, AKA pure agony internal static void LoadConfigCode(string code) { //This is the length of the code int length = code.Length; //Pointer tells us where we are at int pointer = 0; //Section helps us identify where tf we at in the code int section = 0; //How many defaults in a row we hittin int numDefaults = 0; //For every config value, should be in same order as person who did the getconfig foreach (KeyValuePair <ConfigDefinition, ConfigEntryBase> config in configFile) { //Helps us reference it easier ConfigEntryBase configEntry = config.Value; //Pointed is the character we are pointed at rn char pointed = code[pointer]; //Num helps us identify default values int num; //If we are dangerously close to indexoutofbounds this will helps us not be that bool isLast = false; //If we haven't hit any defaults yet, check for them if (numDefaults == 0) { //Keep scanning through basically until we are no longer viewing a number, so we can read off any length of number of defaults while (int.TryParse(code.Substring(pointer, section + 1), out num)) { //Section lets us look further each loop until we hit a nothing section += 1; //Numdefaults is just the num so we know how many defaults we just hit numDefaults = num; //If we are boutta go out of bounds say so and gtfo before we die if (pointer + section >= code.Length) { isLast = true; break; } } //If we did hit any defaults... if (section > 0) { //Mark the pointer for that length so we know how far to be for next config value pointer += section - (isLast ? 1 : 0); //Reset the section section = 0; } } //If we DID encounter defaults last step... if (numDefaults > 0) { //Count down the defaults we have handled numDefaults -= 1; //Set the value to default configEntry.BoxedValue = configEntry.DefaultValue; //We ain't gotta do shit else so skip the rest of the logic continue; } //Push pointer up by one beforehand so it is ready to read off the value pointer += 1; //If the string is saying we expect a bool... if (pointed == Convert.ToChar("b")) { //Bools are only 1 digit values, so we read off a length of 1 only section = 1; //Set the value to true if 1, false if 0, simple configEntry.BoxedValue = code.Substring(pointer, section) == "1"; } //If the string says we expect a float (short)... else if (pointed == Convert.ToChar("s")) { //We will be reading off 2 numbers at a time, once for the whole part and again for the decimal section = 2; //Whole is just the first two parts of the value converted back to an int int whole = Conversions.FromBase62(code.Substring(pointer, section)); //Dec is just the second to parts of the value converted to an int int dec = Conversions.FromBase62(code.Substring(pointer + section, section)); //Put the two pieces together and make it an actual float float convertedValue = whole + (dec / 100f); //The finished value is put into the converted value part configEntry.BoxedValue = convertedValue; //Section +2 so we know that we skip ahead by 4 total spots in the string section += 2; } //If the string says we expect an int... else if (pointed == Convert.ToChar("i")) { //Only a 2 digit value to read and skip off of section = 2; //Set it straight to the value, simple no problem configEntry.BoxedValue = Conversions.FromBase62(code.Substring(pointer, section)); } //If the string says we expect a uint... else if (pointed == Convert.ToChar("u")) { //Again it's just a 2 digit num to read off section = 2; //Tempval is cause it is slightly more painful than int to do all in a single line uint tempVal = (uint)Conversions.FromBase62(code.Substring(pointer, section)); //Then set value to the one we found out configEntry.BoxedValue = tempVal; } //If somehow the string has no idea what is going on... else { //Cancel the whole reading and note it in console LogToConsole("Invalid code section, process aborted"); return; } //Move the pointer up the necessary amount to read the next value pointer += section; //Reset section section = 0; } //Tell them the config code went through just fine LogToConsole("Config code loaded, restart game for it to take effect"); //Save the file configFile.Save(); //Reload the file configFile.Reload(); }
//Makes the config code from all of the config values private static void PrepareConfigCode() { //Start with blank string, this will slowly become the config code configCode = string.Empty; //How many default values we find in a row, this helps us to simply skip over sections where all values are default int defaultCounter = 0; //For every value in the file... foreach (KeyValuePair <ConfigDefinition, ConfigEntryBase> config in configFile) { //This just is easier reference for us ConfigEntryBase value = config.Value; //Start with another blank string string tempValue = string.Empty; //This is the 'type', since we can have bools, floats, ints, and we need to know which one so we convert it properly string tempType; //If the value is just the default value... if (value.BoxedValue.Equals(value.DefaultValue)) { //Note it defaultCounter += 1; //This just exits if the last value was a default safely, basically prevents things from exploding if (configFile.Last().Equals(config)) { tempType = defaultCounter.ToString(); } //We do this so nothing is added until AFTER all the defaults are found and marked else { tempType = string.Empty; } } //Otherwise if the value is NOT the default value... else { //If there are any default values queue'd up to be marked... if (defaultCounter > 0) { //Put the number where it goes configCode += defaultCounter.ToString(); //Reset the counter defaultCounter = 0; } //This gets us b if bool, s if short (float), i if int, and u if uint tempType = value.BoxedValue.GetType().Name[0].ToString().ToLower(); //If it is a bool, the string section will be b1 or b0 for true or false if (tempType == "b") { tempValue = (bool)value.BoxedValue ? "1" : "0"; } //If it is a float... else if (tempType == "s") { //Grab the whole float first off float floatValue = (float)value.BoxedValue; //If it's too high... if (floatValue > 3843) { //Tell them it too high and set to default LogToConsole("Value of config field : " + value.Definition.Key + " too high, resetting to default)"); value.BoxedValue = value.DefaultValue; //Then perform the usual default stuff so we brick things defaultCounter += 1; if (configFile.Last().Equals(config)) { tempType = defaultCounter.ToString(); } else { tempType = string.Empty; } } //If it too low... else if (floatValue < 0) { //Tell them too low and set to default LogToConsole("Value of config field : " + value.Definition.Key + " below zero, resetting to default)"); value.BoxedValue = value.DefaultValue; //Then perform the usual default stuff so we brick things defaultCounter += 1; if (configFile.Last().Equals(config)) { tempType = defaultCounter.ToString(); } else { tempType = string.Empty; } } //Otherwise we can move onto encoding it normally else { //Grab the whole number int whole = Convert.ToInt32(System.Math.Floor(floatValue)); //Set the value to the whole number as a base62 2 digit value tempValue = Conversions.ToBase62(whole); //Now we get the decimals in the back, as a 2 digit int int dec = Convert.ToInt32((floatValue - whole) * 100f); //Fix boxed value so it's not painfully precise anymore value.BoxedValue = (float)whole + Convert.ToSingle(System.Math.Round(dec / 100f, 2)); //Convert the decimal part to base62 also and pass it along tempValue += Conversions.ToBase62(dec); } } //Otherwise if it is an int... else if (tempType == "i") { //intvalue is just the value of the int duh int intValue = (int)value.BoxedValue; //If too big tell them and default it if (intValue > 3843) { LogToConsole("Value of config field : " + value.Definition.Key + " too high, resetting to default)"); value.BoxedValue = value.DefaultValue; //Then perform the usual default stuff so we brick things defaultCounter += 1; if (configFile.Last().Equals(config)) { tempType = defaultCounter.ToString(); } else { tempType = string.Empty; } } //If too small tell them and default it else if (intValue < 0) { LogToConsole("Value of config field : " + value.Definition.Key + " below zero, resetting to default)"); value.BoxedValue = value.DefaultValue; //Then perform the usual default stuff so we brick things defaultCounter += 1; if (configFile.Last().Equals(config)) { tempType = defaultCounter.ToString(); } else { tempType = string.Empty; } } //If value is fine set the value to it else { tempValue = Conversions.ToBase62(intValue); } } //Otherwise if it is a uint... else if (tempType == "u") { //Grab uint value uint uintValue = (uint)value.BoxedValue; //If too big default and say it if (uintValue > 3843) { LogToConsole("Value of config field : " + value.Definition.Key + " too high, resetting to default)"); value.BoxedValue = value.DefaultValue; //Then perform the usual default stuff so we brick things defaultCounter += 1; if (configFile.Last().Equals(config)) { tempType = defaultCounter.ToString(); } else { tempType = string.Empty; } } //If too small default and say it else if (uintValue < 0) { LogToConsole("Value of config field : " + value.Definition.Key + " below zero, resetting to default)"); value.BoxedValue = value.DefaultValue; //Then perform the usual default stuff so we brick things defaultCounter += 1; if (configFile.Last().Equals(config)) { tempType = defaultCounter.ToString(); } else { tempType = string.Empty; } } //If it works then put it in value else { tempValue = Conversions.ToBase62(Convert.ToInt32(uintValue)); } } } //Finally add the type + value to the code, loop until end and boom done configCode += tempType + tempValue; } //Reload the file for safety configFile.Reload(); }
public static T Get <T>(this ConfigEntryBase def) { return((T)def.BoxedValue); }
private static bool TryGetBase(ConfigFile file, ConfigDefinition key, out ConfigEntryBase entryBase) { try { entryBase = file[key]; return(true); } catch (Exception) { entryBase = null; } return(false); }