diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 60102865c..8de4bcfcb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -231,8 +231,6 @@ jobs: run: | cp -rf packaging/epic/* epic/ cp -rf packaging/steam/* steam/ - cp -rf packaging/il2cppinterop/* steam/BepInEx/core/ - cp -rf packaging/il2cppinterop/* epic/BepInEx/core/ - name: Steam App ID run: | diff --git a/Gamemodes/BedWars.cs b/Gamemodes/BedWars.cs index 670855d66..953f02e9b 100644 --- a/Gamemodes/BedWars.cs +++ b/Gamemodes/BedWars.cs @@ -380,7 +380,7 @@ public static class BedWars public static void Initialize() { - GracePeriodEnd = Utils.TimeStamp + 60; + GracePeriodEnd = Utils.TimeStamp + 1000; Data = []; InShop = []; @@ -454,11 +454,11 @@ public static class BedWars .Flatten() .ToDictionary(x => x.Key, x => x.Value); - yield return vanilla ? new WaitForSeconds(1f) : WaitFrameIfNecessary(); + yield return vanilla ? new WaitForSeconds(2f) : WaitFrameIfNecessary(); Main.AllAlivePlayerControlsToList.SetChatVisible(true); - yield return vanilla ? new WaitForSeconds(1f) : WaitFrameIfNecessary(); + yield return vanilla ? new WaitForSeconds(2f) : WaitFrameIfNecessary(); MapNames map = Main.CurrentMap; Dictionary bases = Bases[map]; @@ -519,12 +519,12 @@ public static class BedWars Data[pc.PlayerId] = data; - yield return vanilla ? new WaitForSeconds(0.3f) : WaitFrameIfNecessary(); + yield return vanilla ? new WaitForSeconds(0.6f) : WaitFrameIfNecessary(); } sender.SendMessage(dispose: PlayerControl.AllPlayerControls.Count <= 1); - yield return vanilla ? new WaitForSeconds(1f) : WaitFrameIfNecessary(); + yield return vanilla ? new WaitForSeconds(2f) : WaitFrameIfNecessary(); if (GameStates.IsEnded || !GameStates.InGame || GameStates.IsLobby) { @@ -551,14 +551,14 @@ public static class BedWars if (bed != null) AllNetObjects[team] = new(bed, new(itemShop), new(upgradeShop)); rooms.Add(Utils.ColorString(team.GetColor(), Translator.GetString(room))); - yield return vanilla ? new WaitForSeconds(1f) : WaitFrameIfNecessary(); + yield return vanilla ? new WaitForSeconds(2f) : WaitFrameIfNecessary(); } - yield return vanilla ? new WaitForSeconds(1f) : WaitFrameIfNecessary(); + yield return vanilla ? new WaitForSeconds(2f) : WaitFrameIfNecessary(); players.NotifyPlayers($"{rooms[0]}\n{string.Join(" | ", rooms.Skip(1))}", 20f, setName: false); - yield return vanilla ? new WaitForSeconds(1f) : WaitFrameIfNecessary(); + yield return vanilla ? new WaitForSeconds(2f) : WaitFrameIfNecessary(); foreach ((Item item, List positions) in ItemGeneratorPositions[map]) { @@ -579,7 +579,7 @@ public static class BedWars if (generator != null) ItemGenerators.Add(generator); }); - yield return vanilla ? new WaitForSeconds(1f) : WaitFrameIfNecessary(); + yield return vanilla ? new WaitForSeconds(2f) : WaitFrameIfNecessary(); } GracePeriodEnd = Utils.TimeStamp + GracePeriod; diff --git a/Gamemodes/CustomHnS.cs b/Gamemodes/CustomHnS.cs index 795cb99f9..2ccab4d19 100644 --- a/Gamemodes/CustomHnS.cs +++ b/Gamemodes/CustomHnS.cs @@ -41,6 +41,7 @@ internal static class CustomHnS Color color = new(52, 94, 235, byte.MaxValue); MaxGameLength = new IntegerOptionItem(id, "FFA_GameTime", new(0, 1200, 10), 600, TabGroup.GameSettings) + .SetHeader(true) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(color); diff --git a/Main.cs b/Main.cs index 0d5f0c194..61ecd28c0 100644 --- a/Main.cs +++ b/Main.cs @@ -78,7 +78,11 @@ public class Main : BaseUnityPlugin public static readonly Version Version = Version.Parse(PluginVersion); - public static readonly bool Mono = !OperatingSystem.IsAndroid() && Directory.Exists("./MonoBleedingEdge"); +#if IL2CPP + private const bool Mono = false; +#else + private const bool Mono = true; +#endif //public static ManualLogSource Logger; public static bool HasArgumentException; diff --git a/Modules/Camouflage.cs b/Modules/Camouflage.cs index da8768202..1a0c7b0c6 100644 --- a/Modules/Camouflage.cs +++ b/Modules/Camouflage.cs @@ -142,6 +142,8 @@ public static class Camouflage private static IEnumerator UpdateCamouflageStatusAsync() { + bool camouflage = IsCamouflage; + foreach (PlayerControl pc in Main.EnumeratePlayerControls()) { if (pc.inVent || pc.walkingToVent || pc.onLadder || pc.inMovingPlat) @@ -153,9 +155,14 @@ public static class Camouflage RpcSetSkin(pc); yield return new WaitForSecondsRealtime(0.1f); + + if (camouflage != IsCamouflage) yield break; } yield return new WaitForSecondsRealtime(0.5f); + + if (camouflage != IsCamouflage) yield break; + yield return Utils.NotifyEveryoneAsync(); } diff --git a/Modules/ClientControlGUI.cs b/Modules/ClientControlGUI.cs index ab199059c..35e15fcfe 100644 --- a/Modules/ClientControlGUI.cs +++ b/Modules/ClientControlGUI.cs @@ -548,7 +548,7 @@ public class ClientControlGUI : MonoBehaviour } bool canZoom = Zoom.CanZoom; - bool canNoClip = canMove && Main.IntroDestroyed && (!AmongUsClient.Instance.IsGameStarted || !GameStates.IsOnlineGame) && (!GameStartManager.Instance || GameStartManager.Instance.startState == GameStartManager.StartingStates.NotStarting); + bool canNoClip = canMove && GameStartManager.Instance && GameStartManager.Instance.startState == GameStartManager.StartingStates.NotStarting; bool canToggleHud = Main.IntroDestroyed && !inMeeting && !ExileController.Instance && !ReportDeadBodyPatch.MeetingStarted; if (canZoom || canNoClip || canToggleHud) @@ -591,7 +591,7 @@ public class ClientControlGUI : MonoBehaviour if (OperatingSystem.IsAndroid()) PlayerControl.LocalPlayer.Collider.offset = ControllerManagerUpdatePatch.NoClipEnabled ? new Vector2(0f, 127f) : new Vector2(0f, -0.3636f); }); } - else if (ControllerManagerUpdatePatch.NoClipEnabled && OperatingSystem.IsAndroid() && PlayerControl.LocalPlayer) + else if (ControllerManagerUpdatePatch.NoClipEnabled && OperatingSystem.IsAndroid() && PlayerControl.LocalPlayer && Main.IntroDestroyed && !Main.HasJustStarted) { PlayerControl.LocalPlayer.Collider.offset = new Vector2(0f, -0.3636f); ControllerManagerUpdatePatch.NoClipEnabled = false; diff --git a/Modules/EAC.cs b/Modules/EAC.cs index 2c04ed575..db790c640 100644 --- a/Modules/EAC.cs +++ b/Modules/EAC.cs @@ -295,7 +295,7 @@ internal static class EAC break; } - case RpcCalls.Shapeshift when !pc.IsNonHostModdedClient(): + case RpcCalls.Shapeshift when !pc.IsNonHostModdedClient() && pc.PlayerId < 254: { Report(pc, "Directly Shapeshift"); MessageWriter swriter = AmongUsClient.Instance.StartRpcImmediately(pc.NetId, (byte)RpcCalls.Shapeshift, SendOption.Reliable); diff --git a/Modules/GuessManager.cs b/Modules/GuessManager.cs index d9f563431..c07174705 100644 --- a/Modules/GuessManager.cs +++ b/Modules/GuessManager.cs @@ -63,7 +63,7 @@ public static class GuessManager public static bool GuesserMsg(PlayerControl pc, string msg, bool isUI = false) { if (!AmongUsClient.Instance.AmHost) return false; - if (!GameStates.IsMeeting || MeetingHud.Instance.state is MeetingHud.MeetingStates.Results or MeetingHud.MeetingStates.Proceeding || !pc) return false; + if (!GameStates.IsMeeting || MeetingHud.Instance.state is MeetingHud.MeetingStates.Results or MeetingHud.MeetingStates.Proceeding || !pc || Starspawn.IsDayBreak) return false; bool hasGuessingRole = pc.GetCustomRole() is CustomRoles.NiceGuesser or CustomRoles.EvilGuesser or CustomRoles.Doomsayer or CustomRoles.Prosecutor or CustomRoles.Swapper or CustomRoles.Councillor or CustomRoles.NecroGuesser or CustomRoles.Augur; if (!hasGuessingRole && !pc.Is(CustomRoles.Guesser) && !Options.GuesserMode.GetBool()) return false; diff --git a/Modules/LobbySharingAPI.cs b/Modules/LobbySharingAPI.cs index 917c7701a..50cfe777c 100644 --- a/Modules/LobbySharingAPI.cs +++ b/Modules/LobbySharingAPI.cs @@ -184,7 +184,7 @@ internal static class ExitGamePatch } if (GameSettingMenu.Instance) - GameSettingMenuPatch.Close_Prefix(); + CustomSettingsUIPatches.GameSettingMenuPatches.PreClose(GameSettingMenu.Instance); } public static void Postfix(InnerNetClient __instance) diff --git a/Modules/OnlinePresetsManager.cs b/Modules/OnlinePresetsManager.cs index 6c8ef94e7..7091ed324 100644 --- a/Modules/OnlinePresetsManager.cs +++ b/Modules/OnlinePresetsManager.cs @@ -14,12 +14,13 @@ using System.Text.Json; using Newtonsoft.Json; #endif +// ReSharper disable PossibleLossOfFraction + namespace EHR.Modules; public static class OnlinePresetsManager { - private static readonly Dictionary OptionBehaviourCache = []; - private static readonly Dictionary HeaderCache = []; + public static readonly Dictionary Buttons = []; public static List CachedPresets = []; public static bool PresetsLoaded = false; @@ -28,15 +29,86 @@ public static class OnlinePresetsManager if (!PresetsLoaded) return; float y = 2.0f; - + { - CategoryHeaderMasked header = HeaderCache.TryGetValue(0, out CategoryHeaderMasked cache) ? cache : ModGameOptionsMenu.Track(Object.Instantiate( + CategoryHeaderMasked header = Object.Instantiate( menu.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, menu.settingsContainer - )); - HeaderCache[0] = header; + ); + + header.SetHeader(StringNames.RolesCategory, 20); + header.Title.DestroyTranslator(); + header.Title.text = Translator.GetString("LocalPresets"); + header.transform.localScale = Vector3.one * 0.63f; + header.transform.localPosition = new(-0.903f, y, -2f); + + y -= 0.8f; + + PassiveButton template = CustomSettingsUIPatches.GamePresetsTabPatches.TemplatePresetButton; + string[] childrenNames = ["Active", "Inactive", "Selected", "InactiveSelected"]; + + for (int i = 1; i <= 20; i++) + { + int num = i - 1; + GameObject button = Object.Instantiate(template.gameObject, Vector3.zero, Quaternion.identity, menu.settingsContainer); + button.SetActive(true); + button.name = $"PresetButton_{i}"; + button.transform.localScale *= 0.2f; + button.transform.localPosition = new Vector3(-1.6f + (num % 10 * 0.6f), 1f - (0.85f * (num / 10)), -2f); + var passiveButton = button.GetComponent(); + passiveButton.SelectButton(OptionItem.CurrentPreset == num); + passiveButton.OnClick.RemoveAllListeners(); + passiveButton.OnClick.AddListener(() => + { + Options.Preset.SetValue(num); + foreach (GameObject gameObject in Buttons.Values) + gameObject.GetComponent().SelectButton(false); + passiveButton.SelectButton(true); + GameSettingMenu.Instance.RoleSettingsButton.gameObject.SetActive(Options.CurrentGameMode is CustomGameMode.Standard or CustomGameMode.HideAndSeek); + CustomSettingsUIPatches.GameSettingMenuPatches.IsDirty = true; + CustomSettingsUIPatches.GameOptionsMenuPatches.SetAllDirty(); + }); + + Color color = Color.black; + + foreach (string name in childrenNames) + { + Transform transform = button.transform.Find(name); + var label = transform.Find("Label").GetComponent(); + label.maskInteraction = SpriteMaskInteraction.VisibleInsideMask; + label.color = color; + var frame = transform.Find("Frame").GetComponent(); + frame.maskInteraction = SpriteMaskInteraction.VisibleInsideMask; + frame.color = color; + Object.Destroy(transform.Find("Background").gameObject); + } + + var textMeshPro = button.transform.Find("ModeText").GetComponent(); + textMeshPro.DestroyTranslator(); + textMeshPro.text = $"{Translator.GetString("Preset").ToUpper()}"; + textMeshPro.fontWeight = FontWeight.Bold; + textMeshPro.color = Color.white; + + var numberText = Object.Instantiate(textMeshPro, textMeshPro.transform.parent); + numberText.transform.localPosition += new Vector3(0f, 1.8f, 0f); + numberText.GetComponent().sizeDelta = new(1.5f, 1.5f); + numberText.text = $"{i}"; + + Buttons[i] = button; + } + + y -= 1.8f; + } + + { + CategoryHeaderMasked header = Object.Instantiate( + menu.categoryHeaderOrigin, + Vector3.zero, + Quaternion.identity, + menu.settingsContainer + ); header.SetHeader(StringNames.RolesCategory, 20); header.Title.DestroyTranslator(); @@ -46,7 +118,7 @@ public static class OnlinePresetsManager y -= 0.8f; - StringOption upload = OptionBehaviourCache.TryGetValue(-1, out StringOption uploadCache) ? uploadCache : ModGameOptionsMenu.Track(Object.Instantiate(menu.stringOptionOrigin, Vector3.zero, Quaternion.identity, menu.settingsContainer)); + StringOption upload = Object.Instantiate(menu.stringOptionOrigin, Vector3.zero, Quaternion.identity, menu.settingsContainer); upload.name = nameof(OnlinePresetsManager) + ";" + Translator.GetString("UploadPreset"); upload.transform.localPosition = new Vector3(0.952f, y, -2f); upload.SetClickMask(menu.ButtonClickMask); @@ -70,19 +142,17 @@ public static class OnlinePresetsManager upload.gameObject.SetActive(true); menu.Children.Add(upload); - OptionBehaviourCache[-1] = upload; y -= 0.6f; } { - CategoryHeaderMasked header = HeaderCache.TryGetValue(1, out CategoryHeaderMasked cache) ? cache : ModGameOptionsMenu.Track(Object.Instantiate( + CategoryHeaderMasked header = Object.Instantiate( menu.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, menu.settingsContainer - )); - HeaderCache[1] = header; + ); header.SetHeader(StringNames.RolesCategory, 20); header.Title.DestroyTranslator(); @@ -96,7 +166,7 @@ public static class OnlinePresetsManager for (var index = 0; index < CachedPresets.Count; index++) { PresetMeta preset = CachedPresets[index]; - StringOption row = OptionBehaviourCache.TryGetValue(index, out StringOption cache) ? cache : ModGameOptionsMenu.Track(Object.Instantiate(menu.stringOptionOrigin, Vector3.zero, Quaternion.identity, menu.settingsContainer)); + StringOption row = Object.Instantiate(menu.stringOptionOrigin, Vector3.zero, Quaternion.identity, menu.settingsContainer); row.name = $"{nameof(OnlinePresetsManager)};{string.Format(Translator.GetString("OnlinePresetInfo"), preset.name, preset.author, (Utils.TimeStamp - (long)preset.created_at) / 86400, preset.downloads)}"; row.transform.localPosition = new Vector3(0.952f, y, -2f); row.SetClickMask(menu.ButtonClickMask); @@ -119,21 +189,48 @@ public static class OnlinePresetsManager row.PlusBtn.OnClick = new(); row.PlusBtn.OnClick.AddListener(() => { - bool b = plusText.text == "ⓘ"; - GameObject.Find("PlayerOptionsMenu(Clone)").transform.Find("What Is This?").gameObject.SetActive(b); - GameSettingMenuPatch.GMButtons.Values.Do(x => x.gameObject.SetActive(!b)); - if (b) GameSettingMenu.Instance.MenuDescriptionText.text = preset.description; - plusText.text = b ? "∅" : "ⓘ"; + TransitionOpen popup = Object.Instantiate(CustomSettingsUIPatches.GamePresetsTabPatches.TemplateConfirmPopUp, menu.transform, false); + popup.gameObject.SetActive(true); + popup.transform.localPosition = new Vector3(3f, -2f, popup.transform.localPosition.z); + Transform background = popup.transform.Find("Background"); + Object.Destroy(background.Find("TitleText_TMP").gameObject); + Object.Destroy(background.Find("DividerImage").gameObject); + Object.Destroy(background.Find("BackButton").gameObject); + Object.Destroy(background.Find("ContinueButton").gameObject); + TextMeshPro textMeshPro = background.Find("Text_TMP").GetComponent(); + textMeshPro.DestroyTranslator(); + textMeshPro.text = preset.description; + RectTransform rectTransform = textMeshPro.GetComponent(); + rectTransform.sizeDelta = new(rectTransform.sizeDelta.x, 2.5f); + PassiveButton closeButton = background.Find("CloseButton").GetComponent(); + closeButton.OnClick.RemoveAllListeners(); + closeButton.OnClick.AddListener(() => + { + LateTask.New(() => Object.Destroy(popup.gameObject), 0.5f); + ControllerManager.Instance.CloseOverlayMenu(popup.name); + popup.Close(); + }); + ControllerManager.Instance.OpenOverlayMenu(popup.name, closeButton, closeButton); }); row.MinusBtn.transform.localPosition += new Vector3(1.7f, 0f, 0f); row.MinusBtn.OnClick = new(); row.MinusBtn.OnClick.AddListener(() => { - LateTask.New(() => { }, 0.01f); - GameSettingMenu.Instance.Close(); - - Prompt.Show(Translator.GetString("Promt.ApplyPreset"), () => + var confirmPresetPopUp = Object.Instantiate(CustomSettingsUIPatches.GamePresetsTabPatches.TemplateConfirmPopUp, menu.transform, false); + confirmPresetPopUp.transform.localPosition = new Vector3(3f, -2f, confirmPresetPopUp.transform.localPosition.z); + Transform background = confirmPresetPopUp.transform.Find("Background"); + PassiveButton presetConfirmButton = background.Find("ContinueButton").GetComponent(); + PassiveButton[] presetCancelButtons = [background.Find("BackButton").GetComponent(), background.Find("CloseButton").GetComponent()]; + confirmPresetPopUp.gameObject.SetActive(true); + presetConfirmButton.OnClick.RemoveAllListeners(); +#if IL2CPP + foreach (PassiveButton presetCancelButton in presetCancelButtons) + presetCancelButton.OnClick.RemoveAllListeners(); +#else + presetCancelButtons.ForEach(x => x.OnClick.RemoveAllListeners()); +#endif + presetConfirmButton.OnClick.AddListener(() => { Logger.SendInGame(Translator.GetString("DownloadingPreset")); @@ -153,22 +250,36 @@ public static class OnlinePresetsManager Logger.SendInGame(Translator.GetString("PresetApplied"), Color.green); }) ); - }, () => - { - LateTask.New(() => - { - if (!GameStates.IsLobby) return; - GameObject.Find("Host Buttons").transform.Find("Edit").GetComponent().ReceiveClickDown(); - }, 0.1f); + + ControllerManager.Instance.CloseOverlayMenu(confirmPresetPopUp.name); + confirmPresetPopUp.Close(); LateTask.New(() => { - if (!GameStates.IsLobby || !GameSettingMenu.Instance) return; - const int tabIndex = (int)TabGroup.PresetExplorer + 3; - GameSettingMenu.Instance.ChangeTab(tabIndex, Controller.currentTouchType == Controller.TouchType.Joystick); - ModGameOptionsMenu.TabIndex = tabIndex; - }, 0.4f); - }, showBackButton: false); + Object.Destroy(confirmPresetPopUp.gameObject); + if (!GameSettingMenu.Instance) return; + GameSettingMenu.Instance.Close(); + }, 0.5f); + }); +#if IL2CPP + foreach (PassiveButton presetCancelButton in presetCancelButtons) + { + presetCancelButton.OnClick.AddListener(() => + { + ControllerManager.Instance.CloseOverlayMenu(confirmPresetPopUp.name); + confirmPresetPopUp.Close(); + LateTask.New(() => Object.Destroy(confirmPresetPopUp.gameObject), 0.5f); + }); + } +#else + presetCancelButtons.ForEach(x => x.OnClick.AddListener(() => + { + ControllerManager.Instance.CloseOverlayMenu(confirmPresetPopUp.name); + confirmPresetPopUp.Close(); + LateTask.New(() => Object.Destroy(confirmPresetPopUp.gameObject), 0.5f); + })); +#endif + ControllerManager.Instance.OpenOverlayMenu(confirmPresetPopUp.name, presetCancelButtons[0], presetConfirmButton); }); TextMeshPro minusText = row.MinusBtn.GetComponentInChildren(); minusText.DestroyTranslator(); @@ -177,7 +288,6 @@ public static class OnlinePresetsManager row.gameObject.SetActive(true); menu.Children.Add(row); - OptionBehaviourCache[index] = row; y -= 0.6f; } @@ -330,6 +440,7 @@ public static class OnlinePresetsManager if (request.result != UnityWebRequest.Result.Success) { Logger.SendInGame($"Preset list fetch failed: {request.error}"); + onSuccess?.Invoke([]); yield break; } @@ -348,12 +459,14 @@ public static class OnlinePresetsManager Logger.SendInGame("Preset list parse failed"); Logger.Info(request.downloadHandler.text.Trim(), "Response"); Utils.ThrowException(ex); + onSuccess?.Invoke([]); yield break; } if (response?.presets == null) { Logger.SendInGame("Preset list empty or invalid"); + onSuccess?.Invoke([]); yield break; } diff --git a/Modules/OptionHolder.cs b/Modules/OptionHolder.cs index 01ea23bc9..5683053a6 100644 --- a/Modules/OptionHolder.cs +++ b/Modules/OptionHolder.cs @@ -949,7 +949,7 @@ public static class Options _ => CustomGameMode.Standard }; - public static float DefaultKillCooldown = Main.NormalOptions == null ? FallBackKillCooldownValue?.GetFloat() ?? 25f : Main.NormalOptions.KillCooldown; + public static float DefaultKillCooldown = Main.NormalOptions == null || Main.NormalOptions.KillCooldown <= 1.1f ? FallBackKillCooldownValue?.GetFloat() ?? 25f : Main.NormalOptions.KillCooldown; public static float AdjustedDefaultKillCooldown => !GameStates.InGame ? DefaultKillCooldown @@ -981,6 +981,7 @@ public static class Options GroupAddons(); LoadUserData(); Achievements.LoadAllData(); + CustomSettingsUIPatches.GameOptionsMenuPatches.InitializeSections(); // OptionShower.LastText = Translator.GetString("Loading"); if (AllCrewRolesHaveVanillaColor.GetBool()) @@ -1316,6 +1317,8 @@ public static class Options if (IsLoaded) yield break; + while (!Main.Loaded) yield return null; + OptionSaver.Initialize(); yield return null; @@ -3131,8 +3134,8 @@ public static class Options .SetColor(new Color32(193, 255, 209, byte.MaxValue)); IntegrateNaturalDisasters = new BooleanOptionItem(24454, "IntegrateNaturalDisasters", false, TabGroup.GameSettings) - .SetColor(new Color32(193, 255, 209, byte.MaxValue)) - .RegisterUpdateValueEvent((_, _, _) => GameOptionsMenuPatch.ReCreateSettings(TabGroup.GameSettings)); + .SetHidden(true) + .SetColor(new Color32(193, 255, 209, byte.MaxValue)); EnableGameTimeLimit = new BooleanOptionItem(24455, "EnableGameTimeLimit", false, TabGroup.GameSettings) .SetColor(new Color32(193, 255, 209, byte.MaxValue)) @@ -3203,7 +3206,8 @@ public static class Options id = 68000; new TextOptionItem(110040, "MenuTitle.AutoFactionMinMaxSettings", TabGroup.SystemSettings) - .SetHeader(true); + .SetHeader(true) + .SetGameMode(CustomGameMode.Standard); EnableAutoFactionMinMaxSettings = new BooleanOptionItem(id++, "EnableAutoFactionMinMaxSettings", false, TabGroup.SystemSettings) .SetHeader(true) @@ -3330,11 +3334,6 @@ public static class Options for (var index = 1; index <= MaxAutoGMRotationRandomGroups; index++) { - new TextOptionItem(100031 + index, "MenuTitle.AGMR.RandomGroup", TabGroup.SystemSettings) - .SetHeader(true) - .SetParent(EnableAutoGMRotation) - .AddReplacement(("{index}", index.ToString())); - Dictionary dict = []; foreach (CustomGameMode customGameMode in Main.CustomGameModeValues[..^1]) @@ -3343,7 +3342,9 @@ public static class Options .SetParent(EnableAutoGMRotation) .SetValueFormat(OptionFormat.Percent) .SetColor(Main.GameModeColors[customGameMode]) - .AddReplacement(("{gm}", Translator.GetString($"{customGameMode}"))); + .SetHeader(customGameMode == CustomGameMode.Standard) + .AddReplacement(("{gm}", Translator.GetString($"{customGameMode}"))) + .AddReplacement(("{index}", index.ToString())); dict[customGameMode] = chanceToSelectGMInGroup; } diff --git a/Modules/OptionItem/OptionItem.cs b/Modules/OptionItem/OptionItem.cs index a4adda7ba..e6694c4c6 100644 --- a/Modules/OptionItem/OptionItem.cs +++ b/Modules/OptionItem/OptionItem.cs @@ -12,8 +12,6 @@ public abstract class OptionItem public const int PresetId = 0; public readonly List Children; - public OptionBehaviour OptionBehaviour; - protected OptionItem(int id, string name, int defaultValue, TabGroup tab, bool isSingleValue) { Id = id; @@ -57,7 +55,7 @@ public abstract class OptionItem public bool IsSingleValue { get; } public Color NameColor { get; set; } - private OptionFormat ValueFormat { get; set; } + public OptionFormat ValueFormat { get; set; } public CustomGameMode GameMode { get; private set; } public bool IsHeader { get; protected set; } private bool IsHidden { get; set; } @@ -229,13 +227,13 @@ public abstract class OptionItem return IsSingleValue ? SingleValue : AllValues[CurrentPreset]; } - public bool IsCurrentlyHidden(bool forLobbyView = false, bool checkCollapsedSection = true) + public bool IsCurrentlyHidden(bool forLobbyView = false, bool checkParentEnabled = false) { try { for (OptionItem current = this; current != null; current = current.Parent) { - if (Hidden(current, forLobbyView, checkCollapsedSection)) + if (Hidden(this, current, forLobbyView, checkParentEnabled)) return true; } } @@ -243,9 +241,9 @@ public abstract class OptionItem return false; - static bool Hidden(OptionItem oi, bool forLobbyView, bool checkCollapsedSection) + static bool Hidden(OptionItem instance, OptionItem oi, bool forLobbyView, bool checkParentEnabled) { - if (checkCollapsedSection && oi.Header is { CollapsesSection: true }) return true; + if (checkParentEnabled && oi != instance && !oi.GetBool()) return true; CustomGameMode mode = !forLobbyView ? EHR.Options.CurrentGameMode : LobbyViewSettingsPanePatch.LastGameModeSelected; const CustomGameMode nd = CustomGameMode.NaturalDisasters; return (oi.IsHidden || oi.GameMode != CustomGameMode.All && oi.GameMode != mode || @@ -262,12 +260,6 @@ public abstract class OptionItem private void Refresh() { - if (OptionBehaviour is StringOption opt) - { - opt.TitleText.text = GetName(); - opt.ValueText.text = GetString(); - opt.oldValue = opt.Value = CurrentValue; - } } public void SetValue(int afterValue, bool doSave, bool doSync = true) @@ -348,6 +340,8 @@ public abstract class OptionItem #region static + public static readonly Dictionary BehaviourNameToItem = []; + public static readonly Dictionary SettingObjectNameToRole = []; public static IReadOnlyList AllOptions => Options; private static readonly List Options = new(1024); public static IReadOnlyDictionary FastOptions => FastOpts; diff --git a/Modules/Utils.cs b/Modules/Utils.cs index b8f5249dc..02c1bc502 100644 --- a/Modules/Utils.cs +++ b/Modules/Utils.cs @@ -209,20 +209,22 @@ public static class Utils nt.SnapTo(location, (ushort)(nt.lastSequenceId + 328)); nt.SetDirtyBit(uint.MaxValue); - + if (NumSnapToCallsThisRound >= 80) { if (log) Logger.Warn($"Too many Reliable SnapTo calls this round ({NumSnapToCallsThisRound}) - Changed to SendOption.None", "TP"); sendOption = SendOption.None; } - - if (NumSnapToCallsThisRound >= 100) + + if (GameStates.CurrentServerType == GameStates.ServerType.Vanilla) { - if (log) Logger.Warn($"Too many Total SnapTo calls this round and this second ({NumSnapToCallsThisRound}) - Canceled", "TP"); - return false; + if (NumSnapToCallsThisRound >= 100) + { + if (log) Logger.Warn($"Too many Total SnapTo calls this round and this second ({NumSnapToCallsThisRound}) - Canceled", "TP"); + return false; + } } - - if (GameStates.CurrentServerType != GameStates.ServerType.Vanilla) + else sendOption = SendOption.Reliable; var newSid = (ushort)(nt.lastSequenceId + 8); @@ -1272,7 +1274,7 @@ public static class Utils void CheckAndAppendOptionString(OptionItem item) { - if (item.GetBool() && item.Parent == null && !item.IsCurrentlyHidden(checkCollapsedSection: false)) + if (item.GetBool() && item.Parent == null && !item.IsCurrentlyHidden()) sb.Append($"\n{item.GetName(true)}: {item.GetString()}"); } } @@ -1317,7 +1319,7 @@ public static class Utils foreach (OptionItem opt in OptionItem.AllOptions) { - if (opt.GetBool() && opt.Parent == null && opt.Id is >= 80000 and < 640000 && !opt.IsCurrentlyHidden(checkCollapsedSection: false)) + if (opt.GetBool() && opt.Parent == null && opt.Id is >= 80000 and < 640000 && !opt.IsCurrentlyHidden()) { if (opt.Name is "KillFlashDuration" or "RoleAssigningAlgorithm") sb.Append($"\n【{opt.GetName(true)}: {opt.GetString()}】\n"); @@ -1365,7 +1367,7 @@ public static class Utils sb.Append($"━━━━━━━━━━━━【{GetString("Settings")}】━━━━━━━━━━━━"); - foreach (OptionItem opt in OptionItem.AllOptions.Where(x => x.GetBool() && x.Parent == null && x.Id is >= 80000 and < 640000 && !x.IsCurrentlyHidden(checkCollapsedSection: false))) + foreach (OptionItem opt in OptionItem.AllOptions.Where(x => x.GetBool() && x.Parent == null && x.Id is >= 80000 and < 640000 && !x.IsCurrentlyHidden())) { if (opt.Name == "KillFlashDuration") sb.Append($"\n【{opt.GetName(true)}: {opt.GetString()}】\n"); @@ -4302,6 +4304,9 @@ public static class Utils switch (target.GetCustomRole()) { + case CustomRoles.Trapster: + Trapster.TrapsterBody.Remove(target.PlayerId); + break; case CustomRoles.Veteran when target.AmOwner && Veteran.VeteranInProtect.Contains(target.PlayerId): Achievements.Type.BadEncounter.Complete(); break; diff --git a/Patches/ControlPatch.cs b/Patches/ControlPatch.cs index 783a04c5e..157a7dfe4 100644 --- a/Patches/ControlPatch.cs +++ b/Patches/ControlPatch.cs @@ -87,23 +87,7 @@ internal static class ControllerManagerUpdatePatch PlayerControl.LocalPlayer.Collider.offset = shouldNoclip ? new Vector2(0f, 127f) : new Vector2(0f, -0.3636f); } - if (!chatIsOpen) - { - if (isLobby) - { - /*if (Input.GetKeyDown(KeyCode.Tab)) OptionShower.Next(); - - for (var i = 0; i < 9; i++) - { - if (OrGetKeysDown(KeyCode.Alpha1 + i, KeyCode.Keypad1 + i) && OptionShower.Pages.Count >= i + 1) - OptionShower.CurrentPage = i; - }*/ - - if (Input.GetKeyDown(KeyCode.Return) && GameSettingMenu.Instance && GameSettingMenu.Instance.isActiveAndEnabled) - GameSettingMenuPatch.SearchForOptionsAction?.Invoke(); - } - } - else + if (chatIsOpen) { ChatController chat = HudManager.Instance.Chat; @@ -113,19 +97,19 @@ internal static class ControllerManagerUpdatePatch if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.C)) ClipboardHelper.PutClipboardString(chat.freeChatField.textArea.text); - - if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && - Input.GetKeyDown(KeyCode.V)) - { - var textArea = chat.freeChatField.textArea; - - string currentText = textArea.text ?? string.Empty; - string clipboard = GUIUtility.systemCopyBuffer ?? string.Empty; - - int caretPos = Mathf.Clamp(textArea.caretPos, 0, currentText.Length); - - textArea.SetText(currentText.Insert(caretPos, clipboard)); - textArea.caretPos = caretPos + clipboard.Length; + + if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && + Input.GetKeyDown(KeyCode.V)) + { + var textArea = chat.freeChatField.textArea; + + string currentText = textArea.text ?? string.Empty; + string clipboard = GUIUtility.systemCopyBuffer ?? string.Empty; + + int caretPos = Mathf.Clamp(textArea.caretPos, 0, currentText.Length); + + textArea.SetText(currentText.Insert(caretPos, clipboard)); + textArea.caretPos = caretPos + clipboard.Length; } if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.X)) @@ -308,10 +292,6 @@ internal static class ControllerManagerUpdatePatch OptionSaver.Save(); IsResetting = false; - - GameOptionsMenuPatch.ReCreateAllSettings(); - GameOptionsMenuPatch.RefreshSettingValues(); - GameOptionsMenuPatch.RefreshTabButtons(); } } } diff --git a/Patches/CustomSettingsUIPatches.cs b/Patches/CustomSettingsUIPatches.cs new file mode 100644 index 000000000..d9668e828 --- /dev/null +++ b/Patches/CustomSettingsUIPatches.cs @@ -0,0 +1,2035 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using AmongUs.GameOptions; +using EHR; +using EHR.Gamemodes; +using EHR.Modules; +using EHR.Patches; +using EHR.Roles; +using HarmonyLib; +using Rewired; +using TMPro; +using UnityEngine; + +// ReSharper disable PossibleLossOfFraction + +[HarmonyPatch] +internal static class CustomSettingsUIPatches +{ + [HarmonyPatch(typeof(GamePresetsTab))] + internal static class GamePresetsTabPatches + { + public static PassiveButton TemplatePresetButton; + public static TransitionOpen TemplateConfirmPopUp; + public static readonly Dictionary Buttons = []; + public static GameObject NDIntegrationButton; + + private static readonly Dictionary SpriteKey = new() + { + [CustomGameMode.Standard] = "ExamineBody", + [CustomGameMode.SoloPVP] = "Attack", + [CustomGameMode.FFA] = "Assassinate", + [CustomGameMode.StopAndGo] = "TimeMaster", + [CustomGameMode.HotPotato] = "Bomb", + [CustomGameMode.HideAndSeek] = "Lighter", + [CustomGameMode.Speedrun] = "Timer", + [CustomGameMode.CaptureTheFlag] = "Tag", + [CustomGameMode.NaturalDisasters] = "Tornado", + [CustomGameMode.RoomRush] = "TPToLoca", + [CustomGameMode.KingOfTheZones] = "Scanner", + [CustomGameMode.Quiz] = "Camo", + [CustomGameMode.TheMindGame] = "Puttpuer", + [CustomGameMode.BedWars] = "Drink", + [CustomGameMode.Deathrace] = "Gaulois", + [CustomGameMode.Mingle] = "InspectorIcon", + [CustomGameMode.Snowdown] = "Snowdown", + [CustomGameMode.DoomTag] = "Hangman" + }; + + [HarmonyPatch(nameof(GamePresetsTab.OnEnable))] + [HarmonyPrefix] + private static bool OnEnable(GamePresetsTab __instance) + { + try + { + CustomGameMode currentGameMode = Options.CurrentGameMode; + + if (Buttons.Count > 0) + { + foreach ((CustomGameMode customGameMode, GameObject button) in Buttons) + button.GetComponent().SelectButton(customGameMode == currentGameMode); + + NDIntegrationButton.GetComponent().SelectButton(Options.IntegrateNaturalDisasters.GetBool()); + Object.Destroy(__instance.StandardPresetButton.gameObject); + Object.Destroy(__instance.SecondPresetButton.gameObject); + __instance.StandardPresetButton = null; + __instance.SecondPresetButton = null; + __instance.PresetDescriptionText.DestroyTranslator(); + __instance.PresetDescriptionText.text = Translator.GetString($"{(CustomRoleSelector.GameModeRoles.TryGetValue(currentGameMode, out CustomRoles role) ? role.ToString() : currentGameMode.ToString())}Info").ToUpper(); + return false; + } + + PassiveButton original = __instance.StandardPresetButton; + string[] childrenNames = ["Active", "Inactive", "Selected", "InactiveSelected"]; + + foreach (CustomGameMode customGameMode in Main.CustomGameModeValues[..^1]) + { + if (SubmergedCompatibility.Loaded && Main.NormalOptions.MapId == 6 && customGameMode == CustomGameMode.NaturalDisasters) continue; + if (Main.LIMap && customGameMode is CustomGameMode.CaptureTheFlag or CustomGameMode.Quiz or CustomGameMode.BedWars or CustomGameMode.Deathrace) continue; + int num = (int)customGameMode - 1; + GameObject button = Object.Instantiate(original.gameObject, original.transform.parent); + button.name = $"{customGameMode}PresetButton"; + button.transform.localScale *= 0.3f; + button.transform.localPosition = new Vector3(-3.05f + (num % 8 * 0.9f), 1.35f - (1.25f * (num / 8)), original.transform.localPosition.z); + var passiveButton = button.GetComponent(); + passiveButton.SelectButton(currentGameMode == customGameMode); + passiveButton.OnClick.RemoveAllListeners(); + passiveButton.OnClick.AddListener(() => + { + Options.GameMode.SetValue(num); + foreach ((CustomGameMode gameMode, GameObject gameObject) in Buttons) + gameObject.GetComponent().SelectButton(gameMode == customGameMode); + __instance.PresetDescriptionText.text = Translator.GetString($"{(CustomRoleSelector.GameModeRoles.TryGetValue(customGameMode, out CustomRoles customRoles) ? customRoles.ToString() : customGameMode.ToString())}Info").ToUpper(); + GameSettingMenu.Instance.RoleSettingsButton.gameObject.SetActive(customGameMode is CustomGameMode.Standard or CustomGameMode.HideAndSeek); + GameOptionsMenuPatches.SetAllDirty(); + + if (customGameMode == CustomGameMode.NaturalDisasters && Options.IntegrateNaturalDisasters.GetBool()) + { + Options.IntegrateNaturalDisasters.SetValue(0); + NDIntegrationButton.GetComponent().SelectButton(false); + } + }); + passiveButton.OnMouseOver.RemoveAllListeners(); + passiveButton.OnMouseOver.AddListener(() => __instance.PresetDescriptionText.text = Translator.GetString($"{(CustomRoleSelector.GameModeRoles.TryGetValue(customGameMode, out CustomRoles customRoles) ? customRoles.ToString() : customGameMode.ToString())}Info").ToUpper()); + passiveButton.OnMouseOut.RemoveAllListeners(); + passiveButton.OnMouseOut.AddListener(() => __instance.PresetDescriptionText.text = Translator.GetString($"{(CustomRoleSelector.GameModeRoles.TryGetValue(currentGameMode, out CustomRoles customRoles) ? customRoles.ToString() : currentGameMode.ToString())}Info").ToUpper()); + + Color color = Main.GameModeColors.GetValueOrDefault(customGameMode, Color.white); + + foreach (string name in childrenNames) + { + Transform transform = button.transform.Find(name); + transform.Find("Label").GetComponent().color = color; + transform.Find("Frame").GetComponent().color = color; + transform.Find("Background").GetComponent().sprite = Utils.LoadSprite($"EHR.Resources.Images.Skills.{SpriteKey[customGameMode]}.png", 35f); + } + + var textMeshPro = button.transform.Find("ModeText").GetComponent(); + textMeshPro.DestroyTranslator(); + textMeshPro.text = $"{Translator.GetString(customGameMode.ToString()).ToUpper()}"; + textMeshPro.fontWeight = FontWeight.Bold; + textMeshPro.color = Color.white; + + Buttons[customGameMode] = button; + } + + // ND integration button + { + GameObject button = Object.Instantiate(original.gameObject, original.transform.parent); + button.name = "NDIntegrationPresetButton"; + button.transform.localScale *= 0.3f; + button.transform.localPosition = new Vector3(3.25f, -1.15f, original.transform.localPosition.z); + var passiveButton = button.GetComponent(); + passiveButton.SelectButton(Options.IntegrateNaturalDisasters.GetBool()); + passiveButton.OnClick.RemoveAllListeners(); + passiveButton.OnClick.AddListener(() => + { + if (Options.CurrentGameMode == CustomGameMode.NaturalDisasters) return; + Options.IntegrateNaturalDisasters.SetValue(Options.IntegrateNaturalDisasters.GetBool() ? 0 : 1); + passiveButton.SelectButton(Options.IntegrateNaturalDisasters.GetBool()); + GameOptionsMenuPatches.SetAllDirty(); + }); + passiveButton.OnMouseOver.RemoveAllListeners(); + passiveButton.OnMouseOver.AddListener(() => __instance.PresetDescriptionText.text = Translator.GetString("IntegrateNaturalDisasters").ToUpper()); + passiveButton.OnMouseOut.RemoveAllListeners(); + passiveButton.OnMouseOut.AddListener(() => __instance.PresetDescriptionText.text = Translator.GetString($"{(CustomRoleSelector.GameModeRoles.TryGetValue(Options.CurrentGameMode, out CustomRoles customRoles) ? customRoles.ToString() : Options.CurrentGameMode.ToString())}Info").ToUpper()); + + var textMeshPro = button.transform.Find("ModeText").GetComponent(); + textMeshPro.DestroyTranslator(); + textMeshPro.text = string.Empty; + + var text = Object.Instantiate(textMeshPro, textMeshPro.transform.parent); + text.transform.localPosition += new Vector3(0f, 1.6f, 0f); + text.GetComponent().sizeDelta = new(2.5f, 2.5f); + text.text = $"{Translator.GetString("NDIntegrationShort").ToUpper()}"; + + Color color = Main.GameModeColors[CustomGameMode.NaturalDisasters]; + + foreach (string name in childrenNames) + { + Transform transform = button.transform.Find(name); + transform.Find("Frame").GetComponent().color = color; + Object.Destroy(transform.Find("Label").GetComponent().gameObject); + Object.Destroy(transform.Find("Background").GetComponent().gameObject); + } + + NDIntegrationButton = button; + } + + if (!TemplatePresetButton) + { + TemplatePresetButton = Object.Instantiate(original, original.transform.parent); + TemplatePresetButton.gameObject.SetActive(false); + } + + if (!TemplateConfirmPopUp) + { + TemplateConfirmPopUp = Object.Instantiate(__instance.ConfirmPresetPopUp, __instance.ConfirmPresetPopUp.transform.parent); + TemplateConfirmPopUp.gameObject.SetActive(false); + } + + Object.Destroy(original.gameObject); + Object.Destroy(__instance.SecondPresetButton.gameObject); + __instance.StandardPresetButton = null; + __instance.SecondPresetButton = null; + __instance.PresetDescriptionText.DestroyTranslator(); + __instance.PresetDescriptionText.text = Translator.GetString($"{(CustomRoleSelector.GameModeRoles.TryGetValue(currentGameMode, out CustomRoles roles) ? roles.ToString() : currentGameMode.ToString())}Info").ToUpper(); + } + catch { } + + return false; + } + + [HarmonyPatch(nameof(GamePresetsTab.Start))] + [HarmonyPrefix] + private static bool Start(GamePresetsTab __instance) + { + return false; + } + + [HarmonyPatch(nameof(GamePresetsTab.SetSelectedText))] + [HarmonyPrefix] + private static bool SetSelectedText(GamePresetsTab __instance) + { + return false; + } + } + + [HarmonyPatch(typeof(GameOptionsMenu))] + internal static class GameOptionsMenuPatches + { + private static readonly Dictionary> Sections = []; + private static readonly HashSet DirtySections = []; + private static string BasicSettingsSection; + + public static void InitializeSections() + { + List irrelevantOptionIds = + [ + .. Options.CustomRoleSpawnChances.Values + .Concat(Options.CustomRoleSpawnChances.Values.SelectMany(x => x.Children)) + .Concat(Options.CustomRoleCounts.Values) + .Concat(Options.AddonGuessSettings.Values) + .Concat(Options.CustomAdtRoleSpawnRate.Values) + .Concat(Options.AddonCanBeSettings.Values.SelectMany(x => new[] + { + x.Imp, + x.Neutral, + x.Crew, + x.Coven + })) + .Select(x => x.Id), + + 0, + 1 + ]; + + BasicSettingsSection = $"MODDED_{Translator.GetString("BasicSettings").ToUpper()}"; + Sections[BasicSettingsSection] = []; + + foreach ((EHR.TabGroup tab, OptionItem[] options) in Options.GroupedOptions) + { + if (tab == EHR.TabGroup.OtherRoles) continue; + bool gameSettings = tab == EHR.TabGroup.GameSettings; + string section = null; + bool any = false; + + foreach (OptionItem optionItem in options) + { + if (irrelevantOptionIds.Contains(optionItem.Id) || optionItem.GameMode is not (CustomGameMode.Standard or CustomGameMode.All) && !gameSettings) continue; + + if (optionItem is TextOptionItem textOptionItem && !textOptionItem.Name.StartsWith("ROT.")) + { + if (!any && !string.IsNullOrEmpty(section)) Sections.Remove(section); + section = $"MODDED_{textOptionItem.GetName(true).Trim('★', ' ').ToUpper()}"; + any = false; + continue; + } + + if (string.IsNullOrEmpty(section)) + section = $"MODDED_{Translator.GetString(gameSettings ? "GameModeSettings" : $"TabGroup.{tab}").ToUpper()}"; + + Sections.TryAdd(section, []); + Sections[section].Add(optionItem); + any = true; + } + } + } + + public static void SetAllDirty() + { + DirtySections.UnionWith(Sections.Keys); + } + + [HarmonyPatch(nameof(GameOptionsMenu.OpenMenu))] + [HarmonyPrefix] + static bool OpenMenu(GameOptionsMenu __instance) + { + ControllerManager.Instance.OpenOverlayMenu(__instance.name, __instance.BackButton, __instance.ControllerSelectable[0], __instance.ControllerSelectable); + return false; + } + + [HarmonyPatch(nameof(GameOptionsMenu.Initialize))] + [HarmonyPrefix] + private static bool Initialize(GameOptionsMenu __instance) + { + if (__instance.name.StartsWith("IDX_")) + { + int idx = int.Parse(__instance.name[4..]); + if (idx == 1000) return false; + __instance.name = Sections.Keys.ElementAt(idx - 10); + } + + if (__instance.name == BasicSettingsSection) return true; + + if (__instance.Children != null && __instance.Children.Count != 0) + { + if (DirtySections.Remove(__instance.name)) + ValueChanged(__instance, null); + + return false; + } + + Object.Destroy(__instance.MapPicker.gameObject); + __instance.Children = new(); + __instance.CreateSettings(); + __instance.cachedData = GameOptionsManager.Instance.CurrentGameOptions; + + for (var index = 0; index < __instance.Children.Count; ++index) + { + OptionBehaviour child = __instance.Children[index]; +#if IL2CPP + child.OnValueChanged = (Action)__instance.ValueChanged; +#else + child.OnValueChanged = __instance.ValueChanged; +#endif + if (AmongUsClient.Instance && !AmongUsClient.Instance.AmHost) + child.SetAsPlayer(); + } + + __instance.InitializeControllerNavigation(); + return false; + } + + [HarmonyPatch(nameof(GameOptionsMenu.CreateSettings))] + [HarmonyPrefix] + private static bool CreateSettings(GameOptionsMenu __instance) + { + if (__instance.name == BasicSettingsSection) + return true; + + var y = 2f; + + if (Sections.TryGetValue(__instance.name, out List options)) + { + StringOption back = Object.Instantiate(__instance.stringOptionOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer); + back.name = $"BACK_BUTTON_{__instance.name}"; + back.transform.localPosition = new Vector3(0.952f, y, -2f); + back.SetClickMask(__instance.ButtonClickMask); + back.SetUpFromData(null, 20); + + Object.Destroy(back.ValueText.gameObject); + Object.Destroy(back.transform.Find("ValueBox").gameObject); + Object.Destroy(back.PlusBtn.gameObject); + back.ValueText = null; + back.PlusBtn = null; + + back.MinusBtn.OnClick = new(); + back.MinusBtn.OnClick.AddListener(() => GameSettingMenu.Instance.ChangeTab(1, false)); + back.MinusBtn.transform.localPosition -= new Vector3(3f, 0f, 0f); + Vector3 scale = back.MinusBtn.transform.localScale; + back.MinusBtn.transform.localScale = new Vector3(scale.x * 7f, scale.y, scale.z); + var text = back.MinusBtn.GetComponentInChildren(); + Vector3 textScale = text.transform.localScale; + text.transform.localScale = new Vector3(textScale.x / 7f, textScale.y, textScale.z); + text.autoSizeTextContainer = false; + text.GetComponent().sizeDelta = new(3f, 0.37f); + text.DestroyTranslator(); + text.text = $"⬅ {Translator.GetString("BackToList")}"; + back.TitleText.enabled = false; + back.LabelBackground.enabled = false; + back.gameObject.SetActive(true); + + __instance.Children.Add(back); + + for (var i = 0; i < options.Count; i++) + { + OptionItem optionItem = options[i]; + + if (!InstantiateOptionBehaviour(optionItem, __instance.settingsContainer, out OptionBehaviour optionBehaviour, out BaseGameSetting baseGameSetting, __instance.checkboxOrigin, __instance.numberOptionOrigin, __instance.stringOptionOrigin)) + continue; + + Vector3 positionOffset = new(0f, 0f, 0f); + Vector3 scaleOffset = new(0f, 0f, 0f); + Color color = new(0.35f, 0.35f, 0.35f); + var sizeDeltaX = 5.7f; + + var depth = 0; + OptionItem parent = optionItem.Parent; + + while (parent != null && depth < 3) + { + depth++; + parent = parent.Parent; + } + + if (depth > 0) + { + scaleOffset.x = -0.06f * depth; + positionOffset.x = 0.1f * depth; + sizeDeltaX = 5.7f - (0.2f * depth); + + color = depth switch + { + 1 => new(0f, 0f, 0.35f), + 2 => new(0.35f, 0.35f, 0f), + _ => new(0.35f, 0f, 0f) + }; + } + + SpriteRenderer labelBackground = optionBehaviour.LabelBackground; + labelBackground.color = color; + Transform labelBackgroundTransform = labelBackground.transform; + labelBackgroundTransform.localScale += new Vector3(0.9f, -0.2f, 0f) + scaleOffset; + labelBackgroundTransform.localPosition += new Vector3(-0.4f, 0f, 0f) + positionOffset; + +#if IL2CPP + TextMeshPro titleText = GetTitleTextAndSetPositions(optionBehaviour, optionItem); +#else + TextMeshPro titleText = GetTitleTextAndSetPositions(optionBehaviour); +#endif + titleText.transform.localPosition += new Vector3(-0.4f, 0f, 0f) + positionOffset; + titleText.GetComponent().sizeDelta = new(sizeDeltaX, 0.37f); + titleText.alignment = TextAlignmentOptions.MidlineLeft; + titleText.fontStyle = FontStyles.Bold; + titleText.outlineWidth = 0.17f; + + bool hidden = optionItem.IsCurrentlyHidden(checkParentEnabled: true); + + if (!hidden) + { + y -= 0.45f; + if (optionItem.IsHeader) y -= 0.18f; + } + + optionBehaviour.transform.localPosition = new Vector3(0.952f, y, -2f); + optionBehaviour.SetClickMask(__instance.ButtonClickMask); + optionBehaviour.SetUpFromData(baseGameSetting, 20); + optionBehaviour.gameObject.SetActive(!hidden); + __instance.Children.Add(optionBehaviour); + } + + y -= 0.45f; + } + else + { + var index = 0; + + foreach (string sectionTitle in Sections.Keys) + { + StringOption section = Object.Instantiate(__instance.stringOptionOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer); + section.name = sectionTitle; + section.transform.localPosition = new Vector3(0.952f, y, -2f); + section.SetClickMask(__instance.ButtonClickMask); + section.SetUpFromData(null, 20); + + Object.Destroy(section.ValueText.gameObject); + Object.Destroy(section.transform.Find("ValueBox").gameObject); + Object.Destroy(section.PlusBtn.gameObject); + section.ValueText = null; + section.PlusBtn = null; + + int currentIndex = index; + section.MinusBtn.OnClick = new(); + section.MinusBtn.OnClick.AddListener(() => GameSettingMenu.Instance.ChangeTab(10 + currentIndex, false)); + section.MinusBtn.transform.localPosition += new Vector3(1.3f, 0f, 0f); + Vector3 scale = section.MinusBtn.transform.localScale; + section.MinusBtn.transform.localScale = new Vector3(scale.x * 2f, scale.y, scale.z); + var text = section.MinusBtn.GetComponentInChildren(); + text.DestroyTranslator(); + text.text = "➡"; + section.TitleText.DestroyTranslator(); + section.TitleText.GetComponent().sizeDelta = new(5.7f, 0.37f); + section.TitleText.alignment = TextAlignmentOptions.MidlineLeft; + section.TitleText.fontStyle = FontStyles.Bold; + section.TitleText.outlineWidth = 0.17f; + section.LabelBackground.enabled = false; + section.gameObject.SetActive(true); + + __instance.Children.Add(section); + + y -= 0.45f; + index++; + } + } + +#if IL2CPP + foreach (var uiElement in __instance.scrollBar.GetComponentsInChildren()) + __instance.ControllerSelectable.Add(uiElement); +#else + __instance.ControllerSelectable.AddRange(__instance.scrollBar.GetComponentsInChildren()); +#endif + __instance.scrollBar.SetYBoundsMax(-y - 1.65f); + return false; + } + + [HarmonyPatch(nameof(GameOptionsMenu.Update))] + [HarmonyPrefix] + private static void PreUpdate(GameOptionsMenu __instance) + { + if (!HudManager.InstanceExists || !__instance.gameObject.activeSelf || !GameSettingMenu.Instance) return; + __instance.scrollBar.enabled = !HudManager.Instance.Chat.IsOpenOrOpening; + } + + [HarmonyPatch(nameof(GameOptionsMenu.ValueChanged))] + [HarmonyPrefix] + private static bool ValueChanged(GameOptionsMenu __instance, OptionBehaviour option) + { + if (option) + { + if (!OptionItem.BehaviourNameToItem.TryGetValue(option.name, out OptionItem item)) return true; + if (item.Children.Count == 0) return false; + } + + var y = 2f; + + foreach (OptionBehaviour optionBehaviour in __instance.Children) + { + if (!OptionItem.BehaviourNameToItem.TryGetValue(optionBehaviour.name, out OptionItem optionItem)) continue; + +#if IL2CPP + switch (optionItem) + { + case BooleanOptionItem when optionBehaviour.TryCastFast(out ToggleOption toggleOption): + toggleOption.CheckMark.enabled = optionItem.GetBool(); + break; + case StringOptionItem when optionBehaviour.TryCastFast(out StringOption stringOption): + stringOption.Value = optionItem.GetInt(); + stringOption.oldValue = stringOption.Value; + stringOption.ValueText.SetText(optionItem.GetString()); + stringOption.TitleText.SetText(optionItem.GetName()); + break; + case FloatOptionItem: + case IntegerOptionItem: + NumberOption numberOption = optionBehaviour.CastFast(); + numberOption.Value = optionItem.GetFloat(); + break; + } +#else + switch (optionBehaviour) + { + case ToggleOption toggleOption: + toggleOption.CheckMark.enabled = optionItem.GetBool(); + break; + case StringOption stringOption: + stringOption.Value = optionItem.GetInt(); + stringOption.oldValue = stringOption.Value; + stringOption.ValueText.SetText(optionItem.GetString()); + stringOption.TitleText.SetText(optionItem.GetName()); + break; + case NumberOption numberOption: + numberOption.Value = optionItem.GetFloat(); + break; + } +#endif + + bool hidden = optionItem.IsCurrentlyHidden(checkParentEnabled: true); + optionBehaviour.gameObject.SetActive(!hidden); + if (hidden) continue; + y -= 0.45f; + if (optionItem.IsHeader) y -= 0.18f; + + optionBehaviour.transform.localPosition = new Vector3(0.952f, y, -2f); + } + + y -= 0.45f; + __instance.scrollBar.SetYBoundsMax(-y - 1.65f); + return false; + } + } + + [HarmonyPatch(typeof(RolesSettingsMenu))] + private static class RolesSettingsMenuPatches + { + private static StringOption BackButton; + private static readonly int StencilComp = Shader.PropertyToID("_StencilComp"); + private static readonly int Stencil = Shader.PropertyToID("_Stencil"); + private static readonly Dictionary Tabs = []; + private static readonly Dictionary TabChildrenCount = []; + private static readonly Dictionary TabButtons = []; + private static Vector3 TabPosition; + private static Transform TempParent; + + [HarmonyPatch(nameof(RolesSettingsMenu.OnEnable))] + [HarmonyPrefix] + public static bool OnEnable(RolesSettingsMenu __instance) + { + if (Tabs.Count > 0) + { + __instance.roleChances = new(); + __instance.QuotaTabSelectables = new(); + + foreach (GameObject gameObject in Tabs.Values) + { + gameObject.transform.SetParent(__instance.scrollBar.Inner); + gameObject.transform.localPosition = TabPosition; + + foreach (RoleOptionSetting roleOptionSetting in gameObject.GetComponentsInChildren(true)) + { + __instance.roleChances.Add(roleOptionSetting); +#if IL2CPP + roleOptionSetting.OnValueChanged = (Action)ValueChanged; + + foreach (var button in roleOptionSetting.ControllerSelectable) + __instance.QuotaTabSelectables.Add(button); +#else + roleOptionSetting.OnValueChanged = ValueChanged; + __instance.QuotaTabSelectables.AddRange(roleOptionSetting.ControllerSelectable); +#endif + } + } + + CustomGameMode currentGameMode = Options.CurrentGameMode; + __instance.roleTabs = new(); + + foreach ((Vector3 position, PassiveButton button) in TabButtons) + { + button.transform.SetParent(__instance.roleSettingsTabParent); + button.transform.localPosition = position; + button.gameObject.SetActive(currentGameMode == CustomGameMode.Standard); + __instance.roleTabs.Add(button); + } + + __instance.roleTabs[^1].gameObject.SetActive(currentGameMode == CustomGameMode.HideAndSeek); + + if (__instance.AllButton) + TidyStuff(__instance); + + Tabs[currentGameMode == CustomGameMode.HideAndSeek ? (EHR.TabGroup)100 : EHR.TabGroup.ImpostorRoles].SetActive(true); + } + else + __instance.RoleChancesSettings.SetActive(true); + __instance.AdvancedRolesSettings.SetActive(false); + RefreshChildren(); + foreach (SpriteRenderer componentsInChild in __instance.AdvancedRolesSettings.GetComponentsInChildren(true)) + componentsInChild.material.SetInt(PlayerMaterial.MaskLayer, 20); + foreach (TextMeshPro componentsInChild in __instance.AdvancedRolesSettings.GetComponentsInChildren(true)) + { + componentsInChild.fontMaterial.SetFloat(StencilComp, 3f); + componentsInChild.fontMaterial.SetFloat(Stencil, 20f); + } + + return false; + } + + [HarmonyPatch(nameof(RolesSettingsMenu.OpenMenu))] + [HarmonyPrefix] + static bool OpenMenu(RolesSettingsMenu __instance, bool controllerSelected = true) + { + if (controllerSelected) + { + ControllerManager.Instance.OpenOverlayMenu(__instance.name, __instance.BackButton, __instance.DefaultButtonSelected, __instance.ControllerSelectable); + __instance.EnableTabControllerGlyphs(true); + } + EnsureSetupCompleted(controllerSelected); + OpenChancesTab(Options.CurrentGameMode == CustomGameMode.HideAndSeek ? (EHR.TabGroup)100 : EHR.TabGroup.ImpostorRoles, __instance.roleTabs[0], controllerSelected); + return false; + } + + [HarmonyPatch(nameof(RolesSettingsMenu.CloseMenu))] + [HarmonyPrefix] + public static void PreCloseMenu(RolesSettingsMenu __instance) + { + if (BackButton) + { + Object.Destroy(BackButton.gameObject); + BackButton = null; + } + + if (!TempParent) + { + var gameObject = new GameObject("Forever-living parent"); + Object.DontDestroyOnLoad(gameObject); + gameObject.SetActive(true); + TempParent = gameObject.transform; + } + + foreach (PassiveButton passiveButton in TabButtons.Values) + { + passiveButton.transform.SetParent(TempParent); + passiveButton.gameObject.SetActive(false); + } + + foreach (GameObject tab in Tabs.Values) + { + tab.transform.SetParent(TempParent); + tab.SetActive(false); + } + } + + [HarmonyPatch(nameof(RolesSettingsMenu.Update))] + [HarmonyPrefix] + public static bool Update(RolesSettingsMenu __instance) + { + if (__instance.cachedData != GameOptionsManager.Instance.CurrentGameOptions.RoleOptions) + { + __instance.cachedData = GameOptionsManager.Instance.CurrentGameOptions.RoleOptions; + RefreshChildren(); + } + if (ControllerManager.Instance.CurrentUiState.MenuName == __instance.name) + { + Player player = ReInput.players.GetPlayer(0); + bool flag = false; + if (__instance.selectedRoleTab > 0 && player.GetButtonDown(35)) + { + --__instance.selectedRoleTab; + flag = true; + if (__instance.roleTabs[__instance.selectedRoleTab].transform.position.x < (double) __instance.roleTabsMinPos.position.x) + __instance.roleTabsScroller.ScrollRelative(new Vector2(0.762f, 0.0f)); + } + if (__instance.selectedRoleTab < __instance.roleTabs.Count - 1 && player.GetButtonDown(34)) + { + ++__instance.selectedRoleTab; + flag = true; + if (__instance.roleTabs[__instance.selectedRoleTab].transform.position.x > (double) __instance.roleTabsMaxPos.position.x) + __instance.roleTabsScroller.ScrollRelative(new Vector2(-0.762f, 0.0f)); + } + if (flag) + { + __instance.roleTabs[__instance.selectedRoleTab].OnClick.Invoke(); + } + __instance.glyphL.color = __instance.selectedRoleTab <= 0 ? __instance.glyphUnavailableColor : Color.white; + __instance.glyphR.color = __instance.selectedRoleTab >= __instance.roleTabs.Count - 1 ? __instance.glyphUnavailableColor : Color.white; + } + + __instance.roleTabsGradient.SetActive(!__instance.roleTabsScroller.AtLeft); + return false; + } + + private static void AddRoleTab(EHR.TabGroup tabGroup, ref float tabXPos) + { + RolesSettingsMenu instance = GameSettingMenu.Instance.RoleSettingsTab; + PassiveButton tabButton = Object.Instantiate(instance.AllButton, Vector3.zero, Quaternion.identity, instance.roleSettingsTabParent); + tabButton.name = $"MODDED_{tabGroup}"; + tabButton.transform.localPosition = new Vector3(tabXPos, 2.275f, -2f); + Color color = tabGroup switch + { + EHR.TabGroup.ImpostorRoles => new Color32(255, 25, 25, 255), + EHR.TabGroup.CrewmateRoles => new Color32(140, 255, 255, 255), + EHR.TabGroup.NeutralRoles => new Color32(255, 171, 27, 255), + EHR.TabGroup.CovenRoles => new Color32(123, 63, 187, 255), + EHR.TabGroup.Addons => new Color32(0, 255, 107, 255), + EHR.TabGroup.OtherRoles => new Color32(255, 255, 68, 255), + _ => Color.white + }; + tabButton.transform.Find("Inactive").GetComponent().color = color; + tabButton.transform.Find("Highlight").GetComponent().color = color; + tabButton.transform.Find("Selected").GetComponent().color = color; + + TextMeshPro textMeshPro = tabButton.transform.Find("Text").GetComponent(); + textMeshPro.DestroyTranslator(); + textMeshPro.color = Color.black; + textMeshPro.text = tabGroup switch + { + EHR.TabGroup.ImpostorRoles => "★", + EHR.TabGroup.CrewmateRoles => "⚽", + EHR.TabGroup.NeutralRoles => "◈", + EHR.TabGroup.CovenRoles => "†", + EHR.TabGroup.Addons => "✚", + EHR.TabGroup.OtherRoles => "☁", + _ => "" + } + $"\n{Translator.GetString($"ShortTabName.{tabGroup}")} "; + + tabButton.OnClick.RemoveAllListeners(); + tabButton.OnClick.AddListener(() => OpenChancesTab(tabGroup, tabButton, ActiveInputManager.currentControlType == ActiveInputManager.InputType.Joystick)); + tabButton.gameObject.SetActive(Options.CurrentGameMode == CustomGameMode.Standard); + tabXPos += 0.762f; + instance.roleTabs.Add(tabButton); + TabButtons[tabButton.transform.localPosition] = tabButton; + } + + [HarmonyPatch(nameof(RolesSettingsMenu.SetQuotaTab))] + [HarmonyPrefix] + public static bool SetQuotaTab(RolesSettingsMenu __instance) + { + Main.Instance.StartCoroutine(CreateRoleSettingsTabs()); + return false; + + System.Collections.IEnumerator CreateRoleSettingsTabs() + { + float tabXPos = -1.928f; + __instance.roleTabs = new(); + + for (EHR.TabGroup tabGroup = EHR.TabGroup.ImpostorRoles; tabGroup <= EHR.TabGroup.OtherRoles; tabGroup++) + { + AddRoleTab(tabGroup, ref tabXPos); + + GameObject tab = Object.Instantiate(__instance.RoleChancesSettings, __instance.RoleChancesSettings.transform.parent, false); + var localPosition = tab.transform.localPosition; + localPosition.z = -3f; + TabPosition = tab.transform.localPosition = localPosition; + + float y = 1f; + int index = 0; + int num = 0; + + foreach (var group in Options.CustomRoleSpawnChances.Where(x => x.Value.Tab == tabGroup && x.Value.GameMode == CustomGameMode.Standard).GroupBy(x => tabGroup switch + { + EHR.TabGroup.Addons => (int)Options.GroupedAddons.First(k => k.Value.Contains(x.Key)).Key, + EHR.TabGroup.OtherRoles => (int)RoleOptionType.Crewmate_Miscellaneous, + _ => (int)x.Key.GetRoleOptionType() + })) + { + bool addons = tabGroup == EHR.TabGroup.Addons; + Color color = addons ? ((AddonTypes)group.Key).GetAddonTypeColor() : ((RoleOptionType)group.Key).GetRoleOptionTypeColor(); + + var categoryHeaderEditRole = Object.Instantiate(__instance.categoryHeaderEditRoleOrigin, Vector3.zero, Quaternion.identity, tab.transform); + categoryHeaderEditRole.SetHeader(StringNames.None, 20); + categoryHeaderEditRole.Title.text = Translator.GetString(addons ? $"ROT.AddonType.{((AddonTypes)group.Key)}" : $"ROT.{((RoleOptionType)group.Key)}").Trim('★', ' ').ToUpper(); + categoryHeaderEditRole.Title.color = Utils.GetTextColor(color); + categoryHeaderEditRole.Background.color = color; + categoryHeaderEditRole.blankLabel.color = color.ShadeColor(0.5f); + categoryHeaderEditRole.chanceLabel.color = color.ShadeColor(0.25f); + categoryHeaderEditRole.countLabel.color = color.ShadeColor(0.25f); + categoryHeaderEditRole.transform.localPosition = new Vector3(4.986f, y, -2f); + categoryHeaderEditRole.gameObject.SetActive(true); + num++; + y -= 0.522f; + bool any = false; + + foreach ((CustomRoles role, StringOptionItem stringOptionItem) in group) + { + CreateQuotaOption(role, ref y, index, tab, stringOptionItem); + any = true; + index++; + } + + if (!any) + { + Object.Destroy(categoryHeaderEditRole.gameObject); + y += 0.742f; + } + + y -= 0.22f; + } + + tab.SetActive(false); + Tabs[tabGroup] = tab; + TabChildrenCount[tabGroup] = index + num * 2; + + yield return null; + } + + // HNS Roles tab + { + const EHR.TabGroup tabGroup = (EHR.TabGroup)100; + + // AddRoleTab reimplementation + { + PassiveButton tabButton = Object.Instantiate(__instance.AllButton, Vector3.zero, Quaternion.identity, __instance.roleSettingsTabParent); + tabButton.name = "MODDED_HNSRoles"; + tabButton.transform.localPosition = new Vector3(-2.69f, 2.275f, -2f); + Color color = Main.GameModeColors[CustomGameMode.HideAndSeek]; + tabButton.transform.Find("Inactive").GetComponent().color = color; + tabButton.transform.Find("Highlight").GetComponent().color = color; + tabButton.transform.Find("Selected").GetComponent().color = color; + + TextMeshPro textMeshPro = tabButton.transform.Find("Text").GetComponent(); + textMeshPro.DestroyTranslator(); + textMeshPro.color = Color.black; + textMeshPro.text = $"☯\n{Translator.GetString("ShortTabName.HNSRoles")} "; + + tabButton.OnClick.RemoveAllListeners(); + tabButton.OnClick.AddListener(() => OpenChancesTab(tabGroup, tabButton, ActiveInputManager.currentControlType == ActiveInputManager.InputType.Joystick)); + tabButton.gameObject.SetActive(Options.CurrentGameMode == CustomGameMode.HideAndSeek); + __instance.roleTabs.Add(tabButton); + TabButtons[tabButton.transform.localPosition] = tabButton; + } + + GameObject tab = Object.Instantiate(__instance.RoleChancesSettings, __instance.RoleChancesSettings.transform.parent, false); + var localPosition = tab.transform.localPosition; + localPosition.z = -3f; + tab.transform.localPosition = localPosition; + + float y = 1f; + int index = 0; + int num = 0; + + foreach (var group in CustomHnS.GetAllHnsRoleTypes().Select(x => (Role: Enum.Parse(ignoreCase: true, value: x.Name), Interface: (IHideAndSeekRole)Activator.CreateInstance(x))).Where(x => x.Role is not (CustomRoles.Hider or CustomRoles.Seeker)).GroupBy(x => x.Interface.Team)) + { + Team team = group.Key; + Color color = team.GetColor(); + + var categoryHeaderEditRole = Object.Instantiate(__instance.categoryHeaderEditRoleOrigin, Vector3.zero, Quaternion.identity, tab.transform); + categoryHeaderEditRole.SetHeader(StringNames.None, 20); + categoryHeaderEditRole.Title.text = Translator.GetString($"HNS.{team}Roles").ToUpper(); + categoryHeaderEditRole.Title.color = Utils.GetTextColor(color); + categoryHeaderEditRole.Background.color = color; + categoryHeaderEditRole.blankLabel.color = color.ShadeColor(0.5f); + categoryHeaderEditRole.chanceLabel.color = color.ShadeColor(0.25f); + categoryHeaderEditRole.countLabel.color = color.ShadeColor(0.25f); + categoryHeaderEditRole.transform.localPosition = new Vector3(4.986f, y, -2f); + categoryHeaderEditRole.gameObject.SetActive(true); + num++; + y -= 0.522f; + bool any = false; + + foreach ((CustomRoles role, _) in group) + { + CreateQuotaOption(role, ref y, index, tab, Options.CustomRoleSpawnChances[role]); + any = true; + index++; + } + + if (!any) + { + Object.Destroy(categoryHeaderEditRole.gameObject); + y += 0.742f; + } + + y -= 0.22f; + } + + tab.SetActive(false); + Tabs[tabGroup] = tab; + TabChildrenCount[tabGroup] = index + num * 2; + + yield return null; + } + + TidyStuff(__instance); + } + } + + private static void TidyStuff(RolesSettingsMenu __instance) + { + Object.Destroy(__instance.roleScreenshot.gameObject); + Object.Destroy(__instance.AdvancedRolesSettings.transform.Find("Background").gameObject); + Object.Destroy(__instance.AdvancedRolesSettings.transform.Find("Imagebackground").gameObject); + Object.Destroy(__instance.AdvancedRolesSettings.transform.Find("InfoLabelBackground").gameObject); + Object.Destroy(__instance.AdvancedRolesSettings.GetComponentInChildren().gameObject); + Object.Destroy(__instance.RoleChancesSettings); + Object.Destroy(__instance.AllButton.gameObject); + __instance.roleScreenshot = null; + __instance.RoleChancesSettings = null; + __instance.AllButton = null; + + Transform roleDescriptionBox = __instance.roleDescriptionText.transform.parent; + roleDescriptionBox.localPosition = new Vector3(1.4f, - 0.2531f, -1f); + roleDescriptionBox.localScale = new Vector3(0.114f, 0.3f, roleDescriptionBox.localScale.z); + Vector3 scale = __instance.roleDescriptionText.transform.localScale; + __instance.roleDescriptionText.transform.localScale = new Vector3(scale.x / 1.6f, scale.y / 2f, scale.z); + __instance.roleDescriptionText.GetComponent().sizeDelta = new Vector2(5.55f, 1.15f); + } + + private static void CreateQuotaOption(CustomRoles role, ref float yPos, int index, GameObject tab, StringOptionItem optionItem) + { + RolesSettingsMenu instance = GameSettingMenu.Instance.RoleSettingsTab; + RoleOptionSetting roleOptionSetting = Object.Instantiate(instance.roleOptionSettingOrigin, Vector3.zero, Quaternion.identity, tab.transform); + roleOptionSetting.transform.localPosition = new Vector3(-0.15f, yPos, -2f); + RoleOptionSettingPatches.SetRole(roleOptionSetting, role, 20); +#if IL2CPP + roleOptionSetting.OnValueChanged = (Action)ValueChanged; +#else + roleOptionSetting.OnValueChanged = ValueChanged; +#endif + roleOptionSetting.SetClickMask(instance.ButtonClickMask); + roleOptionSetting.name = $"MODDED_{role}"; + roleOptionSetting.gameObject.SetActive(true); + OptionItem.SettingObjectNameToRole[roleOptionSetting.name] = role; + instance.roleChances.Add(roleOptionSetting); + + if (optionItem.Children.Count > 1) + { + GameOptionButton settingsButton = Object.Instantiate(roleOptionSetting.CountMinusBtn, roleOptionSetting.CountMinusBtn.transform.parent, true); + settingsButton.name = $"MODDED_{role}_AdvancedSettingsButton"; + var text = settingsButton.GetComponentInChildren(); + text.SetText("✽"); + text.color = Color.white; + settingsButton.buttonSprite.color = Color.black; + settingsButton.interactableColor = Color.black; + settingsButton.interactableHoveredColor = Utils.GetRoleColor(role); + settingsButton.transform.localPosition += new Vector3(-2.4f, 0f, 0f); + settingsButton.OnClick = new(); + settingsButton.OnClick.AddListener(() => ChangeTab(role)); + settingsButton.gameObject.SetActive(role.IsEnable()); + } + + if (index != 0) + { + for (var i = 0; i < roleOptionSetting.ControllerSelectable.Count; ++i) + { + roleOptionSetting.ControllerSelectable[i].ControllerNav.selectOnUp = instance.roleChances[index - 1].ControllerSelectable[i]; + instance.roleChances[index - 1].ControllerSelectable[i].ControllerNav.selectOnDown = roleOptionSetting.ControllerSelectable[i]; + } + } + +#if IL2CPP + foreach (var button in roleOptionSetting.ControllerSelectable) + instance.QuotaTabSelectables.Add(button); +#else + instance.QuotaTabSelectables.AddRange(roleOptionSetting.ControllerSelectable); +#endif + yPos -= 0.43f; + } + + private static void ChangeTab(CustomRoles role) + { + RolesSettingsMenu instance = GameSettingMenu.Instance.RoleSettingsTab; + CreateAdvancedSettings(role); + string info = Translator.GetString($"{role}InfoLong"); + if (info.Length > 500) info = info.Split("\n\n")[0]; + if (!role.IsGhostRole() && info.Contains("):\n")) info = info.Split("):\n")[1]; + instance.roleDescriptionText.text = info; + instance.roleTitleText.text = Translator.GetString(role.ToString()).ToUpper(); + Color roleColor = Utils.GetRoleColor(role); + instance.roleHeaderSprite.color = roleColor; + instance.roleHeaderText.color = Utils.GetTextColor(roleColor); + + for (var index = 0; index < instance.advancedSettingChildren.Count; ++index) + { + OptionBehaviour advancedSettingChild = instance.advancedSettingChildren[index]; +#if IL2CPP + advancedSettingChild.OnValueChanged = (Action)ValueChanged; +#else + advancedSettingChild.OnValueChanged = ValueChanged; +#endif + if (AmongUsClient.Instance && !AmongUsClient.Instance.AmHost) + advancedSettingChild.SetAsPlayer(); + } + + foreach (GameObject gameObject in Tabs.Values) + gameObject.SetActive(false); + instance.AdvancedRolesSettings.SetActive(true); + RefreshChildren(); + ControllerManager.Instance.CurrentUiState.SelectableUiElements = instance.ControllerSelectable; + ControllerManager.Instance.SetDefaultSelection(instance.ControllerSelectable[0]); + } + + [HarmonyPatch(nameof(RolesSettingsMenu.OpenChancesTab))] + [HarmonyPrefix] + static bool OpenChancesTabRedirect(RolesSettingsMenu __instance, bool controllerSelected = true) + { + EnsureSetupCompleted(controllerSelected); + OpenChancesTab(Options.CurrentGameMode == CustomGameMode.HideAndSeek ? (EHR.TabGroup)100 : EHR.TabGroup.ImpostorRoles, __instance.roleTabs[0], controllerSelected); + return false; + } + + private static void OpenChancesTab(EHR.TabGroup tabGroup, PassiveButton button, bool controllerSelected = true, bool goneBack = false) + { + RolesSettingsMenu instance = GameSettingMenu.Instance.RoleSettingsTab; + instance.selectedRoleTab = (int)tabGroup == 100 ? 6 : tabGroup - EHR.TabGroup.ImpostorRoles; + EnsureSetupCompleted(controllerSelected); + foreach (GameObject gameObject in Tabs.Values) + gameObject.SetActive(false); + Tabs[tabGroup].SetActive(true); + instance.AdvancedRolesSettings.SetActive(false); + instance.scrollBar.CalculateAndSetYBounds(TabChildrenCount[tabGroup] + 3, 1f, 6f, 0.43f); + if (!goneBack) instance.scrollBar.ScrollToTop(); + + if (controllerSelected) + { + ControllerManager.Instance.CurrentUiState.SelectableUiElements = instance.ControllerSelectable; + ControllerManager.Instance.SetDefaultSelection(instance.roleChances[0].ControllerSelectable[0]); + } + + instance.currentTabButton?.SelectButton(false); + button.SelectButton(true); + instance.currentTabButton = button; + } + + private static void EnsureSetupCompleted(bool controllerSelected) + { + RolesSettingsMenu instance = GameSettingMenu.Instance.RoleSettingsTab; + if (instance.QuotaTabSelectables == null) + instance.InitialSetup(); + instance.ControllerSelectable.Clear(); + if (controllerSelected) +#if IL2CPP + foreach (var uiElement in instance.QuotaTabSelectables!) + instance.ControllerSelectable.Add(uiElement); +#else + instance.ControllerSelectable.AddRange(instance.QuotaTabSelectables!); +#endif + } + + private static void RefreshChildren() + { + RolesSettingsMenu instance = GameSettingMenu.Instance.RoleSettingsTab; + if (instance.advancedSettingChildren is { Count: > 0 }) + { + for (var index = 0; index < instance.advancedSettingChildren.Count; ++index) + { + OptionBehaviour advancedSettingChild = instance.advancedSettingChildren[index]; + advancedSettingChild.enabled = false; + advancedSettingChild.enabled = true; + } + } + + if (instance.roleChances is not { Count: > 0 }) + return; + for (var index = 0; index < instance.roleChances.Count; ++index) + { + RoleOptionSetting roleOptionSetting = instance.roleChances[index]; + if (OptionItem.SettingObjectNameToRole.TryGetValue(roleOptionSetting.name, out CustomRoles role)) + RoleOptionSettingPatches.UpdateValuesAndText(roleOptionSetting, role); + } + } + + private static void ValueChanged(OptionBehaviour obj) + { + RolesSettingsMenu instance = GameSettingMenu.Instance.RoleSettingsTab; + if (obj is RoleOptionSetting roleOptionSetting) + { + CustomRoles role = OptionItem.SettingObjectNameToRole[roleOptionSetting.name]; + Options.CustomRoleSpawnChances[role].SetValue(roleOptionSetting.RoleChance / 5); + if (!Options.SingleRoles.Contains(role)) + Options.CustomRoleCounts[role].SetValue(Math.Max(roleOptionSetting.RoleMaxCount - 1, 0)); + else + roleOptionSetting.roleMaxCount = Math.Clamp(roleOptionSetting.roleMaxCount, 0, 1); + roleOptionSetting.CountMinusBtn.transform.parent.Find($"MODDED_{role}_AdvancedSettingsButton").gameObject.SetActive(role.IsEnable()); + } + else + { + OptionItem optionItem = OptionItem.BehaviourNameToItem[obj.name]; + + if (optionItem.Children.Count > 0) + { + float y = -1.2f; + int num = 1; + + foreach (OptionBehaviour optionBehaviour in instance.advancedSettingChildren) + { + if (OptionItem.BehaviourNameToItem.TryGetValue(optionBehaviour.name, out OptionItem item)) + { + bool hidden = item.IsCurrentlyHidden(checkParentEnabled: true); + optionBehaviour.gameObject.SetActive(!hidden); + if (hidden) continue; + optionBehaviour.transform.localPosition = new Vector3(0.952f, y, -2f); + y -= 0.45f; + } + + num++; + } + + instance.scrollBar.CalculateAndSetYBounds(num + 3, 1f, 6f, 0.45f); + } + } + + GameOptionsManager.Instance.CurrentGameOptions.SetInt(Int32OptionNames.RulePreset, 100); + GameOptionsManager.Instance.CurrentGameOptions.SetBool(BoolOptionNames.IsDefaults, false); + RefreshChildren(); + GameOptionsManager.Instance.GameHostOptions = GameOptionsManager.Instance.CurrentGameOptions; + GameManager.Instance.LogicOptions.SyncOptions(); + } + + private static void CreateAdvancedSettings(CustomRoles role) + { + RolesSettingsMenu instance = GameSettingMenu.Instance.RoleSettingsTab; + instance.advancedSettingChildren ??= new(); + for (var i = 0; i < instance.advancedSettingChildren.Count; ++i) + Object.Destroy(instance.advancedSettingChildren[i].gameObject); + instance.ControllerSelectable.Clear(); + instance.advancedSettingChildren.Clear(); + float scrollPercY = instance.scrollBar.GetScrollPercY(); + float y = -1.2f; + int skip = role.IsAdditionRole() ? 2 : 1; + int index = 0; + int num = 1; + StringOptionItem stringOptionItem = Options.CustomRoleSpawnChances[role]; + EHR.TabGroup tab = Options.CurrentGameMode == CustomGameMode.HideAndSeek ? (EHR.TabGroup)100 : stringOptionItem.Tab; + + if (!BackButton) + { + StringOption back = Object.Instantiate(instance.stringOptionOrigin, Vector3.zero, Quaternion.identity, instance.AdvancedRolesSettings.transform); + back.name = $"BACK_BUTTON_{role}"; + back.transform.localPosition = new Vector3(-1.25f, 0.9f, -2f); + back.SetClickMask(instance.ButtonClickMask); + back.SetUpFromData(null, 20); + + Object.Destroy(back.ValueText.gameObject); + Object.Destroy(back.transform.Find("ValueBox").gameObject); + Object.Destroy(back.PlusBtn.gameObject); + back.ValueText = null; + back.PlusBtn = null; + + back.MinusBtn.OnClick = new(); + back.MinusBtn.OnClick.AddListener(() => + { + OpenChancesTab(tab, instance.currentTabButton, ActiveInputManager.currentControlType == ActiveInputManager.InputType.Joystick, true); + instance.scrollBar.ScrollPercentY(scrollPercY); + }); + Vector3 scale = back.MinusBtn.transform.localScale; + back.MinusBtn.transform.localScale = new Vector3(scale.x * 7f, scale.y, scale.z); + var text = back.MinusBtn.GetComponentInChildren(); + Vector3 textScale = text.transform.localScale; + text.transform.localScale = new Vector3(textScale.x / 7f, textScale.y, textScale.z); + text.autoSizeTextContainer = false; + text.GetComponent().sizeDelta = new(3f, 0.37f); + text.DestroyTranslator(); + text.text = $"⬅ {Translator.GetString("BackToList")}"; + back.TitleText.enabled = false; + back.LabelBackground.enabled = false; + back.gameObject.SetActive(true); + +#if IL2CPP + foreach (var uiElement in back.GetComponentsInChildren(false)) + instance.ControllerSelectable.Add(uiElement); +#else + instance.ControllerSelectable.AddRange(back.GetComponentsInChildren(false)); +#endif + BackButton = back; + } + else + { + BackButton.MinusBtn.OnClick = new(); + BackButton.MinusBtn.OnClick.AddListener(() => + { + OpenChancesTab(tab, instance.currentTabButton, ActiveInputManager.currentControlType == ActiveInputManager.InputType.Joystick); + instance.scrollBar.ScrollPercentY(scrollPercY); + }); + } + + foreach (OptionItem optionItem in GetAllChildren(stringOptionItem)) + { + if (index++ < skip) continue; + + if (!InstantiateOptionBehaviour(optionItem, instance.AdvancedRolesSettings.transform, out OptionBehaviour optionBehaviour, out BaseGameSetting baseGameSetting, instance.checkboxOrigin, instance.numberOptionOrigin, instance.stringOptionOrigin)) + continue; + + optionBehaviour.transform.localPosition = new Vector3(0.952f, y, -2f); + optionBehaviour.SetUpFromData(baseGameSetting, 20); + optionBehaviour.SetClickMask(instance.ButtonClickMask); + optionBehaviour.LabelBackground.enabled = false; + optionBehaviour.AssociatedRole = RoleTypes.Engineer; + +#if IL2CPP + TextMeshPro titleText = GetTitleTextAndSetPositions(optionBehaviour, optionItem); +#else + TextMeshPro titleText = GetTitleTextAndSetPositions(optionBehaviour); +#endif + titleText.transform.localPosition += new Vector3(-0.4f, 0f, 0f); + RectTransform rectTransform = titleText.GetComponent(); + rectTransform.sizeDelta = new(5.7f, rectTransform.sizeDelta.y); + titleText.alignment = TextAlignmentOptions.MidlineRight; + instance.advancedSettingChildren.Add(optionBehaviour); +#if IL2CPP + foreach (var uiElement in optionBehaviour.GetComponentsInChildren(false)) + instance.ControllerSelectable.Add(uiElement); +#else + instance.ControllerSelectable.AddRange(optionBehaviour.GetComponentsInChildren(false)); +#endif + + bool hidden = optionItem.IsCurrentlyHidden(checkParentEnabled: true); + optionBehaviour.gameObject.SetActive(!hidden); + if (hidden) continue; + y -= 0.45f; + num++; + } + + instance.scrollBar.CalculateAndSetYBounds(num + 3, 1f, 6f, 0.45f); + instance.InitializeControllerNavigation(); + instance.scrollBar.ScrollToTop(); + } + + private static IEnumerable GetAllChildren(OptionItem optionItem) + { + for (var index = 0; index < optionItem.Children.Count; index++) + { + OptionItem child = optionItem.Children[index]; + yield return child; + + foreach (OptionItem descendant in GetAllChildren(child)) + yield return descendant; + } + } + } + + [HarmonyPatch(typeof(RoleOptionSetting))] + static class RoleOptionSettingPatches + { + private static readonly int StencilComp = Shader.PropertyToID("_StencilComp"); + private static readonly int Stencil = Shader.PropertyToID("_Stencil"); + + public static void SetRole(RoleOptionSetting __instance, CustomRoles role, int maskLayer) + { + foreach (SpriteRenderer componentsInChild in __instance.GetComponentsInChildren(true)) + componentsInChild.material.SetInt(PlayerMaterial.MaskLayer, maskLayer); + foreach (TextMeshPro componentsInChild in __instance.GetComponentsInChildren(true)) + { + componentsInChild.fontMaterial.SetFloat(StencilComp, 3f); + componentsInChild.fontMaterial.SetFloat(Stencil, maskLayer); + } +#if IL2CPP + __instance.role = RoleManager.Instance.AllRoles.Find((Il2CppSystem.Predicate)(x => x.Role == RoleTypes.Engineer)); +#else + __instance.role = RoleManager.Instance.AllRoles.Find(x => x.Role == RoleTypes.Engineer); +#endif + __instance.titleText.text = Translator.GetString(role.ToString()); + Color roleColor = Utils.GetRoleColor(role); + __instance.titleText.color = Utils.GetTextColor(roleColor); + __instance.labelSprite.color = roleColor; + UpdateValuesAndText(__instance, role); + } + + public static void UpdateValuesAndText(RoleOptionSetting __instance, CustomRoles role) + { + __instance.roleMaxCount = role.GetCount(); + __instance.roleChance = role.GetMode(); + __instance.countText.text = __instance.roleMaxCount.ToString(); + __instance.chanceText.text = __instance.roleChance.ToString(); + __instance.AdjustCountButtonsActiveState(); + __instance.AdjustChanceButtonsActiveState(); + } + + [HarmonyPatch(nameof(RoleOptionSetting.IncreaseChance))] + [HarmonyPrefix] + public static bool IncreaseChance(RoleOptionSetting __instance) + { + switch (__instance.roleChance) + { + case 100: + return false; + case 0: + __instance.roleMaxCount = 1; + __instance.AdjustCountButtonsActiveState(); + break; + } + + __instance.roleChance = Mathf.Clamp(__instance.roleChance + 5, 10, 100); +#if IL2CPP + __instance.OnValueChanged.Invoke(__instance); +#else + __instance.OnValueChanged(__instance); +#endif + __instance.AdjustChanceButtonsActiveState(); + return false; + } + + [HarmonyPatch(nameof(RoleOptionSetting.DecreaseChance))] + [HarmonyPrefix] + public static bool DecreaseChance(RoleOptionSetting __instance) + { + if (__instance.roleChance == 0) + return false; + __instance.roleChance = Mathf.Clamp(__instance.roleChance - 5, 0, 100); + if (__instance.roleChance == 0) + { + __instance.roleMaxCount = 0; + __instance.AdjustCountButtonsActiveState(); + } +#if IL2CPP + __instance.OnValueChanged.Invoke(__instance); +#else + __instance.OnValueChanged(__instance); +#endif + __instance.AdjustChanceButtonsActiveState(); + return false; + } + } + + [HarmonyPatch(typeof(GameSettingMenu))] + internal static class GameSettingMenuPatches + { + private static GameOptionsMenu TemplateGameOptionsMenu; + private static readonly Dictionary CachedGameOptionsMenus = []; + public static bool IsDirty; + + private static int NumImpsOnOpen = 1; + private static int MinImpsOnOpen = 1; + private static int MaxImpsOnOpen = 1; + private static float VanillaKillCooldownOnOpen = 1; + private static float ModdedKillCooldownOnOpen = 1; + + [HarmonyPatch(nameof(GameSettingMenu.ChangeTab))] + [HarmonyPrefix] + private static bool ChangeTab(GameSettingMenu __instance, int tabNum, bool previewOnly) + { + if (previewOnly || !IsDirty || tabNum is 0 or 1) return true; + + Main.Instance.StartCoroutine(ReOpen()); + return false; + + System.Collections.IEnumerator ReOpen() + { + __instance.Close(); + + yield return new WaitForEndOfFrame(); + + if (!GameStartManager.Instance) yield break; + GameStartManager.Instance.ClickEdit(); + + yield return new WaitForSecondsRealtime(0.2f); + + if (!GameStates.IsLobby || !GameSettingMenu.Instance) yield break; + GameSettingMenu.Instance.ChangeTab(tabNum, false); + } + } + + [HarmonyPatch(nameof(GameSettingMenu.ChangeTab))] + [HarmonyPostfix] + private static void PostChangeTab(GameSettingMenu __instance, int tabNum, bool previewOnly) + { + if (previewOnly) return; + + foreach (GameOptionsMenu irrelevantMenu in CachedGameOptionsMenus.Values) + irrelevantMenu.gameObject.SetActive(false); + + if (tabNum == 0) + __instance.MenuDescriptionText.text = Translator.GetString("MenuDescription.GameModes"); + + if (tabNum < 10) return; + + if (!CachedGameOptionsMenus.TryGetValue(tabNum, out GameOptionsMenu gameOptionsMenu)) + { + gameOptionsMenu = Object.Instantiate(TemplateGameOptionsMenu, __instance.GameSettingsTab.transform.parent); + gameOptionsMenu.name = $"IDX_{tabNum}"; + CachedGameOptionsMenus[tabNum] = gameOptionsMenu; + } + + gameOptionsMenu.transform.SetParent(__instance.GameSettingsTab.transform.parent, false); + gameOptionsMenu.gameObject.SetActive(true); + } + + [HarmonyPatch(nameof(GameSettingMenu.OnEnable))] + [HarmonyPrefix] + private static void PreOnEnable(GameSettingMenu __instance) + { + if (!TemplateGameOptionsMenu) + { + TemplateGameOptionsMenu = Object.Instantiate(__instance.GameSettingsTab, __instance.GameSettingsTab.transform.parent); + TemplateGameOptionsMenu.gameObject.SetActive(false); + } + } + + [HarmonyPatch(nameof(GameSettingMenu.Start))] + [HarmonyPostfix] + private static void PostStart(GameSettingMenu __instance) + { + PassiveButton[] buttons = [__instance.RoleSettingsButton, __instance.GameSettingsButton, __instance.GamePresetsButton]; + + for (var index = 0; index < buttons.Length; index++) + { + PassiveButton passiveButton = buttons[index]; + + passiveButton.inactiveSprites.GetComponent().color = new(0f, 0.647f, 1f, 1f); + passiveButton.activeSprites.GetComponent().color = new(0f, 0.847f, 1f, 1f); + passiveButton.selectedSprites.GetComponent().color = new(0f, 0.847f, 1f, 1f); + + Vector3 scale = passiveButton.transform.localScale; + passiveButton.transform.localScale = new Vector3(scale.x, scale.y * 0.75f, scale.z); + passiveButton.transform.localPosition -= new Vector3(0f, (index + 1) * 0.16f, 0f); + } + + __instance.RoleSettingsButton.gameObject.SetActive(Options.CurrentGameMode is CustomGameMode.Standard or CustomGameMode.HideAndSeek); + + PassiveButton presetsButton = Object.Instantiate(__instance.GamePresetsButton, __instance.GamePresetsButton.transform.parent); + presetsButton.gameObject.SetActive(false); + presetsButton.transform.localPosition += new Vector3(0f, buttons.Length * 0.16f, 0f); + var buttonComponent = presetsButton.GetComponent(); + buttonComponent.OnClick = new(); + buttonComponent.OnClick.AddListener(() => GameSettingMenu.Instance.ChangeTab(1000, false)); + + if (!OnlinePresetsManager.PresetsLoaded) + { + Main.Instance.StartCoroutine(OnlinePresetsManager.FetchPresetList(list => + { + OnlinePresetsManager.CachedPresets = list; + OnlinePresetsManager.PresetsLoaded = true; + CreatePresetExplorerUI(); + presetsButton.gameObject.SetActive(true); + })); + } + else + { + CreatePresetExplorerUI(); + presetsButton.gameObject.SetActive(true); + } + + var label = __instance.GamePresetsButton.GetComponentInChildren(); + label.DestroyTranslator(); + label.SetText(Translator.GetString("GameModeListTitle")); + + __instance.transform.Find("Background").gameObject.SetActive(false); + __instance.MenuDescriptionText.text = Translator.GetString("MenuDescription.GameModes"); + + (OptionItem minSetting, OptionItem maxSetting) = Options.FactionMinMaxSettings[Team.Impostor]; + MinImpsOnOpen = minSetting.GetInt(); + MaxImpsOnOpen = maxSetting.GetInt(); + NumImpsOnOpen = Main.NormalOptions.NumImpostors; + VanillaKillCooldownOnOpen = Main.NormalOptions.KillCooldown; + ModdedKillCooldownOnOpen = Options.FallBackKillCooldownValue.GetFloat(); + } + + private static void CreatePresetExplorerUI() + { + GameOptionsMenu gameOptionsMenu = Object.Instantiate(TemplateGameOptionsMenu, GameSettingMenu.Instance.GameSettingsTab.transform.parent); + gameOptionsMenu.name = "IDX_1000"; + Object.Destroy(gameOptionsMenu.MapPicker.gameObject); + gameOptionsMenu.Children = new(); + gameOptionsMenu.cachedData = GameOptionsManager.Instance.CurrentGameOptions; + CachedGameOptionsMenus[1000] = gameOptionsMenu; + OnlinePresetsManager.CreatePresetExplorerUI(gameOptionsMenu); + gameOptionsMenu.InitializeControllerNavigation(); + } + + [HarmonyPatch(nameof(GameSettingMenu.Close))] + [HarmonyPrefix] + public static void PreClose(GameSettingMenu __instance) + { + IsDirty = false; + + try + { + foreach (GameObject gameObject in GamePresetsTabPatches.Buttons.Values) + { + try + { + var button = gameObject.GetComponent(); + button.OnClick.RemoveAllListeners(); + button.OnMouseOver.RemoveAllListeners(); + button.OnMouseOut.RemoveAllListeners(); + Object.Destroy(gameObject); + } + catch { } + } + } + catch { } + + GamePresetsTabPatches.Buttons.Clear(); + + try + { + GameObject gameObject = GamePresetsTabPatches.NDIntegrationButton; + var button = gameObject.GetComponent(); + button.OnClick.RemoveAllListeners(); + button.OnMouseOver.RemoveAllListeners(); + button.OnMouseOut.RemoveAllListeners(); + Object.Destroy(gameObject); + } + catch { } + + GamePresetsTabPatches.NDIntegrationButton = null; + + try + { + foreach (GameObject gameObject in OnlinePresetsManager.Buttons.Values) + { + try + { + var button = gameObject.GetComponent(); + button.OnClick.RemoveAllListeners(); + Object.Destroy(gameObject); + } + catch { } + } + } + catch { } + + OnlinePresetsManager.Buttons.Clear(); + + foreach (GameOptionsMenu gameOptionsMenu in CachedGameOptionsMenus.Values) + { + try + { + for (var index = 0; index < gameOptionsMenu.Children.Count; index++) + { + try + { + OptionBehaviour optionBehaviour = gameOptionsMenu.Children[index]; + + foreach (PassiveButton button in optionBehaviour.GetComponentsInChildren(true)) + button.OnClick.RemoveAllListeners(); + + optionBehaviour.OnValueChanged = null; + optionBehaviour.SetClickMask(null); + + Object.Destroy(optionBehaviour.Data); + Object.Destroy(optionBehaviour.gameObject); + } + catch { } + } + + gameOptionsMenu.Children.Clear(); + Object.Destroy(gameOptionsMenu.gameObject); + } + catch { } + } + + CachedGameOptionsMenus.Clear(); + + try + { + foreach (OptionBehaviour optionBehaviour in __instance.GameSettingsTab.GetComponentsInChildren(true)) + { + try + { + foreach (PassiveButton button in optionBehaviour.GetComponentsInChildren(true)) + button.OnClick.RemoveAllListeners(); + + optionBehaviour.OnValueChanged = null; + optionBehaviour.SetClickMask(null); + + Object.Destroy(optionBehaviour.Data); + Object.Destroy(optionBehaviour.gameObject); + } + catch { } + } + } + catch { } + + int numImpostors = Main.NormalOptions.NumImpostors; + (OptionItem minSetting, OptionItem maxSetting) = Options.FactionMinMaxSettings[Team.Impostor]; + + if (numImpostors != NumImpsOnOpen && MinImpsOnOpen == minSetting.GetInt() && MaxImpsOnOpen == maxSetting.GetInt()) + { + minSetting.SetValue(numImpostors); + maxSetting.SetValue(numImpostors); + EHR.Logger.SendInGame(string.Format(Translator.GetString("MinMaxModdedImpCountsSettingsChangedAuto"), numImpostors)); + } + + float vanillaKillCooldown = Main.NormalOptions.KillCooldown; + float moddedKillCooldown = Options.FallBackKillCooldownValue.GetFloat(); + bool vanillaChanged = !Mathf.Approximately(vanillaKillCooldown, VanillaKillCooldownOnOpen); + bool moddedChanged = !Mathf.Approximately(moddedKillCooldown, ModdedKillCooldownOnOpen); + + if (!Mathf.Approximately(vanillaKillCooldown, moddedKillCooldown) && vanillaChanged && !moddedChanged) + Options.FallBackKillCooldownValue.SetValue((int)Math.Round(Math.Round(vanillaKillCooldown, 1) / 0.5f - 1)); + + if (Options.AutoGMRotationRecompileOnClose) + Options.CompileAutoGMRotationSettings(); + + Options.AutoSetFactionMinMaxSettings(); + + NotificationPopperPatch.ReleaseRpcs(); + } + } + + [HarmonyPatch(typeof(ToggleOption))] + internal static class ToggleOptionPatches + { + private static readonly Color DefaultCheckMarkColor = new Color32(0, 165, 255, 255); + + [HarmonyPatch(nameof(ToggleOption.Initialize))] + [HarmonyPrefix] + private static bool Initialize(ToggleOption __instance) + { + if (!OptionItem.BehaviourNameToItem.TryGetValue(__instance.name, out OptionItem item)) return true; + + CustomGameMode currentGameMode = Options.CurrentGameMode; + var color = currentGameMode != CustomGameMode.Standard ? Main.GameModeColors.GetValueOrDefault(currentGameMode, DefaultCheckMarkColor) : DefaultCheckMarkColor; + __instance.CheckMark.sprite = Utils.LoadSprite("EHR.Resources.Images.Checkmark.png", 100f); + __instance.CheckMark.color = color; + var spriteRenderer = __instance.CheckMark.transform.parent.Find("ActiveSprite").GetComponent(); + spriteRenderer.sprite = Utils.LoadSprite("EHR.Resources.Images.CheckMarkBox.png", 100f); + spriteRenderer.color = color; + + __instance.TitleText.SetText(item.GetName()); + __instance.CheckMark.enabled = item.GetBool(); + return false; + } + + [HarmonyPatch(nameof(ToggleOption.UpdateValue))] + [HarmonyPrefix] + private static bool UpdateValue(ToggleOption __instance) + { + if (!OptionItem.BehaviourNameToItem.TryGetValue(__instance.name, out OptionItem item)) return true; + + item.SetValue(__instance.GetBool() ? 1 : 0, doSave: true, doSync: false); + NotificationPopperPatch.AddSettingsChangeMessage(item); + return false; + } + } + + [HarmonyPatch(typeof(NumberOption))] + internal static class NumberOptionPatches + { + [HarmonyPatch(nameof(NumberOption.Initialize))] + [HarmonyPrefix] + private static bool Initialize(NumberOption __instance) + { + switch (__instance.Title) + { + case StringNames.GameVotingTime: + __instance.ValidRange = new(0, 600); + __instance.Value = (float)Math.Round(__instance.Value, 2); + break; + case StringNames.GameShortTasks: + case StringNames.GameLongTasks: + case StringNames.GameCommonTasks: + __instance.ValidRange = new(0, 85); + __instance.Value = (float)Math.Round(__instance.Value, 2); + break; + case StringNames.GameKillCooldown: + __instance.ValidRange = new(0, 180); + __instance.Increment = 0.5f; + __instance.Value = (float)Math.Round(__instance.Value, 2); + break; + case StringNames.GamePlayerSpeed: + __instance.Increment = 0.05f; + __instance.Value = Mathf.Clamp((float)Math.Round(__instance.Value, 2), __instance.ValidRange.min, __instance.ValidRange.max); + break; + case StringNames.GameCrewLight: + case StringNames.GameImpostorLight: + __instance.Increment = 0.05f; + __instance.Value = (float)Math.Round(__instance.Value, 2); + break; + case StringNames.GameNumImpostors: + __instance.ValidRange = new(0, Crowded.MaxImpostors); + __instance.Value = Mathf.Clamp((float)Math.Round(__instance.Value, 2), __instance.ValidRange.min, __instance.ValidRange.max); + if (DebugModeManager.AmDebugger) __instance.ValidRange.min = 0; + break; + case StringNames.CapacityLabel: + __instance.ValidRange = new(4, 127); + __instance.Value = Mathf.Clamp(__instance.Value, __instance.ValidRange.min, __instance.ValidRange.max); + break; + } + + if (!OptionItem.BehaviourNameToItem.TryGetValue(__instance.name, out OptionItem item)) return true; + + __instance.TitleText.SetText(item.GetName()); + __instance.ValueText.SetText(GetValueString(__instance, __instance.Value, item)); + __instance.AdjustButtonsActiveState(); + return false; + } + + [HarmonyPatch(nameof(NumberOption.UpdateValue))] + [HarmonyPrefix] + private static bool UpdateValue(NumberOption __instance) + { + if (!OptionItem.BehaviourNameToItem.TryGetValue(__instance.name, out OptionItem item)) return true; + + switch (item) + { + case IntegerOptionItem integerOptionItem: + integerOptionItem.SetValue(integerOptionItem.Rule.GetNearestIndex(__instance.GetInt()), doSave: true, doSync: false); + break; + case FloatOptionItem floatOptionItem: + floatOptionItem.SetValue(floatOptionItem.Rule.GetNearestIndex(__instance.GetFloat()), doSave: true, doSync: false); + break; + } + + NotificationPopperPatch.AddSettingsChangeMessage(item); + __instance.oldValue = __instance.Value; + __instance.ValueText.SetText(GetValueString(__instance, __instance.Value, item)); + return false; + } + + private static string GetValueString(NumberOption __instance, float value, OptionItem item) + { + if (__instance.ZeroIsInfinity && Mathf.Abs(value) < 0.0001f) return "∞"; + return item == null ? value.ToString(__instance.FormatString) : item.GetString(); + } + + static float GetIncrement(float increment) + { + if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) increment *= 10; + else if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) increment *= 5; + return increment; + } + + [HarmonyPatch(nameof(NumberOption.Increase))] + [HarmonyPrefix] + public static bool Increase(NumberOption __instance) + { + if (Mathf.Approximately(__instance.Value, __instance.ValidRange.max)) + { + __instance.Value = __instance.ValidRange.min; + __instance.UpdateValue(); + __instance.OnValueChanged?.Invoke(__instance); + return false; + } + + float increment = GetIncrement(__instance.Increment); + + if (__instance.Value + increment < __instance.ValidRange.max) + { + __instance.Value += increment; + __instance.UpdateValue(); + __instance.OnValueChanged?.Invoke(__instance); + return false; + } + + return true; + } + + [HarmonyPatch(nameof(NumberOption.Decrease))] + [HarmonyPrefix] + public static bool Decrease(NumberOption __instance) + { + if (Mathf.Approximately(__instance.Value, __instance.ValidRange.min)) + { + __instance.Value = __instance.ValidRange.max; + __instance.UpdateValue(); + __instance.OnValueChanged?.Invoke(__instance); + return false; + } + + float increment = GetIncrement(__instance.Increment); + + if (__instance.Value - increment > __instance.ValidRange.min) + { + __instance.Value -= increment; + __instance.UpdateValue(); + __instance.OnValueChanged?.Invoke(__instance); + return false; + } + + return true; + } + + [HarmonyPatch(nameof(NumberOption.AdjustButtonsActiveState))] + [HarmonyPrefix] + static bool AdjustButtonsActiveState(NumberOption __instance) + { + __instance.MinusBtn.SetInteractable(true); + __instance.PlusBtn.SetInteractable(true); + return false; + } + } + + [HarmonyPatch(typeof(StringOption))] + internal static class StringOptionPatches + { + [HarmonyPatch(nameof(StringOption.Initialize))] + [HarmonyPrefix] + private static bool Initialize(StringOption __instance) + { + if (__instance.name.StartsWith(nameof(OnlinePresetsManager)) || __instance.name.StartsWith("BACK_BUTTON_") || __instance.name.StartsWith("MODDED_")) return false; + + if (!OptionItem.BehaviourNameToItem.TryGetValue(__instance.name, out OptionItem item)) return true; + + __instance.TitleText.SetText(item.GetName()); + return false; + } + + [HarmonyPatch(nameof(StringOption.UpdateValue))] + [HarmonyPrefix] + private static bool UpdateValue(StringOption __instance) + { + if (__instance.name.StartsWith(nameof(OnlinePresetsManager)) || __instance.name.StartsWith("BACK_BUTTON_") || __instance.name.StartsWith("MODDED_")) return false; + + if (!OptionItem.BehaviourNameToItem.TryGetValue(__instance.name, out OptionItem item)) return true; + + item.SetValue(__instance.GetInt(), doSave: true, doSync: false); + NotificationPopperPatch.AddSettingsChangeMessage(item); + __instance.TitleText.SetText(item.GetName()); + return false; + } + + [HarmonyPatch(nameof(StringOption.FixedUpdate))] + [HarmonyPrefix] + private static bool FixedUpdate(StringOption __instance) + { + if (__instance.name.StartsWith(nameof(OnlinePresetsManager))) + { + __instance.TitleText.SetText(__instance.name[(nameof(OnlinePresetsManager).Length + 1)..]); + return false; + } + + if (__instance.name.StartsWith("BACK_BUTTON_")) + { + __instance.TitleText.SetText("⬅"); + return false; + } + + if (__instance.name.StartsWith("MODDED_")) + { + __instance.TitleText.SetText(__instance.name[7..]); + return false; + } + + if (!OptionItem.BehaviourNameToItem.TryGetValue(__instance.name, out OptionItem item)) return true; + + if (__instance.oldValue != __instance.Value) + { + __instance.oldValue = __instance.Value; + __instance.ValueText.SetText(item.GetString()); + __instance.TitleText.SetText(item.GetName()); + __instance.AdjustButtonsActiveState(); + } + + return false; + } + + [HarmonyPatch(nameof(StringOption.Increase))] + [HarmonyPrefix] + public static bool IncreasePrefix(StringOption __instance) + { + if (__instance.Value == __instance.Values.Length - 1) + { + __instance.Value = 0; + __instance.UpdateValue(); + __instance.OnValueChanged?.Invoke(__instance); + return false; + } + + return true; + } + + [HarmonyPatch(nameof(StringOption.Decrease))] + [HarmonyPrefix] + public static bool DecreasePrefix(StringOption __instance) + { + if (__instance.Value == 0) + { + __instance.Value = __instance.Values.Length - 1; + __instance.UpdateValue(); + __instance.OnValueChanged?.Invoke(__instance); + return false; + } + + return true; + } + + [HarmonyPatch(nameof(StringOption.AdjustButtonsActiveState))] + [HarmonyPrefix] + static bool AdjustButtonsActiveState(StringOption __instance) + { + __instance.MinusBtn.SetInteractable(true); + __instance.PlusBtn.SetInteractable(true); + return false; + } + } + + private static bool InstantiateOptionBehaviour(OptionItem optionItem, Transform parent, out OptionBehaviour optionBehaviour, out BaseGameSetting baseGameSetting, params OptionBehaviour[] templates) + { + int templateIndex; + + switch (optionItem) + { + case BooleanOptionItem: + var checkboxGameSetting = ScriptableObject.CreateInstance(); + checkboxGameSetting.Type = OptionTypes.Checkbox; + checkboxGameSetting.Title = StringNames.Accept; + baseGameSetting = checkboxGameSetting; + templateIndex = 0; + break; + case IntegerOptionItem integerOptionItem: + var intGameSetting = ScriptableObject.CreateInstance(); + intGameSetting.Type = OptionTypes.Int; + intGameSetting.Value = integerOptionItem.GetInt(); + intGameSetting.Increment = integerOptionItem.Rule.Step; + intGameSetting.ValidRange = new(integerOptionItem.Rule.MinValue, integerOptionItem.Rule.MaxValue); + intGameSetting.ZeroIsInfinity = false; + intGameSetting.SuffixType = GetNumberSuffix(); + intGameSetting.FormatString = string.Empty; + intGameSetting.Title = StringNames.Accept; + baseGameSetting = intGameSetting; + templateIndex = 1; + break; + case FloatOptionItem floatOptionItem: + var floatGameSetting = ScriptableObject.CreateInstance(); + floatGameSetting.Type = OptionTypes.Float; + floatGameSetting.Value = floatOptionItem.GetFloat(); + floatGameSetting.Increment = floatOptionItem.Rule.Step; + floatGameSetting.ValidRange = new(floatOptionItem.Rule.MinValue, floatOptionItem.Rule.MaxValue); + floatGameSetting.ZeroIsInfinity = false; + floatGameSetting.SuffixType = GetNumberSuffix(); + floatGameSetting.FormatString = string.Empty; + floatGameSetting.Title = StringNames.Accept; + baseGameSetting = floatGameSetting; + templateIndex = 1; + break; + case StringOptionItem stringOptionItem: + var stringGameSetting = ScriptableObject.CreateInstance(); + stringGameSetting.Type = OptionTypes.String; + stringGameSetting.Values = new StringNames[stringOptionItem.Selections.Count]; + stringGameSetting.Index = stringOptionItem.GetInt(); + stringGameSetting.Title = StringNames.Accept; + baseGameSetting = stringGameSetting; + templateIndex = 2; + break; + default: + optionBehaviour = null; + baseGameSetting = null; + return false; + } + + optionBehaviour = Object.Instantiate(templates[templateIndex], Vector3.zero, Quaternion.identity, parent); + optionBehaviour.name = $"IDX_{optionItem.Id}"; + OptionItem.BehaviourNameToItem[optionBehaviour.name] = optionItem; + return true; + + NumberSuffixes GetNumberSuffix() => optionItem.ValueFormat switch + { + OptionFormat.Multiplier => NumberSuffixes.Multiplier, + OptionFormat.Seconds => NumberSuffixes.Seconds, + _ => NumberSuffixes.None + }; + } + +#if IL2CPP + private static TextMeshPro GetTitleTextAndSetPositions(OptionBehaviour optionBehaviour, OptionItem optionItem) + { + TextMeshPro titleText = null; + + switch (optionItem) + { + case BooleanOptionItem when optionBehaviour.TryCastFast(out ToggleOption toggleOption): +#else + private static TextMeshPro GetTitleTextAndSetPositions(OptionBehaviour optionBehaviour) + { + TextMeshPro titleText = null; + + switch (optionBehaviour) + { + case ToggleOption toggleOption: +#endif + { + toggleOption.transform.Find("Toggle").localPosition = new(1.46f, -0.042f); + titleText = toggleOption.TitleText; + break; + } +#if IL2CPP + case StringOptionItem when optionBehaviour.TryCastFast(out StringOption stringOption): +#else + case StringOption stringOption: +#endif + { + stringOption.PlusBtn.transform.localPosition += new Vector3(1.7f, 0f, 0f); + stringOption.MinusBtn.transform.localPosition += new Vector3(0.9f, 0f, 0f); + stringOption.ValueText.transform.localPosition += new Vector3(1.3f, 0f, 0f); + stringOption.ValueText.GetComponent().sizeDelta = new(2.3f, 0.4f); + titleText = stringOption.TitleText; + goto default; + } +#if IL2CPP + case FloatOptionItem: + case IntegerOptionItem: + { + NumberOption numberOption = optionBehaviour.CastFast(); +#else + case NumberOption numberOption: + { +#endif + numberOption.PlusBtn.transform.localPosition += new Vector3(1.7f, 0f, 0f); + numberOption.MinusBtn.transform.localPosition += new Vector3(0.9f, 0f, 0f); + numberOption.ValueText.transform.localPosition += new Vector3(1.3f, 0f, 0f); + titleText = numberOption.TitleText; + goto default; + } + default: + { + Transform valueBox = optionBehaviour.transform.Find("ValueBox"); + valueBox.localScale += new Vector3(0.2f, 0f, 0f); + valueBox.localPosition += new Vector3(1.3f, 0f, 0f); + break; + } + } + + if (!titleText) titleText = optionBehaviour.transform.Find("Title Text").GetComponent(); + return titleText; + } +} \ No newline at end of file diff --git a/Patches/DiscordPatch.cs b/Patches/DiscordPatch.cs index f45392f3e..88bc83f2f 100644 --- a/Patches/DiscordPatch.cs +++ b/Patches/DiscordPatch.cs @@ -19,7 +19,7 @@ public static class DiscordRPC activity.Assets = new ActivityAssets { - LargeImage = "https://i.imgur.com/07BjW2j.png" + LargeImage = "https://i.imgur.com/fa7kFkv.png" }; try diff --git a/Patches/ExilePatch.cs b/Patches/ExilePatch.cs index b6e3cf0cb..486f29020 100644 --- a/Patches/ExilePatch.cs +++ b/Patches/ExilePatch.cs @@ -21,13 +21,14 @@ internal static class ExileControllerWrapUpPatch { if (!AmongUsClient.Instance.AmHost) return; - var decidedWinner = false; + CustomRoles role = exiled.GetCustomRole(); + bool collectorWin = Collector.CollectorWin(false); + bool decidedWinner = collectorWin; - if (!Collector.CollectorWin(false) && exiled != null) + if (!collectorWin && exiled != null) { //exiled.IsDead = true; Main.PlayerStates[exiled.PlayerId].deathReason = PlayerState.DeathReason.Vote; - CustomRoles role = exiled.GetCustomRole(); if (Main.EnumeratePlayerControls().Any(x => x.Is(CustomRoles.Innocent) && !x.IsAlive() && x.GetRealKiller()?.PlayerId == exiled.PlayerId)) { @@ -59,21 +60,21 @@ internal static class ExileControllerWrapUpPatch Damocles.OnCrewmateEjected(); } - if (role == CustomRoles.Jester) - { - if (decidedWinner) CustomWinnerHolder.ShiftWinnerAndSetWinner(CustomWinner.Jester); - else CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Jester); - - CustomWinnerHolder.WinnerIds.Add(exiled.PlayerId); - decidedWinner = true; - } - - if (Executioner.CheckExileTarget(exiled)) decidedWinner = true; - if (CustomWinnerHolder.WinnerTeam != CustomWinner.Terrorist) Main.PlayerStates[exiled.PlayerId].SetDead(); } + if (role == CustomRoles.Jester) + { + if (decidedWinner) CustomWinnerHolder.ShiftWinnerAndSetWinner(CustomWinner.Jester); + else CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Jester); + + CustomWinnerHolder.WinnerIds.Add(exiled.PlayerId); + decidedWinner = true; + } + + if (Executioner.CheckExileTarget(exiled)) decidedWinner = true; + Witch.RemoveSpelledPlayer(); Swapper.OnExileFinish(); diff --git a/Patches/GameOptionsMenuPatch.cs b/Patches/GameOptionsMenuPatch.cs deleted file mode 100644 index f984535ad..000000000 --- a/Patches/GameOptionsMenuPatch.cs +++ /dev/null @@ -1,1735 +0,0 @@ -using System; -using System.Collections; -using System.Linq; -#if IL2CPP -using BepInEx.Unity.IL2CPP.Utils.Collections; -using Il2CppSystem.Collections.Generic; -#else -using System.Collections.Generic; -#endif -using EHR.Gamemodes; -using EHR.Modules; -using EHR.Patches; -using EHR.Roles; -using HarmonyLib; -using TMPro; -using UnityEngine; -using Priority = HarmonyLib.Priority; - -// ReSharper disable PossibleLossOfFraction -// ReSharper disable RedundantNameQualifier - -namespace EHR; -// Credit: https://github.com/Yumenopai/TownOfHost_Y - -public static class ModGameOptionsMenu -{ - public static int TabIndex; - public static readonly Dictionary OptionList = new(); - public static readonly Dictionary BehaviourList = new(); - public static readonly Dictionary CategoryHeaderList = new(); - public static readonly System.Collections.Generic.Dictionary HelpIconList = []; - public static readonly System.Collections.Generic.Dictionary BaseGameSettingCache = []; - - public static T Track(T obj) where T : Object - { - return obj; - } - - public static Color32 GetCurrentThemeColor(TabGroup? tab = null) - { - CustomGameMode gm = Options.CurrentGameMode; - Color32 color = gm == CustomGameMode.Standard ? (tab ?? (TabGroup)(TabIndex - 3)) switch - { - TabGroup.ImpostorRoles => new Color32(255, 25, 25, 255), - TabGroup.CrewmateRoles => new Color32(140, 255, 255, 255), - TabGroup.NeutralRoles => new Color32(255, 171, 27, 255), - TabGroup.CovenRoles => new Color32(123, 63, 187, 255), - _ => new Color32(0, 165, 255, 255) - } : Main.GameModeColors.TryGetValue(gm, out var c) ? c : new Color32(0, 165, 255, 255); - return color; - } -} - -[HarmonyPatch(typeof(GameOptionsMenu))] -public static class GameOptionsMenuPatch -{ - private static readonly Dictionary BuildCoroutines = new(); - private static readonly Dictionary BuildGenerations = new(); - - [HarmonyPatch(nameof(GameOptionsMenu.Initialize))] - [HarmonyPrefix] - private static bool InitializePrefix(GameOptionsMenu __instance) - { - if (ModGameOptionsMenu.TabIndex < 3) return true; - - if (__instance.Children == null || __instance.Children.Count == 0) - { - __instance.MapPicker.gameObject.SetActive(false); - __instance.Children = new(); - __instance.CreateSettings(); - __instance.cachedData = GameOptionsManager.Instance.CurrentGameOptions; - __instance.InitializeControllerNavigation(); - } - - return false; - } - - [HarmonyPatch(nameof(GameOptionsMenu.Initialize))] - [HarmonyPostfix] - private static void InitializePostfix() - { - GameObject optionMenu = GameObject.Find("PlayerOptionsMenu(Clone)"); - if (!optionMenu) return; - - optionMenu.transform.Find("Background")?.gameObject.SetActive(false); - - // By TommyXL - LateTask.New(() => - { - if (!optionMenu) return; - - Transform menuDescription = optionMenu.transform.Find("What Is This?"); - if (!menuDescription) return; - - Transform infoImage = menuDescription.transform.Find("InfoImage"); - - if (infoImage) - { - infoImage.transform.localPosition = new(-4.65f, 0.16f, -1f); - infoImage.transform.localScale = new(0.2202f, 0.2202f, 0.3202f); - } - - Transform infoText = menuDescription.transform.Find("InfoText"); - - if (infoText) - { - infoText.transform.localPosition = new(-3.5f, 0.83f, -2f); - infoText.transform.localScale = new(1f, 1f, 1f); - } - - Transform cubeObject = menuDescription.transform.Find("Cube"); - - if (cubeObject) - { - cubeObject.transform.localPosition = new(-3.2f, 0.55f, -0.1f); - cubeObject.transform.localScale = new(0.61f, 0.64f, 1f); - } - - if (GameSettingMenu.Instance && GameSettingMenu.Instance.MenuDescriptionText) - GameSettingMenu.Instance.MenuDescriptionText.m_marginWidth = 2.5f; - }, 0.2f, log: false); - } - - [HarmonyPatch(nameof(GameOptionsMenu.CreateSettings))] - [HarmonyPrefix] - private static bool CreateSettingsPrefix(GameOptionsMenu __instance) - { - if (ModGameOptionsMenu.TabIndex < 3) return true; - - if (!__instance.gameObject.activeInHierarchy) return false; - - var modTab = (TabGroup)(ModGameOptionsMenu.TabIndex - 3); - - if (modTab == TabGroup.PresetExplorer) - { - OnlinePresetsManager.CreatePresetExplorerUI(__instance); - return false; - } - - __instance.scrollBar.SetYBoundsMax(CalculateScrollBarYBoundsMax()); - - // Cancel any in-progress build coroutine on this instance before starting a new one - if (BuildCoroutines.TryGetValue(__instance, out Coroutine existing) && existing != null) - { - __instance.StopCoroutine(existing); - BuildCoroutines.Remove(__instance); - } - - BuildGenerations.TryGetValue(__instance, out int currentGen); - currentGen++; - BuildGenerations[__instance] = currentGen; - -#if IL2CPP - BuildCoroutines[__instance] = __instance.StartCoroutine(CoRoutine(currentGen).WrapToIl2Cpp()); -#else - BuildCoroutines[__instance] = __instance.StartCoroutine(CoRoutine(currentGen)); -#endif - return false; - - IEnumerator CoRoutine(int gen) - { - var num = 2.0f; - const float posX = 0.952f; - const float posZ = -2.0f; - - TextOptionItem header = null; - - for (var index = 0; index < OptionItem.AllOptions.Count; index++) - { - try - { - OptionItem option = OptionItem.AllOptions[index]; - if (option.Tab != modTab) continue; - - bool enabledOrNotCollapsed = !option.IsCurrentlyHidden() && AllParentsEnabledAndVisible(option.Parent); - bool enabled = !option.IsCurrentlyHidden(checkCollapsedSection: false) && AllParentsEnabledAndVisible(option.Parent, checkCollapsedSection: false); - - if (option is TextOptionItem toi) - { - CategoryHeaderMasked categoryHeaderMasked = ModGameOptionsMenu.CategoryHeaderList.TryGetValue(index, out CategoryHeaderMasked cache) ? cache : ModGameOptionsMenu.Track(Object.Instantiate(__instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer)); - categoryHeaderMasked.SetHeader(StringNames.RolesCategory, 20); - categoryHeaderMasked.Title.SetText(option.GetName(disableColor: true).Trim('★', ' ')); - categoryHeaderMasked.Background.color = categoryHeaderMasked.Divider.color = option.NameColor; - categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f; - categoryHeaderMasked.transform.localPosition = new(-0.903f, num, posZ); - var chmText = categoryHeaderMasked.transform.Find("HeaderText").GetComponent(); - chmText.fontStyle = FontStyles.Bold | FontStyles.SmallCaps; - chmText.fontWeight = FontWeight.Black; - chmText.outlineWidth = 0.17f; - var chmCollider = categoryHeaderMasked.gameObject.AddComponent(); - chmCollider.size = new Vector2(7, 0.7f); - chmCollider.offset = new Vector2(1.5f, -0.3f); - var chmButton = categoryHeaderMasked.gameObject.AddComponent(); - chmButton.ClickSound = __instance.BackButton.GetComponent().ClickSound; - chmButton.OnMouseOver = new(); - chmButton.OnMouseOut = new(); - chmButton.OnClick.AddListener(() => - { - toi.CollapsesSection = !toi.CollapsesSection; - ReCreateSettings(__instance); - }); - chmButton.SetButtonEnableState(true); - categoryHeaderMasked.gameObject.SetActive(enabled); - ModGameOptionsMenu.CategoryHeaderList[index] = categoryHeaderMasked; - - if (enabledOrNotCollapsed) num -= 0.63f; - header = toi; - continue; - } - - option.Header = header; - - if (option.IsHeader && enabledOrNotCollapsed) - num -= 0.18f; - - BaseGameSetting baseGameSetting = GetSetting(option); - if (!baseGameSetting) continue; - - if (!ModGameOptionsMenu.BehaviourList.TryGetValue(index, out OptionBehaviour optionBehaviour)) - { - try - { - optionBehaviour = baseGameSetting.Type switch - { - OptionTypes.Checkbox => ModGameOptionsMenu.Track(Object.Instantiate(__instance.checkboxOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer)), - OptionTypes.String => ModGameOptionsMenu.Track(Object.Instantiate(__instance.stringOptionOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer)), - OptionTypes.Float or OptionTypes.Int => ModGameOptionsMenu.Track(Object.Instantiate(__instance.numberOptionOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer)), - _ => throw new Exception() - }; - } - catch { continue; } - - optionBehaviour.transform.localPosition = new(posX, num, posZ); - OptionBehaviourSetSizeAndPosition(optionBehaviour, option, baseGameSetting.Type); - } - else - { - optionBehaviour.transform.localPosition = new(posX, num, posZ); - } - - optionBehaviour.transform.localPosition = new(0.952f, num, -2f); - optionBehaviour.SetClickMask(__instance.ButtonClickMask); - optionBehaviour.SetUpFromData(baseGameSetting, 20); - optionBehaviour.gameObject.SetActive(enabledOrNotCollapsed); -#if IL2CPP - optionBehaviour.OnValueChanged = (Il2CppSystem.Action)__instance.ValueChanged; -#else - optionBehaviour.OnValueChanged = __instance.ValueChanged; -#endif - - ModGameOptionsMenu.OptionList[optionBehaviour] = index; - ModGameOptionsMenu.BehaviourList[index] = optionBehaviour; - - __instance.Children.Add(optionBehaviour); - option.OptionBehaviour = optionBehaviour; - - if (enabledOrNotCollapsed) num -= 0.45f; - } - catch (Exception e) { Utils.ThrowException(e); } - - if (index % 100 == 0) - { - yield return null; - } - } - - // Bail if a newer build coroutine was started on this instance while we were running - if (!BuildGenerations.TryGetValue(__instance, out int latestGen) || latestGen != gen) - { - BuildCoroutines.Remove(__instance); - yield break; - } - - __instance.ControllerSelectable.Clear(); - - foreach (UiElement x in __instance.scrollBar.GetComponentsInChildren()) - __instance.ControllerSelectable.Add(x); - - Canvas.ForceUpdateCanvases(); - BuildCoroutines.Remove(__instance); - } - - float CalculateScrollBarYBoundsMax() - { - var num = 2.0f; - - foreach (OptionItem option in OptionItem.AllOptions) - { - if (option.Tab != modTab) continue; - - bool enabledOrNotCollapsed = !option.IsCurrentlyHidden() && AllParentsEnabledAndVisible(option.Parent); - - if (option is TextOptionItem) - num -= 0.63f; - else if (enabledOrNotCollapsed) - { - if (option.IsHeader) num -= 0.18f; - num -= 0.45f; - } - } - - return -num - 1.65f; - } - } - - private static bool AllParentsEnabledAndVisible(OptionItem o, bool checkCollapsedSection = true) - { - while (true) - { - if (o == null) return true; - if (o.IsCurrentlyHidden(forLobbyView: false, checkCollapsedSection: checkCollapsedSection) || !o.GetBool()) return false; - o = o.Parent; - } - } - - private static void OptionBehaviourSetSizeAndPosition(OptionBehaviour optionBehaviour, OptionItem option, OptionTypes type) - { - Vector3 positionOffset = new(0f, 0f, 0f); - Vector3 scaleOffset = new(0f, 0f, 0f); - Color color = new(0.35f, 0.35f, 0.35f); - var sizeDeltaX = 5.7f; - - if (option.Parent?.Parent?.Parent != null) - { - scaleOffset = new(-0.18f, 0, 0); - positionOffset = new(0.3f, 0f, 0f); - color = new(0.35f, 0f, 0f); - sizeDeltaX = 5.1f; - } - else if (option.Parent?.Parent != null) - { - scaleOffset = new(-0.12f, 0, 0); - positionOffset = new(0.2f, 0f, 0f); - color = new(0.35f, 0.35f, 0f); - sizeDeltaX = 5.3f; - } - else if (option.Parent != null) - { - scaleOffset = new(-0.05f, 0, 0); - positionOffset = new(0.1f, 0f, 0f); - color = new(0f, 0f, 0.35f); - sizeDeltaX = 5.5f; - } - - Transform labelBackground = optionBehaviour.transform.Find("LabelBackground"); - labelBackground.GetComponent().color = color; - labelBackground.localScale += new Vector3(0.9f, -0.2f, 0f) + scaleOffset; - labelBackground.localPosition += new Vector3(-0.4f, 0f, 0f) + positionOffset; - - Transform titleText = optionBehaviour.transform.Find("Title Text"); - titleText.localPosition += new Vector3(-0.4f, 0f, 0f) + positionOffset; - titleText.GetComponent().sizeDelta = new(sizeDeltaX, 0.37f); - var textMeshPro = titleText.GetComponent(); - textMeshPro.alignment = TextAlignmentOptions.MidlineLeft; - textMeshPro.fontStyle = FontStyles.Bold; - textMeshPro.outlineWidth = 0.17f; - - switch (type) - { - case OptionTypes.Checkbox: - { - optionBehaviour.transform.Find("Toggle").localPosition = new(1.46f, -0.042f); - break; - } - case OptionTypes.String: - { - Transform plusButton = optionBehaviour.transform.Find("PlusButton"); - Transform minusButton = optionBehaviour.transform.Find("MinusButton"); - plusButton.localPosition += new Vector3(option.IsText ? 500f : 1.7f, option.IsText ? 500f : 0f, option.IsText ? 500f : 0f); - minusButton.localPosition += new Vector3(option.IsText ? 500f : 0.9f, option.IsText ? 500f : 0f, option.IsText ? 500f : 0f); - Transform valueTMP = optionBehaviour.transform.Find("Value_TMP (1)"); - valueTMP.localPosition += new Vector3(1.3f, 0f, 0f); - valueTMP.GetComponent().sizeDelta = new(2.3f, 0.4f); - goto default; - } - case OptionTypes.Float: - case OptionTypes.Int: - { - optionBehaviour.transform.Find("PlusButton").localPosition += new Vector3(option.IsText ? 500f : 1.7f, option.IsText ? 500f : 0f, option.IsText ? 500f : 0f); - optionBehaviour.transform.Find("MinusButton").localPosition += new Vector3(option.IsText ? 500f : 0.9f, option.IsText ? 500f : 0f, option.IsText ? 500f : 0f); - optionBehaviour.transform.Find("Value_TMP").localPosition += new Vector3(1.3f, 0f, 0f); - goto default; - } - default: - { - Transform valueBox = optionBehaviour.transform.Find("ValueBox"); - valueBox.localScale += new Vector3(0.2f, 0f, 0f); - valueBox.localPosition += new Vector3(1.3f, 0f, 0f); - break; - } - } - } - - [HarmonyPatch(nameof(GameOptionsMenu.Update))] - [HarmonyPrefix] - public static void UpdatePostfix(GameOptionsMenu __instance) - { - // Disable scroll options when chat open - if (!HudManager.InstanceExists || !__instance.gameObject.activeSelf || !GameSettingMenu.Instance) return; - - __instance.scrollBar.enabled = !HudManager.Instance.Chat.IsOpenOrOpening; - } - - [HarmonyPatch(nameof(GameOptionsMenu.ValueChanged))] - [HarmonyPrefix] - private static bool ValueChangedPrefix(GameOptionsMenu __instance, OptionBehaviour option) - { - if (ModGameOptionsMenu.TabIndex < 3) return true; - - if (ModGameOptionsMenu.OptionList.TryGetValue(option, out int index)) - { - OptionItem item = OptionItem.AllOptions[index]; - if (item != null && item.Children.Count > 0) ReCreateSettings(__instance); - } - - return false; - } - - public static void ReCreateSettings(TabGroup tab) - { - if (!GameSettingMenuPatch.ModSettingsTabs.TryGetValue(tab, out GameOptionsMenu menu)) return; - ReCreateSettings(menu, tab); - } - - internal static int ReCreateGeneration; - internal static Coroutine ReCreateAllCoroutine; - - public static void ReCreateAllSettings() - { - ReCreateGeneration++; - int generation = ReCreateGeneration; - - if (ReCreateAllCoroutine != null) - { - Main.Instance.StopCoroutine(ReCreateAllCoroutine); - ReCreateAllCoroutine = null; - } - - ReCreateAllCoroutine = Main.Instance.StartCoroutine(CoReCreateAll(generation)); - return; - - IEnumerator CoReCreateAll(int gen) - { - TabGroup[] tabs = Main.TabGroupValues; - foreach (TabGroup tab in tabs) - { - if (gen != ReCreateGeneration) yield break; - - // Wait for any in-progress build coroutine on this tab to finish before recreating - if (GameSettingMenuPatch.ModSettingsTabs.TryGetValue(tab, out GameOptionsMenu menu) && menu) - { - while (BuildCoroutines.TryGetValue(menu, out Coroutine existing) && existing != null) - { - if (gen != ReCreateGeneration) yield break; - yield return null; - } - } - - // Check again after the wait - Close_Prefix may have fired while we were waiting - if (gen != ReCreateGeneration) yield break; - - ReCreateSettings(tab); - yield return null; - } - ReCreateAllCoroutine = null; - } - } - - public static void ReCreateSettings(GameOptionsMenu __instance, TabGroup? modTab = null) - { - if (!modTab.HasValue && ModGameOptionsMenu.TabIndex < 3) return; - if (!__instance) return; - - modTab ??= (TabGroup)(ModGameOptionsMenu.TabIndex - 3); - - var num = 2.0f; - - for (var index = 0; index < OptionItem.AllOptions.Count; index++) - { - OptionItem option = OptionItem.AllOptions[index]; - if (option.Tab != modTab) continue; - - bool enabledOrNotCollapsed = !option.IsCurrentlyHidden() && AllParentsEnabledAndVisible(option.Parent); - bool enabled = !option.IsCurrentlyHidden(checkCollapsedSection: false) && AllParentsEnabledAndVisible(option.Parent, checkCollapsedSection: false); - - if (ModGameOptionsMenu.CategoryHeaderList.TryGetValue(index, out CategoryHeaderMasked categoryHeaderMasked) && categoryHeaderMasked) - { - categoryHeaderMasked.transform.localPosition = new(-0.903f, num, -2f); - categoryHeaderMasked.gameObject.SetActive(enabled); - if (enabledOrNotCollapsed) num -= 0.63f; - } - else if (option.IsHeader && enabledOrNotCollapsed) num -= 0.18f; - - if (ModGameOptionsMenu.BehaviourList.TryGetValue(index, out OptionBehaviour optionBehaviour) && optionBehaviour) - { - optionBehaviour.transform.localPosition = new(0.952f, num, -2f); - optionBehaviour.gameObject.SetActive(enabledOrNotCollapsed); - if (enabledOrNotCollapsed) num -= 0.45f; - } - } - - if (!__instance.scrollBar) return; - __instance.ControllerSelectable.Clear(); - - foreach (UiElement x in __instance.scrollBar.GetComponentsInChildren()) - __instance.ControllerSelectable.Add(x); - - __instance.scrollBar.SetYBoundsMax(-num - 1.65f); - } - - public static void RefreshSettingValues() - { - // ReSharper disable once UseDeconstruction - unsupported here by Il2Cpp - foreach (KeyValuePair kvp in ModGameOptionsMenu.OptionList) - { - OptionBehaviour optionBehaviour = kvp.Key; - if (!optionBehaviour) continue; - - OptionItem optionItem = OptionItem.AllOptions[kvp.Value]; - - switch (optionItem) - { - case BooleanOptionItem when optionBehaviour is ToggleOption toggleOption: - var color = ModGameOptionsMenu.GetCurrentThemeColor(optionItem.Tab); - toggleOption.CheckMark.color = color; - toggleOption.CheckMark.enabled = optionItem.GetBool(); - toggleOption.CheckMark.transform.parent.Find("ActiveSprite").GetComponent().color = color; - break; - case StringOptionItem stringOptionItem when optionBehaviour is StringOption stringOption: - stringOption.Value = stringOptionItem.GetInt(); - stringOption.oldValue = stringOption.Value; - string selection = stringOptionItem.Selections[stringOptionItem.Rule.GetValueByIndex(stringOption.Value)]; - if (!stringOptionItem.noTranslation) selection = Translator.GetString(selection); - stringOption.ValueText.SetText(selection); - if (!StringOptionPatch.NameCache.TryGetValue(stringOption, out string name)) - stringOption.Initialize(); - else - stringOption.TitleText.SetText(name); - break; - case FloatOptionItem or IntegerOptionItem when optionBehaviour is NumberOption numberOption: - numberOption.Value = optionItem.GetFloat(); - break; - } - } - - GameOptionsManager.Instance.GameHostOptions = GameOptionsManager.Instance.CurrentGameOptions; - GameManager.Instance.LogicOptions.SyncOptions(); - } - - public static void RefreshTabButtons() - { - foreach ((TabGroup tab, PassiveButton button) in GameSettingMenuPatch.ModSettingsButtons) - button.gameObject.SetActive(tab.IsRelevant()); - } - - public static void RefreshCheckMarkColors() - { - // ReSharper disable once UseDeconstruction - unsupported here by Il2Cpp - foreach (KeyValuePair kvp in ModGameOptionsMenu.OptionList) - { - if (kvp.Key is ToggleOption toggleOption) - { - var color = ModGameOptionsMenu.GetCurrentThemeColor(OptionItem.AllOptions[kvp.Value].Tab); - toggleOption.CheckMark.color = color; - toggleOption.CheckMark.transform.parent.Find("ActiveSprite").GetComponent().color = color; - } - } - } - - public static BaseGameSetting GetSetting(OptionItem item) - { - if (ModGameOptionsMenu.BaseGameSettingCache.TryGetValue(item, out BaseGameSetting cache)) return cache; - - BaseGameSetting baseGameSetting; - - switch (item) - { - case BooleanOptionItem: - var checkboxGameSetting = ScriptableObject.CreateInstance(); - checkboxGameSetting.Type = OptionTypes.Checkbox; - baseGameSetting = checkboxGameSetting; - break; - case IntegerOptionItem integerOptionItem: - var intGameSetting = ScriptableObject.CreateInstance(); - intGameSetting.Type = OptionTypes.Int; - intGameSetting.Value = integerOptionItem.GetInt(); - intGameSetting.Increment = integerOptionItem.Rule.Step; - intGameSetting.ValidRange = new(integerOptionItem.Rule.MinValue, integerOptionItem.Rule.MaxValue); - intGameSetting.ZeroIsInfinity = false; - intGameSetting.SuffixType = NumberSuffixes.Multiplier; - intGameSetting.FormatString = string.Empty; - baseGameSetting = intGameSetting; - break; - case FloatOptionItem floatOptionItem: - var floatGameSetting = ScriptableObject.CreateInstance(); - floatGameSetting.Type = OptionTypes.Float; - floatGameSetting.Value = floatOptionItem.GetFloat(); - floatGameSetting.Increment = floatOptionItem.Rule.Step; - floatGameSetting.ValidRange = new(floatOptionItem.Rule.MinValue, floatOptionItem.Rule.MaxValue); - floatGameSetting.ZeroIsInfinity = false; - floatGameSetting.SuffixType = NumberSuffixes.Multiplier; - floatGameSetting.FormatString = string.Empty; - baseGameSetting = floatGameSetting; - break; - case StringOptionItem stringOptionItem: - var stringGameSetting = ScriptableObject.CreateInstance(); - stringGameSetting.Type = OptionTypes.String; - stringGameSetting.Values = new StringNames[stringOptionItem.Selections.Count]; - stringGameSetting.Index = stringOptionItem.GetInt(); - baseGameSetting = stringGameSetting; - break; - default: - return null; - } - - baseGameSetting.Title = StringNames.Accept; - ModGameOptionsMenu.BaseGameSettingCache[item] = baseGameSetting; - return baseGameSetting; - } -} - -[HarmonyPatch(typeof(ToggleOption))] -public static class ToggleOptionPatch -{ - [HarmonyPatch(nameof(ToggleOption.Initialize))] - [HarmonyPrefix] - private static bool InitializePrefix(ToggleOption __instance) - { - if (ModGameOptionsMenu.OptionList.TryGetValue(__instance, out int index)) - { - OptionItem item = OptionItem.AllOptions[index]; - - var color = ModGameOptionsMenu.GetCurrentThemeColor(); - __instance.CheckMark.sprite = Utils.LoadSprite("EHR.Resources.Images.Checkmark.png", 100f); - __instance.CheckMark.color = color; - var renderer = __instance.CheckMark.transform.parent.Find("ActiveSprite").GetComponent(); - renderer.sprite = Utils.LoadSprite("EHR.Resources.Images.CheckMarkBox.png", 100f); - renderer.color = color; - - __instance.TitleText.SetText(item.GetName()); - __instance.CheckMark.enabled = item.GetBool(); - item.OptionBehaviour = __instance; - return false; - } - - return true; - } - - // For some reason, ToggleOption.UpdateValue isn't called for Steam users - [HarmonyPatch(nameof(ToggleOption.Toggle))] - [HarmonyPrefix] - private static bool TogglePrefix(ToggleOption __instance) - { - if (ModGameOptionsMenu.OptionList.TryGetValue(__instance, out int index)) - { - __instance.CheckMark.enabled = !__instance.CheckMark.enabled; - OptionItem item = OptionItem.AllOptions[index]; - item.SetValue(__instance.GetBool() ? 1 : 0, doSave: true, doSync: false); - __instance.OnValueChanged?.Invoke(__instance); - NotificationPopperPatch.AddSettingsChangeMessage(item); - return false; - } - - return true; - } -} - -[HarmonyPatch(typeof(NumberOption))] -public static class NumberOptionPatch -{ - //private static bool IsVanillaServer => GameStates.CurrentServerType == GameStates.ServerType.Vanilla; - - private static int IncrementMultiplier - { - get - { - if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) return 5; - if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) return 10; - return 1; - } - } - - [HarmonyPatch(nameof(NumberOption.Initialize))] - [HarmonyPrefix] - private static bool InitializePrefix(NumberOption __instance) - { - switch (__instance.Title) - { - case StringNames.GameVotingTime: - __instance.ValidRange = new(0, 600); - __instance.Value = (float)Math.Round(__instance.Value, 2); - break; - case StringNames.GameShortTasks: - case StringNames.GameLongTasks: - case StringNames.GameCommonTasks: - __instance.ValidRange = new(0, 85); - __instance.Value = (float)Math.Round(__instance.Value, 2); - break; - case StringNames.GameKillCooldown: - __instance.ValidRange = new(0, 180); - __instance.Increment = 0.5f; - __instance.Value = (float)Math.Round(__instance.Value, 2); - break; - case StringNames.GamePlayerSpeed: - __instance.Increment = 0.05f; - __instance.Value = Mathf.Clamp((float)Math.Round(__instance.Value, 2), __instance.ValidRange.min, __instance.ValidRange.max); - break; - case StringNames.GameCrewLight: - case StringNames.GameImpostorLight: - __instance.Increment = 0.05f; - __instance.Value = (float)Math.Round(__instance.Value, 2); - break; - case StringNames.GameNumImpostors: - __instance.ValidRange = new(0, Crowded.MaxImpostors); - __instance.Value = Mathf.Clamp((float)Math.Round(__instance.Value, 2), __instance.ValidRange.min, __instance.ValidRange.max); - if (DebugModeManager.AmDebugger) __instance.ValidRange.min = 0; - break; - case StringNames.CapacityLabel: - __instance.ValidRange = new(4, 127); - __instance.Value = Mathf.Clamp(__instance.Value, __instance.ValidRange.min, __instance.ValidRange.max); - break; - } - - if (ModGameOptionsMenu.OptionList.TryGetValue(__instance, out int index)) - { - OptionItem item = OptionItem.AllOptions[index]; - __instance.TitleText.SetText(item.GetName()); - item.OptionBehaviour = __instance; - return false; - } - - return true; - } - - [HarmonyPatch(nameof(NumberOption.UpdateValue))] - [HarmonyPrefix] - private static bool UpdateValuePrefix(NumberOption __instance) - { - if (ModGameOptionsMenu.OptionList.TryGetValue(__instance, out int index)) - { - OptionItem item = OptionItem.AllOptions[index]; - - switch (item) - { - case IntegerOptionItem integerOptionItem: - integerOptionItem.SetValue(integerOptionItem.Rule.GetNearestIndex(__instance.GetInt()), doSave: true, doSync: false); - break; - case FloatOptionItem floatOptionItem: - floatOptionItem.SetValue(floatOptionItem.Rule.GetNearestIndex(__instance.GetFloat()), doSave: true, doSync: false); - break; - } - - NotificationPopperPatch.AddSettingsChangeMessage(item); - return false; - } - - return true; - } - - [HarmonyPatch(nameof(NumberOption.FixedUpdate))] - [HarmonyPrefix] - private static bool FixedUpdatePrefix(NumberOption __instance) - { - if (ModGameOptionsMenu.OptionList.TryGetValue(__instance, out int index)) - { - __instance.MinusBtn.SetInteractable(true); - __instance.PlusBtn.SetInteractable(true); - - if (!Mathf.Approximately(__instance.oldValue, __instance.Value)) - { - __instance.oldValue = __instance.Value; - __instance.ValueText.SetText(GetValueString(__instance, __instance.Value, OptionItem.AllOptions[index])); - } - - return false; - } - - return true; - } - - private static string GetValueString(NumberOption __instance, float value, OptionItem item) - { - if (__instance.ZeroIsInfinity && Mathf.Abs(value) < 0.0001f) return "∞"; - - return item == null ? value.ToString(__instance.FormatString) : item.GetString(); - } - - [HarmonyPatch(nameof(NumberOption.Increase))] - [HarmonyPrefix] - public static bool IncreasePrefix(NumberOption __instance) - { - if (Mathf.Approximately(__instance.Value, __instance.ValidRange.max)) - { - __instance.Value = __instance.ValidRange.min; - __instance.UpdateValue(); - __instance.OnValueChanged?.Invoke(__instance); - return false; - } - - float increment = IncrementMultiplier * __instance.Increment; - - if (__instance.Value + increment < __instance.ValidRange.max) - { - __instance.Value += increment; - __instance.UpdateValue(); - __instance.OnValueChanged?.Invoke(__instance); - return false; - } - - return true; - } - - [HarmonyPatch(nameof(NumberOption.Decrease))] - [HarmonyPrefix] - public static bool DecreasePrefix(NumberOption __instance) - { - if (Mathf.Approximately(__instance.Value, __instance.ValidRange.min)) - { - __instance.Value = __instance.ValidRange.max; - __instance.UpdateValue(); - __instance.OnValueChanged?.Invoke(__instance); - return false; - } - - float increment = IncrementMultiplier * __instance.Increment; - - if (__instance.Value - increment > __instance.ValidRange.min) - { - __instance.Value -= increment; - __instance.UpdateValue(); - __instance.OnValueChanged?.Invoke(__instance); - return false; - } - - return true; - } -} - -[HarmonyPatch(typeof(StringOption))] -public static class StringOptionPatch -{ - private static long HelpShowEndTS; - internal static readonly Dictionary NameCache = new(); - - [HarmonyPatch(nameof(StringOption.Initialize))] - [HarmonyPrefix] - private static bool InitializePrefix(StringOption __instance) - { - if (__instance.name.StartsWith(nameof(OnlinePresetsManager))) return false; - - if (ModGameOptionsMenu.OptionList.TryGetValue(__instance, out int index)) - { - OptionItem item = OptionItem.AllOptions[index]; - string name = item.GetName(); - item.OptionBehaviour = __instance; - string name1 = name; - - if (Main.CustomRoleValues.FindFirst(x => Translator.GetString($"{x}") == name1.RemoveHtmlTags(), out CustomRoles role)) - { - if (role.ToString().Contains("GuardianAngel")) role = CustomRoles.GA; - - name = name.RemoveHtmlTags(); - - switch (Options.UsePets.GetBool()) - { - case false when role.OnlySpawnsWithPets(): - name += Translator.GetString("RequiresPetIndicator"); - break; - case true when role.PetActivatedAbility(): - name += Translator.GetString("SupportsPetIndicator"); - break; - } - - if (role.IsExperimental()) name += $"{Translator.GetString("ExperimentalRoleIndicator")}"; - if (role.IsGhostRole()) name += GetGhostRoleTeam(role); - if (role.IsDevFavoriteRole()) name += " <#00ffff>★"; - - __instance.TitleText.fontWeight = FontWeight.Black; - __instance.TitleText.outlineColor = new(255, 255, 255, 255); - __instance.TitleText.outlineWidth = 0.04f; - __instance.LabelBackground.color = Utils.GetRoleColor(role); - __instance.TitleText.color = Color.white; - name = $"{name}"; - SetupHelpIcon(role, __instance); - } - - __instance.TitleText.SetText(name); - NameCache[__instance] = name; - return false; - } - - return true; - } - - private static void SetupHelpIcon(CustomRoles role, StringOption option) - { - Transform template = option.MinusBtn.transform; - bool cached = ModGameOptionsMenu.HelpIconList.TryGetValue(role, out Transform cache); - Transform icon = cached ? cache : ModGameOptionsMenu.Track(Object.Instantiate(template, template.parent, true)); - icon.name = $"{role}HelpIcon"; - var text = icon.GetComponentInChildren(); - text.SetText("?"); - text.color = Color.white; - icon.Find("ButtonSprite").GetComponent().color = Color.black; - var gameOptionButton = icon.GetComponent(); - gameOptionButton.OnClick = new(); - - gameOptionButton.OnClick.AddListener(() => - { - if (ModGameOptionsMenu.OptionList.TryGetValue(option, out int index)) - { - OptionItem item = OptionItem.AllOptions[index]; - string name = item.GetName(); - - if (Main.CustomRoleValues.FindFirst(x => Translator.GetString($"{x}") == name.RemoveHtmlTags(), out CustomRoles value)) - { - string roleName = value.IsVanilla() ? value + "EHR" : value.ToString(); - string str = Translator.GetString($"{roleName}InfoLong").FixRoleName(value); - string infoLong; - - try { infoLong = CustomHnS.AllHnSRoles.Contains(value) ? str : str[(str.IndexOf('\n') + 1)..str.Split("\n\n")[0].Length]; } - catch { infoLong = str; } - - GameObject.Find("PlayerOptionsMenu(Clone)").transform.Find("What Is This?").gameObject.SetActive(true); - GameSettingMenuPatch.GMButtons.Values.Do(x => x.gameObject.SetActive(false)); - - var info = $"{value.ToColoredString()}: {infoLong}"; - GameSettingMenu.Instance.MenuDescriptionText.SetText(info); - - long now = Utils.TimeStamp; - bool startCoRoutine = now > HelpShowEndTS; - HelpShowEndTS = now + 15; -#if IL2CPP - if (startCoRoutine) GameSettingMenu.Instance.StartCoroutine(CoRoutine().WrapToIl2Cpp()); -#else - if (startCoRoutine) GameSettingMenu.Instance.StartCoroutine(CoRoutine()); -#endif - - IEnumerator CoRoutine() - { - while (HelpShowEndTS > Utils.TimeStamp) - yield return new WaitForSecondsRealtime(1f); - - GameObject gameObject = GameObject.Find("PlayerOptionsMenu(Clone)"); - - if (gameObject) - { - Transform Find = gameObject.transform.Find("What Is This?"); - if (Find) Find.gameObject.SetActive(false); - } - - GameSettingMenuPatch.GMButtons.Values.Do(x => x.gameObject.SetActive(true)); - } - } - } - }); - - gameOptionButton.interactableColor = Color.black; - gameOptionButton.interactableHoveredColor = ModGameOptionsMenu.GetCurrentThemeColor(); - // Only apply position offset on first creation, not on reuse (prevents icon drifting left on switching presets) - if (!cached) - icon.localPosition += new Vector3(-0.8f, 0f, 0f); - icon.SetAsLastSibling(); - ModGameOptionsMenu.HelpIconList[role] = icon; - } - - public static string GetGhostRoleTeam(CustomRoles role) - { - IGhostRole instance = GhostRolesManager.CreateGhostRoleInstance(role); - if (instance == null) return string.Empty; - - Team team = instance.Team; - if ((int)team is 1 or 2 or 4 or 8) return $" {GetColoredShortTeamName(team)}"; - - Team[] teams = (int)team switch - { - 3 => [Team.Impostor, Team.Neutral], - 5 => [Team.Impostor, Team.Crewmate], - 6 => [Team.Neutral, Team.Crewmate], - 7 => [Team.Impostor, Team.Neutral, Team.Crewmate], - 9 => [Team.Impostor, Team.Coven], - 10 => [Team.Neutral, Team.Coven], - 11 => [Team.Impostor, Team.Neutral, Team.Coven], - 12 => [Team.Crewmate, Team.Coven], - 13 => [Team.Impostor, Team.Crewmate, Team.Coven], - 14 => [Team.Neutral, Team.Crewmate, Team.Coven], - 15 => [Team.Impostor, Team.Neutral, Team.Crewmate, Team.Coven], - _ => [] - }; - - return $" {teams.Join('/', GetColoredShortTeamName)}"; - - string GetColoredShortTeamName(Team t) => Utils.ColorString(t.GetColor(), Translator.GetString($"ShortTeamName.{t}").ToUpper()); - } - - [HarmonyPatch(nameof(StringOption.UpdateValue))] - [HarmonyPrefix] - private static bool UpdateValuePrefix(StringOption __instance) - { - if (__instance.name.StartsWith(nameof(OnlinePresetsManager))) return false; - - if (ModGameOptionsMenu.OptionList.TryGetValue(__instance, out int index)) - { - OptionItem item = OptionItem.AllOptions[index]; - item.SetValue(__instance.GetInt(), doSave: true, doSync: false); - NotificationPopperPatch.AddSettingsChangeMessage(item); - if (!NameCache.TryGetValue(__instance, out string name)) - __instance.Initialize(); - else - __instance.TitleText.SetText(name); - return false; - } - - return true; - } - - [HarmonyPatch(nameof(StringOption.FixedUpdate))] - [HarmonyPrefix] - private static bool FixedUpdatePrefix(StringOption __instance) - { - if (__instance.name.StartsWith(nameof(OnlinePresetsManager))) - { - __instance.TitleText.SetText(__instance.name.Split(';')[1]); - return false; - } - - if (ModGameOptionsMenu.OptionList.TryGetValue(__instance, out int index)) - { - __instance.MinusBtn.SetInteractable(true); - __instance.PlusBtn.SetInteractable(true); - - if (__instance.oldValue != __instance.Value && OptionItem.AllOptions[index] is StringOptionItem stringOptionItem) - { - __instance.oldValue = __instance.Value; - string selection = stringOptionItem.Selections[stringOptionItem.Rule.GetValueByIndex(__instance.Value)]; - if (!stringOptionItem.noTranslation) selection = Translator.GetString(selection); - __instance.ValueText.SetText(selection); - } - - return false; - } - - return true; - } - - [HarmonyPatch(nameof(StringOption.Increase))] - [HarmonyPrefix] - public static bool IncreasePrefix(StringOption __instance) - { - if (__instance.Value == __instance.Values.Length - 1) - { - __instance.Value = 0; - __instance.UpdateValue(); - __instance.OnValueChanged?.Invoke(__instance); - return false; - } - - return true; - } - - [HarmonyPatch(nameof(StringOption.Decrease))] - [HarmonyPrefix] - public static bool DecreasePrefix(StringOption __instance) - { - if (__instance.Value == 0) - { - __instance.Value = __instance.Values.Length - 1; - __instance.UpdateValue(); - __instance.OnValueChanged?.Invoke(__instance); - return false; - } - - return true; - } -} - -[HarmonyPatch(typeof(GameSettingMenu))] -public static class GameSettingMenuPatch -{ - public static readonly System.Collections.Generic.Dictionary GMButtons = []; - - private static readonly Vector3 ButtonPositionLeft = new(-3.9f, -0.55f, 0f); - private static readonly Vector3 ButtonPositionRight = new(-2.4f, -0.55f, 0f); - - private static readonly Vector3 ButtonSize = new(0.45f, 0.35f, 1f); - - private static GameOptionsMenu TemplateGameOptionsMenu; - private static PassiveButton TemplateGameSettingsButton; - - public static readonly System.Collections.Generic.Dictionary ModSettingsButtons = []; - public static readonly System.Collections.Generic.Dictionary ModSettingsTabs = []; - - public static long LastPresetChange; - public static bool ChangingPreset; - - public static FreeChatInputField InputField; - private static System.Collections.Generic.List HiddenBySearch = []; - public static Action SearchForOptionsAction; - - private static int NumImpsOnOpen = 1; - private static int MinImpsOnOpen = 1; - private static int MaxImpsOnOpen = 1; - - private static float VanillaKillCooldownOnOpen = 1; - private static float ModdedKillCooldownOnOpen = 1; - - [HarmonyPatch(nameof(GameSettingMenu.Start))] - [HarmonyPrefix] - [HarmonyPriority(Priority.First)] - public static void StartPrefix(ref GameSettingMenu __instance) - { - try - { - (OptionItem minSetting, OptionItem maxSetting) = Options.FactionMinMaxSettings[Team.Impostor]; - MinImpsOnOpen = minSetting.GetInt(); - MaxImpsOnOpen = maxSetting.GetInt(); - NumImpsOnOpen = Main.NormalOptions.NumImpostors; - - VanillaKillCooldownOnOpen = Main.NormalOptions.KillCooldown; - ModdedKillCooldownOnOpen = Options.FallBackKillCooldownValue.GetFloat(); - } - catch (Exception e) { Utils.ThrowException(e); } - - foreach (TabGroup tab in Main.TabGroupValues) - { - bool cached = ModSettingsButtons.TryGetValue(tab, out PassiveButton cache); - PassiveButton button = cached ? cache : ModGameOptionsMenu.Track(Object.Instantiate(TemplateGameSettingsButton, __instance.GameSettingsButton.transform.parent)); - if (cached) button.transform.SetParent(__instance.GameSettingsButton.transform.parent, false); - button.gameObject.SetActive(tab.IsRelevant()); - button.name = "Button_" + tab; - var label = button.GetComponentInChildren(); - label.DestroyTranslator(); - label.SetText(Translator.GetString($"TabGroup.{tab}")); - label.color = Color.white; - button.activeTextColor = button.inactiveTextColor = Color.white; - button.selectedTextColor = new(0.7f, 0.7f, 0.7f); - Color color = tab.GetTabColor(); - - button.inactiveSprites.GetComponent().color = color; - button.activeSprites.GetComponent().color = color; - button.selectedSprites.GetComponent().color = color; - - // ReSharper disable once PossibleLossOfFraction - Vector3 offset = new(0f, 0.3f * (((int)tab + 1) / 2), 0f); - button.transform.localPosition = (((int)tab + 1) % 2 == 0 ? ButtonPositionLeft : ButtonPositionRight) - offset; - button.transform.localScale = ButtonSize; - - var buttonComponent = button.GetComponent(); - buttonComponent.OnClick = new(); - buttonComponent.OnClick.AddListener(() => GameSettingMenu.Instance.ChangeTab((int)tab + 3, false)); - - ModSettingsButtons[tab] = button; - } - - foreach (TabGroup tab in Main.TabGroupValues) - { - bool cached = ModSettingsTabs.TryGetValue(tab, out GameOptionsMenu cache); - GameOptionsMenu setTab = cached ? cache : ModGameOptionsMenu.Track(Object.Instantiate(TemplateGameOptionsMenu, __instance.GameSettingsTab.transform.parent)); - if (cached) setTab.transform.SetParent(__instance.GameSettingsTab.transform.parent, false); - setTab.name = "tab_" + tab; - setTab.gameObject.SetActive(false); - - ModSettingsTabs[tab] = setTab; - } - - foreach (TabGroup tab in Main.TabGroupValues) - { - if (ModSettingsButtons.TryGetValue(tab, out PassiveButton button)) - __instance.ControllerSelectable.Add(button); - } - - HiddenBySearch.Do(x => x.SetHidden(false)); - HiddenBySearch.Clear(); - - SetupExtendedUI(__instance); - } - - private static readonly System.Collections.Generic.Dictionary ExtraObjectsCache = []; - private static Coroutine KeepSearchBarDarkThemedCoroutine; - - // Thanks: Drakos for the preset button and search bar code (https://github.com/0xDrMoe/TownofHost-Enhanced/pull/1115) - private static void SetupExtendedUI(GameSettingMenu __instance) - { - Transform parentLeftPanel = __instance.GamePresetsButton.transform.parent; - bool cached = ExtraObjectsCache.TryGetValue(0, out GameObject cache); - GameObject preset = cached ? cache : ModGameOptionsMenu.Track(Object.Instantiate(GameObject.Find("ModeValue"), parentLeftPanel)); - if (cached) - { - preset.transform.SetParent(parentLeftPanel, false); - preset.SetActive(true); - } - ExtraObjectsCache[0] = preset; - - preset.transform.localPosition = new(-1.8f, 0f, -2f); - preset.transform.localScale = new(0.65f, 0.63f, 1f); - var renderer = preset.GetComponentInChildren(); - renderer.color = Color.white; - renderer.sprite = null; - - var presetTmp = preset.GetComponentInChildren(); - presetTmp.DestroyTranslator(); - presetTmp.SetText(Translator.GetString($"Preset_{OptionItem.CurrentPreset + 1}")); - - bool russian = TranslationController.Instance.currentLanguage.languageID == SupportedLangs.Russian; - float size = !russian ? 2.45f : 1.45f; - presetTmp.fontSizeMax = presetTmp.fontSizeMin = size; - - - var gameSettingsLabel = __instance.GameSettingsButton.transform.parent.parent.Find("GameSettingsLabel").GetComponent(); - gameSettingsLabel.DestroyTranslator(); - gameSettingsLabel.SetText($"{Translator.GetString($"Mode{Options.CurrentGameMode}")}\n"); - gameSettingsLabel.transform.localPosition += new Vector3(0f, 0.1f, 0f); - - if (russian) - { - gameSettingsLabel.transform.localScale = new(0.7f, 0.7f, 1f); - gameSettingsLabel.transform.localPosition = new(-3.77f, 1.62f, -4); - } - - Vector3 gameSettingsLabelPos = gameSettingsLabel.transform.localPosition; - - - GameObject tempMinus = GameObject.Find("MinusButton").gameObject; - cached = ExtraObjectsCache.TryGetValue(1, out cache); - GameObject gMinus = cached ? cache : ModGameOptionsMenu.Track(Object.Instantiate(__instance.GamePresetsButton.gameObject, preset.transform)); - if (cached) gMinus.transform.SetParent(preset.transform, false); - ExtraObjectsCache[1] = gMinus; - gMinus.gameObject.SetActive(true); - gMinus.transform.localScale = new(0.08f, 0.4f, 1f); - - var mLabel = gMinus.transform.Find("FontPlacer/Text_TMP").GetComponent(); - mLabel.alignment = TextAlignmentOptions.Center; - mLabel.DestroyTranslator(); - mLabel.SetText("-"); - if (!cached) mLabel.transform.localPosition = new(mLabel.transform.localPosition.x, mLabel.transform.localPosition.y + 0.26f, mLabel.transform.localPosition.z); - mLabel.color = Color.white; - mLabel.SetFaceColor(new Color(255f, 255f, 255f)); - mLabel.transform.localScale = new(12f, 4f, 1f); - - var minus = gMinus.GetComponent(); - minus.OnClick.RemoveAllListeners(); - - minus.OnClick.AddListener(() => - { - ChangingPreset = true; - LastPresetChange = Utils.TimeStamp; - Options.Preset--; - GameOptionsMenuPatch.ReCreateAllSettings(); - GameOptionsMenuPatch.RefreshSettingValues(); - GameOptionsMenuPatch.RefreshTabButtons(); - presetTmp.SetText(Translator.GetString($"Preset_{OptionItem.CurrentPreset + 1}")); - gameSettingsLabel.SetText($"{Translator.GetString($"Mode{Options.CurrentGameMode}")}\n"); - Logger.Info($"Current preset: {OptionItem.CurrentPreset + 1}", "GameOptionsMenuPatch"); - ChangingPreset = false; - NotificationPopperPatch.AddSettingsChangeMessage(Options.Preset); - }); - - minus.activeTextColor = minus.inactiveTextColor = minus.disabledTextColor = minus.selectedTextColor = Color.white; - minus.transform.localPosition = new(-2f, -3.37f, -4f); - - var inactiveSprites = minus.inactiveSprites.GetComponent(); - var activeSprites = minus.activeSprites.GetComponent(); - var selectedSprites = minus.selectedSprites.GetComponent(); - - inactiveSprites.sprite = tempMinus.GetComponentInChildren().sprite; - activeSprites.sprite = tempMinus.GetComponentInChildren().sprite; - selectedSprites.sprite = tempMinus.GetComponentInChildren().sprite; - - inactiveSprites.color = new Color32(55, 59, 60, 255); - activeSprites.color = new Color32(0, 165, 255, 255); - selectedSprites.color = new Color32(0, 255, 165, 255); - - - cached = ExtraObjectsCache.TryGetValue(2, out cache); - GameObject plusFab = cached ? cache : ModGameOptionsMenu.Track(Object.Instantiate(gMinus, preset.transform)); - if (cached) - { - plusFab.transform.SetParent(preset.transform, false); - plusFab.SetActive(true); - } - ExtraObjectsCache[2] = plusFab; - var plusLabel = plusFab.transform.Find("FontPlacer/Text_TMP").GetComponent(); - plusLabel.alignment = TextAlignmentOptions.Center; - plusLabel.DestroyTranslator(); - plusLabel.SetText("+"); - plusLabel.color = Color.white; - if (!cached) plusLabel.transform.localPosition = new(plusLabel.transform.localPosition.x, plusLabel.transform.localPosition.y + 0.26f, plusLabel.transform.localPosition.z); - plusLabel.transform.localScale = new(18f, 4f, 1f); - - var plus = plusFab.GetComponent(); - plus.OnClick.RemoveAllListeners(); - - plus.OnClick.AddListener(() => - { - ChangingPreset = true; - LastPresetChange = Utils.TimeStamp; - Options.Preset++; - GameOptionsMenuPatch.ReCreateAllSettings(); - GameOptionsMenuPatch.RefreshSettingValues(); - GameOptionsMenuPatch.RefreshTabButtons(); - presetTmp.SetText(Translator.GetString($"Preset_{OptionItem.CurrentPreset + 1}")); - gameSettingsLabel.SetText($"{Translator.GetString($"Mode{Options.CurrentGameMode}")}\n"); - Logger.Info($"Current preset: {OptionItem.CurrentPreset + 1}", "GameOptionsMenuPatch"); - ChangingPreset = false; - NotificationPopperPatch.AddSettingsChangeMessage(Options.Preset); - }); - - plus.activeTextColor = plus.inactiveTextColor = plus.disabledTextColor = plus.selectedTextColor = Color.white; - plus.transform.localPosition = new(-0.4f, -3.37f, -4f); - - - GameObject.Find("PlayerOptionsMenu(Clone)").transform.Find("What Is This?").gameObject.SetActive(false); - - var gms = Main.CustomGameModeValues[..^1].ToList(); - gms.Remove(CustomGameMode.TheMindGame); - - if (SubmergedCompatibility.Loaded && Main.NormalOptions.MapId == 6) - gms.Remove(CustomGameMode.NaturalDisasters); - - if (Main.LIMap) - { - gms.Remove(CustomGameMode.CaptureTheFlag); - gms.Remove(CustomGameMode.Quiz); - gms.Remove(CustomGameMode.BedWars); - gms.Remove(CustomGameMode.Deathrace); - } - - const int totalCols = 2; - int itemsPerCol = Mathf.CeilToInt(gms.Count / (float)totalCols); - - GMButtons.Clear(); - - for (var index = 0; index < gms.Count; index++) - { - CustomGameMode gm = gms[index]; - - cached = GMButtons.TryGetValue(gm, out cache); - var gmButton = cached ? cache : ModGameOptionsMenu.Track(Object.Instantiate(gMinus, gameSettingsLabel.transform, true)); - if (cached) - { - gmButton.transform.SetParent(gameSettingsLabel.transform, false); - gmButton.SetActive(true); - } - gmButton.transform.localPosition = new Vector3((index / itemsPerCol - (totalCols - 1) / 2f) * 1.4f + 0.16f, gameSettingsLabelPos.y - 1.9f - 0.17f * (index % itemsPerCol), -1f); - gmButton.transform.localScale = new(0.4f, 0.22f, 1f); - var color = Main.GameModeColors[gm]; - var gmButtonTmp = gmButton.transform.Find("FontPlacer/Text_TMP").GetComponent(); - gmButtonTmp.alignment = TextAlignmentOptions.Center; - gmButtonTmp.DestroyTranslator(); - gmButtonTmp.SetText(Translator.GetString(gm.ToString()).ToUpper()); - gmButtonTmp.color = color; - gmButtonTmp.transform.localPosition = new(gameSettingsLabelPos.x + 3.35f, gameSettingsLabelPos.y - 1.62f, gameSettingsLabelPos.z); - gmButtonTmp.transform.localScale = new(1f, 1f, 1f); - - var gmPassiveButton = gmButton.GetComponent(); - gmPassiveButton.OnClick.RemoveAllListeners(); - gmPassiveButton.OnClick.AddListener(() => - { - if (ModSettingsTabLoaded && !((TabGroup)(ModGameOptionsMenu.TabIndex - 3)).IsRelevant(gm)) - GameSettingMenu.Instance.ChangeTab(4, false); - Options.GameMode.SetValue((int)gm - 1); - GameOptionsMenuPatch.ReCreateSettings(TabGroup.GameSettings); - if (gm is CustomGameMode.Standard or CustomGameMode.HideAndSeek) - { - GameOptionsMenuPatch.ReCreateSettings(TabGroup.ImpostorRoles); - GameOptionsMenuPatch.ReCreateSettings(TabGroup.CrewmateRoles); - GameOptionsMenuPatch.ReCreateSettings(TabGroup.NeutralRoles); - } - GameOptionsMenuPatch.RefreshTabButtons(); - GameOptionsMenuPatch.RefreshCheckMarkColors(); - gameSettingsLabel.SetText($"{Translator.GetString($"Mode{Options.CurrentGameMode}")}\n"); - }); - gmPassiveButton.activeTextColor = Utils.GetTextColor(color); - gmPassiveButton.inactiveTextColor = color; - gmPassiveButton.activeSprites.GetComponent().color = color; - - GMButtons[gm] = gmButton; - } - - - if (!HudManager.InstanceExists) return; - - FreeChatInputField freeChatField = HudManager.Instance.Chat.freeChatField; - cached = InputField; - FreeChatInputField field = cached ? InputField : ModGameOptionsMenu.Track(Object.Instantiate(freeChatField, parentLeftPanel.parent)); - if (cached) - { - field.transform.SetParent(parentLeftPanel.parent, false); - field.gameObject.SetActive(true); - } - else if (Main.DarkTheme.Value) - { - KeepSearchBarDarkThemedCoroutine ??= Main.Instance.StartCoroutine(KeepSearchBarDarkThemed()); - } - field.transform.localScale = new(0.3f, 0.59f, 1); - field.transform.localPosition = new(-0.47f, 2.15f, -5f); - field.textArea.outputText.transform.localScale = new(3.5f, 2f, 1f); - field.textArea.outputText.font = plusLabel.font; - field.charCountText.enabled = false; - - InputField = field; - - Transform button = field.transform.Find("ChatSendButton"); - - Transform buttonNormal = button.Find("Normal"); - Transform buttonHover = button.Find("Hover"); - Transform buttonDisabled = button.Find("Disabled"); - - Object.Destroy(buttonNormal.Find("Icon").GetComponent()); - Object.Destroy(buttonHover.Find("Icon").GetComponent()); - Object.Destroy(buttonDisabled.Find("Icon").GetComponent()); - Object.Destroy(button.transform.Find("Text").GetComponent()); - - Transform buttonNormalBackground = buttonNormal.Find("Background"); - Transform buttonHoverBackground = buttonHover.Find("Background"); - Transform buttonDisabledBackground = buttonDisabled.Find("Background"); - - buttonNormalBackground.GetComponent().sprite = Utils.LoadSprite("EHR.Resources.Images.SearchIconActive.png", 100f); - buttonHoverBackground.GetComponent().sprite = Utils.LoadSprite("EHR.Resources.Images.SearchIconHover.png", 100f); - buttonDisabledBackground.GetComponent().sprite = Utils.LoadSprite("EHR.Resources.Images.SearchIcon.png", 100f); - - if (russian) - { - Vector3 fixedScale = new(0.7f, 1f, 1f); - buttonNormalBackground.transform.localScale = fixedScale; - buttonHoverBackground.transform.localScale = fixedScale; - buttonDisabledBackground.transform.localScale = fixedScale; - } - - - var passiveButton = button.GetComponent(); - - passiveButton.OnClick = new(); - passiveButton.OnClick.AddListener(() => SearchForOptions(field)); - - SearchForOptionsAction = () => - { - if (field.textArea.text != string.Empty) SearchForOptions(field); - }; - - return; - - static void SearchForOptions(FreeChatInputField textField) - { - if (ModGameOptionsMenu.TabIndex < 3) return; - - HiddenBySearch.Do(x => x.SetHidden(false)); - string text = textField.textArea.text.Trim().ToLower(); - var modTab = (TabGroup)(ModGameOptionsMenu.TabIndex - 3); - OptionItem[] optionItems = Options.GroupedOptions[modTab]; - var result = optionItems.Where(x => x.Parent == null && !x.IsCurrentlyHidden() && !Translator.GetString($"{x.Name}").Contains(text, StringComparison.OrdinalIgnoreCase)).ToList(); - HiddenBySearch = result; - var searchWinners = optionItems.Where(x => x.Parent == null && !x.IsCurrentlyHidden() && !result.Contains(x)).ToList(); - - if (searchWinners.Count == 0 || !ModSettingsTabs.TryGetValue(modTab, out GameOptionsMenu gameSettings) || !gameSettings) - { - HiddenBySearch.Clear(); - Logger.SendInGame(Translator.GetString("SearchNoResult"), Palette.Orange); - return; - } - - result.ForEach(x => x.SetHidden(true)); - - gameSettings.scrollBar.ScrollToTop(); - GameOptionsMenuPatch.ReCreateSettings(gameSettings); - textField.Clear(); - } - - IEnumerator KeepSearchBarDarkThemed() - { - while (true) - { - if (InputField && GameSettingMenu.Instance && InputField.gameObject.activeSelf) - { - InputField.background.color = ChatControllerAwakePatch.DarkBackgroundColor; - InputField.textArea.compoText.Color(Color.white); - InputField.textArea.outputText.color = Color.white; - } - - yield return null; - } - // ReSharper disable once IteratorNeverReturns - } - } - - private static void SetDefaultButton(GameSettingMenu __instance) - { - __instance.GamePresetsButton.gameObject.SetActive(false); - - PassiveButton gameSettingButton = __instance.GameSettingsButton; - gameSettingButton.transform.localPosition = new(-3f, -0.55f, 0f); - - var textLabel = gameSettingButton.GetComponentInChildren(); - textLabel.DestroyTranslator(); - textLabel.SetText(Translator.GetString("TabGroup.VanillaSettings")); - - gameSettingButton.activeTextColor = gameSettingButton.inactiveTextColor = Color.white; - gameSettingButton.selectedTextColor = Color.gray; - - gameSettingButton.inactiveSprites.GetComponent().color = Color.black; - gameSettingButton.activeSprites.GetComponent().color = Color.gray; - gameSettingButton.selectedSprites.GetComponent().color = Color.black; - - gameSettingButton.transform.localPosition = ButtonPositionLeft; - gameSettingButton.transform.localScale = ButtonSize; - - __instance.RoleSettingsButton.gameObject.SetActive(false); - - __instance.DefaultButtonSelected = gameSettingButton; - __instance.ControllerSelectable = new(); - __instance.ControllerSelectable.Add(gameSettingButton); - } - - private static bool ModSettingsTabLoaded; - - [HarmonyPatch(nameof(GameSettingMenu.ChangeTab))] - [HarmonyPrefix] - public static bool ChangeTabPrefix(GameSettingMenu __instance, ref int tabNum, [HarmonyArgument(1)] bool previewOnly) - { - if (HiddenBySearch.Count > 0) - { - HiddenBySearch.Do(x => x.SetHidden(false)); - - if (ModSettingsTabs.TryGetValue((TabGroup)(ModGameOptionsMenu.TabIndex - 3), out GameOptionsMenu gameSettings) && gameSettings) - GameOptionsMenuPatch.ReCreateSettings(gameSettings); - - HiddenBySearch.Clear(); - } - - if (!previewOnly || tabNum != 1) ModGameOptionsMenu.TabIndex = tabNum; - - GameOptionsMenu settingsTab; - PassiveButton button; - - if (previewOnly && Controller.currentTouchType == Controller.TouchType.Joystick || !previewOnly) - { - TabGroup[] tabGroups = Main.TabGroupValues; - - foreach (TabGroup tab in tabGroups) - { - if (ModSettingsTabs.TryGetValue(tab, out settingsTab) && settingsTab) - settingsTab.gameObject.SetActive(false); - } - - foreach (TabGroup tab in tabGroups) - { - if (ModSettingsButtons.TryGetValue(tab, out button) && button) - button.SelectButton(false); - } - } - - if (tabNum < 3) return true; - - var tabGroup = (TabGroup)(tabNum - 3); - - if (!OnlinePresetsManager.PresetsLoaded && tabGroup == TabGroup.PresetExplorer) - { - __instance.StartCoroutine( - OnlinePresetsManager.FetchPresetList(list => - { - OnlinePresetsManager.CachedPresets = list; - OnlinePresetsManager.PresetsLoaded = true; - if (ModSettingsTabs.TryGetValue(tabGroup, out settingsTab) && settingsTab) - OnlinePresetsManager.CreatePresetExplorerUI(settingsTab); - }) -#if IL2CPP - .WrapToIl2Cpp() -#endif - ); - } - - if (previewOnly && Controller.currentTouchType == Controller.TouchType.Joystick || !previewOnly) - { - __instance.PresetsTab.gameObject.SetActive(false); - __instance.GameSettingsTab.gameObject.SetActive(false); - __instance.RoleSettingsTab.gameObject.SetActive(false); - __instance.GamePresetsButton.SelectButton(false); - __instance.GameSettingsButton.SelectButton(false); - __instance.RoleSettingsButton.SelectButton(false); - - if (ModSettingsTabs.TryGetValue(tabGroup, out settingsTab) && settingsTab) - { - settingsTab.gameObject.SetActive(true); - __instance.MenuDescriptionText.DestroyTranslator(); - __instance.MenuDescriptionText.SetText(Translator.GetString("TabInfoTip")); - } - } - - if (previewOnly) - { - __instance.ToggleLeftSideDarkener(false); - __instance.ToggleRightSideDarkener(true); - return false; - } - - __instance.ToggleLeftSideDarkener(true); - __instance.ToggleRightSideDarkener(false); - - if (ModSettingsButtons.TryGetValue(tabGroup, out button) && button) - button.SelectButton(true); - - if (tabGroup == TabGroup.GameSettings) - ModSettingsTabLoaded = true; - - return false; - } - - [HarmonyPatch(nameof(GameSettingMenu.OnEnable))] - [HarmonyPrefix] - private static bool OnEnablePrefix(GameSettingMenu __instance) - { - if (!TemplateGameOptionsMenu) - { - TemplateGameOptionsMenu = ModGameOptionsMenu.Track(Object.Instantiate(__instance.GameSettingsTab, __instance.GameSettingsTab.transform.parent)); - TemplateGameOptionsMenu.gameObject.SetActive(false); - } - - if (!TemplateGameSettingsButton) - { - TemplateGameSettingsButton = ModGameOptionsMenu.Track(Object.Instantiate(__instance.GameSettingsButton, __instance.GameSettingsButton.transform.parent)); - TemplateGameSettingsButton.gameObject.SetActive(false); - } - - SetDefaultButton(__instance); - - ControllerManager.Instance.OpenOverlayMenu(__instance.name, __instance.BackButton, __instance.DefaultButtonSelected, __instance.ControllerSelectable); - if (HudManager.InstanceExists) HudManager.Instance.menuNavigationPrompts.SetActive(false); - if (Controller.currentTouchType != Controller.TouchType.Joystick) __instance.ChangeTab(1, false); - - __instance.StartCoroutine(__instance.CoSelectDefault()); - - return false; - } - - private static Transform TempParent; - - [HarmonyPatch(nameof(GameSettingMenu.Close))] - [HarmonyPrefix] - public static void Close_Prefix() - { - if (TempParent == null) - { - var go = new GameObject("EHR Settings UI Cache Root"); - Object.DontDestroyOnLoad(go); - go.SetActive(true); - TempParent = go.transform; - } - - GameOptionsMenuPatch.ReCreateGeneration++; - - if (GameOptionsMenuPatch.ReCreateAllCoroutine != null) - { - Main.Instance.StopCoroutine(GameOptionsMenuPatch.ReCreateAllCoroutine); - GameOptionsMenuPatch.ReCreateAllCoroutine = null; - } - - // Clear GMButton listeners before hiding them so they can't fire stale callbacks - foreach (var x in GMButtons.Values) - { - var pb = x.GetComponent(); - if (pb) pb.OnClick.RemoveAllListeners(); - SetTempParent(x); - } - - foreach (var x in ModSettingsTabs.Values) SetTempParent(x.gameObject); - foreach (var x in ModSettingsButtons.Values) SetTempParent(x.gameObject); - foreach (var x in ExtraObjectsCache.Values) SetTempParent(x); - foreach (var x in GMButtons.Values) SetTempParent(x); - SetTempParent(InputField.gameObject); - return; - - void SetTempParent(GameObject go) - { - go.gameObject.transform.SetParent(TempParent, false); - go.gameObject.SetActive(false); - } - } - - [HarmonyPatch(nameof(GameSettingMenu.Close))] - [HarmonyPostfix] - public static void Close_Postfix() - { - try - { - int numImpostors = Main.NormalOptions.NumImpostors; - (OptionItem minSetting, OptionItem maxSetting) = Options.FactionMinMaxSettings[Team.Impostor]; - - if (numImpostors != NumImpsOnOpen && MinImpsOnOpen == minSetting.GetInt() && MaxImpsOnOpen == maxSetting.GetInt()) - { - minSetting.SetValue(numImpostors); - maxSetting.SetValue(numImpostors); - Logger.SendInGame(string.Format(Translator.GetString("MinMaxModdedImpCountsSettingsChangedAuto"), numImpostors)); - } - - - float vanillaKillCooldown = Main.NormalOptions.KillCooldown; - float moddedKillCooldown = Options.FallBackKillCooldownValue.GetFloat(); - - bool vanillaChanged = !Mathf.Approximately(vanillaKillCooldown, VanillaKillCooldownOnOpen); - bool moddedChanged = !Mathf.Approximately(moddedKillCooldown, ModdedKillCooldownOnOpen); - - if (!Mathf.Approximately(vanillaKillCooldown, moddedKillCooldown) && vanillaChanged && !moddedChanged) - Options.FallBackKillCooldownValue.SetValue((int)Math.Round(Math.Round(vanillaKillCooldown, 1) / 0.5f - 1)); - } - catch (Exception e) { Utils.ThrowException(e); } - - try - { - if (Options.AutoGMRotationRecompileOnClose) - Options.CompileAutoGMRotationSettings(); - } - catch (Exception e) { Utils.ThrowException(e); } - - Options.AutoSetFactionMinMaxSettings(); - - NotificationPopperPatch.ReleaseRpcs(); - } -} - -[HarmonyPatch(typeof(FreeChatInputField), nameof(FreeChatInputField.UpdateCharCount))] -public static class FixInputChatField -{ - public static bool Prefix(FreeChatInputField __instance) - { - if (GameSettingMenuPatch.InputField && __instance == GameSettingMenuPatch.InputField && __instance.gameObject.activeSelf) - { - Vector2 size = __instance.Background.size; - size.y = Math.Max(0.62f, __instance.textArea.TextHeight + 0.2f); - __instance.Background.size = size; - return false; - } - - return true; - } -} diff --git a/Patches/HudPatch.cs b/Patches/HudPatch.cs index ad2310b99..c8d23cdb2 100644 --- a/Patches/HudPatch.cs +++ b/Patches/HudPatch.cs @@ -979,7 +979,7 @@ internal static class MapRoomDoorsUpdatePatch if (!doorSprite || !shipStatusInstance) return false; #if IL2CPP - if (SubmergedCompatibility.IsSubmerged() || Main.LIMap) return true; + if (SubmergedCompatibility.IsSubmerged() || Main.LIMap || Main.CurrentMap == MapNames.MiraHQ) return true; #endif SystemTypes room = __instance.room; diff --git a/Patches/IntroPatch.cs b/Patches/IntroPatch.cs index 008f52604..32a3e3a6a 100644 --- a/Patches/IntroPatch.cs +++ b/Patches/IntroPatch.cs @@ -439,7 +439,7 @@ internal static class SetUpRoleTextPatch foreach (OptionItem o in options) { - if (!o.IsCurrentlyHidden(checkCollapsedSection: false) && (o.Parent == null ? !o.GetString().Equals(disabledRoleStr) : AllParentsEnabled(o))) + if (!o.IsCurrentlyHidden() && (o.Parent == null ? !o.GetString().Equals(disabledRoleStr) : AllParentsEnabled(o))) sb.Append($"{(o.Parent == null ? o.GetName(true, true).RemoveHtmlTags().PadRightV2(40) : $"┗ {o.GetName(true, true).RemoveHtmlTags()}".PadRightV2(41))}:{o.GetString().RemoveHtmlTags()}\n"); if (i++ > 20) @@ -1211,7 +1211,11 @@ internal static class IntroCutsceneDestroyPatch Main.IntroDestroyed = true; PreventKill = true; - LateTask.New(() => PreventKill = false, Options.StartingKillCooldown?.GetFloat() ?? 10f, "PreventKillReset"); + LateTask.New(() => + { + PreventKill = false; + Main.ProcessShapeshifts = true; + }, Options.StartingKillCooldown?.GetFloat() ?? 10f, "PreventKillReset"); var apc = Main.AllPlayerControlsToList; diff --git a/Patches/LobbyViewSettingsPanePatch.cs b/Patches/LobbyViewSettingsPanePatch.cs index f2b3fcf9f..6d8ca0eb1 100644 --- a/Patches/LobbyViewSettingsPanePatch.cs +++ b/Patches/LobbyViewSettingsPanePatch.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using EHR.Modules; #if IL2CPP using BepInEx.Unity.IL2CPP.Utils.Collections; #endif @@ -622,7 +623,7 @@ public static class LobbyViewSettingsPanePatch foreach (OptionItem option in OptionItem.AllOptions) { if (option.Tab != tabName) continue; - BaseGameSetting data = GameOptionsMenuPatch.GetSetting(option); + BaseGameSetting data = GetSetting(option); bool enabledOrNotCollapsed = !option.IsCurrentlyHidden(true) && AllParentsEnabledAndVisible(option.Parent); @@ -800,8 +801,8 @@ public static class LobbyViewSettingsPanePatch if (option.GameMode is not CustomGameMode.All && option.GameMode != LastGameModeSelected) continue; bool enabledOrNotCollapsed = !option.IsCurrentlyHidden(true) && AllParentsEnabledAndVisible(option.Parent); - bool enabled = !option.IsCurrentlyHidden(true, false) && AllParentsEnabledAndVisible(option.Parent, false); - BaseGameSetting data = GameOptionsMenuPatch.GetSetting(option); + bool enabled = !option.IsCurrentlyHidden(true) && AllParentsEnabledAndVisible(option.Parent); + BaseGameSetting data = GetSetting(option); string titleName = option.GetName(true).Trim('★', ' ').RemoveHtmlTags(); string realName = option.Name; @@ -902,7 +903,7 @@ public static class LobbyViewSettingsPanePatch } if (role.IsExperimental()) titleName += $"{Translator.GetString("ExperimentalRoleIndicator")}"; - if (role.IsGhostRole()) titleName += StringOptionPatch.GetGhostRoleTeam(role); + if (role.IsGhostRole()) titleName += GetGhostRoleTeam(role); if (role.IsDevFavoriteRole()) titleName += " <#00ffff>★"; int chanceAddOnPerGame = Options.CustomAdtRoleSpawnRate.TryGetValue(role, out IntegerOptionItem valueAddOnOpt) ? valueAddOnOpt.GetInt() : 0; @@ -1104,7 +1105,7 @@ public static class LobbyViewSettingsPanePatch bool show = firstOption.Name != "Maximum"; if (!show) continue; - BaseGameSetting data = GameOptionsMenuPatch.GetSetting(firstOption); + BaseGameSetting data = GetSetting(firstOption); if (!data) continue; DrawSetting(firstOption, data); @@ -1112,7 +1113,7 @@ public static class LobbyViewSettingsPanePatch foreach (OptionItem secondOption in firstOption.Children) { - data = GameOptionsMenuPatch.GetSetting(secondOption); + data = GetSetting(secondOption); if (!data) continue; DrawSetting(secondOption, data); @@ -1120,7 +1121,7 @@ public static class LobbyViewSettingsPanePatch foreach (OptionItem thirdOption in secondOption.Children) { - data = GameOptionsMenuPatch.GetSetting(thirdOption); + data = GetSetting(thirdOption); if (!data) continue; DrawSetting(thirdOption, data); @@ -1181,13 +1182,80 @@ public static class LobbyViewSettingsPanePatch } } - private static bool AllParentsEnabledAndVisible(OptionItem o, bool checkCollapsedSection = true) + private static bool AllParentsEnabledAndVisible(OptionItem o) { while (true) { if (o == null) return true; - if (o.IsCurrentlyHidden(true, checkCollapsedSection) || !o.GetBool()) return false; + if (o.IsCurrentlyHidden(true) || !o.GetBool()) return false; o = o.Parent; } } + + public static BaseGameSetting GetSetting(OptionItem item) + { + BaseGameSetting baseGameSetting; + + switch (item) + { + case BooleanOptionItem: + var checkboxGameSetting = ScriptableObject.CreateInstance(); + checkboxGameSetting.Type = OptionTypes.Checkbox; + baseGameSetting = checkboxGameSetting; + break; + case IntegerOptionItem integerOptionItem: + var intGameSetting = ScriptableObject.CreateInstance(); + intGameSetting.Type = OptionTypes.Int; + intGameSetting.Value = integerOptionItem.GetInt(); + intGameSetting.Increment = integerOptionItem.Rule.Step; + intGameSetting.ValidRange = new(integerOptionItem.Rule.MinValue, integerOptionItem.Rule.MaxValue); + intGameSetting.ZeroIsInfinity = false; + intGameSetting.SuffixType = NumberSuffixes.Multiplier; + intGameSetting.FormatString = string.Empty; + baseGameSetting = intGameSetting; + break; + case FloatOptionItem floatOptionItem: + var floatGameSetting = ScriptableObject.CreateInstance(); + floatGameSetting.Type = OptionTypes.Float; + floatGameSetting.Value = floatOptionItem.GetFloat(); + floatGameSetting.Increment = floatOptionItem.Rule.Step; + floatGameSetting.ValidRange = new(floatOptionItem.Rule.MinValue, floatOptionItem.Rule.MaxValue); + floatGameSetting.ZeroIsInfinity = false; + floatGameSetting.SuffixType = NumberSuffixes.Multiplier; + floatGameSetting.FormatString = string.Empty; + baseGameSetting = floatGameSetting; + break; + case StringOptionItem stringOptionItem: + var stringGameSetting = ScriptableObject.CreateInstance(); + stringGameSetting.Type = OptionTypes.String; + stringGameSetting.Values = new StringNames[stringOptionItem.Selections.Count]; + stringGameSetting.Index = stringOptionItem.GetInt(); + baseGameSetting = stringGameSetting; + break; + default: + return null; + } + + baseGameSetting.Title = StringNames.Accept; + return baseGameSetting; + } + + public static string GetGhostRoleTeam(CustomRoles role) + { + IGhostRole instance = GhostRolesManager.CreateGhostRoleInstance(role); + if (instance == null) return string.Empty; + + StringBuilder stringBuilder = new(""); + + foreach (Team team in Main.TeamValues[1..]) + { + if ((instance.Team & team) != 0) + { + if (stringBuilder.Length > 8) stringBuilder.Append('/'); + stringBuilder.Append(Utils.ColorString(team.GetColor(), Translator.GetString($"ShortTeamName.{team}").ToUpper())); + } + } + + return stringBuilder.Append("").ToString(); + } } \ No newline at end of file diff --git a/Patches/MatchInfoGuidePatch.cs b/Patches/MatchInfoGuidePatch.cs index 71a68ae60..c7186d296 100644 --- a/Patches/MatchInfoGuidePatch.cs +++ b/Patches/MatchInfoGuidePatch.cs @@ -63,7 +63,7 @@ public static class MatchInfoGuidePatch { foreach (OptionItem optionItem in settings) { - if (optionItem.IsCurrentlyHidden(checkCollapsedSection: false) || optionItem.Parent != null || optionItem is PresetOptionItem or TextOptionItem) continue; + if (optionItem.IsCurrentlyHidden() || optionItem.Parent != null || optionItem is PresetOptionItem or TextOptionItem) continue; string value = optionItem switch { diff --git a/Patches/NotificationPopperPatch.cs b/Patches/NotificationPopperPatch.cs index a3efcc057..a4636061e 100644 --- a/Patches/NotificationPopperPatch.cs +++ b/Patches/NotificationPopperPatch.cs @@ -23,8 +23,6 @@ internal static class NotificationPopperPatch public static void AddSettingsChangeMessage(OptionItem option) { - if (GameSettingMenuPatch.ChangingPreset) return; - string optValue = option.GetString(); if (optValue == "STRMISS") return; diff --git a/Patches/PlayerControlPatch.cs b/Patches/PlayerControlPatch.cs index b5a54e2dc..7abe5213e 100644 --- a/Patches/PlayerControlPatch.cs +++ b/Patches/PlayerControlPatch.cs @@ -1248,7 +1248,7 @@ internal static class ReportDeadBodyPatch x.IsBlackOut = false; x.Player.MarkDirtySettings(); }); - }, 15f, "RemoveBlackout"); + }, 5f, "RemoveBlackout"); if (Main.GameTimer.IsRunning && !Options.GameTimeLimitRunsDuringMeetings.GetBool()) Main.GameTimer.Stop(); @@ -1695,7 +1695,7 @@ internal static class FixedUpdatePatch AmongUsClient.Instance.ChangeGamePublic(false); // Kick low-level people - if (!lowLoad && isLobby && GameSettingMenuPatch.LastPresetChange + 5 < TimeStamp && !player.AmOwner && Options.KickLowLevelPlayer.GetInt() != 0 && ( + if (!lowLoad && isLobby && !player.AmOwner && Options.KickLowLevelPlayer.GetInt() != 0 && ( player.Data.PlayerLevel != 0 && player.Data.PlayerLevel < Options.KickLowLevelPlayer.GetInt() || player.Data.FriendCode == string.Empty )) diff --git a/Patches/PlayerJoinAndLeftPatch.cs b/Patches/PlayerJoinAndLeftPatch.cs index 70173ee38..eb8edf6a9 100644 --- a/Patches/PlayerJoinAndLeftPatch.cs +++ b/Patches/PlayerJoinAndLeftPatch.cs @@ -233,7 +233,7 @@ internal static class OnGameJoinedPatch float timer; if (nextGM != CustomGameMode.All) timer = 0f; else if (Options.AutoGMPollCommandAfterJoin.GetBool()) timer = Options.AutoGMPollCommandCooldown.GetInt() - 10; - else if (Main.AutoStart.Value) timer = Options.MinWaitAutoStart.GetFloat() * 60 - 65; + else if (Main.AutoStart.Value) timer = Options.MinWaitAutoStart.GetFloat() * 60 - 70; else timer = 30f; Logger.Info($"Auto GM Rotation timer: {timer}", "Auto GM Rotation"); diff --git a/Resources/Lang/en_US.json b/Resources/Lang/en_US.json index 5361e5841..43a6b6845 100644 --- a/Resources/Lang/en_US.json +++ b/Resources/Lang/en_US.json @@ -1935,6 +1935,7 @@ "FrightenerInfo": "Prevent Players From Reporting", "FrightenerInfoLong": "(Impostors):\\nAs the Frightener, you can shapeshift into a player to alarm them for some time. Alarmed players can't report bodies (or even call meetings), else they die.", "Frightener.KillOnEmergencyMeetingCall": "Alarmed Players Die When Calling an Emergency Meeting", + "Frightener.Suffix": "Alarmed players: {0}", "Gambler": "Gambler", "GamblerInfo": "Each Kill gets you an Effect", "GamblerInfoLong": "(Impostors):\\nAs the Gambler, a random event happens after each kill you get. These effects can be anywhere between a self-report and an extra sniper shot.", @@ -2168,6 +2169,7 @@ "PenguinTimerText": "Drag Timer", "PenguinVictimCanUseAbilities": "Victim Can Use Their Abilities While Being Dragged", "PenguinVictimKill": "As the victim of the Penguin/Goose, you cannot interact with others", + "PenguinCanVentWhileDragging": "Can Vent While Dragging", "Perplexer": "Perplexer", "PerplexerInfo": "Invert a player's movement controls", "PerplexerInfoLong": "(Impostors):\\nAs the Perplexer, use your shapeshift menu to select a player. That player will get their movement controls inverted for a certain amount of time.", @@ -2303,7 +2305,7 @@ "TransposerInfoLong": "(Impostors):\\nAs the Transposer, you can select 2 players using your shapeshift menu to forcefully shapeshift them into each other for some time.", "Trapster": "Trapster", "TrapsterInfo": "Start a killing chain", - "TrapsterInfoLong": "(Impostors):\\nAs the Trapster, you can vanish/pet to create a fake dead body. Anyone who reports this body will die, and depending on settings, the body will be reported.\\n\\n(Legacy Version):\\nIn the game, the Trapster kills a player and then puts a trap on their body. If another player reports the dead body and it has the Trapster's trap on it, the player who reports it will die instantly without the body getting reported. The player killed by the Trapster's trap will also become a Trapster. This chain reaction continues until no more players are left to become Trapsters. However, the Trapster will die immediately after making a kill. It's worth noting that the Trapster's own dead body cannot trigger their trap.", + "TrapsterInfoLong": "(Impostors):\\nAs the Trapster, you can vanish/pet to create a fake dead body. Anyone who reports this body will die, and depending on settings, the body will be reported. After you die, your fake bodies won't cause deaths anymore.\\n\\n(Legacy Version):\\nIn the game, the Trapster kills a player and then puts a trap on their body. If another player reports the dead body and it has the Trapster's trap on it, the player who reports it will die instantly without the body getting reported. The player killed by the Trapster's trap will also become a Trapster. This chain reaction continues until no more players are left to become Trapsters. However, the Trapster will die immediately after making a kill. It's worth noting that the Trapster's own dead body cannot trigger their trap.", "Trickster": "Trickster", "TricksterInfo": "Kill and trick the crew", "TricksterInfoLong": "(Impostors):\\nAs the Trickster, you function as a regular Impostor but with one key difference. You appear crewmate to crewmate roles.\\n\\nThe Sheriff cannot kill you.\\nPsychic does not see you as evil.\\nSnitch cannot find you.", @@ -4257,6 +4259,7 @@ "NToCheckGameModeSettings": "Type /n to view the settings for this game mode", "Standard": "Standard", "ModeStandard": "Gamemode: Standard", + "StandardInfo": "Classic gameplay with custom roles", "BedWars": "BED WARS", "ModeBedWars": "Gamemode: Bed Wars", "ModeDescribe.BedWars": "In the Bed Wars gamemode, players are split into teams. Each team has a bed. If a team's bed is destroyed, all players in that team can no longer respawn. The goal is to destroy all other teams' beds (via Pet button) and be the last team alive.\\n\\nYou can buy items (blocks, weapons, tool, etc.) and team upgrades (heal pool, haste, trap, etc.) in shops from the resources (iron, gold, diamond, emerald) you can collect from the generators on the map. These are useful for protecting the bed with various layers to make it harder to break it, increase your attack damage, increase your defense, or give you or your team various abilities.\\n\\nIn the beginning, there's a grace period, where no attacks are allowed, and players can't leave their own base.\\n\\nEach player has an inventory with all of their items. Cycle through the slots using the Vanish button or by typing the number of the slot in the chat (ex. '5'). Use weapons through the kill button, other items via Pet. To start breaking someone's bed, Pet. Make sure to always have the correct item selected in your inventory (blocks when you protect the bed, tools when you break beds, etc.).\\nYou can break beds with anything, but using the correct tool for each layer will make the process significantly faster.\\n\\nIf you die, you will respawn after a few seconds, unless your bed is broken. If your bed is broken, you will not respawn anymore.", @@ -4486,8 +4489,12 @@ "HideAndSeek": "HIDE AND SEEK", "ModeHideAndSeek": "Gamemode: Hide And Seek", "ModeShiftAndSeek": "Gamemode: Shift And Seek", + "HideAndSeekInfo": "Custom HNS gameplay with unique roles", "ModeDescribe.HideAndSeek": "In the Hide And Seek gamemode, seekers have to kill all hiders, while hiders have to complete all tasks without being killed in order to win.\\nIf the time limit reaches 0, hiders win.\\nIf everyone apart from the Seekers die, the Seekers win.\\n\\nRoles: Hider, Seeker, Fox, Troll, Jumper, Detector, Jet, Dasher, Locator, Venter, Agent, Taskinator", "GameModeTutorial.HideAndSeek": "The current game mode is <#345eeb>Hide And Seek (Modded).\\nSeekers must kill all hiders to win,\\nhiders must complete tasks to lower the timer.\\nIf the time limit ends, hiders win.", + "HNS.CrewmateRoles": "HIDER ROLES", + "HNS.ImpostorRoles": "SEEKER ROLES", + "HNS.NeutralRoles": "NEUTRAL ROLES", "HNS.DangerMeter": "Show (Custom) Danger Meter", "HNS.MaxNeutrals": "<#0000ff>Maximum Number of <#ffab1b>Neutrals", "HNS.MinNeutrals": "<#00ffff>Minimum Number of <#ffab1b>Neutrals", @@ -8698,6 +8705,8 @@ "Achievement.YoureMyFriendNow.Description": "Recruit anyone as Gangster/Jackal/Infection/Virus/Cultist", "Achievement.YoureTooLate": "You're Too Late", "Achievement.YoureTooLate.Description": "As Pestilence, have a killer try to kill you, but unsuccessfully for them", + "BasicSettings": "Basic Settings", + "GameModeSettings": "Game Mode Settings", "TabGroup.VanillaSettings": "Vanilla Settings", "TabGroup.SystemSettings": "System Settings", "ModLanguage": "Mod Language", @@ -8844,8 +8853,7 @@ "GameMode": "Game Mode", "AGMR.Slot.RandomGroupId": "Number/ID of the random group to use for choosing the game mode for this slot/game", "AGMR.Slot.Count": "How many times should we repeat this?", - "MenuTitle.AGMR.RandomGroup": "Random Group {index}", - "AGMR.RandomGroup.GMChance": "Chance of selecting {gm}", + "AGMR.RandomGroup.GMChance": "[Random Group {index}] Chance of selecting {gm}", "TabGroup.GameSettings": "Mod Settings", "MenuTitle.Ejections": "★ Ejection ★", "ConfirmEjectionsMode": "Confirm Ejections Mode", @@ -9053,6 +9061,8 @@ "ShowTaskCountWhenAlive": "Show Task Count When Alive", "ShowTaskCountWhenDead": "Show Task Count When Dead", "IntegrateNaturalDisasters": "Integrate the Natural Disasters game mode into the current game mode", + "NDIntegrationShort": "Integrate\\nNatural\\nDisasters", + "MenuDescription.GameModes": "Choose which game mode you want to play.", "EnableGameTimeLimit": "Enable Game Time Limit (Expired = No One Wins)", "GameTimeLimit": "Game Time Limit", "GameTimerEnded": "Game Time Limit Ended", @@ -10227,7 +10237,6 @@ "PromotedSKCanRecruit": "New Jackal can recruit new Sidekick", "DownloadingPreset": "Downloading preset....", "PresetApplied": "Preset applied successfully!", - "Promt.ApplyPreset": "<#ffff00>⚠ WARNING ⚠\\nApplying this preset OVERRIDES your current preset! Back it up if you need it or switch to an unused preset slot. It will be permanently deleted!\\nDo you wish to proceed?", "Promt.EnableAllRoles": "Enable all roles and add-ons?\\n\\nYes - Enable all roles and add-ons\\nNo - Enter the quick setup dialog of roles and add-ons", "Promt.EnableRole": "({0}/{1}) {2}\\nEnable {3}?\\n\\n{4}", "Promt.ResetAllOptions": "Are you sure you want to reset all options? This action is irreversible and may take few minutes.", @@ -10294,6 +10303,14 @@ "ShortTeamName.Crewmate": "Crew", "ShortTeamName.Impostor": "Imp", "ShortTeamName.Neutral": "Neut", + "ShortTabName.ImpostorRoles": "IMPOSTORS", + "ShortTabName.CrewmateRoles": "CREWMATES", + "ShortTabName.NeutralRoles": "NEUTRALS", + "ShortTabName.CovenRoles": "COVEN", + "ShortTabName.Addons": "ADD-ONS", + "ShortTabName.OtherRoles": "GHOSTS", + "ShortTabName.HNSRoles": "HNS ROLES", + "BackToList": "BACK TO LIST", "ShowArrows": "Has Arrows pointing toward bodies", "ShowResults": "Show Results", "ShowSpecificRole": "Know specific roles on Task Completion", @@ -10710,6 +10727,7 @@ "Untouched": "Global Setting Decides", "UploadPreset": "Upload current preset to database", "UploadPresetHeader": "Upload & Publish", + "LocalPresets": "Local Presets", "UseLegacyVersion": "Use Legacy Version", "UsesPetInsteadOfKillNotice": "<#ffff00>⚠ As this role, you need to use your pet button as your kill button!", "VengefulHasImpVision": "Vengeful Romantic Has <#ff1919>Impostor Vision", diff --git a/Roles/HideAndSeek/Hider.cs b/Roles/HideAndSeek/Hider.cs index 2cf15dc7c..7df759eb9 100644 --- a/Roles/HideAndSeek/Hider.cs +++ b/Roles/HideAndSeek/Hider.cs @@ -6,7 +6,7 @@ internal class Hider : RoleBase, IHideAndSeekRole { private static bool On; - public const int StartId = 69_211_199; + public const int StartId = 69_211_101; private static OptionItem Vision; private static OptionItem Speed; @@ -25,41 +25,38 @@ internal class Hider : RoleBase, IHideAndSeekRole public override void SetupCustomOption() { - new TextOptionItem(StartId, "Hider", TabGroup.CrewmateRoles) - .SetGameMode(CustomGameMode.HideAndSeek) - .SetHeader(true); - - Vision = new FloatOptionItem(69_211_101, "HiderVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.CrewmateRoles) + Vision = new FloatOptionItem(StartId, "HiderVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.GameSettings) + .SetHeader(true) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(52, 94, 235, byte.MaxValue)); - Speed = new FloatOptionItem(69_211_102, "HiderSpeed", new(0.05f, 5f, 0.05f), 1.4f, TabGroup.CrewmateRoles) + Speed = new FloatOptionItem(StartId + 1, "HiderSpeed", new(0.05f, 5f, 0.05f), 1.4f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(52, 94, 235, byte.MaxValue)); - TimeDecreaseOnShortTaskComplete = new IntegerOptionItem(69_211_103, "TimeDecreaseOnShortTaskComplete", new(0, 60, 1), 5, TabGroup.CrewmateRoles) + TimeDecreaseOnShortTaskComplete = new IntegerOptionItem(StartId + 2, "TimeDecreaseOnShortTaskComplete", new(0, 60, 1), 5, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(52, 94, 235, byte.MaxValue)); - TimeDecreaseOnCommonTaskComplete = new IntegerOptionItem(69_211_104, "TimeDecreaseOnCommonTaskComplete", new(0, 60, 1), 10, TabGroup.CrewmateRoles) + TimeDecreaseOnCommonTaskComplete = new IntegerOptionItem(StartId + 3, "TimeDecreaseOnCommonTaskComplete", new(0, 60, 1), 10, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(52, 94, 235, byte.MaxValue)); - TimeDecreaseOnLongTaskComplete = new IntegerOptionItem(69_211_105, "TimeDecreaseOnLongTaskComplete", new(0, 60, 1), 15, TabGroup.CrewmateRoles) + TimeDecreaseOnLongTaskComplete = new IntegerOptionItem(StartId + 4, "TimeDecreaseOnLongTaskComplete", new(0, 60, 1), 15, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(52, 94, 235, byte.MaxValue)); - TimeDecreaseOnSituationalTaskComplete = new IntegerOptionItem(69_211_106, "TimeDecreaseOnSituationalTaskComplete", new(0, 60, 1), 20, TabGroup.CrewmateRoles) + TimeDecreaseOnSituationalTaskComplete = new IntegerOptionItem(StartId + 5, "TimeDecreaseOnSituationalTaskComplete", new(0, 60, 1), 20, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(52, 94, 235, byte.MaxValue)); - TimeDecreaseOnOtherTaskComplete = new IntegerOptionItem(69_211_107, "TimeDecreaseOnOtherTaskComplete", new(0, 60, 1), 5, TabGroup.CrewmateRoles) + TimeDecreaseOnOtherTaskComplete = new IntegerOptionItem(StartId + 6, "TimeDecreaseOnOtherTaskComplete", new(0, 60, 1), 5, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(52, 94, 235, byte.MaxValue)); diff --git a/Roles/HideAndSeek/Seeker.cs b/Roles/HideAndSeek/Seeker.cs index d58a979f0..1377ae6a8 100644 --- a/Roles/HideAndSeek/Seeker.cs +++ b/Roles/HideAndSeek/Seeker.cs @@ -6,7 +6,7 @@ internal class Seeker : RoleBase, IHideAndSeekRole { public static bool On; - public const int StartId = 69_211_299; + public const int StartId = 69_211_201; public static OptionItem Vision; public static OptionItem Speed; @@ -23,30 +23,27 @@ internal class Seeker : RoleBase, IHideAndSeekRole public override void SetupCustomOption() { - new TextOptionItem(StartId, "Seeker", TabGroup.ImpostorRoles) - .SetGameMode(CustomGameMode.HideAndSeek) - .SetHeader(true); - - Vision = new FloatOptionItem(69_211_201, "SeekerVision", new(0.05f, 5f, 0.05f), 0.25f, TabGroup.ImpostorRoles) + Vision = new FloatOptionItem(StartId, "SeekerVision", new(0.05f, 5f, 0.05f), 0.25f, TabGroup.GameSettings) + .SetHeader(true) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(255, 25, 25, byte.MaxValue)); - Speed = new FloatOptionItem(69_211_202, "SeekerSpeed", new(0.05f, 5f, 0.05f), 1.5f, TabGroup.ImpostorRoles) + Speed = new FloatOptionItem(StartId + 1, "SeekerSpeed", new(0.05f, 5f, 0.05f), 1.5f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(255, 25, 25, byte.MaxValue)); - CanVent = new BooleanOptionItem(69_211_204, "CanVent", false, TabGroup.ImpostorRoles) + CanVent = new BooleanOptionItem(StartId + 3, "CanVent", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(new(255, 25, 25, byte.MaxValue)); - BlindTime = new FloatOptionItem(69_211_206, "BlindTime", new(0f, 60f, 1f), 10f, TabGroup.ImpostorRoles) + BlindTime = new FloatOptionItem(StartId + 5, "BlindTime", new(0f, 60f, 1f), 10f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(255, 25, 25, byte.MaxValue)); - KillCooldown = new IntegerOptionItem(69_211_207, "KillCooldown", new(0, 60, 1), 10, TabGroup.ImpostorRoles) + KillCooldown = new IntegerOptionItem(StartId + 6, "KillCooldown", new(0, 60, 1), 10, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(255, 25, 25, byte.MaxValue)); diff --git a/Roles/Standard/Coven/Poache.cs b/Roles/Standard/Coven/Poache.cs index 7c248d112..2c9ce700f 100644 --- a/Roles/Standard/Coven/Poache.cs +++ b/Roles/Standard/Coven/Poache.cs @@ -91,7 +91,7 @@ public class Poache : CovenBase public override void OnReportDeadBody() { - KillDelays.ForEach(x => x.GetPlayer()?.Suicide(PlayerState.DeathReason.Poison, realKiller: PoacheId.GetPlayer())); + KillDelays?.ForEach(x => x.GetPlayer()?.Suicide(PlayerState.DeathReason.Poison, realKiller: PoacheId.GetPlayer())); KillDelays = null; } diff --git a/Roles/Standard/Crewmate/Killing/Prosecutor.cs b/Roles/Standard/Crewmate/Killing/Prosecutor.cs index 17999b0c8..23e98c5c6 100644 --- a/Roles/Standard/Crewmate/Killing/Prosecutor.cs +++ b/Roles/Standard/Crewmate/Killing/Prosecutor.cs @@ -77,7 +77,7 @@ public class Prosecutor : RoleBase public static bool TrialMsg(PlayerControl pc, string msg, bool isUI = false) { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsInGame || !pc || !pc.Is(CustomRoles.Prosecutor)) return false; + if (!AmongUsClient.Instance.AmHost || !GameStates.IsInGame || !pc || !pc.Is(CustomRoles.Prosecutor) || Starspawn.IsDayBreak) return false; int operate; // 1:ID 2:Trial msg = msg.ToLower().TrimStart().TrimEnd(); diff --git a/Roles/Standard/Crewmate/Power/Adventurer.cs b/Roles/Standard/Crewmate/Power/Adventurer.cs index 4eff50f59..5aa234ef3 100644 --- a/Roles/Standard/Crewmate/Power/Adventurer.cs +++ b/Roles/Standard/Crewmate/Power/Adventurer.cs @@ -92,6 +92,18 @@ internal class Adventurer : RoleBase } } + private static void RelocateObject(Resource resource, Vector2 newPosition) + { + for (int objIndex = 0; objIndex < CustomNetObject.AllObjects.Count; objIndex++) + { + if (CustomNetObject.AllObjects[objIndex] is AdventurerItem item && item.Resource == resource) + { + item.TP(newPosition); + break; + } + } + } + private static OptionItem CreateWeaponEnabledSetting(int id, Weapon weapon) { return new BooleanOptionItem(id, $"AdventurerWeaponEnabled.{weapon}", true, TabGroup.CrewmateRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.Adventurer]); @@ -287,16 +299,18 @@ internal class Adventurer : RoleBase if (LastRandomResourceTimeStamp + 20 <= now && pc.PlayerId != AdventurerPC.PlayerId && IRandom.Instance.Next(500) == 0) { + Vector2 pos = pc.Pos(); + if (ResourceLocations.TryGetValue(Resource.Random, out Vector2 location)) { LocateArrow.Remove(AdventurerPC.PlayerId, location); - HideObject(Resource.Random); + RelocateObject(Resource.Random, pos); } + else + _ = new AdventurerItem(pos, Resource.Random, AdventurerPC); - Vector2 pos = pc.Pos(); LocateArrow.Add(AdventurerPC.PlayerId, pos); ResourceLocations[Resource.Random] = pos; - _ = new AdventurerItem(pos, Resource.Random, AdventurerPC); LastRandomResourceTimeStamp = now; Utils.NotifyRoles(SpecifySeer: AdventurerPC, SpecifyTarget: AdventurerPC); } @@ -323,12 +337,13 @@ internal class Adventurer : RoleBase if (ResourceLocations.TryGetValue(Resource.Grouping, out Vector2 location)) { LocateArrow.Remove(AdventurerPC.PlayerId, location); - HideObject(Resource.Grouping); + RelocateObject(Resource.Grouping, pcPos); } + else + _ = new AdventurerItem(pcPos, Resource.Grouping, AdventurerPC); LocateArrow.Add(AdventurerPC.PlayerId, pcPos); ResourceLocations[Resource.Grouping] = pcPos; - _ = new AdventurerItem(pcPos, Resource.Grouping, AdventurerPC); LastGroupingResourceTimeStamp = now; Utils.NotifyRoles(SpecifySeer: AdventurerPC, SpecifyTarget: AdventurerPC); } @@ -377,9 +392,11 @@ internal class Adventurer : RoleBase { if (!AmongUsClient.Instance.AmHost) return; Vector2 pos = shapeshifter.Pos(); + if (av.ResourceLocations.ContainsKey(Resource.ShapeshiftSkin)) + RelocateObject(Resource.ShapeshiftSkin, pos); + else + _ = new AdventurerItem(pos, Resource.ShapeshiftSkin, av.AdventurerPC); av.ResourceLocations[Resource.ShapeshiftSkin] = pos; - HideObject(Resource.ShapeshiftSkin); - _ = new AdventurerItem(pos, Resource.ShapeshiftSkin, av.AdventurerPC); } public static void OnAnyoneDead(PlayerControl target) @@ -389,9 +406,11 @@ internal class Adventurer : RoleBase if (state.Role is Adventurer { IsEnable: true } av) { Vector2 pos = target.Pos(); + if (av.ResourceLocations.ContainsKey(Resource.DeadBody)) + RelocateObject(Resource.DeadBody, pos); + else + _ = new AdventurerItem(pos, Resource.DeadBody, av.AdventurerPC); av.ResourceLocations[Resource.DeadBody] = pos; - HideObject(Resource.DeadBody); - _ = new AdventurerItem(pos, Resource.DeadBody, av.AdventurerPC); } } } diff --git a/Roles/Standard/Crewmate/Support/TimeMaster.cs b/Roles/Standard/Crewmate/Support/TimeMaster.cs index fdb587697..ac0d243c1 100644 --- a/Roles/Standard/Crewmate/Support/TimeMaster.cs +++ b/Roles/Standard/Crewmate/Support/TimeMaster.cs @@ -131,8 +131,6 @@ internal class TimeMaster : RoleBase private static IEnumerator Rewind() { - Dictionary originalSpeeds = Main.AllPlayerSpeed.ToDictionary(x => x.Key, x => x.Value); - try { Rewinding = true; @@ -142,7 +140,6 @@ internal class TimeMaster : RoleBase int length = TimeMasterRewindTimeLength.GetInt(); float duration = length * delay + 0.55f; - Main.AllPlayerSpeed.SetAllValues(Main.MinSpeed); ReportDeadBodyPatch.CanReport.SetAllValues(false); string notify = Utils.ColorString(Color.yellow, string.Format(Translator.GetString("TimeMasterRewindStart"), CustomRoles.TimeMaster.ToColoredString())); @@ -204,8 +201,6 @@ internal class TimeMaster : RoleBase finally { Rewinding = false; - Main.AllPlayerSpeed.AddRange(originalSpeeds); - Utils.MarkEveryoneDirtySettings(); ReportDeadBodyPatch.CanReport.SetAllValues(true); } } @@ -220,7 +215,6 @@ internal class TimeMaster : RoleBase if (Rewinding) { Rewinding = false; - Main.AllPlayerSpeed.SetAllValues(Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod)); ReportDeadBodyPatch.CanReport.SetAllValues(true); } } diff --git a/Roles/Standard/Impostor/Concealing/Penguin.cs b/Roles/Standard/Impostor/Concealing/Penguin.cs index 0a1157d4f..b8256727a 100644 --- a/Roles/Standard/Impostor/Concealing/Penguin.cs +++ b/Roles/Standard/Impostor/Concealing/Penguin.cs @@ -16,6 +16,7 @@ public class Penguin : RoleBase private static OptionItem OptionMeetingKill; private static OptionItem OptionSpeedDuringDrag; private static OptionItem OptionVictimCanUseAbilities; + private static OptionItem OptionCanVentWhileDragging; private Stopwatch AbductTimer; private float AbductTimerLimit; @@ -33,6 +34,7 @@ public class Penguin : RoleBase private float SpeedDuringDrag; private bool VictimCanUseAbilities; + private bool CanVentWhileDragging; public override bool IsEnable => PenguinId != byte.MaxValue; @@ -65,6 +67,9 @@ public class Penguin : RoleBase OptionVictimCanUseAbilities = new BooleanOptionItem(Id + 14, "PenguinVictimCanUseAbilities", false, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Penguin]); + + OptionCanVentWhileDragging = new BooleanOptionItem(Id + 15, "PenguinCanVentWhileDragging", false, TabGroup.ImpostorRoles) + .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Penguin]); } public override void Init() @@ -83,6 +88,7 @@ public class Penguin : RoleBase MeetingKill = OptionMeetingKill.GetBool(); SpeedDuringDrag = OptionSpeedDuringDrag.GetFloat(); VictimCanUseAbilities = OptionVictimCanUseAbilities.GetBool(); + CanVentWhileDragging = OptionCanVentWhileDragging.GetBool(); Cooldown = Options.AdjustedDefaultKillCooldown; } else @@ -91,6 +97,7 @@ public class Penguin : RoleBase MeetingKill = false; SpeedDuringDrag = Goose.OptionSpeedDuringDrag.GetFloat(); VictimCanUseAbilities = Goose.OptionVictimCanUseAbilities.GetBool(); + CanVentWhileDragging = false; Cooldown = Goose.Cooldown.GetFloat(); } @@ -109,7 +116,7 @@ public class Penguin : RoleBase public override bool CanUseImpostorVentButton(PlayerControl pc) { - return !AbductVictim && !IsGoose; + return !IsGoose && (CanVentWhileDragging || AbductTimer == null); } public override bool CanUseKillButton(PlayerControl pc) diff --git a/Roles/Standard/Impostor/Killing/Trapster.cs b/Roles/Standard/Impostor/Killing/Trapster.cs index 56b431e5d..e31fa9eda 100644 --- a/Roles/Standard/Impostor/Killing/Trapster.cs +++ b/Roles/Standard/Impostor/Killing/Trapster.cs @@ -7,7 +7,7 @@ namespace EHR.Roles; internal class Trapster : RoleBase { - private static List TrapsterBody = []; + public static List TrapsterBody = []; private static Dictionary KillerOfTrapsterBody = []; public static bool On; @@ -138,8 +138,7 @@ internal class Trapster : RoleBase { Vector2 location = player.Pos(); TrapsterBody.Add(player.PlayerId); - PlayerControl randomPlayer = Main.EnumerateAlivePlayerControls().Without(player).RandomElement(); - Utils.RpcCreateDeadBody(location, (byte)randomPlayer.CurrentOutfit.ColorId, randomPlayer); + Utils.RpcCreateDeadBody(location, (byte)IRandom.Instance.Next(0, 18), player); return false; } diff --git a/Roles/Standard/Impostor/Killing/Wiper.cs b/Roles/Standard/Impostor/Killing/Wiper.cs index e6998ab17..7c73f2fb2 100644 --- a/Roles/Standard/Impostor/Killing/Wiper.cs +++ b/Roles/Standard/Impostor/Killing/Wiper.cs @@ -129,7 +129,7 @@ public class Wiper : RoleBase PlainShipRoom room = pc.GetPlainShipRoom(); if (IsInvalidRoom(room)) return; - Main.EnumerateAlivePlayerControls().Without(pc).DoIf(x => x.IsInRoom(room) && pc.RpcCheckAndMurder(x, true), x => x.Suicide(PlayerState.DeathReason.WipedOut, pc)); + Main.EnumerateAlivePlayerControls().Without(pc).DoIf(x => (!x.IsImpostor() || KillOtherImpostors.GetBool()) && x.IsInRoom(room) && pc.RpcCheckAndMurder(x, true), x => x.Suicide(PlayerState.DeathReason.WipedOut, pc)); } public override void OnFixedUpdate(PlayerControl pc) diff --git a/Roles/Standard/Impostor/Miscellaneous/Frightener.cs b/Roles/Standard/Impostor/Miscellaneous/Frightener.cs index 16a1ae56c..18555328d 100644 --- a/Roles/Standard/Impostor/Miscellaneous/Frightener.cs +++ b/Roles/Standard/Impostor/Miscellaneous/Frightener.cs @@ -52,8 +52,12 @@ public class Frightener : RoleBase public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (shapeshifting && AlarmedPlayers.Add(target.PlayerId)) + if (!shapeshifting) return true; + + if (shapeshifter.GetAbilityUseLimit() >= 1f && AlarmedPlayers.Add(target.PlayerId)) { + shapeshifter.RpcRemoveAbilityUse(notify: false); + LateTask.New(() => { AlarmedPlayers.Remove(target.PlayerId); diff --git a/Roles/Standard/Impostor/Miscellaneous/Gambler.cs b/Roles/Standard/Impostor/Miscellaneous/Gambler.cs index 5aa20558f..7d40f1679 100644 --- a/Roles/Standard/Impostor/Miscellaneous/Gambler.cs +++ b/Roles/Standard/Impostor/Miscellaneous/Gambler.cs @@ -37,8 +37,6 @@ public class Gambler : RoleBase private static readonly HashSet IsShielded = []; private static HashSet IsVisionChange = []; - private byte EffectID = byte.MaxValue; - public override bool IsEnable => PlayerIdList.Count > 0; public override void SetupCustomOption() @@ -116,7 +114,6 @@ public class Gambler : RoleBase public override void Init() { PlayerIdList = []; - EffectID = byte.MaxValue; WaitingDelayedKills = []; IsVisionChange = []; } @@ -124,7 +121,6 @@ public class Gambler : RoleBase public override void Add(byte playerId) { PlayerIdList.Add(playerId); - EffectID = byte.MaxValue; } public override void Remove(byte playerId) @@ -148,22 +144,21 @@ public class Gambler : RoleBase public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (EffectID != byte.MaxValue) return true; - var rd = IRandom.Instance; + byte effectID; if (rd.Next(1, 101) <= PositiveEffectChance.GetInt()) { - EffectID = (byte)rd.Next(1, 8); + effectID = (byte)rd.Next(1, 8); - switch (EffectID) + switch (effectID) { case 1: // Delayed kill killer.Notify(string.Format(GetString("GamblerGet.DelayedKill"), KillDelay.GetInt())); WaitingDelayedKills.TryAdd(target.PlayerId, new CountdownTimer(KillDelay.GetInt(), () => { WaitingDelayedKills.Remove(target.PlayerId); - if (target == null || !target.IsAlive()) return; + if (!target || !target.IsAlive()) return; target.Suicide(PlayerState.DeathReason.Poison, killer); })); return false; @@ -218,13 +213,13 @@ public class Gambler : RoleBase killer.Notify(string.Format(GetString("GamblerGet.Speedup"), speedDur, Speed.GetFloat())); _ = new CountdownTimer(speedDur, () => { - if (killer == null) return; + if (!killer) return; Main.AllPlayerSpeed[killer.PlayerId] = Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod); if (!killer.IsAlive()) return; killer.MarkDirtySettings(); }, onCanceled: () => { - if (killer == null) return; + if (!killer) return; Main.AllPlayerSpeed[killer.PlayerId] = Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod); }); Main.AllPlayerSpeed[killer.PlayerId] = Speed.GetFloat(); @@ -237,9 +232,9 @@ public class Gambler : RoleBase } else { - EffectID = (byte)rd.Next(1, 5); + effectID = (byte)rd.Next(1, 5); - switch (EffectID) + switch (effectID) { case 1: // BSR float delay = Math.Max(0.15f, BsrDelay.GetFloat()); @@ -256,13 +251,13 @@ public class Gambler : RoleBase killer.Notify(string.Format(GetString("GamblerGet.Freeze"), freezeDur)); _ = new CountdownTimer(freezeDur, () => { - if (killer == null) return; + if (!killer) return; Main.AllPlayerSpeed[killer.PlayerId] = Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod); if (!killer.IsAlive()) return; killer.MarkDirtySettings(); }, onCanceled: () => { - if (killer == null) return; + if (!killer) return; Main.AllPlayerSpeed[killer.PlayerId] = Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod); }); Main.AllPlayerSpeed[killer.PlayerId] = Main.MinSpeed; @@ -273,13 +268,13 @@ public class Gambler : RoleBase IsVisionChange.Add(killer.PlayerId); _ = new CountdownTimer(LowVisionDur.GetInt(), () => { - if (killer == null) return; + if (!killer) return; IsVisionChange.Remove(killer.PlayerId); if (!killer.IsAlive()) return; killer.MarkDirtySettings(); }, onCanceled: () => { - if (killer == null) return; + if (!killer) return; IsVisionChange.Remove(killer.PlayerId); }); killer.MarkDirtySettings(); @@ -294,8 +289,6 @@ public class Gambler : RoleBase } } - EffectID = byte.MaxValue; - return true; } @@ -306,8 +299,6 @@ public class Gambler : RoleBase public override void OnReportDeadBody() { - EffectID = byte.MaxValue; - foreach ((byte playerId, CountdownTimer timer) in WaitingDelayedKills) { timer.Dispose(); diff --git a/Roles/Standard/Neutral/Killing/Amogus.cs b/Roles/Standard/Neutral/Killing/Amogus.cs index 753ce7540..f995132b8 100644 --- a/Roles/Standard/Neutral/Killing/Amogus.cs +++ b/Roles/Standard/Neutral/Killing/Amogus.cs @@ -78,7 +78,7 @@ public class Amogus : RoleBase public override bool CanUseKillButton(PlayerControl pc) { - return AmogusFormTimer == null; + return AmogusFormTimer != null; } public override void ApplyGameOptions(IGameOptions opt, byte id) @@ -107,7 +107,7 @@ public class Amogus : RoleBase AmogusFormTimer = new CountdownTimer(AbilityDuration.GetInt(), () => { - if (pc == null || !pc.IsAlive()) return; + if (!pc || !pc.IsAlive()) return; FormExpired(); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); }, onCanceled: () => AmogusFormTimer = null); diff --git a/Roles/Standard/Neutral/Killing/Bargainer.cs b/Roles/Standard/Neutral/Killing/Bargainer.cs index 35a6d670c..7f88d3bc3 100644 --- a/Roles/Standard/Neutral/Killing/Bargainer.cs +++ b/Roles/Standard/Neutral/Killing/Bargainer.cs @@ -280,6 +280,7 @@ internal class Bargainer : RoleBase List list = OrderedItems.ToList(); SelectedItem = list[(list.IndexOf(SelectedItem) + 1) % list.Count]; Utils.SendRPC(CustomRPC.SyncBargainer, pc.PlayerId, 2, (int)SelectedItem); + Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); } public override void OnPet(PlayerControl pc) @@ -344,18 +345,20 @@ internal class Bargainer : RoleBase Money -= cost; Update(); - pc.Notify(string.Format(Translator.GetString("Bargainer.Notify.PurchasedItem"), Translator.GetString($"Bargainer.{SelectedItem}"))); - switch (SelectedItem) { case Item.EnergyDrink: pc.ResetKillCooldown(); pc.SyncSettings(); if (Main.KillTimers[pc.PlayerId] > ReducedKillCooldown.GetFloat()) pc.SetKillCooldown(ReducedKillCooldown.GetFloat()); - - break; + goto default; case Item.LensOfTruth: Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: Utils.GetPlayerById(target)); + goto default; + case Item.None: + break; + default: + pc.Notify(string.Format(Translator.GetString("Bargainer.Notify.PurchasedItem"), Translator.GetString($"Bargainer.{SelectedItem}"))); break; } diff --git a/Roles/Standard/Neutral/Killing/SoulCollector.cs b/Roles/Standard/Neutral/Killing/SoulCollector.cs index d6d820bfe..0f4eb6067 100644 --- a/Roles/Standard/Neutral/Killing/SoulCollector.cs +++ b/Roles/Standard/Neutral/Killing/SoulCollector.cs @@ -100,6 +100,7 @@ public class SoulCollector : RoleBase { Main.AllPlayerSpeed[x.PlayerId] = Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod); x.RpcSetRoleGlobal(x.GetGhostRoleBasis()); + Utils.AfterPlayerDeathTasks(x, onMeeting: true); }); ToExile = []; } diff --git a/Roles/Standard/Neutral/Pariah/Auditor.cs b/Roles/Standard/Neutral/Pariah/Auditor.cs index a2b4b4d43..586017760 100644 --- a/Roles/Standard/Neutral/Pariah/Auditor.cs +++ b/Roles/Standard/Neutral/Pariah/Auditor.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using AmongUs.GameOptions; using EHR.Modules; using Hazel; @@ -79,6 +80,11 @@ public class Auditor : RoleBase opt.SetFloat(FloatOptionNames.ImpostorLightMod, vision); } + public override void SetKillCooldown(byte id) + { + Main.AllPlayerKillCooldown[id] = Math.Min(AuditCooldown.GetFloat(), SmokebombCooldown.GetFloat()); + } + public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { switch (Mode) @@ -100,13 +106,15 @@ public class Auditor : RoleBase if (LoweredVisionPlayers.Add(target.PlayerId)) target.MarkDirtySettings(); LateTask.New(() => { - if (target == null || !LoweredVisionPlayers.Remove(target.PlayerId) || !GameStates.IsInTask || ExileController.Instance || AntiBlackout.SkipTasks) return; + if (!target || !LoweredVisionPlayers.Remove(target.PlayerId) || !GameStates.IsInTask || ExileController.Instance || AntiBlackout.SkipTasks) return; target.MarkDirtySettings(); }, LoweredVisionDuration.GetInt()); killer.SetKillCooldown(SmokebombCooldown.GetFloat()); break; } } + + killer.RpcRemoveAbilityUse(); if (RevealedPlayers.Add(target.PlayerId)) { diff --git a/packaging/epic/BepInEx/config/at.duikbo.regioninstall.cfg b/packaging/epic/BepInEx/config/at.duikbo.regioninstall.cfg index c3a670533..772279d55 100644 --- a/packaging/epic/BepInEx/config/at.duikbo.regioninstall.cfg +++ b/packaging/epic/BepInEx/config/at.duikbo.regioninstall.cfg @@ -6,10 +6,10 @@ ## Create an array of regions you want to add/update. To create this array, go to https://impostor.github.io/Impostor/ and put the Regions array from the server file in here # Setting type: String # Default value: {\"CurrentRegionIdx\":0,\"Regions\":[]} -Regions = { \"CurrentRegionIdx\": 0, \"Regions\": [ { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded EU (MEU)\", \"PingServer\": \"https://au-eu.duikbo.at\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://au-eu.duikbo.at\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded NA (MNA)\", \"PingServer\": \"https://aumods.org\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://aumods.org\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded Asia (MAS)\", \"PingServer\": \"https://au-as.duikbo.at\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://au-as.duikbo.at\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"GG-HU\", \"PingServer\": \"https://play-hu.gurge44.eu\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://play-hu.gurge44.eu\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"GG-US\", \"PingServer\": \"https://play-us.gurge44.eu\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://play-us.gurge44.eu\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Niko-NA\", \"PingServer\": \"https://au-us.niko233.top\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://au-us.niko233.top\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Niko-AS\", \"PingServer\": \"https://au-as.niko233.top\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://au-as.niko233.top\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"AOU-EU\", \"PingServer\": \"https://eu.allofus.dev\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://eu.allofus.dev\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 } ] } +Regions = { \"CurrentRegionIdx\": 0, \"Regions\": [ { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded EU (MEU)\", \"PingServer\": \"https://au-eu.duikbo.at\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://au-eu.duikbo.at\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded NA (MNA)\", \"PingServer\": \"https://aumods.org\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://aumods.org\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded Asia (MAS)\", \"PingServer\": \"https://au-as.duikbo.at\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://au-as.duikbo.at\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"GG-HU\", \"PingServer\": \"https://play-hu.gurge44.eu\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://play-hu.gurge44.eu\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"GG-US\", \"PingServer\": \"https://play-us.gurge44.eu\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://play-us.gurge44.eu\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"AOU-EU\", \"PingServer\": \"https://eu.allofus.dev\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://eu.allofus.dev\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 } ] } ## Comma-seperated list of region names that should be removed. # Setting type: String # Default value: -RemoveRegions = Niko233(NA_US),Niko233(NA_US2),Niko233(AS_CN),Niko233(AS_CN2),NikoCat233(US),NikoCat233(CN),Niko233(AS3),Niko233(NA2),Niko233(EU2),Niko233(AS2),Custom,Niko233(NA),Niko233(EU),Niko233(AS),Niko233(CN),Modded SA (MSA),Niko-CN,Niko-EU +RemoveRegions = Niko233(NA_US),Niko233(NA_US2),Niko233(AS_CN),Niko233(AS_CN2),NikoCat233(US),NikoCat233(CN),Niko233(AS3),Niko233(NA2),Niko233(EU2),Niko233(AS2),Custom,Niko233(NA),Niko233(EU),Niko233(AS),Niko233(CN),Modded SA (MSA),Niko-CN,Niko-EU,Niko-NA,Niko-AS,Niko_CN,Niko_EU,Niko_NA,Niko_AS diff --git a/packaging/epic/BepInEx/patchers/Il2CppInteropGcFix.dll b/packaging/epic/BepInEx/patchers/Il2CppInteropGcFix.dll new file mode 100644 index 000000000..ae0d3b12d Binary files /dev/null and b/packaging/epic/BepInEx/patchers/Il2CppInteropGcFix.dll differ diff --git a/packaging/il2cppinterop/Il2CppInterop.Common.dll b/packaging/il2cppinterop/Il2CppInterop.Common.dll deleted file mode 100644 index 805ce2c10..000000000 Binary files a/packaging/il2cppinterop/Il2CppInterop.Common.dll and /dev/null differ diff --git a/packaging/il2cppinterop/Il2CppInterop.Common.xml b/packaging/il2cppinterop/Il2CppInterop.Common.xml deleted file mode 100644 index 814103eef..000000000 --- a/packaging/il2cppinterop/Il2CppInterop.Common.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - Il2CppInterop.Common - - - - diff --git a/packaging/il2cppinterop/Il2CppInterop.Generator.dll b/packaging/il2cppinterop/Il2CppInterop.Generator.dll deleted file mode 100644 index 99bd3af85..000000000 Binary files a/packaging/il2cppinterop/Il2CppInterop.Generator.dll and /dev/null differ diff --git a/packaging/il2cppinterop/Il2CppInterop.HarmonySupport.dll b/packaging/il2cppinterop/Il2CppInterop.HarmonySupport.dll deleted file mode 100644 index 165e489e7..000000000 Binary files a/packaging/il2cppinterop/Il2CppInterop.HarmonySupport.dll and /dev/null differ diff --git a/packaging/il2cppinterop/Il2CppInterop.HarmonySupport.xml b/packaging/il2cppinterop/Il2CppInterop.HarmonySupport.xml deleted file mode 100644 index ae775717d..000000000 --- a/packaging/il2cppinterop/Il2CppInterop.HarmonySupport.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - Il2CppInterop.HarmonySupport - - - - - Constructs a new instance of method patcher. - - - - - - - - - - - - - - diff --git a/packaging/il2cppinterop/Il2CppInterop.Runtime.dll b/packaging/il2cppinterop/Il2CppInterop.Runtime.dll deleted file mode 100644 index 30ae9bd06..000000000 Binary files a/packaging/il2cppinterop/Il2CppInterop.Runtime.dll and /dev/null differ diff --git a/packaging/il2cppinterop/Il2CppInterop.Runtime.xml b/packaging/il2cppinterop/Il2CppInterop.Runtime.xml deleted file mode 100644 index 2bfd45e82..000000000 --- a/packaging/il2cppinterop/Il2CppInterop.Runtime.xml +++ /dev/null @@ -1,233 +0,0 @@ - - - - Il2CppInterop.Runtime - - - - - This attribute indicates that the target should not be exposed to IL2CPP in injected classes - - - - type.FullName - - - (method) : (method_inst, method) - - - Common version of the Il2CppType, the only thing that changed between unity version are the bitfields values that we don't use - - - Unity 6 (6000.x.x): the 1-param GetMethod(const Il2CppGenericMethod&) is inlined into - the 3-param GetMethod(const MethodInfo*, const Il2CppGenericInst*, const Il2CppGenericInst*). - We use the hook with 3 param correctly - - - (namespace, class, image) : class - - - - The pointer to the first element in the array. - - - - - Tries to get the Garbage collector pointer from the m_target object from the m_target of the delegate. - Fixes Harmony in Unity 2021.2.x . - - - - - Indicates that an API is experimental and it may change in the future. - - - This attribute allows call sites to be flagged with a diagnostic that indicates that an experimental - feature is used. Authors can use this attribute to ship preview features in their assemblies. - - - - - Initializes a new instance of the class, - specifying the ID that the compiler will use when reporting a use of the API the attribute applies to. - - The ID that the compiler will use when reporting a use of the API the attribute applies to. - - - - Gets the ID that the compiler will use when reporting a use of the API the attribute applies to. - - The unique diagnostic ID. - - The diagnostic ID is shown in build output for warnings and errors. - This property represents the unique ID that can be used to suppress the warnings or errors, if needed. - - - - - Gets or sets the URL for corresponding documentation. - The API accepts a format string instead of an actual URL, creating a generic URL that includes the diagnostic ID. - - The format string that represents a URL to corresponding documentation. - An example format string is https://contoso.com/obsoletion-warnings/{0}. - - - - Specifies that this constructor sets all required members for the current type, - and callers do not need to set any required members themselves. - - - - - Specifies the syntax used in a string. - - - - - Initializes the with the identifier of the syntax used. - - The syntax identifier. - - - Initializes the with the identifier of the syntax used. - The syntax identifier. - Optional arguments associated with the specific syntax employed. - - - Gets the identifier of the syntax used. - - - Optional arguments associated with the specific syntax employed. - - - The syntax identifier for strings containing composite formats for string formatting. - - - The syntax identifier for strings containing date format specifiers. - - - The syntax identifier for strings containing date and time format specifiers. - - - The syntax identifier for strings containing format specifiers. - - - The syntax identifier for strings containing format specifiers. - - - The syntax identifier for strings containing JavaScript Object Notation (JSON). - - - The syntax identifier for strings containing numeric format specifiers. - - - The syntax identifier for strings containing regular expressions. - - - The syntax identifier for strings containing time format specifiers. - - - The syntax identifier for strings containing format specifiers. - - - The syntax identifier for strings containing URIs. - - - The syntax identifier for strings containing XML. - - - - Used to indicate a byref escapes and is not scoped. - - - - There are several cases where the C# compiler treats a as implicitly - - where the compiler does not allow the to escape the method. - - - For example: - - for instance methods. - parameters that refer to types. - parameters. - - - - This attribute is used in those instances where the should be allowed to escape. - - - Applying this attribute, in any form, has impact on consumers of the applicable API. It is necessary for - API authors to understand the lifetime implications of applying this attribute and how it may impact their users. - - - - - - Initialize the attribute to refer to the method on the type. - - The type of the builder to use to construct the collection. - The name of the method on the builder to use to construct the collection. - - must refer to a static method that accepts a single parameter of - type and returns an instance of the collection being built containing - a copy of the data from that span. In future releases of .NET, additional patterns may be supported. - - - - - Gets the type of the builder to use to construct the collection. - - - - - Gets the name of the method on the builder to use to construct the collection. - - - This should match the metadata name of the target method. - For example, this might be ".ctor" if targeting the type's constructor. - - - - - Indicates that compiler support for a particular feature is required for the location where this attribute is applied. - - - - - Creates a new instance of the type. - - The name of the feature to indicate. - - - - The name of the compiler feature. - - - - - If true, the compiler can choose to allow access to the location where this attribute is applied if it does not understand . - - - - - The used for the ref structs C# feature. - - - - - The used for the required members C# feature. - - - - - Specifies that a type has required members or that a member is required. - - - - - Reserved for use by a compiler for tracking metadata. - This attribute should not be used by developers in source code. - - - - diff --git a/packaging/steam/BepInEx/config/at.duikbo.regioninstall.cfg b/packaging/steam/BepInEx/config/at.duikbo.regioninstall.cfg index c3a670533..772279d55 100644 --- a/packaging/steam/BepInEx/config/at.duikbo.regioninstall.cfg +++ b/packaging/steam/BepInEx/config/at.duikbo.regioninstall.cfg @@ -6,10 +6,10 @@ ## Create an array of regions you want to add/update. To create this array, go to https://impostor.github.io/Impostor/ and put the Regions array from the server file in here # Setting type: String # Default value: {\"CurrentRegionIdx\":0,\"Regions\":[]} -Regions = { \"CurrentRegionIdx\": 0, \"Regions\": [ { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded EU (MEU)\", \"PingServer\": \"https://au-eu.duikbo.at\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://au-eu.duikbo.at\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded NA (MNA)\", \"PingServer\": \"https://aumods.org\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://aumods.org\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded Asia (MAS)\", \"PingServer\": \"https://au-as.duikbo.at\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://au-as.duikbo.at\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"GG-HU\", \"PingServer\": \"https://play-hu.gurge44.eu\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://play-hu.gurge44.eu\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"GG-US\", \"PingServer\": \"https://play-us.gurge44.eu\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://play-us.gurge44.eu\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Niko-NA\", \"PingServer\": \"https://au-us.niko233.top\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://au-us.niko233.top\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Niko-AS\", \"PingServer\": \"https://au-as.niko233.top\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://au-as.niko233.top\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"AOU-EU\", \"PingServer\": \"https://eu.allofus.dev\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://eu.allofus.dev\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 } ] } +Regions = { \"CurrentRegionIdx\": 0, \"Regions\": [ { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded EU (MEU)\", \"PingServer\": \"https://au-eu.duikbo.at\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://au-eu.duikbo.at\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded NA (MNA)\", \"PingServer\": \"https://aumods.org\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://aumods.org\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"Modded Asia (MAS)\", \"PingServer\": \"https://au-as.duikbo.at\", \"Servers\": [ { \"Name\": \"Http-1\", \"Ip\": \"https://au-as.duikbo.at\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"GG-HU\", \"PingServer\": \"https://play-hu.gurge44.eu\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://play-hu.gurge44.eu\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"GG-US\", \"PingServer\": \"https://play-us.gurge44.eu\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://play-us.gurge44.eu\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 }, { \"$type\": \"StaticHttpRegionInfo, Assembly-CSharp\", \"Name\": \"AOU-EU\", \"PingServer\": \"https://eu.allofus.dev\", \"Servers\": [ { \"Name\": \"http-1\", \"Ip\": \"https://eu.allofus.dev\", \"Port\": 443, \"UseDtls\": false, \"Players\": 0, \"ConnectionFailures\": 0 } ], \"TargetServer\": null, \"TranslateName\": 1003 } ] } ## Comma-seperated list of region names that should be removed. # Setting type: String # Default value: -RemoveRegions = Niko233(NA_US),Niko233(NA_US2),Niko233(AS_CN),Niko233(AS_CN2),NikoCat233(US),NikoCat233(CN),Niko233(AS3),Niko233(NA2),Niko233(EU2),Niko233(AS2),Custom,Niko233(NA),Niko233(EU),Niko233(AS),Niko233(CN),Modded SA (MSA),Niko-CN,Niko-EU +RemoveRegions = Niko233(NA_US),Niko233(NA_US2),Niko233(AS_CN),Niko233(AS_CN2),NikoCat233(US),NikoCat233(CN),Niko233(AS3),Niko233(NA2),Niko233(EU2),Niko233(AS2),Custom,Niko233(NA),Niko233(EU),Niko233(AS),Niko233(CN),Modded SA (MSA),Niko-CN,Niko-EU,Niko-NA,Niko-AS,Niko_CN,Niko_EU,Niko_NA,Niko_AS diff --git a/packaging/steam/BepInEx/patchers/Il2CppInteropGcFix.dll b/packaging/steam/BepInEx/patchers/Il2CppInteropGcFix.dll new file mode 100644 index 000000000..ae0d3b12d Binary files /dev/null and b/packaging/steam/BepInEx/patchers/Il2CppInteropGcFix.dll differ