From 329cc85f9637d816125c5942ad457a7bbb0cf0a4 Mon Sep 17 00:00:00 2001 From: Az <56699741+AlchlcDvl@users.noreply.github.com> Date: Sun, 6 Sep 2026 09:54:01 -0400 Subject: [PATCH] make resharper happy --- ExternalAnnotations/0Harmony.xml | 29 ++ MiraAPI.Example/Roles/ChameleonRole.cs | 5 +- .../Vanilla/Meeting/Voting/HandleVoteEvent.cs | 11 +- MiraAPI/GameModes/.editorconfig | 4 - MiraAPI/GameModes/AbstractGameMode.cs | 4 +- MiraAPI/GameModes/ClassicMode.cs | 2 +- MiraAPI/GameModes/GameModeOption.cs | 3 +- MiraAPI/GameModes/HideAndSeekMode.cs | 288 ++++++++---------- MiraAPI/GameOptions/ModdedOptionsManager.cs | 2 +- .../GameOptions/OptionNotifConfiguration.cs | 2 +- .../OptionTypes/ModdedPlayerOption.cs | 2 +- .../HnsReimplemented/HideAndSeekHudHelper.cs | 118 +++---- MiraAPI/HnsReimplemented/HnsDangerMeter.cs | 14 +- MiraAPI/HnsReimplemented/HnsMusicHandler.cs | 24 +- .../Options/HnsCrewmateOptions.cs | 1 + .../Options/HnsFinalHideOptions.cs | 1 + .../Options/HnsImpostorOptions.cs | 1 + .../Options/HnsTaskOptions.cs | 1 + MiraAPI/Hud/CustomActionButton.cs | 92 +++--- MiraAPI/Hud/CustomButtonManager.cs | 6 +- MiraAPI/Hud/CustomPlayerMenu.cs | 2 +- MiraAPI/Hud/MiraHudHelper.cs | 12 +- MiraAPI/Keybinds/BaseKeybind.cs | 4 +- MiraAPI/Keybinds/KeybindUtils.cs | 4 +- .../Attributes/LocalSettingAttribute.cs | 4 +- MiraAPI/LocalSettings/LocalSettingsButton.cs | 2 +- .../SettingTypes/LocalEnumSetting.cs | 9 +- .../SettingTypes/LocalNumberSetting.cs | 7 +- .../SettingTypes/LocalSliderSetting.cs | 2 +- .../SettingTypes/LocalToggleSetting.cs | 2 +- .../MeetingAbilityBehaviour.cs | 13 +- MiraAPI/MiraAPI.csproj | 6 + MiraAPI/MiraApiPlugin.cs | 1 + MiraAPI/MiraApiSettings.cs | 40 ++- MiraAPI/ModCompatibility.cs | 2 +- .../ModifierDisplayComponent.cs | 16 +- MiraAPI/Modifiers/ModifierUtils.cs | 4 +- MiraAPI/Networking/CustomGameOverRpc.cs | 1 + .../Networking/Modifiers/AddModifierRpc.cs | 1 + MiraAPI/Networking/SyncOptionsRpc.cs | 1 + MiraAPI/Networking/SyncRoleOptionsRpc.cs | 1 + .../Accessibility/HudManagerFlashPatches.cs | 5 +- MiraAPI/Patches/Events/CanUsePatches.cs | 14 +- .../Patches/Events/FreeplayRoundStartPatch.cs | 8 +- MiraAPI/Patches/Events/VentEventPatches.cs | 2 +- MiraAPI/Patches/Freeplay/TaskAdderPatches.cs | 25 +- MiraAPI/Patches/GameModes/.editorconfig | 4 - MiraAPI/Patches/GameModes/BodyTypePatch.cs | 10 +- .../Patches/GameModes/ImpostorTargetPatch.cs | 2 +- .../Patches/GameModes/IntroCutscenePatch.cs | 10 +- .../Patches/GameModes/MapBehaviourPatch.cs | 10 +- .../Patches/GameModes/ProgressTrackerPatch.cs | 9 +- MiraAPI/Patches/GameModes/TaskPanelPatch.cs | 9 +- MiraAPI/Patches/HudManagerPatches.cs | 44 ++- .../Keybinds/OptionsMenuBehaviourPatch.cs | 20 +- .../LocalSettings/OptionsMenuPatches.cs | 6 +- MiraAPI/Patches/Menu/HatsTabPatches.cs | 5 +- MiraAPI/Patches/Menu/NameplatesTabPatches.cs | 25 +- MiraAPI/Patches/Menu/SkinsTabPatches.cs | 11 +- MiraAPI/Patches/Menu/VisorsTabPatches.cs | 11 +- MiraAPI/Patches/MinigameBeginErrorPatch.cs | 4 +- .../Patches/Options/GameOptionsMenuPatch.cs | 123 ++++---- .../Patches/Options/LobbyViewPanePatches.cs | 24 +- .../Patches/Options/RoleSettingMenuPatches.cs | 19 +- MiraAPI/Patches/Options/SettingPatches.cs | 52 ++-- MiraAPI/Patches/PlayerControlPatches.cs | 4 +- MiraAPI/Patches/RoleGuidePatches.cs | 68 ++--- MiraAPI/Patches/Roles/HowToPlayPatch.cs | 6 +- .../Roles/LogicRoleSelectionHnsPatch.cs | 242 +++++++-------- .../Roles/RoleOptionsCollectionPatch.cs | 3 +- MiraAPI/Patches/Roles/SelectRolesPatch.cs | 19 +- MiraAPI/Patches/Roles/TaskPanelPatch.cs | 2 +- MiraAPI/Patches/Voting/DummyBehaviourPatch.cs | 4 +- MiraAPI/Patches/Voting/MeetingHudPatches.cs | 12 +- MiraAPI/PluginLoading/IMiraPlugin.cs | 16 +- MiraAPI/Presets/OptionPreset.cs | 2 - MiraAPI/Presets/SavePresetPopup.cs | 7 +- MiraAPI/Roles/CustomRoleConfiguration.cs | 2 +- MiraAPI/Roles/CustomRoleManager.cs | 2 +- MiraAPI/Roles/CustomRoleUtils.cs | 2 +- MiraAPI/Roles/ICustomRole.cs | 24 +- MiraAPI/Translation/MiraLanguage.cs | 1 + MiraAPI/Translation/MiraLocaleManager.cs | 36 ++- .../Utilities/Assets/AddressablesLoader.cs | 2 +- MiraAPI/Utilities/Assets/TmpSpriteUtils.cs | 3 +- .../Components/CenteredGridArrange.cs | 38 +-- MiraAPI/Utilities/ControllableComparer.cs | 18 +- MiraAPI/Utilities/Extensions.cs | 22 +- MiraAPI/Utilities/Helpers.cs | 26 +- MiraAPI/VanillaEvents/JudgeEvents.cs | 21 +- MiraAPI/VanillaEvents/UiResetEvents.cs | 8 +- MiraAPI/Voting/VotingUtils.cs | 4 +- 92 files changed, 886 insertions(+), 904 deletions(-) create mode 100755 ExternalAnnotations/0Harmony.xml delete mode 100644 MiraAPI/GameModes/.editorconfig delete mode 100644 MiraAPI/Patches/GameModes/.editorconfig diff --git a/ExternalAnnotations/0Harmony.xml b/ExternalAnnotations/0Harmony.xml new file mode 100755 index 0000000..0cb768a --- /dev/null +++ b/ExternalAnnotations/0Harmony.xml @@ -0,0 +1,29 @@ + + + + 3 + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MiraAPI.Example/Roles/ChameleonRole.cs b/MiraAPI.Example/Roles/ChameleonRole.cs index 4cd04c5..c805763 100644 --- a/MiraAPI.Example/Roles/ChameleonRole.cs +++ b/MiraAPI.Example/Roles/ChameleonRole.cs @@ -3,7 +3,6 @@ using MiraAPI.Patches.Stubs; using MiraAPI.Roles; using MiraAPI.Utilities.Assets; using Reactor.Utilities; -using TMPro; using UnityEngine; namespace MiraAPI.Example.Roles; @@ -55,8 +54,8 @@ public class ChameleonRole : CrewmateRole, ICustomRole } else { - SpriteRenderer rend = Player.cosmetics.currentBodySprite.BodySprite; - TextMeshPro tmp = Player.cosmetics.nameText; + var rend = Player.cosmetics.currentBodySprite.BodySprite; + var tmp = Player.cosmetics.nameText; tmp.color = Color.Lerp( tmp.color, new Color(tmp.color.r, tmp.color.g, tmp.color.b, Player.AmOwner ? 0.3f : 0), diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs index f8f0e9a..0c67e88 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs @@ -12,7 +12,7 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting; /// The voter's . /// The target's playerId. /// Whether the vote is actually for a Judge. -public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool isOverruling) : MiraCancelableEvent +public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool isOverruling = false) : MiraCancelableEvent { /// /// Gets the instance of the voter's . @@ -43,13 +43,4 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool /// Gets or sets a value indicating whether the vote event is an Overrule caused by a Judge. /// public bool IsOverruling { get; set; } = isOverruling; - - /// - /// Initializes a new instance of the class. - /// - /// The voter's . - /// The target's playerId. - public HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId) : this(playerVoteData, targetId, false) - { - } } diff --git a/MiraAPI/GameModes/.editorconfig b/MiraAPI/GameModes/.editorconfig deleted file mode 100644 index 57cba7e..0000000 --- a/MiraAPI/GameModes/.editorconfig +++ /dev/null @@ -1,4 +0,0 @@ -[*.cs] - -# CS1591: Missing XML comment for publicly visible type or member. -# dotnet_diagnostic.CS1591.severity = none \ No newline at end of file diff --git a/MiraAPI/GameModes/AbstractGameMode.cs b/MiraAPI/GameModes/AbstractGameMode.cs index 3614341..758c54f 100644 --- a/MiraAPI/GameModes/AbstractGameMode.cs +++ b/MiraAPI/GameModes/AbstractGameMode.cs @@ -278,11 +278,11 @@ public abstract class AbstractGameMode : IOptionable instance.background.transform.localScale = (instance.taskText.textBounds.size.x > 0f) ? new Vector3(instance.taskText.textBounds.size.x + 0.2f, instance.taskText.textBounds.size.y + 0.2f, 1f) : Vector3.zero; - Vector3 vector = instance.background.sprite.bounds.extents; + var vector = instance.background.sprite.bounds.extents; vector.y = -vector.y; vector = vector.Mul(instance.background.transform.localScale); instance.background.transform.localPosition = vector; - Vector3 vector2 = instance.tab.sprite.bounds.extents; + var vector2 = instance.tab.sprite.bounds.extents; vector2 = vector2.Mul(instance.tab.transform.localScale); vector2.y = -vector2.y; vector2.x += vector.x * 2f; diff --git a/MiraAPI/GameModes/ClassicMode.cs b/MiraAPI/GameModes/ClassicMode.cs index 440ce75..75499fa 100644 --- a/MiraAPI/GameModes/ClassicMode.cs +++ b/MiraAPI/GameModes/ClassicMode.cs @@ -17,5 +17,5 @@ public class ClassicMode : AbstractGameMode public override string Description => "MiraApi.Gamemode.Classic.Description"; /// - public override LoadableAsset? Icon => MiraAssets.ClassicGamemodeIcon; + public override LoadableAsset Icon => MiraAssets.ClassicGamemodeIcon; } diff --git a/MiraAPI/GameModes/GameModeOption.cs b/MiraAPI/GameModes/GameModeOption.cs index f0fe6ad..494f0a1 100644 --- a/MiraAPI/GameModes/GameModeOption.cs +++ b/MiraAPI/GameModes/GameModeOption.cs @@ -56,6 +56,7 @@ public static class GameModeOption if (!Values.ContainsKey(mode.ID)) Values.Add(mode.ID, MiraLocaleManager.GetOrCreateLocaleString(mode.Name)); } + /*[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.CreateSettings))] [HarmonyPostfix] private static void CreateSettingsPatch(GameOptionsMenu __instance) @@ -126,7 +127,7 @@ public static class GameModeOption } } } - // could make Values a dict of AbstractGameMode too + // TODO: could make Values a dict of AbstractGameMode too } [HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.ValueChanged))] diff --git a/MiraAPI/GameModes/HideAndSeekMode.cs b/MiraAPI/GameModes/HideAndSeekMode.cs index 1f95c73..9c3ea71 100644 --- a/MiraAPI/GameModes/HideAndSeekMode.cs +++ b/MiraAPI/GameModes/HideAndSeekMode.cs @@ -97,19 +97,66 @@ public class HideAndSeekMode : AbstractGameMode .Where(c => c.Character != null && c.Character.Data != null && !c.Character.Data.Disconnected && !c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data)]; - foreach (NetworkedPlayerInfo networkedPlayerInfo in GameData.Instance.AllPlayers) + foreach (var networkedPlayerInfo in GameData.Instance.AllPlayers) { if (networkedPlayerInfo.Object != null && networkedPlayerInfo.Object.isDummy) { list2.Add(networkedPlayerInfo); } } - IGameOptions currentGameOptions = GameOptionsManager.Instance.CurrentGameOptions; - int adjustedNumImpostors = GameOptionsManager.Instance.CurrentGameOptions.GetAdjustedNumImpostors(list2.Count); + var currentGameOptions = GameOptionsManager.Instance.CurrentGameOptions; + var adjustedNumImpostors = GameOptionsManager.Instance.CurrentGameOptions.GetAdjustedNumImpostors(list2.Count); AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Impostor, Math.Max(adjustedNumImpostors, 1), RoleTypes.Impostor); AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Crewmate, int.MaxValue, RoleTypes.Engineer); } + private static void AddGuaranteedRoles(IEnumerable guaranteedRoles, IGameOptions opts, List list) + { + var roleOptions = opts.RoleOptions; + foreach (var roleAssignmentData in guaranteedRoles.Select(x => + new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100))) + { + while (true) + { + var count = roleAssignmentData.Count; + roleAssignmentData.Count = count - 1; + if (count <= 0) break; + + list.Add(roleAssignmentData.Role.Role); + } + } + } + + private static void AddPotentialRoles(IEnumerable source, IGameOptions opts, List list) + { + var roleOptions = opts.RoleOptions; + var potentialRoles = source.Where(x => !x.IsDead).Select(role => + new RoleManager.RoleAssignmentData( + role, + roleOptions.GetNumPerGame(role.Role), + roleOptions.GetChancePerGame(role.Role))).ToList(); + + list.Clear(); + foreach (var roleData in potentialRoles) + { + for (var i = 0; i < roleData.Count; i++) + { + if (HashRandom.Next(101) < roleData.Chance) + { + list.Add(roleData.Role.Role); + } + } + } + } + + private static void AddFallbackRoles(List list, int targetPlayerCount, int teamMax, int rolesAssigned, RoleTypes basicRole) + { + while (list.Count < targetPlayerCount && list.Count + rolesAssigned < teamMax) + { + list.Add(basicRole); + } + } + private static void AssignRolesForTeam( List players, IGameOptions opts, @@ -117,151 +164,90 @@ public class HideAndSeekMode : AbstractGameMode int teamMax, RoleTypes defaultRole) { - Error($"Hide And Seek Mode - AssignRolesForTeam: Team: {team}, Max: {teamMax}, Players: {players.Count}, DefaultRole: {defaultRole}"); - int num = 0; - IRoleOptionsCollection roleOptions = opts.RoleOptions; + Info($"Hide And Seek Mode - AssignRolesForTeam: Team: {team}, Max: {teamMax}, Players: {players.Count}, DefaultRole: {defaultRole}"); + var num = 0; + var roleOptions = opts.RoleOptions; var source = RoleManager.Instance.AllRoles.ToArray() .Where(role => role.TeamType == team && !RoleManager.IsGhostRole(role.Role) && CustomRoleUtils.CanSpawnOnCurrentMode(role)) .ToList(); + var assignmentData = source.Where(x => !x.IsDead).Select(role => new RoleManager.RoleAssignmentData( role, roleOptions.GetNumPerGame(role.Role), roleOptions.GetChancePerGame(role.Role))).ToList(); + var source2 = CustomRoleUtils.GetPossibleRoles(assignmentData, x => x.Chance == 100); - var guaranteedRoles = source.Where(x => source2.Contains(((ushort)x.Role, 100))); + var guaranteedRoles = source.Where(x => source2.Contains(((ushort)x.Role, 100))).ToList(); List list = []; - if (team == RoleTeamTypes.Crewmate) + + switch (team) { - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment"); - foreach (RoleManager.RoleAssignmentData roleAssignmentData in guaranteedRoles.Select((x) => - new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100))) - { - while (true) + case RoleTeamTypes.Crewmate: + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment"); + AddGuaranteedRoles(guaranteedRoles, opts, list); + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment"); + AssignRolesFromList(players, teamMax, list, ref num); + + AddPotentialRoles(source, opts, list); + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Potential Assignment"); + AssignRolesFromList(players, teamMax, list, ref num); + + const RoleTypes basicCrewRole = RoleTypes.Engineer; + AddFallbackRoles(list, players.Count, teamMax, num, basicCrewRole); + AssignRolesFromList(players, teamMax, list, ref num); + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Fallback Assignment"); + break; + + case RoleTeamTypes.Impostor: + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment"); + var newImpostors = new List(); + + // Specified Seeker + if (HasImpostorPlayerID() && + ValidateImpostorPlayerID(players) && + !AmongUsClient.Instance.IsGamePublic) { - RoleManager.RoleAssignmentData roleAssignmentData2 = roleAssignmentData; - int count = roleAssignmentData2.Count; - roleAssignmentData2.Count = count - 1; - if (count <= 0) - { - break; - } - - list.Add(roleAssignmentData.Role.Role); - } - } - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment"); - AssignRolesFromList(players, teamMax, list, ref num); - - var list2 = source.Where(x => !x.IsDead).Select(role => - new RoleManager.RoleAssignmentData( - role, - roleOptions.GetNumPerGame(role.Role), - roleOptions.GetChancePerGame(role.Role))).ToList(); - - list.Clear(); - foreach (RoleManager.RoleAssignmentData roleAssignmentData3 in list2) - { - for (int i = 0; i < roleAssignmentData3.Count; i++) - { - if (HashRandom.Next(101) < roleAssignmentData3.Chance) - { - list.Add(roleAssignmentData3.Role.Role); - } - } - } - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Potential Assignment"); - - AssignRolesFromList(players, teamMax, list, ref num); - var basicRole = RoleTypes.Engineer; - while (list.Count < players.Count && list.Count + num < teamMax) - { - list.Add(basicRole); - } - - AssignRolesFromList(players, teamMax, list, ref num); - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Fallback Assignment"); - } - else if (team == RoleTeamTypes.Impostor) - { - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment"); - var newImpostors = new List(); - // Specified Seeker - if (HasImpostorPlayerID() && - ValidateImpostorPlayerID(players) && - !AmongUsClient.Instance.IsGamePublic) - { - NetworkedPlayerInfo networkedPlayerInfo = players - .First(p => p.PlayerId == ImpostorPlayerID()); - players.Remove(networkedPlayerInfo); - newImpostors.Add(networkedPlayerInfo); - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}"); - } - // Random Seeker - else - { - int num2 = 0; - while (num2 < teamMax && players.Count > 0) - { - PseudoRandomList pseudoRandomList = new(AmongUsClient.Instance.GameId); - players.Do(pseudoRandomList.Add); - for (int i = 0; i < GameData.RoundsPlayedInSession; i++) - { - pseudoRandomList.PickRandom(); - } - NetworkedPlayerInfo networkedPlayerInfo = pseudoRandomList.PickRandom(); + var networkedPlayerInfo = players.First(p => p.PlayerId == ImpostorPlayerID()); players.Remove(networkedPlayerInfo); newImpostors.Add(networkedPlayerInfo); - num2++; - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}"); + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}"); } - } - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment"); - foreach (RoleManager.RoleAssignmentData roleAssignmentData in guaranteedRoles.Select((x) => - new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100))) - { - while (true) + // Random Seeker + else { - RoleManager.RoleAssignmentData roleAssignmentData2 = roleAssignmentData; - int count = roleAssignmentData2.Count; - roleAssignmentData2.Count = count - 1; - if (count <= 0) + var num2 = 0; + while (num2 < teamMax && players.Count > 0) { - break; - } - - list.Add(roleAssignmentData.Role.Role); - } - } - AssignRolesFromList(newImpostors, teamMax, list, ref num); - - var list2 = source.Where(x => !x.IsDead).Select(role => - new RoleManager.RoleAssignmentData( - role, - roleOptions.GetNumPerGame(role.Role), - roleOptions.GetChancePerGame(role.Role))).ToList(); - - list.Clear(); - foreach (RoleManager.RoleAssignmentData roleAssignmentData3 in list2) - { - for (int i = 0; i < roleAssignmentData3.Count; i++) - { - if (HashRandom.Next(101) < roleAssignmentData3.Chance) - { - list.Add(roleAssignmentData3.Role.Role); + PseudoRandomList pseudoRandomList = new(AmongUsClient.Instance.GameId); + players.Do(pseudoRandomList.Add); + for (var i = 0; i < GameData.RoundsPlayedInSession; i++) + { + pseudoRandomList.PickRandom(); + } + var networkedPlayerInfo = pseudoRandomList.PickRandom(); + players.Remove(networkedPlayerInfo); + newImpostors.Add(networkedPlayerInfo); + num2++; + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}"); } } - } + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment"); - AssignRolesFromList(newImpostors, teamMax, list, ref num); - var basicRole = RoleTypes.Impostor; - while (list.Count < newImpostors.Count && list.Count + num < teamMax) - { - list.Add(basicRole); - } + AddGuaranteedRoles(guaranteedRoles, opts, list); + AssignRolesFromList(newImpostors, teamMax, list, ref num); - AssignRolesFromList(newImpostors, teamMax, list, ref num); + AddPotentialRoles(source, opts, list); + AssignRolesFromList(newImpostors, teamMax, list, ref num); + + const RoleTypes basicImpRole = RoleTypes.Impostor; + AddFallbackRoles(list, newImpostors.Count, teamMax, num, basicImpRole); + AssignRolesFromList(newImpostors, teamMax, list, ref num); + break; + + default: + throw new ArgumentOutOfRangeException(nameof(team), team, null); } } @@ -269,10 +255,10 @@ public class HideAndSeekMode : AbstractGameMode { while (roleList.Count > 0 && players.Count > 0 && rolesAssigned < teamMax) { - int index = HashRandom.FastNext(roleList.Count); - RoleTypes roleType = roleList[index]; + var index = HashRandom.FastNext(roleList.Count); + var roleType = roleList[index]; roleList.RemoveAt(index); - int index2 = HashRandom.FastNext(players.Count); + var index2 = HashRandom.FastNext(players.Count); players[index2].Object.RpcSetRole(roleType); players.RemoveAt(index2); rolesAssigned++; @@ -377,7 +363,7 @@ public class HideAndSeekMode : AbstractGameMode PlayerControl.LocalPlayer.CurrentOutfitType, PlayerMaterial.MaskType.None, false); - SpriteAnim component = poolablePlayer.GetComponent(); + var component = poolablePlayer.GetComponent(); poolablePlayer.gameObject.SetActive(true); poolablePlayer.ToggleName(false); component.Play(anim); @@ -423,12 +409,10 @@ public class HideAndSeekMode : AbstractGameMode deadPlayerCount = 0; ShipStatus.Instance.BreakEmergencyButton(); PlayerControl.LocalPlayer.SetKillTimer(0.01f); - if (HudManager.InstanceExists) - { - HudManager.Instance.gameObject.AddComponent(); - HudManager.Instance.gameObject.AddComponent(); - HudManager.Instance.gameObject.AddComponent(); - } + if (!HudManager.InstanceExists) return; + HudManager.Instance.gameObject.AddComponent(); + HudManager.Instance.gameObject.AddComponent(); + HudManager.Instance.gameObject.AddComponent(); } /// @@ -484,30 +468,18 @@ public class HideAndSeekMode : AbstractGameMode } return PlayerBodyTypes.Normal; } - else if (AprilFoolsMode.ShouldHorseAround()) + + if (AprilFoolsMode.ShouldHorseAround()) { - if (player.Data.Role.IsImpostor) - { - return PlayerBodyTypes.Normal; - } - return PlayerBodyTypes.Horse; + return player.Data.Role.IsImpostor ? PlayerBodyTypes.Normal : PlayerBodyTypes.Horse; } - else if (AprilFoolsMode.ShouldLongAround()) + + if (AprilFoolsMode.ShouldLongAround()) { - if (player.Data.Role.IsImpostor) - { - return PlayerBodyTypes.LongSeeker; - } - return PlayerBodyTypes.Long; - } - else - { - if (player.Data.Role.IsImpostor) - { - return PlayerBodyTypes.Seeker; - } - return PlayerBodyTypes.Normal; + return player.Data.Role.IsImpostor ? PlayerBodyTypes.LongSeeker : PlayerBodyTypes.Long; } + + return player.Data.Role.IsImpostor ? PlayerBodyTypes.Seeker : PlayerBodyTypes.Normal; } /// @@ -516,11 +488,11 @@ public class HideAndSeekMode : AbstractGameMode instance.background.transform.localScale = (instance.taskText.textBounds.size.x > 0f) ? new Vector3(instance.taskText.textBounds.size.x + 0.2f, instance.taskText.textBounds.size.y + 0.2f, 1f) : Vector3.zero; - Vector3 vector = instance.background.sprite.bounds.extents; + var vector = instance.background.sprite.bounds.extents; vector.y = -vector.y; vector = vector.Mul(instance.background.transform.localScale); instance.background.transform.localPosition = vector; - Vector3 vector2 = instance.tab.sprite.bounds.extents; + var vector2 = instance.tab.sprite.bounds.extents; vector2 = vector2.Mul(instance.tab.transform.localScale); vector2.y = -vector2.y; vector2.x += vector.x * 2f; diff --git a/MiraAPI/GameOptions/ModdedOptionsManager.cs b/MiraAPI/GameOptions/ModdedOptionsManager.cs index f1dea2c..5c6adcb 100644 --- a/MiraAPI/GameOptions/ModdedOptionsManager.cs +++ b/MiraAPI/GameOptions/ModdedOptionsManager.cs @@ -216,7 +216,7 @@ public static class ModdedOptionsManager internal static void HandleSyncOptions(NetData[] data) { // necessary to disable then re-enable this setting - // we dont know how other plugins handle their configs + // we don't know how other plugins handle their configs // this way, all the options are saved at once, instead of one by one var oldConfigSetting = new Dictionary(); foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins) diff --git a/MiraAPI/GameOptions/OptionNotifConfiguration.cs b/MiraAPI/GameOptions/OptionNotifConfiguration.cs index e8e2369..0ee9b0c 100644 --- a/MiraAPI/GameOptions/OptionNotifConfiguration.cs +++ b/MiraAPI/GameOptions/OptionNotifConfiguration.cs @@ -13,7 +13,7 @@ public record struct OptionNotifConfiguration { [Obsolete("Default constructor is not supported. Please use the constructor that takes an AbstractOptionGroup parameter.")] [SuppressMessage("Info Code Smell", "S1133:Deprecated code should be removed", Justification = "Will not be removed, as this throws instead.")] -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member (Justification: Read above.) public OptionNotifConfiguration() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member { diff --git a/MiraAPI/GameOptions/OptionTypes/ModdedPlayerOption.cs b/MiraAPI/GameOptions/OptionTypes/ModdedPlayerOption.cs index 674868a..d7094b7 100644 --- a/MiraAPI/GameOptions/OptionTypes/ModdedPlayerOption.cs +++ b/MiraAPI/GameOptions/OptionTypes/ModdedPlayerOption.cs @@ -10,7 +10,7 @@ using Object = UnityEngine.Object; namespace MiraAPI.GameOptions.OptionTypes; /// -/// An option for selecting an ingame player. It returns an index of the values list, NOT A PLAYER ID. To get a player out of this, index the list. +/// An option for selecting an in-game player. It returns an index of the values list, NOT A PLAYER ID. To get a player out of this, index the list. /// public class ModdedPlayerOption : ModdedOption { diff --git a/MiraAPI/HnsReimplemented/HideAndSeekHudHelper.cs b/MiraAPI/HnsReimplemented/HideAndSeekHudHelper.cs index 899f4ef..814e6ba 100644 --- a/MiraAPI/HnsReimplemented/HideAndSeekHudHelper.cs +++ b/MiraAPI/HnsReimplemented/HideAndSeekHudHelper.cs @@ -27,6 +27,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) private AudioClip finalHideAlertSfx; private AudioClip finalHideCountdownSfx; [SuppressMessage("Style", "IDE0052:Remove unread private members", Justification = "Ignore for now; tentative code.")] + // ReSharper disable once NotAccessedField.Local (Justification: Read above.) private AudioClip taskFinishedSound; // private const int SECONDS_TO_BEEP = 10; @@ -38,7 +39,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) private float currentFinalHideTime = float.MaxValue; private float secondsSinceLastSetDirty; - private Coroutine beepCoroutine; + private Coroutine? beepCoroutine; private HideAndSeekTimerBar timerBar; private float taskDirtyTimer; @@ -64,7 +65,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) /// true if the player can use the admin ability. public bool SeekerAdminMapEnabled(PlayerControl player) { - int item = Helpers.GetAlivePlayers().Count(x => !x.Data.Role.IsImpostor); + var item = Helpers.GetAlivePlayers().Count(x => !x.Data.Role.IsImpostor); return !player.inVent && player.Data != null && player.Data.Role != null && ((!player.inVent && player.Data.Role.IsImpostor && IsFinalCountdown && OptionGroupSingleton.Instance.FinalHideSeekMap.Value) || @@ -74,7 +75,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) } /// - /// A event that is called when a task is completed. + /// An event that is called when a task is completed. /// /// The amount of time to deduct from the timer. public void OnTaskComplete(float timeDeduction) @@ -93,8 +94,8 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) /// The match duration in seconds. public static float GetTotalRoundTime() { - float escapeTime = OptionGroupSingleton.Instance.HidingTime.Value; - float finalCountdownTime = OptionGroupSingleton.Instance.FinalHideTime.Value; + var escapeTime = OptionGroupSingleton.Instance.HidingTime.Value; + var finalCountdownTime = OptionGroupSingleton.Instance.FinalHideTime.Value; return escapeTime + finalCountdownTime; } @@ -156,55 +157,54 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) { return; } - if (HideCountdown > 0f && taskDirtyTimer > 0.25f) + + if (!(HideCountdown > 0f) || !(taskDirtyTimer > 0.25f)) return; + var num = taskDirtyTimer; + taskDirtyTimer = 0f; + if (!PlayerControl.LocalPlayer) { - float num = taskDirtyTimer; - taskDirtyTimer = 0f; - if (!PlayerControl.LocalPlayer) - { - HudManager.Instance.TaskPanel.SetTaskText(string.Empty); - return; - } - NetworkedPlayerInfo data = PlayerControl.LocalPlayer.Data; - if (data == null) - { - return; - } - bool flag = data.Role != null && data.Role.IsImpostor; - HudManager.Instance.tasksString.Clear(); - if (PlayerControl.LocalPlayer.myTasks == null || PlayerControl.LocalPlayer.myTasks.Count == 0) - { - HudManager.Instance.tasksString.Append("None"); - } - else - { - for (int i = 0; i < PlayerControl.LocalPlayer.myTasks.Count; i++) - { - PlayerTask playerTask = PlayerControl.LocalPlayer.myTasks[i]; - if (playerTask) - { - if (playerTask.TaskType == TaskTypes.FixComms && !flag) - { - HudManager.Instance.tasksString.Clear(); - playerTask.AppendTaskText(HudManager.Instance.tasksString); - break; - } - playerTask.AppendTaskText(HudManager.Instance.tasksString); - } - } - if (data.Role != null) - { - data.Role.AppendTaskHint(HudManager.Instance.tasksString); - } - if (HideCountdown > 0f) - { - HideCountdown -= num; - HudManager.Instance.tasksString.Append("\n\n" + ((int)HideCountdown)); - } - HudManager.Instance.tasksString.TrimEnd(); - } - HudManager.Instance.TaskPanel.SetTaskText(HudManager.Instance.tasksString.ToString()); + HudManager.Instance.TaskPanel.SetTaskText(string.Empty); + return; } + var data = PlayerControl.LocalPlayer.Data; + if (data == null) + { + return; + } + var flag = data.Role != null && data.Role.IsImpostor; + HudManager.Instance.tasksString.Clear(); + if (PlayerControl.LocalPlayer.myTasks == null || PlayerControl.LocalPlayer.myTasks.Count == 0) + { + HudManager.Instance.tasksString.Append("None"); + } + else + { + for (var i = 0; i < PlayerControl.LocalPlayer.myTasks.Count; i++) + { + var playerTask = PlayerControl.LocalPlayer.myTasks[i]; + if (playerTask) + { + if (playerTask.TaskType == TaskTypes.FixComms && !flag) + { + HudManager.Instance.tasksString.Clear(); + playerTask.AppendTaskText(HudManager.Instance.tasksString); + break; + } + playerTask.AppendTaskText(HudManager.Instance.tasksString); + } + } + if (data.Role != null) + { + data.Role.AppendTaskHint(HudManager.Instance.tasksString); + } + if (HideCountdown > 0f) + { + HideCountdown -= num; + HudManager.Instance.tasksString.Append("\n\n" + ((int)HideCountdown)); + } + HudManager.Instance.tasksString.TrimEnd(); + } + HudManager.Instance.TaskPanel.SetTaskText(HudManager.Instance.tasksString.ToString()); } private void FixedUpdate() @@ -230,7 +230,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) private void OnFinalCountdownTriggered() { - foreach (PlayerControl playerControl in PlayerControl.AllPlayerControls) + foreach (var playerControl in PlayerControl.AllPlayerControls) { if (!playerControl.Data.Role.IsImpostor && !playerControl.Data.IsDead) { @@ -242,7 +242,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) if (!PlayerControl.LocalPlayer.Data.IsDead && Minigame.Instance != null) { - Minigame instance = Minigame.Instance; + var instance = Minigame.Instance; if (instance != null) { instance.ForceClose(); @@ -256,7 +256,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) private void AdjustEscapeTimer(float timeDeduction, bool forceDirty) { - float num = currentHideTime; + var num = currentHideTime; currentHideTime -= timeDeduction; currentHideTime = Mathf.Max(currentHideTime, 0f); if (currentHideTime <= 10f && beepCoroutine == null) @@ -281,8 +281,8 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) { while (!IsFinalCountdown) { - float num = currentHideTime / 10f; - float pitch = 1.5f - num / 2f; + var num = currentHideTime / 10f; + var pitch = 1.5f - num / 2f; SoundManager.Instance.PlaySoundImmediate(finalHideCountdownSfx, false, 1f, pitch); yield return new WaitForSeconds(1f); } @@ -290,8 +290,8 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) yield return Effects.Wait(currentFinalHideTime - 10f); while (currentFinalHideTime > 0f) { - float num2 = currentFinalHideTime / 10f; - float pitch2 = 1.5f - num2 / 2f; + var num2 = currentFinalHideTime / 10f; + var pitch2 = 1.5f - num2 / 2f; SoundManager.Instance.PlaySoundImmediate(finalHideCountdownSfx, false, 1f, pitch2); yield return new WaitForSeconds(1f); } diff --git a/MiraAPI/HnsReimplemented/HnsDangerMeter.cs b/MiraAPI/HnsReimplemented/HnsDangerMeter.cs index aa73fad..0309e16 100644 --- a/MiraAPI/HnsReimplemented/HnsDangerMeter.cs +++ b/MiraAPI/HnsReimplemented/HnsDangerMeter.cs @@ -45,7 +45,7 @@ public sealed class HnsDangerMeter(nint cppPtr) : MonoBehaviour(cppPtr) private void FixedUpdate() { - PlayerControl localPlayer = PlayerControl.LocalPlayer; + var localPlayer = PlayerControl.LocalPlayer; if (impostors == null || localPlayer == null) { return; @@ -56,12 +56,12 @@ public sealed class HnsDangerMeter(nint cppPtr) : MonoBehaviour(cppPtr) return; } - float num = float.MaxValue; - foreach (PlayerControl playerControl in impostors) + var num = float.MaxValue; + foreach (var playerControl in impostors) { if (playerControl == null) continue; - float sqrMagnitude = (playerControl.transform.position - localPlayer.transform.position).sqrMagnitude; + var sqrMagnitude = (playerControl.transform.position - localPlayer.transform.position).sqrMagnitude; if (sqrMagnitude < scaryMusicDistance && num > sqrMagnitude) { num = sqrMagnitude; @@ -102,7 +102,7 @@ public sealed class HnsDangerMeter(nint cppPtr) : MonoBehaviour(cppPtr) private void UpdateDangerMusic() { - PlayerControl localPlayer = PlayerControl.LocalPlayer; + var localPlayer = PlayerControl.LocalPlayer; if (localPlayer != null && localPlayer.Data != null && localPlayer.Data.IsDead) { HnsMusicHandler.Instance.SetTaskState(false); @@ -141,8 +141,8 @@ public sealed class HnsDangerMeter(nint cppPtr) : MonoBehaviour(cppPtr) scaryMusicDistance = 55f * baseSpeed; veryScaryMusicDistance = 15f * baseSpeed; if (scaryMusicDistance >= veryScaryMusicDistance) return; - float num = veryScaryMusicDistance; - float num2 = scaryMusicDistance; + var num = veryScaryMusicDistance; + var num2 = scaryMusicDistance; scaryMusicDistance = num; veryScaryMusicDistance = num2; } diff --git a/MiraAPI/HnsReimplemented/HnsMusicHandler.cs b/MiraAPI/HnsReimplemented/HnsMusicHandler.cs index 868ee9e..7d94884 100644 --- a/MiraAPI/HnsReimplemented/HnsMusicHandler.cs +++ b/MiraAPI/HnsReimplemented/HnsMusicHandler.cs @@ -144,27 +144,25 @@ public sealed class HnsMusicHandler(nint cppPtr) : MonoBehaviour(cppPtr) /// public void StartMusicWithIntro() { - if (PlayerControl.LocalPlayer.Data.Role.IsImpostor) + if (!PlayerControl.LocalPlayer.Data.Role.IsImpostor) return; + var clip = OptionGroupSingleton.Instance.HidingTime.Value <= 180f + ? musicCollection.ImpostorShortMusic + : musicCollection.ImpostorLongMusic; + if (AprilFoolsMode.ShouldHorseAround()) { - AudioClip clip = OptionGroupSingleton.Instance.HidingTime.Value <= 180f - ? musicCollection.ImpostorShortMusic - : musicCollection.ImpostorLongMusic; - if (AprilFoolsMode.ShouldHorseAround()) - { - clip = musicCollection.ImpostorRanchMusic; - } - - SoundManager.Instance.PlaySound(clip, true, 1f, SoundManager.Instance.MusicChannel); + clip = musicCollection.ImpostorRanchMusic; } + + SoundManager.Instance.PlaySound(clip, true, 1f, SoundManager.Instance.MusicChannel); } /// /// Sets the current task state to alter music behaviour. /// - /// The new value of the state. - public void SetTaskState(bool isDoingTask) + /// The new value of the state. + public void SetTaskState(bool taskState) { - this.isDoingTask = isDoingTask; + isDoingTask = taskState; } private void FixedUpdate() diff --git a/MiraAPI/HnsReimplemented/Options/HnsCrewmateOptions.cs b/MiraAPI/HnsReimplemented/Options/HnsCrewmateOptions.cs index 2dfcf3f..949cf54 100644 --- a/MiraAPI/HnsReimplemented/Options/HnsCrewmateOptions.cs +++ b/MiraAPI/HnsReimplemented/Options/HnsCrewmateOptions.cs @@ -8,6 +8,7 @@ namespace MiraAPI.HnsReimplemented.Options; /// /// Gets or sets the crewmate options for Hide and Seek. /// +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) public class HnsCrewmateOptions : AbstractOptionGroup { /// diff --git a/MiraAPI/HnsReimplemented/Options/HnsFinalHideOptions.cs b/MiraAPI/HnsReimplemented/Options/HnsFinalHideOptions.cs index cfecee7..ab6d393 100644 --- a/MiraAPI/HnsReimplemented/Options/HnsFinalHideOptions.cs +++ b/MiraAPI/HnsReimplemented/Options/HnsFinalHideOptions.cs @@ -8,6 +8,7 @@ namespace MiraAPI.HnsReimplemented.Options; /// /// Gets or sets the Final Hide options for Hide and Seek. /// +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) public class HnsFinalHideOptions : AbstractOptionGroup { /// diff --git a/MiraAPI/HnsReimplemented/Options/HnsImpostorOptions.cs b/MiraAPI/HnsReimplemented/Options/HnsImpostorOptions.cs index 59adaf2..15da3ff 100644 --- a/MiraAPI/HnsReimplemented/Options/HnsImpostorOptions.cs +++ b/MiraAPI/HnsReimplemented/Options/HnsImpostorOptions.cs @@ -8,6 +8,7 @@ namespace MiraAPI.HnsReimplemented.Options; /// /// Gets or sets the seeker settings on Hide and Seek. /// +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) public class HnsImpostorOptions : AbstractOptionGroup { /// diff --git a/MiraAPI/HnsReimplemented/Options/HnsTaskOptions.cs b/MiraAPI/HnsReimplemented/Options/HnsTaskOptions.cs index 923763d..dddd704 100644 --- a/MiraAPI/HnsReimplemented/Options/HnsTaskOptions.cs +++ b/MiraAPI/HnsReimplemented/Options/HnsTaskOptions.cs @@ -8,6 +8,7 @@ namespace MiraAPI.HnsReimplemented.Options; /// /// Gets or sets the task options for Hide and Seek. /// +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) public class HnsTaskOptions : AbstractOptionGroup { /// diff --git a/MiraAPI/Hud/CustomActionButton.cs b/MiraAPI/Hud/CustomActionButton.cs index aa7ee61..5f1f561 100644 --- a/MiraAPI/Hud/CustomActionButton.cs +++ b/MiraAPI/Hud/CustomActionButton.cs @@ -205,58 +205,54 @@ public abstract class CustomActionButton } })); - if (Keybind != null) + if (Keybind == null) return; + Keybind.OnActivate(() => { - Keybind.OnActivate(() => + if (!Enabled(PlayerControl.LocalPlayer.Data.Role)) return; + // Invoke the generic button click event. + var genericEvent = new MiraButtonClickEvent(this); + MiraEventManager.InvokeEvent(genericEvent); + if (genericEvent.IsCancelled) { - if (Enabled(PlayerControl.LocalPlayer.Data.Role)) + MiraEventManager.InvokeEvent(new MiraButtonCancelledEvent(this)); + } + + // Invoke the button click event for specific button. + var eventType = CustomButtonManager.ButtonEventTypes[GetType()]; + var @event = (MiraCancelableEvent)Activator.CreateInstance(eventType, this, genericEvent)!; + var specificInvoked = MiraEventManager.InvokeEvent(@event, eventType); + if (@event.IsCancelled) + { + var cancelEventType = CustomButtonManager.ButtonCancelledEventTypes[GetType()]; + var cancelEvent = (MiraEvent)Activator.CreateInstance(cancelEventType, this)!; + MiraEventManager.InvokeEvent(cancelEvent, cancelEventType); + } + + if (specificInvoked) + { + if (!@event.IsCancelled) { - // Invoke the generic button click event. - var genericEvent = new MiraButtonClickEvent(this); - MiraEventManager.InvokeEvent(genericEvent); - if (genericEvent.IsCancelled) - { - MiraEventManager.InvokeEvent(new MiraButtonCancelledEvent(this)); - } - - // Invoke the button click event for specific button. - var eventType = CustomButtonManager.ButtonEventTypes[GetType()]; - var @event = (MiraCancelableEvent)Activator.CreateInstance(eventType, this, genericEvent)!; - var specificInvoked = MiraEventManager.InvokeEvent(@event, eventType); - if (@event.IsCancelled) - { - var cancelEventType = CustomButtonManager.ButtonCancelledEventTypes[GetType()]; - var cancelEvent = (MiraEvent)Activator.CreateInstance(cancelEventType, this)!; - MiraEventManager.InvokeEvent(cancelEvent, cancelEventType); - } - - if (specificInvoked) - { - if (!@event.IsCancelled) - { - ClickHandler(); - } - } - else - { - if (!genericEvent.IsCancelled) - { - ClickHandler(); - } - } + ClickHandler(); } - }); + } + else + { + if (!genericEvent.IsCancelled) + { + ClickHandler(); + } + } + }); - KeybindIcon = - Helpers.CreateKeybindIcon( - Button.gameObject, - Keybind.CurrentKey, - new Vector3(0.4f, 0.45f, -9f) - ); - KeybindText = KeybindIcon.transform.GetChild(0).GetComponent(); - HudManagerPatches.ModdedKeybindIcons.Add(KeybindText); - Button.usesRemainingSprite.transform.localPosition = new(-0.341f, 0.45f, -0.1f); - } + KeybindIcon = + Helpers.CreateKeybindIcon( + Button.gameObject, + Keybind.CurrentKey, + new Vector3(0.4f, 0.45f, -9f) + ); + KeybindText = KeybindIcon.transform.GetChild(0).GetComponent(); + HudManagerPatches.ModdedKeybindIcons.Add(KeybindText); + Button.usesRemainingSprite.transform.localPosition = new(-0.341f, 0.45f, -0.1f); } /// @@ -298,6 +294,8 @@ public abstract class CustomActionButton case ButtonLocation.BottomRight: Button.transform.SetParent(HudManagerPatches.BottomRight); break; + default: + throw new ArgumentOutOfRangeException(nameof(location), location, null); } } diff --git a/MiraAPI/Hud/CustomButtonManager.cs b/MiraAPI/Hud/CustomButtonManager.cs index b1e0977..8f8f2e9 100644 --- a/MiraAPI/Hud/CustomButtonManager.cs +++ b/MiraAPI/Hud/CustomButtonManager.cs @@ -21,14 +21,12 @@ public static class CustomButtonManager /// /// Gets a list of all registered button-specific s. /// - public static ReadOnlyDictionary EventTypes { get; internal set; } = new(new Dictionary - { }); + public static ReadOnlyDictionary EventTypes { get; internal set; } = new(new Dictionary()); /// /// Gets a list of all registered button-specific s. /// - public static ReadOnlyDictionary CancelledEventTypes { get; internal set; } = new(new Dictionary - { }); + public static ReadOnlyDictionary CancelledEventTypes { get; internal set; } = new(new Dictionary()); internal static readonly List CustomButtons = []; internal static readonly Dictionary ButtonEventTypes = []; diff --git a/MiraAPI/Hud/CustomPlayerMenu.cs b/MiraAPI/Hud/CustomPlayerMenu.cs index be5714c..435ce12 100644 --- a/MiraAPI/Hud/CustomPlayerMenu.cs +++ b/MiraAPI/Hud/CustomPlayerMenu.cs @@ -77,7 +77,7 @@ public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr) /// public override void Begin(PlayerTask task) { - throw new NotImplementedException("Use the other Begin method."); + throw new NotSupportedException("Use the other Begin method."); } /// diff --git a/MiraAPI/Hud/MiraHudHelper.cs b/MiraAPI/Hud/MiraHudHelper.cs index 5f3ed20..bf71ce6 100644 --- a/MiraAPI/Hud/MiraHudHelper.cs +++ b/MiraAPI/Hud/MiraHudHelper.cs @@ -31,8 +31,8 @@ internal sealed class MiraHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) public static SpriteRenderer SubmergedFloorButtonRenderer; public static SpriteRenderer SubmergedFloorButtonRendererHover; - public static readonly Vector3 BelowOptionPos = new(0.435f, 1.25f, 0f); - public static readonly Vector3 FullTopPos = new(0.435f, 0.475f, 0f); + private static readonly Vector3 BelowOptionPos = new(0.435f, 1.25f, 0f); + private static readonly Vector3 FullTopPos = new(0.435f, 0.475f, 0f); private void Awake() { @@ -71,7 +71,7 @@ internal sealed class MiraHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) UpdateSubmergedButtons(instance); } - public static void CreateUiRow(HudManager instance) + private static void CreateUiRow(HudManager instance) { if (!UiTopRight) { @@ -146,7 +146,7 @@ internal sealed class MiraHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) } } - public static void UpdateSubmergedButtons(HudManager instance) + private static void UpdateSubmergedButtons(HudManager instance) { if (!ModCompatibility.IsSubmerged() || SubmergedFloorButton || !ExtraUiTopRight || SubmergedFloorButton || !ExtraUiTopRight) return; @@ -166,7 +166,7 @@ internal sealed class MiraHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) MiraApiSettings.SetUpButtonPositions(); } - public static void AdjustModifierTab() + private static void AdjustModifierTab() { if (ModifierDisplayObject || !UiTopRight || !ExtraUiTopRight || !ModifierDisplayComponent.Instance) return; @@ -185,7 +185,7 @@ internal sealed class MiraHudHelper(nint cppPtr) : MonoBehaviour(cppPtr) MiraApiSettings.SetUpButtonPositions(); } - public static void CreateNewUiRow(HudManager instance) + private static void CreateNewUiRow(HudManager instance) { if (ExtraUiTopRight || !UiTopRight) return; diff --git a/MiraAPI/Keybinds/BaseKeybind.cs b/MiraAPI/Keybinds/BaseKeybind.cs index a8b9668..95de3c8 100644 --- a/MiraAPI/Keybinds/BaseKeybind.cs +++ b/MiraAPI/Keybinds/BaseKeybind.cs @@ -70,8 +70,8 @@ public class BaseKeybind /// The to remove. public void RemoveOnActivate(Action action) { -#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8601 // Possible null reference assignment (Justification: Shut up.) Handler -= action; -#pragma warning restore CS8601 // Possible null reference assignment. +#pragma warning restore CS8601 // Possible null reference assignment } } diff --git a/MiraAPI/Keybinds/KeybindUtils.cs b/MiraAPI/Keybinds/KeybindUtils.cs index 1ce7f58..e14bf77 100644 --- a/MiraAPI/Keybinds/KeybindUtils.cs +++ b/MiraAPI/Keybinds/KeybindUtils.cs @@ -64,10 +64,10 @@ public static class KeybindUtils /// public static KeyboardKeyCode FindAvailableKey(KeyboardKeyCode exclude) { - foreach (KeyboardKeyCode key in Enum.GetValues()) + foreach (var key in Enum.GetValues()) { if (key == exclude) continue; - bool used = KeybindManager.Keybinds.Exists(e => e.DefaultKey == key); + var used = KeybindManager.Keybinds.Exists(e => e.DefaultKey == key); if (!used) return key; } return KeyboardKeyCode.None; diff --git a/MiraAPI/LocalSettings/Attributes/LocalSettingAttribute.cs b/MiraAPI/LocalSettings/Attributes/LocalSettingAttribute.cs index c582f13..2d6b943 100644 --- a/MiraAPI/LocalSettings/Attributes/LocalSettingAttribute.cs +++ b/MiraAPI/LocalSettings/Attributes/LocalSettingAttribute.cs @@ -10,10 +10,10 @@ namespace MiraAPI.LocalSettings.Attributes; /// The description of the setting. Defaults to entry description. [AttributeUsage(AttributeTargets.Property)] public abstract class LocalSettingAttribute( -#pragma warning disable CS9113 // Parameter is unread. +#pragma warning disable CS9113 // Parameter is unread (Justification: No idea why they exist, but they probably do for a reason unknown to me.) string? name = null, string? description = null -#pragma warning restore CS9113 // Parameter is unread. +#pragma warning restore CS9113 // Parameter is unread ) : Attribute { /// diff --git a/MiraAPI/LocalSettings/LocalSettingsButton.cs b/MiraAPI/LocalSettings/LocalSettingsButton.cs index f89329e..44df186 100644 --- a/MiraAPI/LocalSettings/LocalSettingsButton.cs +++ b/MiraAPI/LocalSettings/LocalSettingsButton.cs @@ -29,7 +29,7 @@ public class LocalSettingsButton(string text, Action onClick) /// public LocalSettingsTab? Tab { get; internal set; } - private TextMeshPro _btnText { get; set; } + private TextMeshPro _btnText; internal GameObject CreateButton(ToggleButtonBehaviour toggle, Transform parent, ref float offset, ref int order, bool last) { diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs index 74d88ef..ee60941 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs @@ -41,9 +41,8 @@ public class LocalEnumSetting( .Cast() .Select(x => x.ToDisplayString())]; - private SpriteRenderer _highlight { get; set; } - - private TextMeshPro _btnText { get; set; } + private SpriteRenderer _highlight; + private TextMeshPro _btnText; /// public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last) @@ -60,7 +59,7 @@ public class LocalEnumSetting( var highlight = button.transform.FindChild("ButtonHighlight")?.GetComponent(); if (highlight != null) { - _highlight = highlight; + this._highlight = highlight; highlight.color = Tab!.TabAppearance.EnumHoverColor; highlight.gameObject.SetActive(false); } @@ -85,7 +84,7 @@ public class LocalEnumSetting( button.OnClick.AddListener((UnityAction)(() => { - int value = GetValue(); + var value = GetValue(); value++; if (value >= Values.Length) { diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalNumberSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalNumberSetting.cs index 2ef007a..326e519 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalNumberSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalNumberSetting.cs @@ -51,9 +51,8 @@ public class LocalNumberSetting( /// public MiraNumberSuffixes SuffixType { get; } = suffixType ?? MiraNumberSuffixes.None; - private SpriteRenderer _highlight { get; set; } - - private TextMeshPro _btnText { get; set; } + private SpriteRenderer _highlight; + private TextMeshPro _btnText; /// public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last) @@ -95,7 +94,7 @@ public class LocalNumberSetting( button.OnClick.AddListener((UnityAction)(() => { - float value = GetValue(); + var value = GetValue(); value += Increment; if (value > NumberRange.max) { diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs index dc4df36..a84b95b 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs @@ -58,7 +58,7 @@ public class LocalSliderSetting( /// public MiraNumberSuffixes SuffixType { get; } = suffixType ?? MiraNumberSuffixes.None; - private SlideBar _slider { get; set; } + private SlideBar _slider; /// public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last) diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalToggleSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalToggleSetting.cs index db47e82..daed9be 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalToggleSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalToggleSetting.cs @@ -23,7 +23,7 @@ public class LocalToggleSetting( string? description = null ) : LocalSettingBase(tab, configEntry, name, description) { - private ToggleButtonBehaviour _toggle { get; set; } + private ToggleButtonBehaviour _toggle; /// public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last) diff --git a/MiraAPI/MeetingAbilities/MeetingAbilityBehaviour.cs b/MiraAPI/MeetingAbilities/MeetingAbilityBehaviour.cs index f26e0df..7959701 100644 --- a/MiraAPI/MeetingAbilities/MeetingAbilityBehaviour.cs +++ b/MiraAPI/MeetingAbilities/MeetingAbilityBehaviour.cs @@ -1,6 +1,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using Il2CppInterop.Runtime.Attributes; +using MiraAPI.Utilities; using Reactor.Utilities.Attributes; using Reactor.Utilities.Extensions; using TMPro; @@ -31,12 +32,12 @@ public class MeetingAbilityBehaviour : MonoBehaviour public PassiveButton Button { get; internal set; } /// - /// Gets he parent . + /// Gets the parent . /// public PlayerVoteArea VoteArea { get; internal set; } /// - /// Gets he button's component. + /// Gets the button's component. /// public SpriteRenderer Renderer { get; internal set; } @@ -102,13 +103,13 @@ public class MeetingAbilityBehaviour : MonoBehaviour if (!_init) return; if (_button.Timer < 0.01f) { - Renderer.material.SetFloat("_Desat", 0.0f); + Renderer.material.SetFloat(ShaderID.Desat, 0.0f); CooldownText.text = string.Empty; UsesText.text = _button.LimitedUses ? _button.UsesLeft.ToString(CultureInfo.InvariantCulture) : string.Empty; } else { - Renderer.material.SetFloat("_Desat", 0.5f); + Renderer.material.SetFloat(ShaderID.Desat, 0.5f); CooldownText.text = _button.Timer.ToString(_button.CooldownTimerFormatString, NumberFormatInfo.InvariantInfo); UsesText.text = string.Empty; } @@ -122,8 +123,8 @@ public class MeetingAbilityBehaviour : MonoBehaviour /// The maximum timer. public void SetFillUp(float timer, float maxTimer) { - float percentCool = Mathf.Clamp(timer / maxTimer, 0.001f, 1f); + var percentCool = Mathf.Clamp(timer / maxTimer, 0.001f, 1f); if (percentCool <= 0) percentCool = 1f; - Renderer.material.SetFloat("_Percent", percentCool); + Renderer.material.SetFloat(ShaderID.Percent, percentCool); } } diff --git a/MiraAPI/MiraAPI.csproj b/MiraAPI/MiraAPI.csproj index 22e128a..f2cf065 100644 --- a/MiraAPI/MiraAPI.csproj +++ b/MiraAPI/MiraAPI.csproj @@ -16,5 +16,11 @@ + + + + + + diff --git a/MiraAPI/MiraApiPlugin.cs b/MiraAPI/MiraApiPlugin.cs index 60a2e99..993744e 100644 --- a/MiraAPI/MiraApiPlugin.cs +++ b/MiraAPI/MiraApiPlugin.cs @@ -25,6 +25,7 @@ namespace MiraAPI; [BepInProcess("Among Us.exe")] [BepInDependency(ReactorPlugin.Id)] [ReactorModFlags(ModFlags.RequireOnAllClients)] +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by BepInEx.) public partial class MiraApiPlugin : BasePlugin, IMiraPlugin { /// diff --git a/MiraAPI/MiraApiSettings.cs b/MiraAPI/MiraApiSettings.cs index ef776f0..408fc11 100644 --- a/MiraAPI/MiraApiSettings.cs +++ b/MiraAPI/MiraApiSettings.cs @@ -154,32 +154,30 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config) var extraAspect = MiraHudHelper.ExtraUiAspectPos; var extraGrid = MiraHudHelper.ExtraUiGrid; var extraUi = MiraHudHelper.ExtraUiTopRight; - if (extraUi && extraAspect && extraGrid) + if (!extraUi || !extraAspect || !extraGrid) return; + extraAspect.DistanceFromEdge = new Vector3(0.435f * scaleFactor, 1.25f * scaleFactor, 0f); + + foreach (var button in extraUi.GetAllChildren()) { - extraAspect.DistanceFromEdge = new Vector3(0.435f * scaleFactor, 1.25f * scaleFactor, 0f); - - foreach (var button in extraUi.GetAllChildren()) + if (button.gameObject == null) { - if (button.gameObject == null) - { - continue; - } - if (button.transform.name.Contains("Modifiers")) - { - button.gameObject.transform.localScale = new Vector3(0.65f * scaleFactor, 0.65f * scaleFactor, 1); - continue; - } - - button.gameObject.transform.localScale = actualScale; + continue; + } + if (button.transform.name.Contains("Modifiers")) + { + button.gameObject.transform.localScale = new Vector3(0.65f * scaleFactor, 0.65f * scaleFactor, 1); + continue; } - extraGrid.CellSize = new Vector2(alteredScale, alteredScale); - if (extraGrid.gameObject.transform.childCount != 0) - { - extraGrid.ArrangeChilds(); - } - extraAspect.AdjustPosition(); + button.gameObject.transform.localScale = actualScale; } + + extraGrid.CellSize = new Vector2(alteredScale, alteredScale); + if (extraGrid.gameObject.transform.childCount != 0) + { + extraGrid.ArrangeChilds(); + } + extraAspect.AdjustPosition(); } /// diff --git a/MiraAPI/ModCompatibility.cs b/MiraAPI/ModCompatibility.cs index ed40be4..870c1fe 100644 --- a/MiraAPI/ModCompatibility.cs +++ b/MiraAPI/ModCompatibility.cs @@ -44,7 +44,7 @@ public static class ModCompatibility InitSubmerged(); } - internal static void InitSubmerged() + private static void InitSubmerged() { if (!IL2CPPChainloader.Instance.Plugins.TryGetValue(SubmergedId, out var plugin)) { diff --git a/MiraAPI/Modifiers/ModifierDisplay/ModifierDisplayComponent.cs b/MiraAPI/Modifiers/ModifierDisplay/ModifierDisplayComponent.cs index 9af6b53..6f6f33a 100644 --- a/MiraAPI/Modifiers/ModifierDisplay/ModifierDisplayComponent.cs +++ b/MiraAPI/Modifiers/ModifierDisplay/ModifierDisplayComponent.cs @@ -99,15 +99,13 @@ public class ModifierDisplayComponent(nint cppPtr) : MonoBehaviour(cppPtr) IsOpen = false; _children.gameObject.SetActive(false); - if (LocalSettingsTabSingleton.Instance.ModifiersHudLeftSide.Value) - { - var aspect = GetComponent(); - _toggleButton.transform.localPosition = new Vector3(-1f, 2.7f, 0f); - _children.transform.localPosition = new Vector3(-0.2f, -0.05f, 0f); - aspect.Alignment = AspectPosition.EdgeAlignments.LeftTop; - aspect.DistanceFromEdge = new Vector3(1.8f, 2.55f, -20f); - aspect.AdjustPosition(); - } + if (!LocalSettingsTabSingleton.Instance.ModifiersHudLeftSide.Value) return; + var aspect = GetComponent(); + _toggleButton.transform.localPosition = new Vector3(-1f, 2.7f, 0f); + _children.transform.localPosition = new Vector3(-0.2f, -0.05f, 0f); + aspect.Alignment = AspectPosition.EdgeAlignments.LeftTop; + aspect.DistanceFromEdge = new Vector3(1.8f, 2.55f, -20f); + aspect.AdjustPosition(); } /// diff --git a/MiraAPI/Modifiers/ModifierUtils.cs b/MiraAPI/Modifiers/ModifierUtils.cs index f536489..caee948 100644 --- a/MiraAPI/Modifiers/ModifierUtils.cs +++ b/MiraAPI/Modifiers/ModifierUtils.cs @@ -17,7 +17,7 @@ public static class ModifierUtils /// An of s. public static IEnumerable GetActiveModifiers(Func? predicate = null) where T : BaseModifier { - return PlayerControl.AllPlayerControls.ToArray().SelectMany(x => x.GetModifiers(predicate)).OfType(); + return PlayerControl.AllPlayerControls.ToArray().SelectMany(x => x.GetModifiers(predicate)); } /// @@ -28,6 +28,6 @@ public static class ModifierUtils /// An of s with that . public static IEnumerable GetPlayersWithModifier(Func? predicate = null) where T : BaseModifier { - return PlayerControl.AllPlayerControls.ToArray().Where(x => x.HasModifier(predicate)); + return PlayerControl.AllPlayerControls.ToArray().Where(x => x.HasModifier(predicate)); } } diff --git a/MiraAPI/Networking/CustomGameOverRpc.cs b/MiraAPI/Networking/CustomGameOverRpc.cs index 6475d6a..42f4889 100644 --- a/MiraAPI/Networking/CustomGameOverRpc.cs +++ b/MiraAPI/Networking/CustomGameOverRpc.cs @@ -12,6 +12,7 @@ namespace MiraAPI.Networking; /// /// [RegisterCustomRpc((uint)MiraRpc.CustomGameOver)] +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) public class CustomGameOverRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc(plugin, id) { /// diff --git a/MiraAPI/Networking/Modifiers/AddModifierRpc.cs b/MiraAPI/Networking/Modifiers/AddModifierRpc.cs index dd225f2..399d436 100644 --- a/MiraAPI/Networking/Modifiers/AddModifierRpc.cs +++ b/MiraAPI/Networking/Modifiers/AddModifierRpc.cs @@ -13,6 +13,7 @@ namespace MiraAPI.Networking.Modifiers; /// Mira plugin. /// RPC ID. [RegisterCustomRpc((uint)MiraRpc.AddModifier)] +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by Reactor.) public class AddModifierRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc(plugin, id) { /// diff --git a/MiraAPI/Networking/SyncOptionsRpc.cs b/MiraAPI/Networking/SyncOptionsRpc.cs index 7b8cc04..e9f091d 100644 --- a/MiraAPI/Networking/SyncOptionsRpc.cs +++ b/MiraAPI/Networking/SyncOptionsRpc.cs @@ -7,6 +7,7 @@ namespace MiraAPI.Networking; // METHOD RPC DOESN'T WORK WITH THE ARRAYS AND STUFF SO THIS IS HOW WE WILL DO IT FOR NOW [RegisterCustomRpc((uint)MiraRpc.SyncGameOptions)] +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) internal sealed class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc(plugin, id) { public override RpcLocalHandling LocalHandling => RpcLocalHandling.None; diff --git a/MiraAPI/Networking/SyncRoleOptionsRpc.cs b/MiraAPI/Networking/SyncRoleOptionsRpc.cs index adfe537..1f965ab 100644 --- a/MiraAPI/Networking/SyncRoleOptionsRpc.cs +++ b/MiraAPI/Networking/SyncRoleOptionsRpc.cs @@ -6,6 +6,7 @@ using Reactor.Networking.Rpc; namespace MiraAPI.Networking; [RegisterCustomRpc((uint)MiraRpc.SyncRoleOptions)] +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) internal sealed class SyncRoleOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc(plugin, id) { public override RpcLocalHandling LocalHandling => RpcLocalHandling.None; diff --git a/MiraAPI/Patches/Accessibility/HudManagerFlashPatches.cs b/MiraAPI/Patches/Accessibility/HudManagerFlashPatches.cs index 2ea1bdd..1389f33 100644 --- a/MiraAPI/Patches/Accessibility/HudManagerFlashPatches.cs +++ b/MiraAPI/Patches/Accessibility/HudManagerFlashPatches.cs @@ -9,6 +9,7 @@ namespace MiraAPI.Patches.Accessibility; [HarmonyPatch] [SuppressMessage("Style", "IDE0074:Use compound assignment", Justification = "Using compound assignment bypasses Unity lifetime checks.")] +// ReSharper disable ConvertIfStatementToNullCoalescingAssignment (Justification: Read above.) public static class HudManagerFlashPatches { [HarmonyPatch(typeof(HudManager), nameof(HudManager.StartReactorFlash))] @@ -22,6 +23,7 @@ public static class HudManagerFlashPatches return false; } + [HarmonyPatch(typeof(HudManager), nameof(HudManager.StartOxyFlash))] [HarmonyPrefix] public static bool OxygenFlashPrefix(HudManager __instance) @@ -33,7 +35,8 @@ public static class HudManagerFlashPatches return false; } - public static IEnumerator CoReactorFlash() + + private static IEnumerator CoReactorFlash() { if (!HudManager.InstanceExists) { diff --git a/MiraAPI/Patches/Events/CanUsePatches.cs b/MiraAPI/Patches/Events/CanUsePatches.cs index 311697e..5ae7519 100644 --- a/MiraAPI/Patches/Events/CanUsePatches.cs +++ b/MiraAPI/Patches/Events/CanUsePatches.cs @@ -30,15 +30,11 @@ public static class CanUsePatches { canUse = couldUse = false; - IUsable usable = __instance.TryCast()!; - if (usable != null) - { - var @event = new PlayerCanUseEvent(usable); - MiraEventManager.InvokeEvent(@event); + var usable = __instance.TryCast(); + if (usable == null) return true; + var @event = new PlayerCanUseEvent(usable); + MiraEventManager.InvokeEvent(@event); - return !@event.IsCancelled; - } - - return true; + return !@event.IsCancelled; } } diff --git a/MiraAPI/Patches/Events/FreeplayRoundStartPatch.cs b/MiraAPI/Patches/Events/FreeplayRoundStartPatch.cs index 0cc6cb8..8427679 100644 --- a/MiraAPI/Patches/Events/FreeplayRoundStartPatch.cs +++ b/MiraAPI/Patches/Events/FreeplayRoundStartPatch.cs @@ -17,10 +17,8 @@ public static class FreeplayRoundStartPatch public static void Postfix(ref bool __result) { - if (!__result) - { - MeetingButtonManager.OnGameStart(); - MiraEventManager.InvokeEvent(new RoundStartEvent(true)); - } + if (__result) return; + MeetingButtonManager.OnGameStart(); + MiraEventManager.InvokeEvent(new RoundStartEvent(true)); } } diff --git a/MiraAPI/Patches/Events/VentEventPatches.cs b/MiraAPI/Patches/Events/VentEventPatches.cs index 9d4ad9f..8eee46f 100644 --- a/MiraAPI/Patches/Events/VentEventPatches.cs +++ b/MiraAPI/Patches/Events/VentEventPatches.cs @@ -11,7 +11,7 @@ namespace MiraAPI.Patches.Events; [HarmonyPatch] public static class VentEventPatches { - // necessary because Vent.Use is inlined in il2cpp. + // necessary because Vent.Use is inlined in IL2Cpp. private static bool _showButtons; [HarmonyPostfix] diff --git a/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs b/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs index be33948..27beb06 100644 --- a/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs +++ b/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs @@ -82,7 +82,7 @@ public static class TaskAdderPatches // folders.Add("Neutrals", neutralFolder); Folders.Add(ModifiersName, modifiersFolder); - int folderIdx = 2; + var folderIdx = 2; foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins) { var pluginFolders = new Dictionary(); @@ -131,11 +131,11 @@ public static class TaskAdderPatches return false; } - TaskFolder crewFolder = folders["Crewmates"] = + var crewFolder = folders["Crewmates"] = Object.Instantiate(__instance.RootFolderPrefab, __instance.transform); crewFolder.gameObject.SetActive(false); crewFolder.SetFolderColor(TaskFolder.FolderColor.Blue); - TaskFolder impFolder = folders["Impostors"] = + var impFolder = folders["Impostors"] = Object.Instantiate(__instance.RootFolderPrefab, __instance.transform); impFolder.gameObject.SetActive(false); impFolder.SetFolderColor(TaskFolder.FolderColor.Red); @@ -165,14 +165,15 @@ public static class TaskAdderPatches return false; } + // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract (Justification: Nullable annotations of reference types do not survive compilation.) if (taskList == null) { return false; } - foreach (NormalPlayerTask normalPlayerTask in taskList) + foreach (var normalPlayerTask in taskList) { - SystemTypes systemTypes = normalPlayerTask.StartAt; + var systemTypes = normalPlayerTask.StartAt; if (normalPlayerTask is DivertPowerTask task) { systemTypes = task.TargetSystem; @@ -252,7 +253,7 @@ public static class TaskAdderPatches .Any(x => x.FolderName == child.FolderName); } - // yes it might be crazy patching the entire method, but i tried so many other methods and only this works :cry: + // yes it might be crazy patching the entire method, but I tried so many other methods and only this works :cry: // true -chip [HarmonyPrefix] [HarmonyPatch(nameof(TaskAdderGame.ShowFolder))] @@ -273,12 +274,12 @@ public static class TaskAdderPatches __instance.ActiveItems.ToArray().Do(x => x.gameObject.DeepDestroy(false)); __instance.ActiveItems.Clear(); - float num = 0f; - float num2 = 0f; - float num3 = 0f; + var num = 0f; + var num2 = 0f; + var num3 = 0f; foreach (var t in taskFolder.SubFolders) { - TaskFolder taskFolder2 = Object.Instantiate(t, __instance.TaskParent); + var taskFolder2 = Object.Instantiate(t, __instance.TaskParent); taskFolder2.gameObject.SetActive(true); taskFolder2.Parent = __instance; taskFolder2.transform.localPosition = new Vector3(num, num2, 0f); @@ -305,7 +306,7 @@ public static class TaskAdderPatches .ToArray(); foreach (var task in list) { - TaskAddButton taskAddButton = Object.Instantiate(__instance.TaskPrefab); + var taskAddButton = Object.Instantiate(__instance.TaskPrefab); taskAddButton.MyTask = task; switch (task.TaskType) { @@ -342,7 +343,7 @@ public static class TaskAdderPatches .ToArray(); foreach (var role in roleChildren) { - TaskAddButton roleAddButton = Object.Instantiate(__instance.RoleButton); + var roleAddButton = Object.Instantiate(__instance.RoleButton); roleAddButton.SafePositionWorld = __instance.SafePositionWorld; roleAddButton.Text.text = role.GetRoleName(); roleAddButton.Role = role; diff --git a/MiraAPI/Patches/GameModes/.editorconfig b/MiraAPI/Patches/GameModes/.editorconfig deleted file mode 100644 index 8e05860..0000000 --- a/MiraAPI/Patches/GameModes/.editorconfig +++ /dev/null @@ -1,4 +0,0 @@ -[*.cs] - -# S125: Sections of code should not be commented out -dotnet_diagnostic.S125.severity = none \ No newline at end of file diff --git a/MiraAPI/Patches/GameModes/BodyTypePatch.cs b/MiraAPI/Patches/GameModes/BodyTypePatch.cs index 2aede92..afd4cbc 100644 --- a/MiraAPI/Patches/GameModes/BodyTypePatch.cs +++ b/MiraAPI/Patches/GameModes/BodyTypePatch.cs @@ -9,12 +9,8 @@ internal static class BodyTypePatch { public static bool Prefix(IntroCutscene __instance, ref Il2CppSystem.Collections.IEnumerator __result) { - if (CustomGameModeManager.ActiveMode?.ShowGameModeIntroCutscene == true) - { - __result = CustomGameModeManager.ActiveMode.IntroCutscene(__instance).WrapToIl2Cpp(); - return false; - } - - return true; + if (CustomGameModeManager.ActiveMode?.ShowGameModeIntroCutscene != true) return true; + __result = CustomGameModeManager.ActiveMode.IntroCutscene(__instance).WrapToIl2Cpp(); + return false; } } diff --git a/MiraAPI/Patches/GameModes/ImpostorTargetPatch.cs b/MiraAPI/Patches/GameModes/ImpostorTargetPatch.cs index de9bbf1..10db226 100644 --- a/MiraAPI/Patches/GameModes/ImpostorTargetPatch.cs +++ b/MiraAPI/Patches/GameModes/ImpostorTargetPatch.cs @@ -4,7 +4,7 @@ using MiraAPI.GameModes; namespace MiraAPI.Patches.GameModes; /// -/// Allow Impostors to kill each other if can kill is enabled in gamemode or friendly fire is toggled on. +/// Allow Impostors to kill each other if CanKill is enabled in gamemode or friendly fire is toggled on. /// [HarmonyPatch(typeof(ImpostorRole), "IsValidTarget")] internal static class ImpostorTargetPatch diff --git a/MiraAPI/Patches/GameModes/IntroCutscenePatch.cs b/MiraAPI/Patches/GameModes/IntroCutscenePatch.cs index 5701014..641c642 100644 --- a/MiraAPI/Patches/GameModes/IntroCutscenePatch.cs +++ b/MiraAPI/Patches/GameModes/IntroCutscenePatch.cs @@ -9,12 +9,8 @@ internal static class IntroCutscenePatch { public static bool Prefix(IntroCutscene __instance, ref Il2CppSystem.Collections.IEnumerator __result) { - if (CustomGameModeManager.ActiveMode?.ShowGameModeIntroCutscene == true) - { - __result = CustomGameModeManager.ActiveMode.IntroCutscene(__instance).WrapToIl2Cpp(); - return false; - } - - return true; + if (CustomGameModeManager.ActiveMode?.ShowGameModeIntroCutscene != true) return true; + __result = CustomGameModeManager.ActiveMode.IntroCutscene(__instance).WrapToIl2Cpp(); + return false; } } diff --git a/MiraAPI/Patches/GameModes/MapBehaviourPatch.cs b/MiraAPI/Patches/GameModes/MapBehaviourPatch.cs index 06ea282..b5ddb46 100644 --- a/MiraAPI/Patches/GameModes/MapBehaviourPatch.cs +++ b/MiraAPI/Patches/GameModes/MapBehaviourPatch.cs @@ -10,12 +10,8 @@ internal static class MapBehaviourPatch public static bool ShowSabotagePatch(MapBehaviour __instance) { var shouldShow = CustomGameModeManager.ActiveMode?.ShouldShowSabotageMap(__instance); - if (shouldShow.HasValue && !shouldShow.Value) - { - __instance.ShowNormalMap(); - return false; - } - - return true; + if (!shouldShow.HasValue || shouldShow.Value) return true; + __instance.ShowNormalMap(); + return false; } } diff --git a/MiraAPI/Patches/GameModes/ProgressTrackerPatch.cs b/MiraAPI/Patches/GameModes/ProgressTrackerPatch.cs index 340f1f7..6c172ba 100644 --- a/MiraAPI/Patches/GameModes/ProgressTrackerPatch.cs +++ b/MiraAPI/Patches/GameModes/ProgressTrackerPatch.cs @@ -8,11 +8,8 @@ internal static class ProgressTrackerPatch { public static bool Prefix(ProgressTracker __instance) { - if (CustomGameModeManager.ActiveMode != null && !CustomGameModeManager.ActiveMode.ShowTaskBar) - { - __instance.gameObject.SetActive(false); - return false; - } - return true; + if (CustomGameModeManager.ActiveMode == null || CustomGameModeManager.ActiveMode.ShowTaskBar) return true; + __instance.gameObject.SetActive(false); + return false; } } diff --git a/MiraAPI/Patches/GameModes/TaskPanelPatch.cs b/MiraAPI/Patches/GameModes/TaskPanelPatch.cs index 17ae848..c7d8589 100644 --- a/MiraAPI/Patches/GameModes/TaskPanelPatch.cs +++ b/MiraAPI/Patches/GameModes/TaskPanelPatch.cs @@ -8,11 +8,8 @@ internal static class TaskPanelPatch { public static bool Prefix(TaskPanelBehaviour __instance) { - if (__instance != Roles.HudManagerPatches.RoleTab && CustomGameModeManager.ActiveMode != null) - { - CustomGameModeManager.ActiveMode.UpdateTaskPanel(__instance); - return false; - } - return true; + if (__instance == Roles.HudManagerPatches.RoleTab || CustomGameModeManager.ActiveMode == null) return true; + CustomGameModeManager.ActiveMode.UpdateTaskPanel(__instance); + return false; } } diff --git a/MiraAPI/Patches/HudManagerPatches.cs b/MiraAPI/Patches/HudManagerPatches.cs index f814847..44b77b9 100644 --- a/MiraAPI/Patches/HudManagerPatches.cs +++ b/MiraAPI/Patches/HudManagerPatches.cs @@ -87,34 +87,30 @@ public static class HudManagerPatches button.gameObject.SetActive(!button.isActiveAndEnabled); } - if (_storedButtonsParent) + if (!_storedButtonsParent) return; + foreach (var arrange in _storedButtonsParent.GetComponentsInChildren(true)) { - foreach (var arrange in _storedButtonsParent.GetComponentsInChildren(true)) + if (!arrange.gameObject || !arrange.transform) { - if (!arrange.gameObject || !arrange.transform) - { - continue; - } + continue; + } - if (arrange.gameObject.name.Contains("TopRight")) - { - continue; - } + if (arrange.gameObject.name.Contains("TopRight")) + { + continue; + } - arrange.gameObject.SetActive(!arrange.isActiveAndEnabled); - arrange.CellSize = new Vector2(scaleFactor, scaleFactor); - arrange.gameObject.SetActive(!arrange.isActiveAndEnabled); - if (arrange.isActiveAndEnabled && arrange.gameObject.transform.childCount != 0) - { - try - { - arrange.ArrangeChilds(); - } - catch - { - // Error($"Error arranging child objects in GridArrange: {e}"); - } - } + arrange.gameObject.SetActive(!arrange.isActiveAndEnabled); + arrange.CellSize = new Vector2(scaleFactor, scaleFactor); + arrange.gameObject.SetActive(!arrange.isActiveAndEnabled); + if (!arrange.isActiveAndEnabled || arrange.gameObject.transform.childCount == 0) continue; + try + { + arrange.ArrangeChilds(); + } + catch + { + // Error($"Error arranging child objects in GridArrange: {e}"); } } } diff --git a/MiraAPI/Patches/Keybinds/OptionsMenuBehaviourPatch.cs b/MiraAPI/Patches/Keybinds/OptionsMenuBehaviourPatch.cs index 75cf989..20fab5e 100644 --- a/MiraAPI/Patches/Keybinds/OptionsMenuBehaviourPatch.cs +++ b/MiraAPI/Patches/Keybinds/OptionsMenuBehaviourPatch.cs @@ -7,8 +7,8 @@ namespace MiraAPI.Patches.Keybinds; [HarmonyPatch(typeof(OptionsMenuBehaviour))] public static class OptionsMenuBehaviourPatch { - private static ButtonRolloverHandler? _remap_rollover; - private static SpriteRenderer? _remap_background; + private static ButtonRolloverHandler? _remapRollover; + private static SpriteRenderer? _remapBackground; private static bool Conflicts => KeybindManager.GetConflicts().Count > 0; @@ -16,11 +16,11 @@ public static class OptionsMenuBehaviourPatch [HarmonyPatch(nameof(OptionsMenuBehaviour.Open))] private static void OpenPostfix() { - _remap_rollover = GameObject.Find("Remap Controls")?.GetComponent()!; + _remapRollover = GameObject.Find("Remap Controls")?.GetComponent()!; try { - _remap_background = _remap_rollover.transform.FindChild("Background").GetComponent(); - _remap_background.color = Conflicts ? Color.red : Color.white; + _remapBackground = _remapRollover.transform.FindChild("Background").GetComponent(); + _remapBackground.color = Conflicts ? Color.red : Color.white; } catch { @@ -32,17 +32,17 @@ public static class OptionsMenuBehaviourPatch [HarmonyPatch(nameof(OptionsMenuBehaviour.Update))] private static void UpdatePostfix() { - if (_remap_rollover == null) + if (_remapRollover == null) { return; } - if (_remap_background == null) + if (_remapBackground == null) { return; } - _remap_rollover.OutColor = Conflicts ? Color.red : Color.white; - _remap_rollover.UnselectedColor = Conflicts ? Color.red : Color.white; - _remap_rollover.OverColor = Conflicts ? new Color32(255, 55, 55, 255) : Palette.AcceptedGreen; + _remapRollover.OutColor = Conflicts ? Color.red : Color.white; + _remapRollover.UnselectedColor = Conflicts ? Color.red : Color.white; + _remapRollover.OverColor = Conflicts ? new Color32(255, 55, 55, 255) : Palette.AcceptedGreen; } } diff --git a/MiraAPI/Patches/LocalSettings/OptionsMenuPatches.cs b/MiraAPI/Patches/LocalSettings/OptionsMenuPatches.cs index 9e9eeb8..d986949 100644 --- a/MiraAPI/Patches/LocalSettings/OptionsMenuPatches.cs +++ b/MiraAPI/Patches/LocalSettings/OptionsMenuPatches.cs @@ -69,9 +69,9 @@ public static class OptionsMenuPatches currentPage = 1; TabButtons.Clear(); float yOffset = 0; - int i = 0; - int tabIdx = 0; - int page = 1; + var i = 0; + var tabIdx = 0; + var page = 1; LocalSettingsTab.TabGroups.Clear(); foreach (var settings in LocalSettingsManager.AvailableTabs) { diff --git a/MiraAPI/Patches/Menu/HatsTabPatches.cs b/MiraAPI/Patches/Menu/HatsTabPatches.cs index cb7b586..cffca31 100644 --- a/MiraAPI/Patches/Menu/HatsTabPatches.cs +++ b/MiraAPI/Patches/Menu/HatsTabPatches.cs @@ -107,7 +107,7 @@ public static class HatsTabPatches var groupNameText = __instance.GetComponentInChildren(false); var group = sortedHats.Where(x => x.Key == StoreNames[page]); - foreach ((string groupName, List hats) in group) + foreach (var (groupName, hats) in group) { var text = Object.Instantiate(groupNameText, __instance.scroller.Inner); text.enabled = true; @@ -120,12 +120,14 @@ public static class HatsTabPatches text.fontSizeMax = 5f; text.fontSizeMin = 0f; var xLerp = __instance.XRange.Lerp(0.5f); + // ReSharper disable once PossibleLossOfFraction (Justification: Intended.) var yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; text.transform.localPosition = new Vector3(xLerp, yLerp, -1f); hatIndex += 5; loadRoutine = Coroutines.Start(CoGenerateChips(__instance, hats)); } + // ReSharper disable once PossibleLossOfFraction (Justification: Intended.) __instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIndex + 1) / __instance.NumPerRow * __instance.YOffset) - 3f; __instance.currentHatIsEquipped = true; } @@ -141,6 +143,7 @@ public static class HatsTabPatches foreach (var hat in batch.OrderBy(HatManager.Instance.allHats.IndexOf)) { var hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); + // ReSharper disable once PossibleLossOfFraction (Justification: Intended.) var hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; GenerateColorChip(__instance, new Vector2(hatXPosition, hatYPosition), hat); hatIndex += 1; diff --git a/MiraAPI/Patches/Menu/NameplatesTabPatches.cs b/MiraAPI/Patches/Menu/NameplatesTabPatches.cs index 62cd441..333309a 100644 --- a/MiraAPI/Patches/Menu/NameplatesTabPatches.cs +++ b/MiraAPI/Patches/Menu/NameplatesTabPatches.cs @@ -88,7 +88,7 @@ public static class NameplatesTabPatches var groupNameText = __instance.GetComponentInChildren(false); - int hatIndex = 0; + var hatIndex = 0; var (groupName, nameplates) = SortedNameplates.ToArray()[page]; var text = Object.Instantiate(groupNameText, __instance.scroller.Inner); @@ -101,15 +101,16 @@ public static class NameplatesTabPatches text.fontSize = 5f; text.fontSizeMax = 5f; text.fontSizeMin = 0f; - float xLerp = __instance.XRange.Lerp(0.5f); - float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; + var xLerp = __instance.XRange.Lerp(0.5f); + var yLerp = __instance.YStart - __instance.YOffset; text.transform.localPosition = new Vector3(xLerp, yLerp, -1f); hatIndex += 2; foreach (var visor in nameplates.OrderBy(HatManager.Instance.allNamePlates.IndexOf)) { - float hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); - float hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; + var hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); + // ReSharper disable once PossibleLossOfFraction (Justification: Intended.) + var hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; GenerateColorChip(__instance, new Vector2(hatXPosition, hatYPosition), visor); hatIndex += 1; } @@ -139,14 +140,16 @@ public static class NameplatesTabPatches colorChip.Button.ClickMask = __instance.scroller.Hitbox; colorChip.ProductId = namePlate.ProdId; - var x = (NamePlateViewData viewData) => - { - colorChip.transform.GetChild(1).GetComponent().sprite = viewData?.Image; - // (colorChip as NameplateChip).image.sprite = viewData?.Image; - }; - __instance.StartCoroutine(AddressableAssetExtensions.CoLoadAssetAsync(__instance, namePlate.GetAssetReference(), x)); + __instance.StartCoroutine(__instance.CoLoadAssetAsync(namePlate.GetAssetReference(), (Action?)LoadNameplate)); colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f); colorChip.Tag = namePlate; __instance.ColorChips.Add(colorChip); + return; + + void LoadNameplate(NamePlateViewData viewData) + { + colorChip.transform.GetChild(1).GetComponent().sprite = viewData.Image; + // (colorChip as NameplateChip).image.sprite = viewData?.Image; + } } } diff --git a/MiraAPI/Patches/Menu/SkinsTabPatches.cs b/MiraAPI/Patches/Menu/SkinsTabPatches.cs index 5bbae0c..1825c1c 100644 --- a/MiraAPI/Patches/Menu/SkinsTabPatches.cs +++ b/MiraAPI/Patches/Menu/SkinsTabPatches.cs @@ -89,7 +89,7 @@ public static class SkinsTabPatches var groupNameText = __instance.GetComponentInChildren(false); - int hatIndex = 0; + var hatIndex = 0; var (groupName, skins) = sortedSkins.ToArray()[page]; var text = Object.Instantiate(groupNameText, __instance.scroller.Inner); @@ -102,15 +102,16 @@ public static class SkinsTabPatches text.fontSize = 5f; text.fontSizeMax = 5f; text.fontSizeMin = 0f; - float xLerp = __instance.XRange.Lerp(0.5f); - float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; + var xLerp = __instance.XRange.Lerp(0.5f); + var yLerp = __instance.YStart - __instance.YOffset; text.transform.localPosition = new Vector3(xLerp, yLerp, -1f); hatIndex += 5; foreach (var skin in skins.OrderBy(HatManager.Instance.allSkins.IndexOf)) { - float hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); - float hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; + var hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); + // ReSharper disable once PossibleLossOfFraction (Justification: Intended.) + var hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; GenerateColorChip(__instance, new Vector2(hatXPosition, hatYPosition), skin); hatIndex += 1; } diff --git a/MiraAPI/Patches/Menu/VisorsTabPatches.cs b/MiraAPI/Patches/Menu/VisorsTabPatches.cs index 65aac7b..fa208de 100644 --- a/MiraAPI/Patches/Menu/VisorsTabPatches.cs +++ b/MiraAPI/Patches/Menu/VisorsTabPatches.cs @@ -87,7 +87,7 @@ public static class VisorsTabPatches var groupNameText = __instance.GetComponentInChildren(false); - int hatIndex = 0; + var hatIndex = 0; var (groupName, visors) = SortedVisors.ToArray()[page]; var text = Object.Instantiate(groupNameText, __instance.scroller.Inner); @@ -100,15 +100,16 @@ public static class VisorsTabPatches text.fontSize = 5f; text.fontSizeMax = 5f; text.fontSizeMin = 0f; - float xLerp = __instance.XRange.Lerp(0.5f); - float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; + var xLerp = __instance.XRange.Lerp(0.5f); + var yLerp = __instance.YStart - __instance.YOffset; text.transform.localPosition = new Vector3(xLerp, yLerp, -1f); hatIndex += 5; foreach (var visor in visors.OrderBy(HatManager.Instance.allVisors.IndexOf)) { - float hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); - float hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; + var hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); + // ReSharper disable once PossibleLossOfFraction (Justification: Intended.) + var hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; GenerateColorChip(__instance, new Vector2(hatXPosition, hatYPosition), visor); hatIndex += 1; } diff --git a/MiraAPI/Patches/MinigameBeginErrorPatch.cs b/MiraAPI/Patches/MinigameBeginErrorPatch.cs index da7de72..71695ff 100644 --- a/MiraAPI/Patches/MinigameBeginErrorPatch.cs +++ b/MiraAPI/Patches/MinigameBeginErrorPatch.cs @@ -8,12 +8,12 @@ namespace MiraAPI.Patches; [HarmonyPatch] public static class MinigameBeginErrorPatch { - private static readonly Logger _logger = new(Logger.Category.Gameplay, "Minigame"); + private static readonly Logger Logger = new(Logger.Category.Gameplay, "Minigame"); [HarmonyPatch(typeof(Minigame), nameof(Minigame.Begin))] [HarmonyPrefix] public static void Prefix(Minigame __instance) { - __instance.logger ??= _logger; + __instance.logger ??= Logger; } } diff --git a/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs b/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs index 4172758..aee94ab 100644 --- a/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs +++ b/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs @@ -25,12 +25,12 @@ namespace MiraAPI.Patches.Options; [HarmonyPatch(typeof(GameOptionsMenu))] internal static class GameOptionsMenuPatch { - private static readonly List _vanillaHeaders = new(); - private static readonly List _vanillaOptions = new(); - private static readonly List _mainOptions = new(); - private static readonly System.Collections.Generic.Dictionary> _gameModeGroups = []; - private static readonly System.Collections.Generic.Dictionary> _gameModeOptions = []; - private static readonly System.Collections.Generic.Dictionary> _gameModeHeaders = []; + private static readonly List VanillaHeaders = new(); + private static readonly List VanillaOptions = new(); + private static readonly List MainOptions = new(); + private static readonly System.Collections.Generic.Dictionary> GameModeGroups = []; + private static readonly System.Collections.Generic.Dictionary> GameModeOptions = []; + private static readonly System.Collections.Generic.Dictionary> GameModeHeaders = []; private static TextMeshPro _gamemodeDescription = null!; private static SpriteRenderer _modIcon = null!; @@ -39,7 +39,7 @@ internal static class GameOptionsMenuPatch // ReSharper disable once InconsistentNaming public static bool InitPatch(GameOptionsMenu __instance) { - __instance.Children ??= new Il2CppSystem.Collections.Generic.List(); + __instance.Children ??= new List(); __instance.Children.Clear(); if (MenuState.Instance.CurrentModIdx == 0) @@ -81,9 +81,9 @@ internal static class GameOptionsMenuPatch internal static void ToggleGamemodeOptions(AbstractGameMode gameMode, GameOptionsMenu instance) { - float num = -1.217f; + var num = -1.217f; instance.Children.Clear(); - foreach (var opt in _mainOptions) + foreach (var opt in MainOptions) { instance.Children.Add(opt); } @@ -117,12 +117,12 @@ internal static class GameOptionsMenuPatch _gamemodeDescription.text = MiraLocaleManager.Get(gameMode.Description); if (gameMode.ShowNormalGameSettings) { - foreach (var opt in _vanillaHeaders) + foreach (var opt in VanillaHeaders) { num -= 0.63f; opt.gameObject.SetActive(true); } - foreach (var opt in _vanillaOptions) + foreach (var opt in VanillaOptions) { opt.gameObject.SetActive(true); instance.Children.Add(opt); @@ -131,29 +131,29 @@ internal static class GameOptionsMenuPatch } else { - foreach (var opt in _vanillaHeaders) + foreach (var opt in VanillaHeaders) { opt.gameObject.SetActive(false); } - foreach (var opt in _vanillaOptions) + foreach (var opt in VanillaOptions) { opt.gameObject.SetActive(false); } } - foreach (var pair in _gameModeGroups) + foreach (var pair in GameModeGroups) { if (pair.Value.Count != 0) { if (gameMode == pair.Key) { - foreach (var opt in _gameModeHeaders[gameMode]) + foreach (var opt in GameModeHeaders[gameMode]) { num -= 0.63f; opt.gameObject.SetActive(true); } - foreach (var opt in _gameModeOptions[gameMode]) + foreach (var opt in GameModeOptions[gameMode]) { opt.gameObject.SetActive(true); instance.Children.Add(opt); @@ -162,12 +162,12 @@ internal static class GameOptionsMenuPatch } else { - foreach (var opt in _gameModeHeaders[pair.Key]) + foreach (var opt in GameModeHeaders[pair.Key]) { opt.gameObject.SetActive(false); } - foreach (var opt in _gameModeOptions[pair.Key]) + foreach (var opt in GameModeOptions[pair.Key]) { opt.gameObject.SetActive(false); } @@ -188,15 +188,15 @@ internal static class GameOptionsMenuPatch private static void CreateSettings(GameOptionsMenu instance, Transform container) { - float num = 0.713f; - _vanillaHeaders.Clear(); - _vanillaOptions.Clear(); - _mainOptions.Clear(); - _gameModeHeaders.Clear(); - _gameModeOptions.Clear(); - _gameModeGroups.Clear(); + var num = 0.713f; + VanillaHeaders.Clear(); + VanillaOptions.Clear(); + MainOptions.Clear(); + GameModeHeaders.Clear(); + GameModeOptions.Clear(); + GameModeGroups.Clear(); - CategoryHeaderMasked gmCategory = Object.Instantiate(instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, container); + var gmCategory = Object.Instantiate(instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, container); gmCategory.SetHeader(GameModeOption.CustomName, 20); gmCategory.transform.localScale = Vector3.one * 0.63f; gmCategory.transform.localPosition = new Vector3(-0.903f, num, -2f); @@ -204,7 +204,7 @@ internal static class GameOptionsMenuPatch num -= 0.63f; GameModeOption.OptionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f); GameModeOption.OptionBehaviour.SetClickMask(instance.ButtonClickMask); - StringGameSetting setting = ScriptableObject.CreateInstance(); + var setting = ScriptableObject.CreateInstance(); setting.Type = OptionTypes.MultipleChoice; setting.Title = GameModeOption.GamemodeName; setting.Index = GameModeOption.LastValue; @@ -215,7 +215,7 @@ internal static class GameOptionsMenuPatch instance.Children.Add(GameModeOption.OptionBehaviour); foreach (var optionBehaviour in instance.Children) { - _mainOptions.Add(optionBehaviour); + MainOptions.Add(optionBehaviour); } for (var i = 1; i < GameModeOption.Values.Count; i++) { @@ -264,35 +264,25 @@ internal static class GameOptionsMenuPatch num -= 1.3f; additionalVanillaScrollNum = 0f; - foreach (RulesCategory rulesCategory in GameManager.Instance.GameSettingsList.AllCategories) + foreach (var rulesCategory in GameManager.Instance.GameSettingsList.AllCategories) { var categoryHeaderMasked = Object.Instantiate(instance.categoryHeaderOrigin, container); categoryHeaderMasked.SetHeader(rulesCategory.CategoryName, 20); categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f; categoryHeaderMasked.transform.localPosition = new Vector3(-0.903f, num, -2f); - _vanillaHeaders.Add(categoryHeaderMasked); + VanillaHeaders.Add(categoryHeaderMasked); num -= 0.63f; additionalVanillaScrollNum -= 0.63f; - foreach (BaseGameSetting baseGameSetting in rulesCategory.AllGameSettings) + foreach (var baseGameSetting in rulesCategory.AllGameSettings) { - OptionBehaviour? optionBehaviour = null; - - switch (baseGameSetting.Type) + OptionBehaviour? optionBehaviour = baseGameSetting.Type switch { - case OptionTypes.Checkbox: - optionBehaviour = Object.Instantiate(instance.checkboxOrigin, container); - break; - case OptionTypes.String: - optionBehaviour = Object.Instantiate(instance.stringOptionOrigin, container); - break; - case OptionTypes.Float: - case OptionTypes.Int: - optionBehaviour = Object.Instantiate(instance.numberOptionOrigin, container); - break; - case OptionTypes.Player: - optionBehaviour = Object.Instantiate(instance.playerOptionOrigin, container); - break; - } + OptionTypes.Checkbox => Object.Instantiate(instance.checkboxOrigin, container), + OptionTypes.String => Object.Instantiate(instance.stringOptionOrigin, container), + OptionTypes.Float or OptionTypes.Int => Object.Instantiate(instance.numberOptionOrigin, container), + OptionTypes.Player => Object.Instantiate(instance.playerOptionOrigin, container), + _ => null, + }; if (!optionBehaviour) continue; @@ -300,13 +290,13 @@ internal static class GameOptionsMenuPatch optionBehaviour!.transform.localPosition = new Vector3(0.952f, num, -2f); optionBehaviour.SetClickMask(instance.ButtonClickMask); optionBehaviour.SetUpFromData(baseGameSetting, 20); - _vanillaOptions.Add(optionBehaviour); + VanillaOptions.Add(optionBehaviour); num -= 0.45f; additionalVanillaScrollNum -= 0.45f; } } - foreach (var optionBehaviour in _vanillaOptions) + foreach (var optionBehaviour in VanillaOptions) { if (AmongUsClient.Instance && !AmongUsClient.Instance.AmHost) { @@ -324,8 +314,11 @@ internal static class GameOptionsMenuPatch { var filteredGroups = ModdedOptionsManager.GameModeOptionGroups - .Where(x => x.Key == mode.GetType()).Select(y => y.Value).SelectMany(y => y) ?? []; - _gameModeGroups.Add(mode, [.. filteredGroups]); + .Where(x => x.Key == mode.GetType()) + .Select(y => y.Value) + .SelectMany(y => y) + .ToList(); + GameModeGroups.Add(mode, [.. filteredGroups]); var optionBehaviours = new System.Collections.Generic.List(); var categoryHeaders = new System.Collections.Generic.List(); @@ -335,8 +328,8 @@ internal static class GameOptionsMenuPatch CreateGroup(instance, group, container, ref newNum, ref optionBehaviours, ref categoryHeaders); group.Ready = true; } - _gameModeHeaders.Add(mode, categoryHeaders); - _gameModeOptions.Add(mode, optionBehaviours); + GameModeHeaders.Add(mode, categoryHeaders); + GameModeOptions.Add(mode, optionBehaviours); } instance.ControllerSelectable.Clear(); @@ -366,7 +359,7 @@ internal static class GameOptionsMenuPatch // ReSharper disable once InconsistentNaming public static void UpdatePatch(GameOptionsMenu __instance) { - if (MenuState.Instance.CurrentModIdx == 0 && _gameModeGroups.Count <= 0) + if (MenuState.Instance.CurrentModIdx == 0 && GameModeGroups.Count <= 0) { return; } @@ -393,7 +386,7 @@ internal static class GameOptionsMenuPatch var filteredGroups = MenuState.Instance.CurrentMod.InternalOptionGroups .Where(x => (x.OptionableType == null || CustomGameModeManager.ActiveMode!.GetType().IsAssignableTo(x.OptionableType)) && - x.ParentMenu == MenuCategory.Game) ?? []; + x.ParentMenu == MenuCategory.Game); foreach (var group in filteredGroups) { @@ -566,7 +559,7 @@ internal static class GameOptionsMenuPatch num += additionalVanillaScrollNum; } - if (!_gameModeGroups.TryGetValue(mode, out var groups) || groups.Count == 0) + if (!GameModeGroups.TryGetValue(mode, out var groups) || groups.Count == 0) { return; } @@ -635,6 +628,7 @@ internal static class GameOptionsMenuPatch } _creationCoroutine = GameSettingMenu.Instance.StartCoroutine(CreateGroups().WrapToIl2Cpp()); + return; IEnumerator CreateGroups() { @@ -763,11 +757,16 @@ internal static class GameOptionsMenuPatch } menu.Children.Add(newOpt); - var resetBtn = new GameObject("ResetOption"); - resetBtn.transform.parent = newOpt.transform; - resetBtn.transform.localScale = new(.5f, .5f, 1); - resetBtn.layer = LayerMask.NameToLayer("UI"); - resetBtn.transform.localPosition = new Vector3(-3.1f, 0f, -2f); + var resetBtn = new GameObject("ResetOption") + { + transform = + { + parent = newOpt.transform, + localScale = new(.5f, .5f, 1), + localPosition = new Vector3(-3.1f, 0f, -2f), + }, + layer = LayerMask.NameToLayer("UI"), + }; var resetRend = resetBtn.AddComponent(); resetRend.sprite = MiraAssets.ResetButton.LoadAsset(); resetRend.maskInteraction = SpriteMaskInteraction.VisibleInsideMask; diff --git a/MiraAPI/Patches/Options/LobbyViewPanePatches.cs b/MiraAPI/Patches/Options/LobbyViewPanePatches.cs index 6456a78..2aaaad1 100644 --- a/MiraAPI/Patches/Options/LobbyViewPanePatches.cs +++ b/MiraAPI/Patches/Options/LobbyViewPanePatches.cs @@ -220,16 +220,16 @@ public static class LobbyViewPanePatches { if (SelectedModIdx == 0) { - float num = 0.95f; - float num2 = -6.53f; - CategoryHeaderMasked categoryHeaderMasked = + var num = 0.95f; + var num2 = -6.53f; + var categoryHeaderMasked = Object.Instantiate(__instance.categoryHeaderOrigin, __instance.settingsContainer); categoryHeaderMasked.SetHeader(StringNames.RoleQuotaLabel, 61); categoryHeaderMasked.transform.localScale = Vector3.one; categoryHeaderMasked.transform.localPosition = new Vector3(-9.77f, 1.26f, -2f); __instance.settingsInfo.Add(categoryHeaderMasked.gameObject); var list = new List(); - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { var categoryHeaderRoleVariant = Object.Instantiate(__instance.categoryHeaderRoleOrigin, __instance.settingsContainer); @@ -245,16 +245,16 @@ public static class LobbyViewPanePatches x.Role != RoleTypes.Impostor && ((i == 0 && x.TeamType is RoleTeamTypes.Crewmate) || (i == 1 && x.TeamType is RoleTeamTypes.Impostor)) && x.Role != RoleTypes.CrewmateGhost && x.Role != RoleTypes.ImpostorGhost).ToList(); - for (int j = 0; j < roles.Count; j++) + for (var j = 0; j < roles.Count; j++) { var roleBehaviour = roles[j]; - int chancePerGame = + var chancePerGame = GameOptionsManager.Instance.CurrentGameOptions.RoleOptions.GetChancePerGame( roleBehaviour.Role); - int numPerGame = + var numPerGame = GameOptionsManager.Instance.CurrentGameOptions.RoleOptions .GetNumPerGame(roleBehaviour.Role); - bool flag = numPerGame == 0; + var flag = numPerGame == 0; var viewSettingsInfoPanelRoleVariant = Object.Instantiate( __instance.infoPanelRoleOrigin, @@ -295,8 +295,8 @@ public static class LobbyViewPanePatches categoryHeaderMasked2.transform.localPosition = new Vector3(-9.77f, num, -2f); __instance.settingsInfo.Add(categoryHeaderMasked2.gameObject); num -= 2.1f; - float num3 = 0f; - for (int k = 0; k < list.Count; k++) + var num3 = 0f; + for (var k = 0; k < list.Count; k++) { float num4; if (k % 2 == 0) @@ -317,7 +317,7 @@ public static class LobbyViewPanePatches Object.Instantiate(__instance.advancedRolePanelOrigin, __instance.settingsContainer); advancedRoleViewPanel.transform.localScale = Vector3.one; advancedRoleViewPanel.transform.localPosition = new Vector3(num4, num, -2f); - float num5 = advancedRoleViewPanel.SetUp(list[k], 0.85f, 61); + var num5 = advancedRoleViewPanel.SetUp(list[k], 0.85f, 61); if (num5 > num3) { num3 = num5; @@ -431,7 +431,7 @@ public static class LobbyViewPanePatches } var num = 0.95f; - var num2 = -6.53f; + const float num2 = -6.53f; var categoryHeaderMasked = Object.Instantiate(instance.categoryHeaderOrigin, instance.settingsContainer, true); categoryHeaderMasked.SetHeader(StringNames.RoleQuotaLabel, 61); diff --git a/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs b/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs index 4790817..3ea9723 100644 --- a/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs +++ b/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs @@ -549,6 +549,7 @@ public static class RoleSettingMenuPatches var categoryHeaderMasked = __instance.AdvancedRolesSettings.transform.Find("CategoryHeaderMasked").GetComponent(); categoryHeaderMasked.Title.text = TranslationController.Instance.GetString(StringNames.RoleSettingsLabel); var labelBg = __instance.AdvancedRolesSettings.transform.FindChild("InfoLabelBackground"); + // ReSharper disable once StringLiteralTypo (Justification: Actual name in-game.) var imgBg = __instance.AdvancedRolesSettings.transform.FindChild("Imagebackground"); imgBg.gameObject.SetActive(true); __instance.roleScreenshot.gameObject.SetActive(true); @@ -573,6 +574,7 @@ public static class RoleSettingMenuPatches __instance.roleDescriptionText.text = customRole.RoleMedDescription; __instance.roleTitleText.text = role.GetRoleName(); + // ReSharper disable once StringLiteralTypo (Justification: Actual name in-game.) var imgBg = __instance.AdvancedRolesSettings.transform.FindChild("Imagebackground"); var labelBg = __instance.AdvancedRolesSettings.transform.FindChild("InfoLabelBackground"); if (role.RoleScreenshot == null) @@ -626,7 +628,7 @@ public static class RoleSettingMenuPatches IEnumerator CoReturnToRoleSettings() { - // set gameobjects + // set game objects __instance.RoleChancesSettings.SetActive(true); __instance.AdvancedRolesSettings.SetActive(false); @@ -706,11 +708,16 @@ public static class RoleSettingMenuPatches if (customRole.Configuration.Icon != null) { - var roleIcon = new GameObject("RoleIcon"); - roleIcon.transform.parent = roleOptionSetting.transform; - roleIcon.transform.localScale = new(.25f, .25f, 1); - roleIcon.layer = LayerMask.NameToLayer("UI"); - roleIcon.transform.localPosition = new Vector3(-1.3f, -0.3f, -2f); + var roleIcon = new GameObject("RoleIcon") + { + transform = + { + parent = roleOptionSetting.transform, + localScale = new(.25f, .25f, 1), + localPosition = new Vector3(-1.3f, -0.3f, -2f), + }, + layer = LayerMask.NameToLayer("UI"), + }; var rend = roleIcon.AddComponent(); rend.sprite = customRole.Configuration.Icon.LoadAsset(); diff --git a/MiraAPI/Patches/Options/SettingPatches.cs b/MiraAPI/Patches/Options/SettingPatches.cs index e19dac6..8fd6581 100644 --- a/MiraAPI/Patches/Options/SettingPatches.cs +++ b/MiraAPI/Patches/Options/SettingPatches.cs @@ -1,4 +1,5 @@ -using System.Globalization; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Linq; using HarmonyLib; using MiraAPI.GameOptions; @@ -23,6 +24,7 @@ public static class SettingPatches /// to skip original method. [HarmonyPrefix] [HarmonyPatch(typeof(FloatGameSetting), nameof(FloatGameSetting.GetValueString))] + [SuppressMessage("Style", "IDE0045:Convert to conditional expression", Justification = "Warning cascades into forcing the entire tree to be ternary operators.")] public static bool ValueStringPatch( FloatGameSetting __instance, ref string __result, @@ -34,23 +36,19 @@ public static class SettingPatches var custom = ModdedOptionsManager.ModdedOptions.Values.FirstOrDefault(opt => opt.OptionBehaviour != null && opt.OptionBehaviour.Data == __instance); - result = custom is ModdedNumberOption moddedNumberOption - ? moddedNumberOption.NegativeWordValue != "#" && (int)value == -1 - ? $"{moddedNumberOption.NegativeWordValue}" - : moddedNumberOption.ZeroWordValue != "#" && Mathf.Abs(value) < 0.0001f - ? $"{moddedNumberOption.ZeroWordValue}" - : suffix switch - { - MiraNumberSuffixes.None => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo), - MiraNumberSuffixes.Multiplier => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo) + "x", - MiraNumberSuffixes.Percent => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo) + "%", - _ => TranslationController.Instance.GetString( - StringNames.GameSecondsAbbrev, - (Il2CppSystem.Object[])[value.ToString(__instance.FormatString, CultureInfo.InvariantCulture)]), - } - : __instance.ZeroIsInfinity && Mathf.Abs(value) < 0.0001f - ? "∞" - : suffix switch + if (custom is ModdedNumberOption moddedNumberOption) + { + if (moddedNumberOption.NegativeWordValue != "#" && (int)value == -1) + { + result = $"{moddedNumberOption.NegativeWordValue}"; + } + else if (moddedNumberOption.ZeroWordValue != "#" && Mathf.Abs(value) < 0.0001f) + { + result = $"{moddedNumberOption.ZeroWordValue}"; + } + else + { + result = suffix switch { MiraNumberSuffixes.None => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo), MiraNumberSuffixes.Multiplier => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo) + "x", @@ -59,6 +57,24 @@ public static class SettingPatches StringNames.GameSecondsAbbrev, (Il2CppSystem.Object[])[value.ToString(__instance.FormatString, CultureInfo.InvariantCulture)]), }; + } + } + else if (__instance.ZeroIsInfinity && Mathf.Abs(value) < 0.0001f) + { + result = "∞"; + } + else + { + result = suffix switch + { + MiraNumberSuffixes.None => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo), + MiraNumberSuffixes.Multiplier => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo) + "x", + MiraNumberSuffixes.Percent => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo) + "%", + _ => TranslationController.Instance.GetString( + StringNames.GameSecondsAbbrev, + (Il2CppSystem.Object[])[value.ToString(__instance.FormatString, CultureInfo.InvariantCulture)]), + }; + } __result = result; return false; diff --git a/MiraAPI/Patches/PlayerControlPatches.cs b/MiraAPI/Patches/PlayerControlPatches.cs index 8876b51..aa47415 100644 --- a/MiraAPI/Patches/PlayerControlPatches.cs +++ b/MiraAPI/Patches/PlayerControlPatches.cs @@ -82,13 +82,13 @@ internal static class PlayerControlPatches if (!target || __instance.Data.IsDead || !__instance.Data.Role.IsImpostor || __instance.Data.Disconnected) { - int num = target ? target!.PlayerId : -1; + var num = target ? target!.PlayerId : -1; __instance.logger.Warning($"Bad kill from {__instance.PlayerId} to {num}"); __instance.RpcMurderPlayer(target, false); return; } - NetworkedPlayerInfo data = target!.Data; + var data = target!.Data; if (data == null || data.IsDead || target.inVent || target.MyPhysics.Animations.IsPlayingEnterVentAnimation() || target.MyPhysics.Animations.IsPlayingAnyLadderAnimation() || target.inMovingPlat) { diff --git a/MiraAPI/Patches/RoleGuidePatches.cs b/MiraAPI/Patches/RoleGuidePatches.cs index 5adbc9e..0ef8f6a 100644 --- a/MiraAPI/Patches/RoleGuidePatches.cs +++ b/MiraAPI/Patches/RoleGuidePatches.cs @@ -72,7 +72,7 @@ public static class RoleGuidePatches ConsoleJoystick.SetMode_MenuAdditive(); } ControllerManager.Instance.OpenOverlayMenu("MatchInfoGuide", __instance.closeButton); - bool enabled = ActiveInputManager.currentControlType == ActiveInputManager.InputType.Joystick; + var enabled = ActiveInputManager.currentControlType == ActiveInputManager.InputType.Joystick; __instance.glyphL.enabled = enabled; __instance.glyphR.enabled = enabled; if (GameManager.Instance.TryCast() != null) @@ -114,24 +114,24 @@ public static class RoleGuidePatches } PlayerControl.LocalPlayer.NetTransform.Halt(); __instance.MatchInfoParent.SetActive(true); - ControllerManager instance = ControllerManager.Instance; - ControllerUiElementsState currentUiState = ControllerManager.Instance.CurrentUiState; - Il2CppSystem.Collections.Generic.List controllerSelectable = __instance.ControllerSelectable; + var instance = ControllerManager.Instance; + var currentUiState = ControllerManager.Instance.CurrentUiState; + var controllerSelectable = __instance.ControllerSelectable; instance.SetUpSelectables(currentUiState, controllerSelectable[^1], __instance.ControllerSelectable); - ControllerManager instance2 = ControllerManager.Instance; - Il2CppSystem.Collections.Generic.List controllerSelectable2 = __instance.ControllerSelectable; + var instance2 = ControllerManager.Instance; + var controllerSelectable2 = __instance.ControllerSelectable; instance2.SetCurrentSelected(controllerSelectable2[^1]); __instance.SetActiveTab(0); return false; } - private static readonly Dictionary _rolePanels = []; + private static readonly Dictionary RolePanels = []; public static void DisplayNormalRoleSettings(MatchInfoGuide instance, bool reset) { if (reset) { - _rolePanels.Clear(); + RolePanels.Clear(); instance.CreateSettingsEntry( StringNames.GameNumImpostors, GameManager.Instance.AllGameSettingData[StringNames.GameNumImpostors] @@ -143,7 +143,7 @@ public static class RoleGuidePatches instance.CreateSettingsEntry( StringNames.GameEmergencyCooldown, GameManager.Instance.AllGameSettingData[StringNames.GameEmergencyCooldown] - .GetValueString((float)GameManager.Instance.LogicOptions.GetEmergencyCooldown())); + .GetValueString(GameManager.Instance.LogicOptions.GetEmergencyCooldown())); instance.CreateSettingsEntry( StringNames.GameVisualTasks, instance.GetBoolString(GameManager.Instance.LogicOptions.GetVisualTasks())); @@ -156,7 +156,7 @@ public static class RoleGuidePatches instance.CreateSettingsEntry( StringNames.GameTaskBarMode, GameManager.Instance.LogicOptions.GetTaskBarMode().ToString()); - foreach (RoleBehaviour roleBehaviour in RoleManager.Instance.AllRoles) + foreach (var roleBehaviour in RoleManager.Instance.AllRoles) { if (roleBehaviour.Role is not RoleTypes.Crewmate and not RoleTypes.Impostor and not RoleTypes.CrewmateGhost and @@ -165,22 +165,20 @@ public static class RoleGuidePatches var panel = Object.Instantiate( instance.MatchInfoRolePanelPrefab, instance.settingsTabs[2].GetComponent().Inner); - _rolePanels.Add(roleBehaviour, panel); + RolePanels.Add(roleBehaviour, panel); } } } - int num = 0; - foreach (var pair in _rolePanels) + var num = 0; + foreach (var (roleData, panel) in RolePanels) { - var role = pair.Key; - var panel = pair.Value; - var amount = GameOptionsManager.Instance.CurrentGameOptions.RoleOptions.GetNumPerGame(role.Role); - var chance = GameOptionsManager.Instance.CurrentGameOptions.RoleOptions.GetChancePerGame(role.Role); - var forciblyShow = role is ICustomRole custom ? custom.ForceShowRoleOnWiki : null; - if (amount == 0 || chance == 0 || (Enum.IsDefined(role.Role) && role.IsRoleBlacklisted()) || - (role is ICustomRole custom2 && ((!custom2.CanSpawnOnCurrentMode() && forciblyShow == null) || - (forciblyShow.HasValue && !forciblyShow.Value)))) + var amount = GameOptionsManager.Instance.CurrentGameOptions.RoleOptions.GetNumPerGame(roleData.Role); + var chance = GameOptionsManager.Instance.CurrentGameOptions.RoleOptions.GetChancePerGame(roleData.Role); + var forciblyShow = roleData is ICustomRole custom ? custom.ForceShowRoleOnWiki : null; + if (amount == 0 || chance == 0 || (Enum.IsDefined(roleData.Role) && roleData.IsRoleBlacklisted()) || + (roleData is ICustomRole custom2 && ((!custom2.CanSpawnOnCurrentMode() && forciblyShow == null) || + (forciblyShow.HasValue && !forciblyShow.Value)))) { panel.gameObject.SetActive(false); continue; @@ -188,7 +186,7 @@ public static class RoleGuidePatches panel.gameObject.SetActive(true); panel.SetPanel( - role, + roleData, amount, chance); num++; @@ -199,7 +197,7 @@ public static class RoleGuidePatches instance.rolesEnabledMessage.SetActive(true); } - instance.MatchInfoRoleScroller.SetYBoundsMax(Mathf.Clamp(Mathf.Ceil((float)num / 2f) * 1.3f - 1.5f, 0f, 999f)); + instance.MatchInfoRoleScroller.SetYBoundsMax(Mathf.Clamp(Mathf.Ceil(num / 2f) * 1.3f - 1.5f, 0f, 999f)); instance.MatchInfoRoleMaskArea.material.SetInt(PlayerMaterial.MaskLayer, 50); instance.matchInfoSettingsMaskArea.material.SetInt(PlayerMaterial.MaskLayer, 50); if (reset) @@ -214,10 +212,10 @@ public static class RoleGuidePatches private static bool CreatePlayerEntries(MatchInfoGuide __instance) { __instance.PlayerPool.ReclaimAll(); - int num = 51; - foreach (NetworkedPlayerInfo networkedPlayerInfo in GameData.Instance.AllPlayers) + var num = 51; + foreach (var networkedPlayerInfo in GameData.Instance.AllPlayers) { - PlayerIdentifierButton component = + var component = __instance.PlayerPool.Get().GetComponent(); component.transform.localPosition = new Vector3(0f, 0f, -1f); component.Populate(networkedPlayerInfo); @@ -227,17 +225,19 @@ public static class RoleGuidePatches component.NameText.transform.localPosition = new Vector3(0.3563f, 0, -2.98f); component.NameText.text += $"\n{networkedPlayerInfo.GetPlayerColorString()}"; var namePlate = HatManager.Instance.GetNamePlateById(networkedPlayerInfo.DefaultOutfit.NamePlateId); - var x = (NamePlateViewData viewdata) => + + __instance.StartCoroutine( + __instance.CoLoadAssetAsync( + namePlate.GetAssetReference(), + (Action?)LoadNameplate)); + continue; + + void LoadNameplate(NamePlateViewData viewdata) { - component.buttonSprite.sprite = viewdata?.Image; + component.buttonSprite.sprite = viewdata.Image; component.buttonSprite.transform.localScale = new Vector3(0.7f, 1.075f, 1); component.buttonSprite.transform.localPosition = new Vector3(-0.395f, 0, 0.1f); - }; - __instance.StartCoroutine( - AddressableAssetExtensions.CoLoadAssetAsync( - __instance, - namePlate.GetAssetReference(), - x)); + } } return false; diff --git a/MiraAPI/Patches/Roles/HowToPlayPatch.cs b/MiraAPI/Patches/Roles/HowToPlayPatch.cs index 5f4dd32..7cbc023 100644 --- a/MiraAPI/Patches/Roles/HowToPlayPatch.cs +++ b/MiraAPI/Patches/Roles/HowToPlayPatch.cs @@ -25,8 +25,8 @@ internal static class HowToPlayPatch { if (!role.IsSimpleRole && role.Role != RoleTypes.CrewmateGhost && role.Role != RoleTypes.ImpostorGhost) { - HowToPlayRoleButton component = Object.Instantiate(__instance.roleButtonPrefab, __instance.roleButtonsParent).GetComponent(); - Sprite roleIcon = __instance.rolesScenes.ToArray().First(r => r.role == role.Role).roleIcon; + var component = Object.Instantiate(__instance.roleButtonPrefab, __instance.roleButtonsParent).GetComponent(); + var roleIcon = __instance.rolesScenes.ToArray().First(r => r.role == role.Role).roleIcon; component.SetRoleInfo(role, roleIcon); component.SetButtonAction((Il2CppSystem.Action)(() => { @@ -35,7 +35,7 @@ internal static class HowToPlayPatch __instance.controllerSelectables.Add(component.GetComponent()); } } - foreach (UiElement uiElement in __instance.controllerSelectables) + foreach (var uiElement in __instance.controllerSelectables) { uiElement.ReceiveMouseOut(); } diff --git a/MiraAPI/Patches/Roles/LogicRoleSelectionHnsPatch.cs b/MiraAPI/Patches/Roles/LogicRoleSelectionHnsPatch.cs index e297106..7b0b44e 100644 --- a/MiraAPI/Patches/Roles/LogicRoleSelectionHnsPatch.cs +++ b/MiraAPI/Patches/Roles/LogicRoleSelectionHnsPatch.cs @@ -1,3 +1,4 @@ +using System; using AmongUs.GameOptions; using HarmonyLib; using Il2CppSystem.Collections.Generic; @@ -19,150 +20,91 @@ public static class LogicRoleSelectionHnsPatch int teamMax, Il2CppSystem.Nullable defaultRole) { - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Team: {team}, Max: {teamMax}, Players: {players.Count}, DefaultRole: {defaultRole}"); - int num = 0; - IRoleOptionsCollection roleOptions = opts.RoleOptions; + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Team: {team}, Max: {teamMax}, Players: {players.Count}, DefaultRole: {defaultRole}"); + var num = 0; + var roleOptions = opts.RoleOptions; + var source = RoleManager.Instance.AllRoles.ToArray() .Where(role => role.TeamType == team && !RoleManager.IsGhostRole(role.Role) && - CustomRoleUtils.CanSpawnOnCurrentMode(role)); + CustomRoleUtils.CanSpawnOnCurrentMode(role)).ToArray(); + var assignmentData = source.Where(x => !x.IsDead).Select(role => new RoleManager.RoleAssignmentData( role, roleOptions.GetNumPerGame(role.Role), roleOptions.GetChancePerGame(role.Role))).ToList(); + var source2 = CustomRoleUtils.GetPossibleRoles(assignmentData, x => x.Chance == 100); var guaranteedRoles = source.Where(x => source2.Contains(((ushort)x.Role, 100))); var list = new List(); - if (team == RoleTeamTypes.Crewmate) + + switch (team) { - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment"); - foreach (RoleManager.RoleAssignmentData roleAssignmentData in guaranteedRoles.Select((x) => - new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100))) - { - while (true) + case RoleTeamTypes.Crewmate: + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment"); + AddGuaranteedRoles(guaranteedRoles, opts, list); + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment"); + AssignRolesFromList(players, teamMax, list, ref num); + + AddPotentialRoles(source, opts, list); + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Potential Assignment"); + AssignRolesFromList(players, teamMax, list, ref num); + + const RoleTypes basicCrewRole = RoleTypes.Engineer; + AddFallbackRoles(list, players.Count, teamMax, num, basicCrewRole); + AssignRolesFromList(players, teamMax, list, ref num); + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Fallback Assignment"); + break; + + case RoleTeamTypes.Impostor: + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment"); + var newImpostors = new List(); + + // Specified Seeker + if (__instance.hnsManager.LogicOptionsHnS.HasImpostorPlayerID() && + __instance.hnsManager.LogicOptionsHnS.ValidateImpostorPlayerID(players) && + !AmongUsClient.Instance.IsGamePublic) { - RoleManager.RoleAssignmentData roleAssignmentData2 = roleAssignmentData; - int count = roleAssignmentData2.Count; - roleAssignmentData2.Count = count - 1; - if (count <= 0) - { - break; - } - - list.Add(roleAssignmentData.Role.Role); - } - } - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment"); - AssignRolesFromList(players, teamMax, list, ref num); - - var list2 = source.Where(x => !x.IsDead).Select(role => - new RoleManager.RoleAssignmentData( - role, - roleOptions.GetNumPerGame(role.Role), - roleOptions.GetChancePerGame(role.Role))).ToList(); - - list.Clear(); - foreach (RoleManager.RoleAssignmentData roleAssignmentData3 in list2) - { - for (int i = 0; i < roleAssignmentData3.Count; i++) - { - if (HashRandom.Next(101) < roleAssignmentData3.Chance) - { - list.Add(roleAssignmentData3.Role.Role); - } - } - } - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Potential Assignment"); - - AssignRolesFromList(players, teamMax, list, ref num); - var basicRole = RoleTypes.Engineer; - while (list.Count < players.Count && list.Count + num < teamMax) - { - list.Add(basicRole); - } - - AssignRolesFromList(players, teamMax, list, ref num); - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Fallback Assignment"); - } - else if (team == RoleTeamTypes.Impostor) - { - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment"); - var newImpostors = new List(); - // Specified Seeker - if (__instance.hnsManager.LogicOptionsHnS.HasImpostorPlayerID() && - __instance.hnsManager.LogicOptionsHnS.ValidateImpostorPlayerID(players) && - !AmongUsClient.Instance.IsGamePublic) - { - NetworkedPlayerInfo networkedPlayerInfo = players.ToArray() - .First(p => p.PlayerId == __instance.hnsManager.LogicOptionsHnS.ImpostorPlayerID()); - players.Remove(networkedPlayerInfo); - newImpostors.Add(networkedPlayerInfo); - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}"); - } - // Random Seeker - else - { - int num2 = 0; - while (num2 < teamMax && players.Count > 0) - { - var pseudoRandomList = new PseudoRandomList(AmongUsClient.Instance.GameId); - players._items.Do(pseudoRandomList.Add); - for (int i = 0; i < GameData.RoundsPlayedInSession; i++) - { - pseudoRandomList.PickRandom(); - } - NetworkedPlayerInfo networkedPlayerInfo = pseudoRandomList.PickRandom(); + var networkedPlayerInfo = players.ToArray() + .First(p => p.PlayerId == __instance.hnsManager.LogicOptionsHnS.ImpostorPlayerID()); players.Remove(networkedPlayerInfo); newImpostors.Add(networkedPlayerInfo); - num2++; - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}"); + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}"); } - } - Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment"); - foreach (RoleManager.RoleAssignmentData roleAssignmentData in guaranteedRoles.Select((x) => - new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100))) - { - while (true) + // Random Seeker + else { - RoleManager.RoleAssignmentData roleAssignmentData2 = roleAssignmentData; - int count = roleAssignmentData2.Count; - roleAssignmentData2.Count = count - 1; - if (count <= 0) + var num2 = 0; + while (num2 < teamMax && players.Count > 0) { - break; - } - - list.Add(roleAssignmentData.Role.Role); - } - } - AssignRolesFromList(newImpostors, teamMax, list, ref num); - - var list2 = source.Where(x => !x.IsDead).Select(role => - new RoleManager.RoleAssignmentData( - role, - roleOptions.GetNumPerGame(role.Role), - roleOptions.GetChancePerGame(role.Role))).ToList(); - - list.Clear(); - foreach (RoleManager.RoleAssignmentData roleAssignmentData3 in list2) - { - for (int i = 0; i < roleAssignmentData3.Count; i++) - { - if (HashRandom.Next(101) < roleAssignmentData3.Chance) - { - list.Add(roleAssignmentData3.Role.Role); + var pseudoRandomList = new PseudoRandomList(AmongUsClient.Instance.GameId); + players._items.Do(pseudoRandomList.Add); + for (var i = 0; i < GameData.RoundsPlayedInSession; i++) + { + pseudoRandomList.PickRandom(); + } + var networkedPlayerInfo = pseudoRandomList.PickRandom(); + players.Remove(networkedPlayerInfo); + newImpostors.Add(networkedPlayerInfo); + num2++; + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}"); } } - } + Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment"); - AssignRolesFromList(newImpostors, teamMax, list, ref num); - var basicRole = RoleTypes.Impostor; - while (list.Count < newImpostors.Count && list.Count + num < teamMax) - { - list.Add(basicRole); - } + AddGuaranteedRoles(guaranteedRoles, opts, list); + AssignRolesFromList(newImpostors, teamMax, list, ref num); - AssignRolesFromList(newImpostors, teamMax, list, ref num); + AddPotentialRoles(source, opts, list); + AssignRolesFromList(newImpostors, teamMax, list, ref num); + + const RoleTypes basicImpRole = RoleTypes.Impostor; + AddFallbackRoles(list, newImpostors.Count, teamMax, num, basicImpRole); + AssignRolesFromList(newImpostors, teamMax, list, ref num); + break; + + default: + throw new ArgumentOutOfRangeException(nameof(team), team, null); } return false; } @@ -171,13 +113,61 @@ public static class LogicRoleSelectionHnsPatch { while (roleList.Count > 0 && players.Count > 0 && rolesAssigned < teamMax) { - int index = HashRandom.FastNext(roleList.Count); - RoleTypes roleType = roleList[index]; + var index = HashRandom.FastNext(roleList.Count); + var roleType = roleList[index]; roleList.RemoveAt(index); - int index2 = HashRandom.FastNext(players.Count); + var index2 = HashRandom.FastNext(players.Count); players[index2].Object.RpcSetRole(roleType); players.RemoveAt(index2); rolesAssigned++; } } + + private static void AddGuaranteedRoles( + System.Collections.Generic.IEnumerable guaranteedRoles, + IGameOptions opts, + List list) + { + var roleOptions = opts.RoleOptions; + foreach (var roleAssignmentData in guaranteedRoles.Select(x => + new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100))) + { + while (true) + { + var count = roleAssignmentData.Count; + roleAssignmentData.Count = count - 1; + if (count <= 0) break; + list.Add(roleAssignmentData.Role.Role); + } + } + } + + private static void AddPotentialRoles(System.Collections.Generic.IEnumerable source, IGameOptions opts, List list) + { + var roleOptions = opts.RoleOptions; + var potentialRoles = source.Where(x => !x.IsDead).Select(role => new RoleManager.RoleAssignmentData( + role, + roleOptions.GetNumPerGame(role.Role), + roleOptions.GetChancePerGame(role.Role))).ToList(); + + list.Clear(); + foreach (var roleData in potentialRoles) + { + for (var i = 0; i < roleData.Count; i++) + { + if (HashRandom.Next(101) < roleData.Chance) + { + list.Add(roleData.Role.Role); + } + } + } + } + + private static void AddFallbackRoles(List list, int targetPlayerCount, int teamMax, int rolesAssigned, RoleTypes basicRole) + { + while (list.Count < targetPlayerCount && list.Count + rolesAssigned < teamMax) + { + list.Add(basicRole); + } + } } diff --git a/MiraAPI/Patches/Roles/RoleOptionsCollectionPatch.cs b/MiraAPI/Patches/Roles/RoleOptionsCollectionPatch.cs index a1c7a6e..303ea6b 100644 --- a/MiraAPI/Patches/Roles/RoleOptionsCollectionPatch.cs +++ b/MiraAPI/Patches/Roles/RoleOptionsCollectionPatch.cs @@ -1,6 +1,5 @@ using AmongUs.GameOptions; using HarmonyLib; -using Il2CppSystem.Collections.Generic; using MiraAPI.Roles; namespace MiraAPI.Patches.Roles; @@ -18,7 +17,7 @@ public static class RoleOptionsCollectionPatch [HarmonyPatch(nameof(RoleOptionsCollectionV11.AnyRolesEnabled))] public static bool AnyRolesEnabledPrefix(RoleOptionsCollectionV11 __instance) { - foreach (KeyValuePair keyValuePair in __instance.roles) + foreach (var keyValuePair in __instance.roles) { if (__instance.GetNumPerGame(keyValuePair.Key) > 0) { diff --git a/MiraAPI/Patches/Roles/SelectRolesPatch.cs b/MiraAPI/Patches/Roles/SelectRolesPatch.cs index 149efdf..692e200 100644 --- a/MiraAPI/Patches/Roles/SelectRolesPatch.cs +++ b/MiraAPI/Patches/Roles/SelectRolesPatch.cs @@ -47,15 +47,15 @@ public static class SelectRolesPatch .Where(c => c.Character != null && c.Character.Data != null && !c.Character.Data.Disconnected && !c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data)]; - foreach (NetworkedPlayerInfo networkedPlayerInfo in GameData.Instance.AllPlayers) + foreach (var networkedPlayerInfo in GameData.Instance.AllPlayers) { if (networkedPlayerInfo.Object != null && networkedPlayerInfo.Object.isDummy) { list2.Add(networkedPlayerInfo); } } - IGameOptions currentGameOptions = GameOptionsManager.Instance.CurrentGameOptions; - int adjustedNumImpostors = GameOptionsManager.Instance.CurrentGameOptions.GetAdjustedNumImpostors(list2.Count); + var currentGameOptions = GameOptionsManager.Instance.CurrentGameOptions; + var adjustedNumImpostors = GameOptionsManager.Instance.CurrentGameOptions.GetAdjustedNumImpostors(list2.Count); AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Impostor, adjustedNumImpostors, RoleTypes.Impostor); AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Crewmate, int.MaxValue, RoleTypes.Crewmate); return false; @@ -68,12 +68,13 @@ public static class SelectRolesPatch int teamMax, RoleTypes defaultRole) { - int num = 0; + var num = 0; var source = RoleManager.Instance.AllRoles.ToArray() .Where(role => role.TeamType == team && !RoleManager.IsGhostRole(role.Role) && - CustomRoleUtils.CanSpawnOnCurrentMode(role)); + CustomRoleUtils.CanSpawnOnCurrentMode(role)) + .ToArray(); var list = new List(); - IRoleOptionsCollection roleOptions = opts.RoleOptions; + var roleOptions = opts.RoleOptions; // Assign guaranteed roles first, just like the vanilla selector. This is // important because the list of players is shared by both team passes. @@ -119,10 +120,10 @@ public static class SelectRolesPatch { while (roleList.Count > 0 && players.Count > 0 && rolesAssigned < teamMax) { - int index = HashRandom.FastNext(roleList.Count); - RoleTypes roleType = roleList[index]; + var index = HashRandom.FastNext(roleList.Count); + var roleType = roleList[index]; roleList.RemoveAt(index); - int index2 = HashRandom.FastNext(players.Count); + var index2 = HashRandom.FastNext(players.Count); players[index2].Object.RpcSetRole(roleType); players.RemoveAt(index2); rolesAssigned++; diff --git a/MiraAPI/Patches/Roles/TaskPanelPatch.cs b/MiraAPI/Patches/Roles/TaskPanelPatch.cs index 09877e5..c858d9f 100644 --- a/MiraAPI/Patches/Roles/TaskPanelPatch.cs +++ b/MiraAPI/Patches/Roles/TaskPanelPatch.cs @@ -9,7 +9,7 @@ internal static class TaskPanelPatch /// /// This patch is to override the automatic updating of the y position on the tab (which is in base game) /// because I can't change the custom tab y pos if it's being overridden every frame. - /// Im sure there is an easier/better way, but this is the fix that worked for me. + /// I'm sure there is an easier/better way, but this is the fix that worked for me. /// [HarmonyPrefix] [HarmonyPatch(nameof(TaskPanelBehaviour.Update))] diff --git a/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs b/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs index 08d1ee6..a893d51 100644 --- a/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs +++ b/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs @@ -19,7 +19,7 @@ internal static class DummyBehaviourPatches [HarmonyPatch(nameof(DummyBehaviour.Update))] public static bool DummyUpdatePatch(DummyBehaviour __instance) { - NetworkedPlayerInfo data = __instance.myPlayer.Data; + var data = __instance.myPlayer.Data; if (data == null || data.IsDead) return false; if (MeetingHud.Instance) @@ -65,7 +65,7 @@ internal static class DummyBehaviourPatches potentialSuspects.Add(253); } - if (CanVote(dummy)) + if (dummy.CanVote()) { VotingUtils.RpcCastVote(PlayerControl.LocalPlayer, dummy.myPlayer.PlayerId, potentialSuspects.Random()); } diff --git a/MiraAPI/Patches/Voting/MeetingHudPatches.cs b/MiraAPI/Patches/Voting/MeetingHudPatches.cs index 8d12db4..6cbcd56 100644 --- a/MiraAPI/Patches/Voting/MeetingHudPatches.cs +++ b/MiraAPI/Patches/Voting/MeetingHudPatches.cs @@ -44,8 +44,8 @@ internal static class MeetingHudPatches if (PlayerControl.LocalPlayer.Data.IsDead || __instance.AmDead || !__instance.Parent) return false; - JudgeRole? judgeRole = PlayerControl.LocalPlayer.Data.Role.TryCast(); - bool flag = judgeRole && PlayerControl.LocalPlayer.PlayerId != __instance.PlayerId; + var judgeRole = PlayerControl.LocalPlayer.Data.Role.TryCast(); + var flag = judgeRole && PlayerControl.LocalPlayer.PlayerId != __instance.PlayerId; __instance.JudgeOverruleButton?.gameObject.SetActive(flag); if (__instance.VoteComplete || !__instance.Parent.Select((byte)__instance.PlayerId)) @@ -53,7 +53,7 @@ internal static class MeetingHudPatches __instance.Buttons.SetActive(true); - float startPos = __instance.AnimateButtonsFromLeft ? 0.2f : 1.95f; + var startPos = __instance.AnimateButtonsFromLeft ? 0.2f : 1.95f; Il2CppSystem.Collections.Generic.List selectableElements = new(); foreach (var btn in __instance.Buttons.GetComponentsInChildren()) @@ -61,11 +61,11 @@ internal static class MeetingHudPatches selectableElements.Add(btn); } - for (int i = 0; i < selectableElements.Count; i++) + for (var i = 0; i < selectableElements.Count; i++) { var button = selectableElements[i]; - float endPos = 1.3f - 0.65f * i; - float duration = 0.25f + 0.1f * i; + var endPos = 1.3f - 0.65f * i; + var duration = 0.25f + 0.1f * i; __instance.StartCoroutine(Effects.All(Effects.Lerp(duration, (Action)(t => button.transform.localPosition = Vector2.Lerp(Vector2.right * startPos, Vector2.right * endPos, Effects.ExpOut(t)))))); } diff --git a/MiraAPI/PluginLoading/IMiraPlugin.cs b/MiraAPI/PluginLoading/IMiraPlugin.cs index 00e3c85..c77a97e 100644 --- a/MiraAPI/PluginLoading/IMiraPlugin.cs +++ b/MiraAPI/PluginLoading/IMiraPlugin.cs @@ -12,12 +12,12 @@ public interface IMiraPlugin /// /// Gets a value indicating whether to display the plugin in the options menu. /// - virtual bool DisplayOnOptionsMenu => true; + bool DisplayOnOptionsMenu => true; /// /// Gets the localization id to use for anything registered under this mod. /// - virtual string ParentLocaleId => GetType().Name.ToLower(CultureInfo.InvariantCulture); + string ParentLocaleId => GetType().Name.ToLower(CultureInfo.InvariantCulture); /// /// Gets the name to display on the options menu. @@ -28,7 +28,7 @@ public interface IMiraPlugin /// Gets the abbreviated name to display for other mods to pick up. /// /// The text for the plugin. - virtual string GetAbbreviatedModName() + string GetAbbreviatedModName() { return new([.. OptionsTitleText.Where(c => !char.IsLower(c) && !char.IsWhiteSpace(c))]); } @@ -36,27 +36,27 @@ public interface IMiraPlugin /// /// Gets the name for the first custom category in the game options menu, if any. /// - virtual string CustomOptionMenuNameOne => "Custom Category 1"; + string CustomOptionMenuNameOne => "Custom Category 1"; /// /// Gets the name for the second custom category in the game options menu, if any. /// - virtual string CustomOptionMenuNameTwo => "Custom Category 2"; + string CustomOptionMenuNameTwo => "Custom Category 2"; /// /// Gets the description for the second custom category in the game options menu, if any. /// - virtual string ModifierMenuDescription => "Configure modifiers and their settings here!"; + string ModifierMenuDescription => "Configure modifiers and their settings here!"; /// /// Gets the description for the first custom category in the game options menu, if any. /// - virtual string CustomOptionMenuOneDescription => "Apply game settings for this mod!"; + string CustomOptionMenuOneDescription => "Apply game settings for this mod!"; /// /// Gets the description for the second custom category in the game options menu, if any. /// - virtual string CustomOptionMenuTwoDescription => "Apply game settings for this mod!"; + string CustomOptionMenuTwoDescription => "Apply game settings for this mod!"; /// /// Gets the for the plugin. diff --git a/MiraAPI/Presets/OptionPreset.cs b/MiraAPI/Presets/OptionPreset.cs index 82d4888..01758c5 100644 --- a/MiraAPI/Presets/OptionPreset.cs +++ b/MiraAPI/Presets/OptionPreset.cs @@ -72,11 +72,9 @@ public class OptionPreset(string name, MiraPluginInfo plugin, ConfigFile presetC { var selectedOpt = Plugin.InternalOptions.First(x => x.OptionBehaviour == baseOption); selectedOpt.LoadFromPreset(PresetConfig); -#pragma warning disable S125 // Sections of code should not be commented out /*ModdedOptionsManager.SyncAllOptions(); CustomRoleManager.SyncAllRoleSettings();*/ -#pragma warning restore S125 // Sections of code should not be commented out } /// diff --git a/MiraAPI/Presets/SavePresetPopup.cs b/MiraAPI/Presets/SavePresetPopup.cs index 271c330..5b93ab6 100644 --- a/MiraAPI/Presets/SavePresetPopup.cs +++ b/MiraAPI/Presets/SavePresetPopup.cs @@ -8,12 +8,13 @@ using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member [RegisterInIl2Cpp] // TODO: Give proper reasoning [SuppressMessage("Design", "CA1050:Declare types in namespaces", Justification = "Reason pending.")] [SuppressMessage("Major Bug", "S3903:Types should be defined in named namespaces", Justification = "Reason pending.")] +[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity Convention.")] +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member (Justification: Unity fields; ignore.) public class SavePresetPopup(nint cppPtr) : Minigame(cppPtr) { private TextMeshPro textBoxText; @@ -22,7 +23,7 @@ public class SavePresetPopup(nint cppPtr) : Minigame(cppPtr) private Action onSave; // Cleanup holder object - public void OnDestroy() + private void OnDestroy() { transform.parent.gameObject.Destroy(); } @@ -32,9 +33,7 @@ public class SavePresetPopup(nint cppPtr) : Minigame(cppPtr) // no-op } -#pragma warning disable IDE0051 // Remove unused private members private void Awake() -#pragma warning restore IDE0051 // Remove unused private members { var textboxHolder = transform.GetChild(1).GetChild(1); var saveButton = transform.FindChild("SaveButton").GetComponent(); diff --git a/MiraAPI/Roles/CustomRoleConfiguration.cs b/MiraAPI/Roles/CustomRoleConfiguration.cs index 3615ea2..b0f2d4a 100644 --- a/MiraAPI/Roles/CustomRoleConfiguration.cs +++ b/MiraAPI/Roles/CustomRoleConfiguration.cs @@ -17,7 +17,7 @@ public record struct CustomRoleConfiguration { [Obsolete("Default constructor is not supported. Please use the constructor that takes an ICustomRole parameter.")] [SuppressMessage("Info Code Smell", "S1133:Deprecated code should be removed", Justification = "Will not be removed, as this throws instead.")] -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member (Justification: Read above.) public CustomRoleConfiguration() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member { diff --git a/MiraAPI/Roles/CustomRoleManager.cs b/MiraAPI/Roles/CustomRoleManager.cs index 64606c2..4a015ad 100644 --- a/MiraAPI/Roles/CustomRoleManager.cs +++ b/MiraAPI/Roles/CustomRoleManager.cs @@ -277,7 +277,7 @@ public static class CustomRoleManager internal static void HandleSyncRoleOptions(NetData[] data) { // necessary to disable then re-enable this setting - // we dont know how other plugins handle their configs + // we don't know how other plugins handle their configs // this way, all the options are saved at once, instead of one by one var oldConfigSetting = new Dictionary(); foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins) diff --git a/MiraAPI/Roles/CustomRoleUtils.cs b/MiraAPI/Roles/CustomRoleUtils.cs index 3c690ac..1487d20 100644 --- a/MiraAPI/Roles/CustomRoleUtils.cs +++ b/MiraAPI/Roles/CustomRoleUtils.cs @@ -27,7 +27,7 @@ public static class CustomRoleUtils ? custom.CanSpawnOnCurrentMode() && custom.Configuration.AssociatedGameMode.IsInstanceOfType(CustomGameModeManager.ActiveMode) : (CustomGameModeManager.ActiveMode is HideAndSeekMode ? role.Role is RoleTypes.Engineer or RoleTypes.Impostor - : !Helpers.IsRoleBlacklisted(role)); + : !role.IsRoleBlacklisted()); } /// diff --git a/MiraAPI/Roles/ICustomRole.cs b/MiraAPI/Roles/ICustomRole.cs index 25b43e9..adf24d2 100644 --- a/MiraAPI/Roles/ICustomRole.cs +++ b/MiraAPI/Roles/ICustomRole.cs @@ -138,7 +138,7 @@ public interface ICustomRole : IOptionable /// Binds the configuration options for this role to the provided ConfigFile. /// /// The ConfigFile to bind the options to. - virtual void BindConfig(ConfigFile config) + void BindConfig(ConfigFile config) { config.Bind(NumConfigDefinition, Configuration.DefaultRoleCount); config.Bind(ChanceConfigDefinition, Configuration.DefaultChance); @@ -149,7 +149,7 @@ public interface ICustomRole : IOptionable /// /// The to save the preset configuration to. /// Whether to use the default values for the configuration. - virtual void SaveToPreset(ConfigFile presetConfig, bool useDefault = false) + void SaveToPreset(ConfigFile presetConfig, bool useDefault = false) { BindConfig(presetConfig); presetConfig[NumConfigDefinition].BoxedValue = useDefault ? Configuration.DefaultRoleCount : GetCount(); @@ -160,7 +160,7 @@ public interface ICustomRole : IOptionable /// Loads the role's configuration from a preset . /// /// The containing the preset configuration. - virtual void LoadFromPreset(ConfigFile presetConfig) + void LoadFromPreset(ConfigFile presetConfig) { if (presetConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry numEntry)) { @@ -177,7 +177,7 @@ public interface ICustomRole : IOptionable /// Gets the role chance option. /// /// The role chance option. - virtual int? GetChance() + int? GetChance() { return !Configuration.CanModifyChance ? Configuration.DefaultChance @@ -190,7 +190,7 @@ public interface ICustomRole : IOptionable /// Gets the role count option. /// /// The role count option. - virtual int? GetCount() + int? GetCount() { return ParentMod.PluginConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry entry) ? Mathf.Clamp(entry.Value, 0, Configuration.MaxRoleCount) @@ -201,7 +201,7 @@ public interface ICustomRole : IOptionable /// Sets the role chance option. /// /// The chance between 0 and 100. - virtual void SetChance(int chance) + void SetChance(int chance) { if (!Configuration.CanModifyChance) { @@ -222,7 +222,7 @@ public interface ICustomRole : IOptionable /// Sets the role count option. /// /// The amount of this role between zero and its MaxRoleCount in the Configuration. - virtual void SetCount(int count) + void SetCount(int count) { if (ParentMod.PluginConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry entry)) { @@ -238,7 +238,7 @@ public interface ICustomRole : IOptionable /// /// The player with the role. /// Whether they can see the role (name color) or not. - virtual bool CanLocalPlayerSeeRole(PlayerControl player) + bool CanLocalPlayerSeeRole(PlayerControl player) { return (PlayerControl.LocalPlayer.Data.Role.IsImpostor && player.Data.Role.IsImpostor) || PlayerControl.LocalPlayer.Data.IsDead; } @@ -249,7 +249,7 @@ public interface ICustomRole : IOptionable /// The intro cutscene instance. /// The reference to the list of player in the team. /// to use the original team intro code, to skip. - virtual bool SetupIntroTeam(IntroCutscene instance, ref Il2CppSystem.Collections.Generic.List yourTeam) + bool SetupIntroTeam(IntroCutscene instance, ref Il2CppSystem.Collections.Generic.List yourTeam) { if (Team == ModdedRoleTeams.Custom) { @@ -296,7 +296,7 @@ public interface ICustomRole : IOptionable /// Determines whether the role can spawn in general, accounting for gamemodes and everything else. /// /// if the role is able to spawn, otherwise . - virtual bool CanSpawnOnCurrentMode() + bool CanSpawnOnCurrentMode() { return Configuration.AssociatedGameMode.IsInstanceOfType(CustomGameModeManager.ActiveMode); } @@ -305,10 +305,10 @@ public interface ICustomRole : IOptionable /// Gets whether the role is forcibly shown or disabled in the wiki screen. /// /// if the role is always displayed, otherwise if it is never displayable, or if it is dictated by amount and chance. - virtual bool? ForceShowRoleOnWiki => null; + bool? ForceShowRoleOnWiki => null; /// /// Gets the function that determines whether the role should be toggled on or off in the game settings. /// - virtual Func VisibleInSettings => () => true; + Func VisibleInSettings => () => true; } diff --git a/MiraAPI/Translation/MiraLanguage.cs b/MiraAPI/Translation/MiraLanguage.cs index 1c6ab83..7f24cd5 100644 --- a/MiraAPI/Translation/MiraLanguage.cs +++ b/MiraAPI/Translation/MiraLanguage.cs @@ -79,6 +79,7 @@ public enum MiraLanguage /// /// TChinese. /// + // ReSharper disable once InconsistentNaming (Justification: Language name.) TChinese, /// diff --git a/MiraAPI/Translation/MiraLocaleManager.cs b/MiraAPI/Translation/MiraLocaleManager.cs index 50560f1..ac0ad54 100644 --- a/MiraAPI/Translation/MiraLocaleManager.cs +++ b/MiraAPI/Translation/MiraLocaleManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; @@ -17,7 +18,7 @@ public static class MiraLocaleManager { private const string LangDirectory = "mira_languages"; - // Language, Xml Name, then Value + // Language, XML Name, then Value /// /// Gets the dictionary containing all loaded localization strings, organized by language and XML name. @@ -153,15 +154,22 @@ public static class MiraLocaleManager /// The string id to find. /// Fallback string to use if no translation is found. /// A based on the key provided. + [SuppressMessage("Style", "IDE0046:Convert to conditional expression", Justification = "Warning cascades into forcing the entire tree to be ternary operators.")] public static string Get(MiraLanguage language, string key, string fallback = "") { - return Locale.TryGetValue(language, out var translations) && - translations.TryGetValue(key, out var translation) - ? translation - : Locale.TryGetValue(MiraLanguage.English, out var translationsEng) && - translationsEng.TryGetValue(key, out var translationEng) - ? translationEng - : fallback; + if (Locale.TryGetValue(language, out var translations) && + translations.TryGetValue(key, out var translation)) + { + return translation; + } + + if (Locale.TryGetValue(MiraLanguage.English, out var translationsEng) && + translationsEng.TryGetValue(key, out var translationEng)) + { + return translationEng; + } + + return fallback; } /// @@ -325,7 +333,7 @@ public static class MiraLocaleManager } using StreamReader reader = new(resourceStream); - string xmlContent = reader.ReadToEnd(); + var xmlContent = reader.ReadToEnd(); try { Locale.TryAdd(locale.Key, []); @@ -351,7 +359,7 @@ public static class MiraLocaleManager try { xmlDoc.LoadXml(xmlContent); - XmlNodeList? stringNodes = xmlDoc.SelectNodes("/resources/string"); + var stringNodes = xmlDoc.SelectNodes("/resources/string"); if (stringNodes == null) { @@ -367,19 +375,19 @@ public static class MiraLocaleManager continue; } - string name = node.Attributes["name"]!.Value; - string value = node.InnerText; + var name = node.Attributes["name"]!.Value; + var value = node.InnerText; if (string.IsNullOrEmpty(name)) continue; if (value.Contains('[')) { - value = value.Replace("[", "<"); + value = value.Replace('[', '<'); } if (value.Contains(']')) { - value = value.Replace("]", ">"); + value = value.Replace(']', '>'); } value = value.Replace("", "\n").Replace("", "&"); diff --git a/MiraAPI/Utilities/Assets/AddressablesLoader.cs b/MiraAPI/Utilities/Assets/AddressablesLoader.cs index d2533c6..c66c8c3 100644 --- a/MiraAPI/Utilities/Assets/AddressablesLoader.cs +++ b/MiraAPI/Utilities/Assets/AddressablesLoader.cs @@ -198,7 +198,7 @@ public static class AddressablesLoader private static T[] PrepareArray(List data, List behaviours) where T : CosmeticData { var count = data.Count; - for (int i = 0; i < behaviours.Count; i++) + for (var i = 0; i < behaviours.Count; i++) { behaviours[i].displayOrder = count + i; data.Add(behaviours[i]); diff --git a/MiraAPI/Utilities/Assets/TmpSpriteUtils.cs b/MiraAPI/Utilities/Assets/TmpSpriteUtils.cs index 1c14435..b6111fa 100644 --- a/MiraAPI/Utilities/Assets/TmpSpriteUtils.cs +++ b/MiraAPI/Utilities/Assets/TmpSpriteUtils.cs @@ -52,12 +52,13 @@ public static class TmpSpriteUtils AssetHolder.fallbackSpriteAssets = new(); } - TMP_SpriteAsset spriteAsset = ScriptableObject.CreateInstance(); + var spriteAsset = ScriptableObject.CreateInstance(); spriteAsset.name = assetName; spriteAsset.spriteSheet = sourceTexture; if (!_spriteShader) { + // ReSharper disable once ShaderLabShaderReferenceNotResolved (Justification: Unnecessary.) _spriteShader = Shader.Find("TextMeshPro/Sprite"); } diff --git a/MiraAPI/Utilities/Components/CenteredGridArrange.cs b/MiraAPI/Utilities/Components/CenteredGridArrange.cs index 17d1cf4..6035f1c 100644 --- a/MiraAPI/Utilities/Components/CenteredGridArrange.cs +++ b/MiraAPI/Utilities/Components/CenteredGridArrange.cs @@ -31,7 +31,7 @@ public class CenteredGridArrange(IntPtr iPtr) : MonoBehaviour(iPtr) private void Start() { cells = []; - GetChildsActive(); + GetChildrenActive(); CheckCurrentChildren(); } @@ -42,16 +42,16 @@ public class CenteredGridArrange(IntPtr iPtr) : MonoBehaviour(iPtr) private void CheckCurrentChildren() { - GetChildsActive(); + GetChildrenActive(); if (cells.SequenceEqual(CurrentChildren)) return; cells.Clear(); - foreach (Transform currentChild in CurrentChildren) + foreach (var currentChild in CurrentChildren) cells.Add(currentChild); - ArrangeChilds(); + ArrangeChildren(); } - private void GetChildsActive() + private void GetChildrenActive() { CurrentChildren.Clear(); foreach (var obj in transform) @@ -63,29 +63,29 @@ public class CenteredGridArrange(IntPtr iPtr) : MonoBehaviour(iPtr) } } - private void ArrangeChilds() + private void ArrangeChildren() { if (cells.Count == 0) return; - int totalRows = Mathf.CeilToInt((float)cells.Count / MaxColumns); - float totalHeight = (totalRows - 1) * CellSize.y; - float startY = transform.position.y + totalHeight * 0.5f; + var totalRows = Mathf.CeilToInt((float)cells.Count / MaxColumns); + var totalHeight = (totalRows - 1) * CellSize.y; + var startY = transform.position.y + totalHeight * 0.5f; - for (int index = 0; index < cells.Count; ++index) + for (var index = 0; index < cells.Count; ++index) { - int row = index / MaxColumns; - int rowStartIndex = row * MaxColumns; - int itemsInRow = Mathf.Min(MaxColumns, cells.Count - rowStartIndex); - int col = index - rowStartIndex; + var row = index / MaxColumns; + var rowStartIndex = row * MaxColumns; + var itemsInRow = Mathf.Min(MaxColumns, cells.Count - rowStartIndex); + var col = index - rowStartIndex; - float rowWidth = (itemsInRow - 1) * CellSize.x; - float startX = transform.position.x - rowWidth * 0.5f; + var rowWidth = (itemsInRow - 1) * CellSize.x; + var startX = transform.position.x - rowWidth * 0.5f; - float x = startX + col * CellSize.x; - float y = startY - row * CellSize.y; + var x = startX + col * CellSize.x; + var y = startY - row * CellSize.y; - Transform cell = cells[index]; + var cell = cells[index]; cell.position = new Vector3(x, y, cell.position.z); } } diff --git a/MiraAPI/Utilities/ControllableComparer.cs b/MiraAPI/Utilities/ControllableComparer.cs index c7d3c43..4881ab0 100644 --- a/MiraAPI/Utilities/ControllableComparer.cs +++ b/MiraAPI/Utilities/ControllableComparer.cs @@ -7,29 +7,25 @@ namespace MiraAPI.Utilities; internal sealed class ControllableComparer(T[] forcedToBottom, T[] forcedToTop, IComparer fallbackComparer) : IComparer where T : IComparable { - private readonly T[] _forcedToBottom = forcedToBottom; - private readonly T[] _forcedToTop = forcedToTop; - private readonly IComparer _fallbackComparer = fallbackComparer; - /// [SuppressMessage("Style", "IDE0046:Convert to conditional expression", Justification = "Warning cascades into forcing the entire tree to be ternary operators.")] public int Compare(T? x, T? y) { - if ((_forcedToBottom.Contains(x) && _forcedToBottom.Contains(y)) || (_forcedToTop.Contains(x) && _forcedToTop.Contains(y))) - return _fallbackComparer.Compare(x, y); + if ((forcedToBottom.Contains(x) && forcedToBottom.Contains(y)) || (forcedToTop.Contains(x) && forcedToTop.Contains(y))) + return fallbackComparer.Compare(x, y); - if (_forcedToBottom.Contains(x)) + if (forcedToBottom.Contains(x)) return 1; - if (_forcedToBottom.Contains(y)) + if (forcedToBottom.Contains(y)) return -1; - if (_forcedToTop.Contains(x)) + if (forcedToTop.Contains(x)) return -1; - if (_forcedToTop.Contains(y)) + if (forcedToTop.Contains(y)) return 1; - return _fallbackComparer.Compare(x, y); + return fallbackComparer.Compare(x, y); } } diff --git a/MiraAPI/Utilities/Extensions.cs b/MiraAPI/Utilities/Extensions.cs index 93d548a..c719148 100644 --- a/MiraAPI/Utilities/Extensions.cs +++ b/MiraAPI/Utilities/Extensions.cs @@ -54,7 +54,6 @@ public static class Extensions /// The . public static void BaseClose(this Minigame self) { - bool isComplete; if (self.amClosing == Minigame.CloseState.Closing) { self.gameObject.Destroy(); @@ -74,12 +73,12 @@ public static class Extensions } self.amClosing = Minigame.CloseState.Closing; self.logger.Info(string.Concat("Closing minigame ", self.GetType().Name)); - IAnalyticsReporter analytics = DebugAnalytics.Instance.Analytics; - NetworkedPlayerInfo data = PlayerControl.LocalPlayer.Data; - TaskTypes taskType = self.TaskType; - float realtimeSinceStartup = Time.realtimeSinceStartup - self.timeOpened; - PlayerTask myTask = self.MyTask; - isComplete = myTask != null && myTask.IsComplete; + var analytics = DebugAnalytics.Instance.Analytics; + var data = PlayerControl.LocalPlayer.Data; + var taskType = self.TaskType; + var realtimeSinceStartup = Time.realtimeSinceStartup - self.timeOpened; + var myTask = self.MyTask; + var isComplete = myTask != null && myTask.IsComplete; analytics.MinigameClosed(data, taskType, realtimeSinceStartup, isComplete); self.StartCoroutine(self.CoDestroySelf()); } @@ -193,6 +192,7 @@ public static class Extensions /// The converted list. public static Il2CppSystem.Collections.Generic.List ToIl2CppList(this List systemList) { + // ReSharper disable once InconsistentNaming (Justification: Acronym.) var il2cppList = new Il2CppSystem.Collections.Generic.List(); foreach (var item in systemList) @@ -266,6 +266,8 @@ public static class Extensions // Left as is intentionally, did you guys mean to use it in DeepDestroy? [SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Not known until intent it clear.")] [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Unclear, but please shut up.")] + // ReSharper disable once UnusedParameter.Local (Justification: Read above.) + // ReSharper disable once UnusedMember.Local (Justification: Read above.) private static IEnumerator Nuke(GameObject? go, bool clearGc) { if (go == null) @@ -403,8 +405,8 @@ public static class Extensions return; } - float spriteWidth = sprite.sprite.rect.width; - float spriteHeight = sprite.sprite.rect.height; + var spriteWidth = sprite.sprite.rect.width; + var spriteHeight = sprite.sprite.rect.height; sprite.size = spriteWidth < spriteHeight ? new Vector2(pixelSize * spriteWidth / spriteHeight, pixelSize) @@ -526,7 +528,7 @@ public static class Extensions /// A proper string for the . public static string ToDisplayString(this Enum @enum) { - var regex = new Regex(@"([^\^])([A-Z][a-z$])", default, default); + var regex = new Regex(@"([^\^])([A-Z][a-z$])", default, Regex.InfiniteMatchTimeout); return regex.Replace(@enum.ToString(), m => $"{m.Groups[1].Value} {m.Groups[2].Value}"); } diff --git a/MiraAPI/Utilities/Helpers.cs b/MiraAPI/Utilities/Helpers.cs index 0aa4a81..db61953 100644 --- a/MiraAPI/Utilities/Helpers.cs +++ b/MiraAPI/Utilities/Helpers.cs @@ -137,18 +137,12 @@ public static class Helpers /// if the number falls in the range, if not. public static bool CheckChance(int probability) { - switch (probability) + return probability switch { - case 0: - return false; - case 100: - return true; - default: - { - var num = Random.RandomRangeInt(1, 101); - return num <= probability; - } - } + 0 => false, + 100 => true, + _ => Random.RandomRangeInt(1, 100) <= probability, + }; } /// @@ -198,11 +192,9 @@ public static class Helpers } var sqrDistance = (obj.transform.position - position).sqrMagnitude; - if (sqrDistance < closestDistanceSqr) - { - closestDistanceSqr = sqrDistance; - closest = obj; - } + if (!(sqrDistance < closestDistanceSqr)) continue; + closestDistanceSqr = sqrDistance; + closest = obj; } return closest; @@ -455,7 +447,7 @@ public static class Helpers /// Gets a by its parent ID. /// /// The player ID. - /// A or if its not found. + /// A or if it's not found. public static DeadBody? GetBodyById(byte id) { return Object.FindObjectsOfType().FirstOrDefault(body => body.ParentId == id); diff --git a/MiraAPI/VanillaEvents/JudgeEvents.cs b/MiraAPI/VanillaEvents/JudgeEvents.cs index fa18d6b..6cfd526 100644 --- a/MiraAPI/VanillaEvents/JudgeEvents.cs +++ b/MiraAPI/VanillaEvents/JudgeEvents.cs @@ -12,17 +12,18 @@ internal static class JudgeEvents MiraEventManager.RegisterEventHandler(ProcessVotesEventHandler, -1000); } - public static void ProcessVotesEventHandler(ProcessVotesEvent @event) + private static void ProcessVotesEventHandler(ProcessVotesEvent @event) { - if (MeetingHud.Instance.TryGetWinningOverrule(out var judgeOverrule, out var networkedPlayerInfo, out var networkedPlayerInfo2)) - { - Error("Judge has overruled votes!"); - @event.OverruledVote = true; - @event.OverruledNonce = judgeOverrule.OverruleNonce; + if (!MeetingHud.Instance.TryGetWinningOverrule( + out var judgeOverrule, + out var networkedPlayerInfo, + out var networkedPlayerInfo2)) return; + Error("Judge has overruled votes!"); + @event.OverruledVote = true; + @event.OverruledNonce = judgeOverrule.OverruleNonce; - @event.ExiledPlayer = networkedPlayerInfo2.Role is ICustomRole { Team: not ModdedRoleTeams.Crewmate } || networkedPlayerInfo2.Role.TeamType == RoleTeamTypes.Impostor - ? GameData.Instance.GetPlayerById(judgeOverrule.OverruledPlayerId) - : networkedPlayerInfo; - } + @event.ExiledPlayer = networkedPlayerInfo2.Role is ICustomRole { Team: not ModdedRoleTeams.Crewmate } || networkedPlayerInfo2.Role.TeamType == RoleTeamTypes.Impostor + ? GameData.Instance.GetPlayerById(judgeOverrule.OverruledPlayerId) + : networkedPlayerInfo; } } diff --git a/MiraAPI/VanillaEvents/UiResetEvents.cs b/MiraAPI/VanillaEvents/UiResetEvents.cs index 931af4e..8c18edb 100644 --- a/MiraAPI/VanillaEvents/UiResetEvents.cs +++ b/MiraAPI/VanillaEvents/UiResetEvents.cs @@ -15,7 +15,7 @@ internal static class UiResetEvents MiraEventManager.RegisterEventHandler(PlaceModifierUi, -700); } - public static void ResetButtonParents(UiButtonResetEvent _) + private static void ResetButtonParents(UiButtonResetEvent _) { var wikiButton = MiraHudHelper.VanillaMatchInfoButton; var subButton = MiraHudHelper.SubmergedFloorButton; @@ -34,7 +34,7 @@ internal static class UiResetEvents } } - public static void PlaceWikiButton(UiButtonPostResetEvent @event) + private static void PlaceWikiButton(UiButtonPostResetEvent @event) { var wikiButton = MiraHudHelper.VanillaMatchInfoButton; if (!wikiButton) @@ -47,7 +47,7 @@ internal static class UiResetEvents wikiButton.transform.SetParent(opts.WikiOnBottomRow.Value ? secondRow.transform : firstRow.transform); } - public static void PlaceSubmergedButton(UiButtonPostResetEvent @event) + private static void PlaceSubmergedButton(UiButtonPostResetEvent @event) { var subButton = MiraHudHelper.SubmergedFloorButton; if (!subButton) @@ -58,7 +58,7 @@ internal static class UiResetEvents subButton.transform.SetParent(secondRow.transform); } - public static void PlaceModifierUi(UiButtonPostResetEvent @event) + private static void PlaceModifierUi(UiButtonPostResetEvent @event) { var modDisplay = MiraHudHelper.ModifierDisplayOnRight ? MiraHudHelper.ModifierDisplayObject : null!; if (!modDisplay) diff --git a/MiraAPI/Voting/VotingUtils.cs b/MiraAPI/Voting/VotingUtils.cs index bb33d0f..4edda79 100644 --- a/MiraAPI/Voting/VotingUtils.cs +++ b/MiraAPI/Voting/VotingUtils.cs @@ -114,7 +114,7 @@ public static class VotingUtils /// Networks the casting of a vote. We replace the vanilla solution with a custom version that works for Judge specifically. /// /// The who sent this RPC. - /// The id of the player who casted the vote. + /// The id of the player who cast the vote. /// The voted player's id. /// Data that is checked by the Judge role to determine which Judge takes priority. [MethodRpc((uint)MiraRpc.QueueOverruleVotes)] @@ -186,7 +186,7 @@ public static class VotingUtils /// Networks the casting of a vote. We replace the vanilla solution with a custom version that works for the use case. /// /// The who sent this RPC. - /// The id of the player who casted the vote. + /// The id of the player who cast the vote. /// The voted player's id. [MethodRpc((uint)MiraRpc.CastVote)] [SuppressMessage(