From df07369376078ddf8134e16400468d0bcfb8cb60 Mon Sep 17 00:00:00 2001 From: Az <56699741+AlchlcDvl@users.noreply.github.com> Date: Thu, 13 Aug 2026 23:20:22 -0400 Subject: [PATCH] clean up warnings and typos --- .editorconfig | 20 +- .gitignore | 2 +- MiraAPI.Example/Buttons/MeetingButton.cs | 8 +- MiraAPI.Example/ExampleLocalSetings.cs | 2 +- MiraAPI.Example/ExamplePlugin.cs | 9 +- MiraAPI.Example/MiraAPI.Example.csproj | 1 + .../Modifiers/GeneralModifierOptions.cs | 2 - MiraAPI.Example/Roles/ChameleonRole.cs | 8 +- MiraAPI.Example/Roles/FreezerRole.cs | 2 +- MiraAPI.Example/Roles/TeleporterRole.cs | 2 +- .../Events/Mira/MiraButtonCancelledEvent.cs | 38 ++-- MiraAPI/Events/Mira/MiraButtonClickEvent.cs | 43 ++--- MiraAPI/Events/MiraEventWrapper.cs | 19 +- MiraAPI/Events/RegisterEventAttribute.cs | 14 +- .../Vanilla/Gameplay/AfterMurderEvent.cs | 24 +-- .../Vanilla/Gameplay/BeforeGameEndEvent.cs | 14 +- .../Vanilla/Gameplay/BeforeMurderEvent.cs | 29 +-- .../Vanilla/Gameplay/BeforeRoundStartEvent.cs | 17 +- .../Events/Vanilla/Gameplay/GameEndEvent.cs | 14 +- .../Vanilla/Gameplay/IntroBeginEvent.cs | 14 +- .../Events/Vanilla/Gameplay/IntroEndEvent.cs | 1 + .../Vanilla/Gameplay/IntroRoleRevealEvent.cs | 14 +- .../Vanilla/Gameplay/RoundStartEvent.cs | 14 +- .../Events/Vanilla/Gameplay/SetRoleEvent.cs | 19 +- .../Gameplay/VanillaButtonCancelledEvent.cs | 28 +-- .../Gameplay/VanillaButtonClickEvent.cs | 43 ++--- MiraAPI/Events/Vanilla/Map/CloseDoorsEvent.cs | 14 +- .../Vanilla/Map/PlayerOpenSabotageEvent.cs | 14 +- .../Events/Vanilla/Map/UpdateSystemEvent.cs | 24 +-- .../Events/Vanilla/Meeting/EjectionEvent.cs | 14 +- .../Events/Vanilla/Meeting/ReportBodyEvent.cs | 24 +-- .../Vanilla/Meeting/StartMeetingEvent.cs | 14 +- .../Vanilla/Meeting/Voting/AfterVoteEvent.cs | 19 +- .../Vanilla/Meeting/Voting/BeforeVoteEvent.cs | 19 +- .../Meeting/Voting/CheckForEndVotingEvent.cs | 14 +- .../Vanilla/Meeting/Voting/DummyVoteEvent.cs | 23 +-- .../Vanilla/Meeting/Voting/HandleVoteEvent.cs | 34 ++-- .../Meeting/Voting/MeetingSelectEvent.cs | 27 +-- .../Meeting/Voting/PopulateResultsEvent.cs | 18 +- .../Meeting/Voting/ProcessVotesEvent.cs | 3 - .../Vanilla/Player/CompleteHnsTaskEvent.cs | 24 +-- .../Vanilla/Player/CompleteTaskEvent.cs | 19 +- .../Events/Vanilla/Player/PlayerDeathEvent.cs | 24 +-- .../Events/Vanilla/Player/PlayerJoinEvent.cs | 14 +- .../Events/Vanilla/Player/PlayerLeaveEvent.cs | 19 +- .../Events/Vanilla/Usables/EnterVentEvent.cs | 19 +- .../Events/Vanilla/Usables/ExitVentEvent.cs | 19 +- .../Vanilla/Usables/PlayerCanUseEvent.cs | 12 +- .../Events/Vanilla/Usables/PlayerUseEvent.cs | 21 +- MiraAPI/GameEnd/GameOverManager.cs | 7 +- MiraAPI/GameModes/.editorconfig | 4 +- MiraAPI/GameModes/CustomGameMode.cs | 50 ++++- MiraAPI/GameModes/CustomGameModeManager.cs | 4 + MiraAPI/GameModes/DefaultMode.cs | 8 + MiraAPI/GameOptions/AbstractOptionGroup.cs | 16 +- .../Attributes/ModdedNumberOptionAttribute.cs | 8 +- .../Attributes/ModdedToggleOptionAttribute.cs | 8 +- MiraAPI/GameOptions/ModdedOptionsManager.cs | 41 ++-- MiraAPI/GameOptions/ModifierOptionGroup.cs | 6 +- MiraAPI/GameOptions/OptionGroupSingleton.cs | 6 +- .../GameOptions/OptionNotifConfiguration.cs | 9 +- .../OptionTypes/ModdedEnumOption.cs | 28 ++- .../OptionTypes/ModdedNumberOption.cs | 2 +- .../GameOptions/OptionTypes/ModdedOption.cs | 2 +- .../OptionTypes/ModdedPlayerOption.cs | 4 +- .../OptionTypes/ModdedToggleOption.cs | 2 +- MiraAPI/Hud/CustomActionButton.cs | 5 +- MiraAPI/Hud/CustomButtonManager.cs | 10 +- MiraAPI/Hud/CustomPlayerMenu.cs | 8 +- MiraAPI/Hud/MultiTargetButton.cs | 7 +- MiraAPI/Keybinds/BaseKeybind.cs | 7 +- MiraAPI/Keybinds/KeybindManager.cs | 8 +- MiraAPI/Keybinds/KeybindUtils.cs | 7 +- MiraAPI/Keybinds/MiraGlobalKeybinds.cs | 4 +- MiraAPI/Keybinds/MiraKeybind.cs | 37 ++-- MiraAPI/Keybinds/VanillaKeybind.cs | 2 +- MiraAPI/Keybinds/VanillaKeybindSingleton.cs | 10 +- .../Attributes/LocalEnumSettingAttribute.cs | 3 +- .../Attributes/LocalNumberSettingAttribute.cs | 4 +- .../Attributes/LocalSettingAttribute.cs | 4 +- .../Attributes/LocalSliderSettingAttribute.cs | 4 + .../Attributes/LocalToggleSettingAttribute.cs | 1 - MiraAPI/LocalSettings/LocalSettingsManager.cs | 10 +- MiraAPI/LocalSettings/LocalSettingsTab.cs | 180 +++++++++--------- .../LocalSettingsTabSingleton.cs | 6 +- .../SettingTypes/LocalEnumSetting.cs | 40 ++-- .../SettingTypes/LocalNumberSetting.cs | 55 +++--- .../SettingTypes/LocalSliderSetting.cs | 63 +++--- .../SettingTypes/LocalToggleSetting.cs | 24 +-- MiraAPI/MiraAPI.csproj | 9 +- MiraAPI/MiraApiPlugin.cs | 1 + MiraAPI/MiraApiSettings.cs | 6 +- MiraAPI/Modifiers/BaseModifier.cs | 10 +- MiraAPI/Modifiers/ModifierComponent.cs | 52 ++--- .../ModifierDisplayComponent.cs | 2 + .../ModifierDisplay/ModifierUiComponent.cs | 4 +- MiraAPI/Modifiers/ModifierManager.cs | 9 +- MiraAPI/Modifiers/Types/GameModifier.cs | 25 ++- .../Networking/Modifiers/AddModifierRpc.cs | 17 +- MiraAPI/Networking/NetData.cs | 5 +- MiraAPI/Networking/SyncOptionsRpc.cs | 2 +- MiraAPI/Patches/.editorconfig | 13 +- .../Accessibility/HudManagerFlashPatches.cs | 13 +- MiraAPI/Patches/ChatControllerPatch.cs | 6 +- .../Patches/DetectiveNotesMinigamePatch.cs | 2 +- MiraAPI/Patches/Events/CanUsePatches.cs | 6 +- .../Patches/Events/SabotageEventPatches.cs | 4 +- .../Patches/Events/VanillaButtonPatches.cs | 15 +- .../Patches/Freeplay/TaskAddButtonPatches.cs | 12 +- MiraAPI/Patches/Freeplay/TaskAdderPatches.cs | 46 ++--- MiraAPI/Patches/GameModes/.editorconfig | 2 + MiraAPI/Patches/HudManagerPatches.cs | 12 +- .../Keybinds/OptionsMenuBehaviourPatch.cs | 15 +- .../LocalSettings/OptionsMenuPatches.cs | 25 +-- MiraAPI/Patches/Menu/HatsTabPatches.cs | 14 +- .../Patches/Menu/MainMenuManagerPatches.cs | 2 +- MiraAPI/Patches/Menu/NameplatesTabPatches.cs | 19 +- MiraAPI/Patches/Menu/SkinsTabPatches.cs | 6 +- MiraAPI/Patches/Menu/VisorsTabPatches.cs | 13 +- .../Patches/Modifiers/EndGameDidWinPatch.cs | 2 +- .../Patches/Options/GameOptionsMenuPatch.cs | 4 +- .../Patches/Options/GamePresetsTabPatches.cs | 3 +- .../Patches/Options/GameSettingMenuPatches.cs | 15 +- .../Patches/Options/LobbyViewPanePatches.cs | 7 +- MiraAPI/Patches/Options/MenuState.cs | 2 +- .../Options/NotificationPopperPatch.cs | 3 +- .../Patches/Options/RoleSettingMenuPatches.cs | 2 +- MiraAPI/Patches/Options/SettingPatches.cs | 48 ++--- MiraAPI/Patches/PlayerControlPatches.cs | 10 +- MiraAPI/Patches/Roles/HudManagerPatches.cs | 9 +- MiraAPI/Patches/Roles/KillButtonPatches.cs | 4 +- .../Roles/LogicRoleSelectionHnsPatch.cs | 6 +- MiraAPI/Patches/Roles/NameTagPatch.cs | 2 +- MiraAPI/Patches/Roles/RoleManagerPatches.cs | 8 +- .../Roles/RoleOptionsCollectionPatch.cs | 2 +- MiraAPI/Patches/Roles/SabotageButtonPatch.cs | 2 +- MiraAPI/Patches/Roles/SelectRolesPatch.cs | 18 +- MiraAPI/Patches/Roles/TaskPanelPatch.cs | 2 +- MiraAPI/Patches/ServerDropdownPatch.cs | 2 +- MiraAPI/Patches/Stubs/MinigameStubs.cs | 4 +- MiraAPI/Patches/Stubs/RoleBehaviourStubs.cs | 9 +- MiraAPI/Patches/TmpAwakePatch.cs | 1 + MiraAPI/Patches/Voting/DummyBehaviourPatch.cs | 14 +- MiraAPI/Patches/Voting/MeetingHudPatches.cs | 12 +- MiraAPI/PluginLoading/IMiraPlugin.cs | 20 +- MiraAPI/PluginLoading/MiraPluginInfo.cs | 10 +- MiraAPI/PluginLoading/MiraPluginManager.cs | 1 - MiraAPI/Presets/OptionPreset.cs | 32 ++-- MiraAPI/Presets/PresetManager.cs | 39 ++-- MiraAPI/Presets/SavePresetPopup.cs | 14 +- MiraAPI/Roles/CustomRoleConfiguration.cs | 5 +- MiraAPI/Roles/CustomRoleManager.cs | 4 +- MiraAPI/Roles/CustomRoleUtils.cs | 55 +++--- MiraAPI/Roles/ICustomRole.cs | 55 +++--- MiraAPI/Roles/RoleId.cs | 18 +- .../Utilities/Assets/AddressablesLoader.cs | 16 +- .../Utilities/Assets/LoadableBundleAsset.cs | 9 +- .../Utilities/Assets/LoadableResourceAsset.cs | 8 +- MiraAPI/Utilities/Assets/TmpSpriteUtils.cs | 43 ++++- MiraAPI/Utilities/ColorExtensions.cs | 17 +- MiraAPI/Utilities/ControllableComparer.cs | 18 +- MiraAPI/Utilities/Extensions.cs | 51 +++-- MiraAPI/Utilities/Helpers.cs | 69 +++---- MiraAPI/Utilities/ShaderID.cs | 160 +++++++++++++++- MiraAPI/Utilities/StateMachineWrapper.cs | 15 +- MiraAPI/Voting/PlayerVoteData.cs | 4 +- MiraAPI/Voting/VotingUtils.cs | 10 +- 167 files changed, 1335 insertions(+), 1433 deletions(-) diff --git a/.editorconfig b/.editorconfig index e091cf9..02994df 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1 +1,19 @@ -[*.{cs,vb}] \ No newline at end of file +[*.{cs,vb}] + +# IDE0008: Use explicit type +dotnet_diagnostic.IDE0008.severity = none + +# IDE0160: Convert to block scoped namespace +dotnet_diagnostic.IDE0160.severity = none + +# IDE0011: Add braces +dotnet_diagnostic.IDE0011.severity = none + +# CS8618: Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. +dotnet_diagnostic.CS8618.severity = none + +# CA1805: Do not initialize unnecessarily +dotnet_diagnostic.CA1805.severity = none + +# S3358: Ternary operators should not be nested +dotnet_diagnostic.S3358.severity = none diff --git a/.gitignore b/.gitignore index aa43b10..b52f379 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ .git/ .idea/ -.vs/ +.vs*/ obj/ bin/ .qodo/ diff --git a/MiraAPI.Example/Buttons/MeetingButton.cs b/MiraAPI.Example/Buttons/MeetingButton.cs index 8ca1b82..650bdac 100644 --- a/MiraAPI.Example/Buttons/MeetingButton.cs +++ b/MiraAPI.Example/Buttons/MeetingButton.cs @@ -10,9 +10,7 @@ namespace MiraAPI.Example.Buttons; public class MeetingButton : CustomActionButton { public override string Name => "Call Meeting"; - public override float Cooldown => 15; - public override int MaxUses => 3; public override LoadableAsset Sprite => ExampleAssets.ExampleButton; @@ -30,10 +28,10 @@ public class MeetingButton : CustomActionButton PlayerControl.LocalPlayer.NetTransform.Halt(); var minigame = Object.Instantiate(bt.MinigamePrefab, Camera.main!.transform, false); - var taskAdderGame = minigame as TaskAdderGame; - if (taskAdderGame != null) + var taskAdderGame = minigame.TryCast(); + if (taskAdderGame) { - taskAdderGame.SafePositionWorld = bt.SafePositionLocal + (Vector2)bt.transform.position; + taskAdderGame!.SafePositionWorld = bt.SafePositionLocal + (Vector2)bt.transform.position; } minigame.transform.localPosition = new Vector3(0f, 0f, -50f); diff --git a/MiraAPI.Example/ExampleLocalSetings.cs b/MiraAPI.Example/ExampleLocalSetings.cs index bac0507..4d277ef 100644 --- a/MiraAPI.Example/ExampleLocalSetings.cs +++ b/MiraAPI.Example/ExampleLocalSetings.cs @@ -33,7 +33,7 @@ public class ExampleLocalSettings(ConfigFile config) : LocalSettingsTab(config) public ConfigEntry ExampleNumber { get; private set; } = config.Bind("General", "Example Number", 4f); [LocalNumberSetting(min: 0.1f, max: 2.5f, increment: 0.1f, formatString: "0.0", suffixType: MiraNumberSuffixes.Multiplier)] - public ConfigEntry ExampleFloatNumber { get; private set; } = config.Bind("General", "Example Multplier", 1f); + public ConfigEntry ExampleFloatNumber { get; private set; } = config.Bind("General", "Example Multiplier", 1f); [LocalEnumSetting] public ConfigEntry ExampleEnum { get; private set; } = config.Bind("General", "Example Enum", ExampleEnumSetting.Fries); diff --git a/MiraAPI.Example/ExamplePlugin.cs b/MiraAPI.Example/ExamplePlugin.cs index b20ec41..85c9487 100644 --- a/MiraAPI.Example/ExamplePlugin.cs +++ b/MiraAPI.Example/ExamplePlugin.cs @@ -17,8 +17,13 @@ namespace MiraAPI.Example; public partial class ExamplePlugin : BasePlugin, IMiraPlugin { public Harmony Harmony { get; } = new(Id); - public string OptionsTitleText => "Mira API\nExample Mod"; - public ConfigFile GetConfigFile() => Config; + public string OptionsTitleText { get; } = "Mira API\nExample Mod"; + + public ConfigFile GetConfigFile() + { + return Config; + } + public override void Load() { ExampleEventHandlers.Initialize(); diff --git a/MiraAPI.Example/MiraAPI.Example.csproj b/MiraAPI.Example/MiraAPI.Example.csproj index d0b23ac..60753ad 100644 --- a/MiraAPI.Example/MiraAPI.Example.csproj +++ b/MiraAPI.Example/MiraAPI.Example.csproj @@ -3,6 +3,7 @@ 1.0.0 Example mod for Mira API Angxl, XtraCube + $(NoWarn);EnableGenerateDocumentationFile diff --git a/MiraAPI.Example/Options/Modifiers/GeneralModifierOptions.cs b/MiraAPI.Example/Options/Modifiers/GeneralModifierOptions.cs index 0bcbcdc..089a33e 100644 --- a/MiraAPI.Example/Options/Modifiers/GeneralModifierOptions.cs +++ b/MiraAPI.Example/Options/Modifiers/GeneralModifierOptions.cs @@ -6,9 +6,7 @@ namespace MiraAPI.Example.Options.Modifiers; public class GeneralModifierOptions : AbstractOptionGroup { public override string GroupName => "General"; - public override uint GroupPriority => 0; - public override MenuCategory ParentMenu => MenuCategory.Modifiers; [ModdedToggleOption("Some Boolean Option")] diff --git a/MiraAPI.Example/Roles/ChameleonRole.cs b/MiraAPI.Example/Roles/ChameleonRole.cs index f601551..d38d406 100644 --- a/MiraAPI.Example/Roles/ChameleonRole.cs +++ b/MiraAPI.Example/Roles/ChameleonRole.cs @@ -8,9 +8,9 @@ using UnityEngine; namespace MiraAPI.Example.Roles; -public class ChameloenRole : CrewmateRole, ICustomRole +public class ChameleonRole : CrewmateRole, ICustomRole { - public string RoleName => "Chamelon"; + public string RoleName => "Chameleon"; public string RoleLongDescription => "Stay invisible while not moving."; public string RoleDescription => RoleLongDescription; public Color RoleColor => Palette.AcceptedGreen; @@ -28,7 +28,7 @@ public class ChameloenRole : CrewmateRole, ICustomRole public override void Initialize(PlayerControl player) { - Logger.Info("Initializing ChamelonRole for player: " + player.PlayerId); + Logger.Info("Initializing ChameleonRole for player: " + player.PlayerId); RoleBehaviourStubs.Initialize(this, player); _shouldHide = true; } @@ -68,7 +68,7 @@ public class ChameloenRole : CrewmateRole, ICustomRole public override void Deinitialize(PlayerControl targetPlayer) { - Logger.Info("Deinitializing ChamelonRole for player: " + targetPlayer.PlayerId); + Logger.Info("Deinitializing ChameleonRole for player: " + targetPlayer.PlayerId); RoleBehaviourStubs.Deinitialize(this, targetPlayer); _shouldHide = false; foreach (var cosmetic in Player.cosmetics.transform.GetComponentsInChildren(true)) diff --git a/MiraAPI.Example/Roles/FreezerRole.cs b/MiraAPI.Example/Roles/FreezerRole.cs index 5a7f4bd..d3a15ac 100644 --- a/MiraAPI.Example/Roles/FreezerRole.cs +++ b/MiraAPI.Example/Roles/FreezerRole.cs @@ -12,7 +12,7 @@ public class FreezerRole : ImpostorRole, ICustomRole public Color RoleColor => Palette.Blue; public ModdedRoleTeams Team => ModdedRoleTeams.Impostor; - public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this) + public CustomRoleConfiguration Configuration => new(this) { Icon = MiraAssets.ImpostorFile, IconTmp = TmpSpriteUtils.CreateSpriteAsset(MiraAssets.ImpostorFile.LoadAsset(), "ApiExample.Role.Impostor.FreezerRole"), diff --git a/MiraAPI.Example/Roles/TeleporterRole.cs b/MiraAPI.Example/Roles/TeleporterRole.cs index 5b00f63..d6a954d 100644 --- a/MiraAPI.Example/Roles/TeleporterRole.cs +++ b/MiraAPI.Example/Roles/TeleporterRole.cs @@ -11,7 +11,7 @@ public class TeleporterRole : CrewmateRole, ICustomRole public Color RoleColor => new Color32(221, 176, 152, 255); public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate; - public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this) + public CustomRoleConfiguration Configuration => new(this) { OptionsScreenshot = ExampleAssets.Banner, CanModifyChance = false, diff --git a/MiraAPI/Events/Mira/MiraButtonCancelledEvent.cs b/MiraAPI/Events/Mira/MiraButtonCancelledEvent.cs index e6c7c15..03bb233 100644 --- a/MiraAPI/Events/Mira/MiraButtonCancelledEvent.cs +++ b/MiraAPI/Events/Mira/MiraButtonCancelledEvent.cs @@ -3,42 +3,32 @@ namespace MiraAPI.Events.Mira; /// -/// Invoked when a click is cancelled. Do not use for vanilla s. +/// Invoked when a click is cancelled. /// +/// +/// Do not use for vanilla s. +/// /// The type. -public sealed class MiraButtonCancelledEvent : MiraEvent where T : CustomActionButton +/// The whose click was cancelled. +public sealed class MiraButtonCancelledEvent(T button) : MiraEvent where T : CustomActionButton { /// /// Gets the whose click was cancelled. /// - public T Button { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The whose click was cancelled. - public MiraButtonCancelledEvent(T button) - { - Button = button; - } + public T Button { get; } = button; } /// -/// Invoked when a click is cancelled. Do not use for vanilla s. +/// Invoked when a click is cancelled. /// -public sealed class MiraButtonCancelledEvent : MiraEvent +/// +/// Do not use for vanilla s. +/// +/// The whose click was cancelled. +public sealed class MiraButtonCancelledEvent(CustomActionButton button) : MiraEvent { /// /// Gets the whose click was cancelled. /// - public CustomActionButton Button { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The whose click was cancelled. - public MiraButtonCancelledEvent(CustomActionButton button) - { - Button = button; - } + public CustomActionButton Button { get; } = button; } diff --git a/MiraAPI/Events/Mira/MiraButtonClickEvent.cs b/MiraAPI/Events/Mira/MiraButtonClickEvent.cs index 401cc11..dea3635 100644 --- a/MiraAPI/Events/Mira/MiraButtonClickEvent.cs +++ b/MiraAPI/Events/Mira/MiraButtonClickEvent.cs @@ -3,49 +3,38 @@ namespace MiraAPI.Events.Mira; /// -/// Button click event for s only. Do not use for vanilla s. +/// Button click event for s only. /// +/// +/// Do not use for vanilla s. +/// /// The type. -public sealed class MiraButtonClickEvent : MiraCancelableEvent where T : CustomActionButton +/// The that was clicked. +/// The generic invoked before button-specific events. +public sealed class MiraButtonClickEvent(T button, MiraButtonClickEvent genericClickEvent) : MiraCancelableEvent where T : CustomActionButton { /// /// Gets the that was clicked. /// - public T Button { get; } + public T Button { get; } = button; /// /// Gets the generic that is invoked before this button-specific event. /// - public MiraButtonClickEvent GenericClickEvent { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The that was clicked. - /// The generic invoked before button-specific events. - public MiraButtonClickEvent(T button, MiraButtonClickEvent genericClickEvent) - { - GenericClickEvent = genericClickEvent; - Button = button; - } + public MiraButtonClickEvent GenericClickEvent { get; } = genericClickEvent; } /// -/// Button click event for s only. Do not use for vanilla s. +/// Button click event for s only. /// -public sealed class MiraButtonClickEvent : MiraCancelableEvent +/// +/// Do not use for vanilla s. +/// +/// The that was clicked. +public sealed class MiraButtonClickEvent(CustomActionButton button) : MiraCancelableEvent { /// /// Gets the that was clicked. /// - public CustomActionButton Button { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The that was clicked. - public MiraButtonClickEvent(CustomActionButton button) - { - Button = button; - } + public CustomActionButton Button { get; } = button; } diff --git a/MiraAPI/Events/MiraEventWrapper.cs b/MiraAPI/Events/MiraEventWrapper.cs index 3784688..2a2c410 100644 --- a/MiraAPI/Events/MiraEventWrapper.cs +++ b/MiraAPI/Events/MiraEventWrapper.cs @@ -5,26 +5,17 @@ namespace MiraAPI.Events; /// /// Wrapper for handlers. /// -public class MiraEventWrapper +/// The action for the event handler. +/// The priority of the handler. +public class MiraEventWrapper(Delegate eventHandler, int priority) { /// /// Gets the event handler delegate. /// - public Delegate EventHandler { get; } + public Delegate EventHandler { get; } = eventHandler; /// /// Gets the priority of the handler. Lower values are called first. /// - public int Priority { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The action for the event handler. - /// The priority of the handler. - public MiraEventWrapper(Delegate eventHandler, int priority) - { - EventHandler = eventHandler; - Priority = priority; - } + public int Priority { get; } = priority; } diff --git a/MiraAPI/Events/RegisterEventAttribute.cs b/MiraAPI/Events/RegisterEventAttribute.cs index 2fee367..062f30e 100644 --- a/MiraAPI/Events/RegisterEventAttribute.cs +++ b/MiraAPI/Events/RegisterEventAttribute.cs @@ -5,20 +5,12 @@ namespace MiraAPI.Events; /// /// Register a handler. /// +/// The priority of the event. Lower values are called first. [AttributeUsage(AttributeTargets.Method)] -public class RegisterEventAttribute : Attribute +public class RegisterEventAttribute(int priority = 0) : Attribute { /// /// Gets the priority of the event. Lower values are called first. /// - public int Priority { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The priority of the event. Lower values are called first. - public RegisterEventAttribute(int priority = 0) - { - Priority = priority; - } + public int Priority { get; } = priority; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/AfterMurderEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/AfterMurderEvent.cs index 8b85622..8b6455c 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/AfterMurderEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/AfterMurderEvent.cs @@ -3,33 +3,23 @@ /// /// Event that is invoked after a player is murdered. Only called after a successful murder. This event is not cancelable. /// -public class AfterMurderEvent : MiraEvent +/// The killer. +/// The killed . +/// The 's , if it exists. +public class AfterMurderEvent(PlayerControl source, PlayerControl target, DeadBody? deadBody) : MiraEvent { /// /// Gets the that killed the . /// - public PlayerControl Source { get; } + public PlayerControl Source { get; } = source; /// /// Gets the that was killed. /// - public PlayerControl Target { get; } + public PlayerControl Target { get; } = target; /// /// Gets the 's , if it exists. /// - public DeadBody? DeadBody { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The killer. - /// The killed . - /// The 's , if it exists. - public AfterMurderEvent(PlayerControl source, PlayerControl target, DeadBody? deadBody) - { - Source = source; - Target = target; - DeadBody = deadBody; - } + public DeadBody? DeadBody { get; } = deadBody; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/BeforeGameEndEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/BeforeGameEndEvent.cs index 9703bd5..0b96741 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/BeforeGameEndEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/BeforeGameEndEvent.cs @@ -3,19 +3,11 @@ /// /// Invoked before is called, allowing cancellation of the game end entirely. /// -public class BeforeGameEndEvent : MiraCancelableEvent +/// The reason for the game end. +public class BeforeGameEndEvent(GameOverReason reason) : MiraCancelableEvent { /// /// Gets the reason for the game end. /// - public GameOverReason Reason { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The reason for the game end. - public BeforeGameEndEvent(GameOverReason reason) - { - Reason = reason; - } + public GameOverReason Reason { get; } = reason; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs index cc07e21..0d2d3e7 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs @@ -5,45 +5,32 @@ namespace MiraAPI.Events.Vanilla.Gameplay; /// /// Event that is invoked before a player is murdered. This event is cancelable. /// -public sealed class BeforeMurderEvent : MiraCancelableEvent +/// The that is killing the . +/// The that is being killed. +/// Whether the murder is intended to be triggered in a meeting. +public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target, MeetingCheck inMeeting) : MiraCancelableEvent { /// /// Gets the that is killing the . /// - public PlayerControl Source { get; } + public PlayerControl Source { get; } = source; /// /// Gets the that is being killed. /// - public PlayerControl Target { get; } + public PlayerControl Target { get; } = target; /// /// Gets whether the murder was meant to be done in a meeting, via an enum. /// - public MeetingCheck InMeeting { get; } + public MeetingCheck InMeeting { get; } = inMeeting; /// /// Initializes a new instance of the class. /// /// The that is killing the . /// The that is being killed. - /// Whether the murder is intended to be triggered in a meeting. - public BeforeMurderEvent(PlayerControl source, PlayerControl target, MeetingCheck inMeeting) + public BeforeMurderEvent(PlayerControl source, PlayerControl target) : this(source, target, MeetingCheck.Ignore) { - Source = source; - Target = target; - InMeeting = inMeeting; - } - - /// - /// Initializes a new instance of the class. - /// - /// The that is killing the . - /// The that is being killed. - public BeforeMurderEvent(PlayerControl source, PlayerControl target) - { - Source = source; - Target = target; - InMeeting = MeetingCheck.Ignore; } } diff --git a/MiraAPI/Events/Vanilla/Gameplay/BeforeRoundStartEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/BeforeRoundStartEvent.cs index 77422af..841f24d 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/BeforeRoundStartEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/BeforeRoundStartEvent.cs @@ -1,22 +1,13 @@ namespace MiraAPI.Events.Vanilla.Gameplay; /// -/// Event invoked on and -/// to determine if it should run the event or not. +/// Event invoked on and to determine if it should run the event or not. /// -public class BeforeRoundStartEvent : MiraCancelableEvent +/// Whether the event was triggered by the intro or not. +public class BeforeRoundStartEvent(bool triggeredByIntro) : MiraCancelableEvent { /// /// Gets a value indicating whether the event was triggered by the or . /// - public bool TriggeredByIntro { get; } - - /// - /// Initializes a new instance of the class. - /// - /// Whether the event was triggered by the intro or not. - public BeforeRoundStartEvent(bool triggeredByIntro) - { - TriggeredByIntro = triggeredByIntro; - } + public bool TriggeredByIntro { get; } = triggeredByIntro; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/GameEndEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/GameEndEvent.cs index d44dae5..df030a8 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/GameEndEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/GameEndEvent.cs @@ -3,19 +3,11 @@ /// /// The event that is invoked when the end game screen is shown. Non cancelable. /// -public class GameEndEvent : MiraEvent +/// The instance. +public class GameEndEvent(EndGameManager manager) : MiraEvent { /// /// Gets the instance. /// - public EndGameManager EndGameManager { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The instance. - public GameEndEvent(EndGameManager manager) - { - EndGameManager = manager; - } + public EndGameManager EndGameManager { get; } = manager; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/IntroBeginEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/IntroBeginEvent.cs index b08ec56..7de4c6c 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/IntroBeginEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/IntroBeginEvent.cs @@ -3,19 +3,11 @@ /// /// The event that is invoked when the intro cutscene is shown. Non cancelable. /// -public class IntroBeginEvent : MiraEvent +/// The intro cutscene. +public class IntroBeginEvent(IntroCutscene introCutscene) : MiraEvent { /// /// Gets the instance. /// - public IntroCutscene IntroCutscene { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The intro cutscene. - public IntroBeginEvent(IntroCutscene introCutscene) - { - IntroCutscene = introCutscene; - } + public IntroCutscene IntroCutscene { get; } = introCutscene; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/IntroEndEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/IntroEndEvent.cs index a23b960..bdd64bd 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/IntroEndEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/IntroEndEvent.cs @@ -3,6 +3,7 @@ /// /// The event that is invoked when the intro cutscene has finished playing. /// +/// The intro cutscene. public class IntroEndEvent(IntroCutscene introCutscene) : MiraEvent { /// diff --git a/MiraAPI/Events/Vanilla/Gameplay/IntroRoleRevealEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/IntroRoleRevealEvent.cs index 1ffdf67..95ff2a2 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/IntroRoleRevealEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/IntroRoleRevealEvent.cs @@ -3,19 +3,11 @@ /// /// The event that is invoked when the player's role is shown on the intro cutscene. Non cancelable. /// -public class IntroRoleRevealEvent : MiraEvent +/// The intro cutscene. +public class IntroRoleRevealEvent(IntroCutscene introCutscene) : MiraEvent { /// /// Gets the instance. /// - public IntroCutscene IntroCutscene { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The intro cutscene. - public IntroRoleRevealEvent(IntroCutscene introCutscene) - { - IntroCutscene = introCutscene; - } + public IntroCutscene IntroCutscene { get; } = introCutscene; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/RoundStartEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/RoundStartEvent.cs index 93a7bfd..e9356ed 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/RoundStartEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/RoundStartEvent.cs @@ -4,19 +4,11 @@ /// Start Round event, invoked on and /// if the isn't cancelled. /// -public class RoundStartEvent : MiraEvent +/// Whether the event was triggered by the intro or not. +public class RoundStartEvent(bool triggeredByIntro) : MiraEvent { /// /// Gets a value indicating whether the event was triggered by the or . /// - public bool TriggeredByIntro { get; } - - /// - /// Initializes a new instance of the class. - /// - /// Whether the event was triggered by the intro or not. - public RoundStartEvent(bool triggeredByIntro) - { - TriggeredByIntro = triggeredByIntro; - } + public bool TriggeredByIntro { get; } = triggeredByIntro; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/SetRoleEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/SetRoleEvent.cs index 1ebfd78..f20996a 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/SetRoleEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/SetRoleEvent.cs @@ -5,26 +5,17 @@ namespace MiraAPI.Events.Vanilla.Gameplay; /// /// Event that is invoked after a player's role is set. This event is not cancelable. /// -public class SetRoleEvent : MiraEvent +/// The player. +/// The new role. +public class SetRoleEvent(PlayerControl player, RoleTypes role) : MiraEvent { /// /// Gets the whose role was changed. /// - public PlayerControl Player { get; } + public PlayerControl Player { get; } = player; /// /// Gets the role that the player was set to. /// - public RoleTypes Role { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The player. - /// The new role. - public SetRoleEvent(PlayerControl player, RoleTypes role) - { - Player = player; - Role = role; - } + public RoleTypes Role { get; } = role; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonCancelledEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonCancelledEvent.cs index 9e334b8..cf1bbbd 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonCancelledEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonCancelledEvent.cs @@ -6,39 +6,23 @@ namespace MiraAPI.Events.Vanilla.Gameplay; /// Invoked when a Vanilla click is cancelled. Do not use for . /// /// The vanilla type. -public sealed class VanillaButtonCancelledEvent : MiraEvent where T : AbilityButton +/// The vanilla whose click was cancelled. +public sealed class VanillaButtonCancelledEvent(T button) : MiraEvent where T : AbilityButton { /// /// Gets the Vanilla whose click was cancelled. /// - public T Button { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The vanilla whose click was cancelled. - public VanillaButtonCancelledEvent(T button) - { - Button = button; - } + public T Button { get; } = button; } /// /// Invoked when a Vanilla click is cancelled. Do not use for s. /// -public sealed class VanillaButtonCancelledEvent : MiraEvent +/// The vanilla whose click was cancelled. +public sealed class VanillaButtonCancelledEvent(AbilityButton button) : MiraEvent { /// /// Gets the Vanilla whose click was cancelled. /// - public AbilityButton Button { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The vanilla whose click was cancelled. - public VanillaButtonCancelledEvent(AbilityButton button) - { - Button = button; - } + public AbilityButton Button { get; } = button; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonClickEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonClickEvent.cs index 563cf66..8c03d30 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonClickEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonClickEvent.cs @@ -6,60 +6,41 @@ namespace MiraAPI.Events.Vanilla.Gameplay; /// Button click event for Vanilla s only. Do not use for s. /// /// The vanilla type. -public sealed class VanillaButtonClickEvent : MiraCancelableEvent where T : AbilityButton +/// The vanilla that was clicked. +/// The generic invoked before button-specific events. +public sealed class VanillaButtonClickEvent(T button, VanillaButtonClickEvent genericClickEvent) : MiraCancelableEvent where T : AbilityButton { /// /// Gets the vanilla that was clicked. /// - public T Button { get; } + public T Button { get; } = button; /// /// Gets the generic that is invoked before this button-specific event. /// - public VanillaButtonClickEvent GenericClickEvent { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The vanilla that was clicked. - /// The generic invoked before button-specific events. - public VanillaButtonClickEvent(T button, VanillaButtonClickEvent genericClickEvent) - { - GenericClickEvent = genericClickEvent; - Button = button; - } + public VanillaButtonClickEvent GenericClickEvent { get; } = genericClickEvent; } /// /// Button click event for Vanilla only. Do not use for s. /// -public sealed class VanillaButtonClickEvent : MiraCancelableEvent +/// The Vanilla that was clicked. +/// The target, if any. +/// The target, if any. +public sealed class VanillaButtonClickEvent(AbilityButton button, PlayerControl? playerTarget = null, Vent? ventTarget = null) : MiraCancelableEvent { /// /// Gets the Vanilla that was clicked. /// - public AbilityButton Button { get; } + public AbilityButton Button { get; } = button; /// /// Gets the target , if any, of the Vanilla that was clicked. /// - public PlayerControl? PlayerTarget { get; } + public PlayerControl? PlayerTarget { get; } = playerTarget; /// /// Gets the target , if any, of the Vanilla that was clicked. /// - public Vent? VentTarget { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The Vanilla that was clicked. - /// The target, if any. - /// The target, if any. - public VanillaButtonClickEvent(AbilityButton button, PlayerControl? playerTarget = null, Vent? ventTarget = null) - { - Button = button; - PlayerTarget = playerTarget; - VentTarget = ventTarget; - } + public Vent? VentTarget { get; } = ventTarget; } diff --git a/MiraAPI/Events/Vanilla/Map/CloseDoorsEvent.cs b/MiraAPI/Events/Vanilla/Map/CloseDoorsEvent.cs index 86f2bfd..d0ce1cc 100644 --- a/MiraAPI/Events/Vanilla/Map/CloseDoorsEvent.cs +++ b/MiraAPI/Events/Vanilla/Map/CloseDoorsEvent.cs @@ -3,19 +3,11 @@ /// /// Event fired when a player closes the doors in a room. /// -public class CloseDoorsEvent : MiraCancelableEvent +/// The room that was closed. +public class CloseDoorsEvent(SystemTypes room) : MiraCancelableEvent { /// /// Gets the room that the doors were closed in. /// - public SystemTypes Room { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The room that was closed. - public CloseDoorsEvent(SystemTypes room) - { - Room = room; - } + public SystemTypes Room { get; } = room; } diff --git a/MiraAPI/Events/Vanilla/Map/PlayerOpenSabotageEvent.cs b/MiraAPI/Events/Vanilla/Map/PlayerOpenSabotageEvent.cs index 6415d70..4e9327f 100644 --- a/MiraAPI/Events/Vanilla/Map/PlayerOpenSabotageEvent.cs +++ b/MiraAPI/Events/Vanilla/Map/PlayerOpenSabotageEvent.cs @@ -3,19 +3,11 @@ /// /// Sabotage from Vanilla Among Us. /// -public class PlayerOpenSabotageEvent : MiraCancelableEvent +/// The . +public class PlayerOpenSabotageEvent(MapBehaviour mapBehaviour) : MiraCancelableEvent { /// /// Gets the . /// - public MapBehaviour MapBehaviour { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The . - public PlayerOpenSabotageEvent(MapBehaviour mapBehaviour) - { - MapBehaviour = mapBehaviour; - } + public MapBehaviour MapBehaviour { get; } = mapBehaviour; } diff --git a/MiraAPI/Events/Vanilla/Map/UpdateSystemEvent.cs b/MiraAPI/Events/Vanilla/Map/UpdateSystemEvent.cs index 5e2219c..b1382e5 100644 --- a/MiraAPI/Events/Vanilla/Map/UpdateSystemEvent.cs +++ b/MiraAPI/Events/Vanilla/Map/UpdateSystemEvent.cs @@ -3,33 +3,23 @@ /// /// that is invoked before a system is updated. Usually used for sabotage events. /// -public class UpdateSystemEvent : MiraCancelableEvent +/// The being updated. +/// The that is updating the system. +/// Amount to update System to. +public class UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byte amount) : MiraCancelableEvent { /// /// Gets the type of system that will be updated. /// - public SystemTypes SystemType { get; } + public SystemTypes SystemType { get; } = systemType; /// /// Gets the that is updating the system. /// - public PlayerControl Player { get; } + public PlayerControl Player { get; } = player; /// /// Gets the byte amount the system is being updated by. /// - public byte Amount { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The being updated. - /// The that is updating the system. - /// Amount to update System to. - public UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byte amount) - { - SystemType = systemType; - Player = player; - Amount = amount; - } + public byte Amount { get; } = amount; } diff --git a/MiraAPI/Events/Vanilla/Meeting/EjectionEvent.cs b/MiraAPI/Events/Vanilla/Meeting/EjectionEvent.cs index 054335c..5c0eaef 100644 --- a/MiraAPI/Events/Vanilla/Meeting/EjectionEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/EjectionEvent.cs @@ -3,19 +3,11 @@ /// /// The event that is invoked when a player is ejected. Non-cancelable. /// -public class EjectionEvent : MiraEvent +/// The instance. +public class EjectionEvent(ExileController controller) : MiraEvent { /// /// Gets the instance. /// - public ExileController ExileController { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The instance. - public EjectionEvent(ExileController controller) - { - ExileController = controller; - } + public ExileController ExileController { get; } = controller; } diff --git a/MiraAPI/Events/Vanilla/Meeting/ReportBodyEvent.cs b/MiraAPI/Events/Vanilla/Meeting/ReportBodyEvent.cs index fb085b6..7847e78 100644 --- a/MiraAPI/Events/Vanilla/Meeting/ReportBodyEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/ReportBodyEvent.cs @@ -4,33 +4,23 @@ /// The event that is invoked when a body is reported. /// This is invoked in . /// -public class ReportBodyEvent : MiraCancelableEvent +/// The player who reported the body. +/// The player being reported. +/// The being reported. +public class ReportBodyEvent(PlayerControl reporter, NetworkedPlayerInfo? target, DeadBody? body) : MiraCancelableEvent { /// /// Gets the player that is reporting the body. /// - public PlayerControl Reporter { get; } + public PlayerControl Reporter { get; } = reporter; /// /// Gets the player that is being reported. Will be for emergency meeting. /// - public NetworkedPlayerInfo? Target { get; } + public NetworkedPlayerInfo? Target { get; } = target; /// /// Gets the that is being reported. Will be for emergency meeting. /// - public DeadBody? Body { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The player who reported the body. - /// The player being reported. - /// The being reported. - public ReportBodyEvent(PlayerControl reporter, NetworkedPlayerInfo? target, DeadBody? body) - { - Reporter = reporter; - Target = target; - Body = body; - } + public DeadBody? Body { get; } = body; } diff --git a/MiraAPI/Events/Vanilla/Meeting/StartMeetingEvent.cs b/MiraAPI/Events/Vanilla/Meeting/StartMeetingEvent.cs index 0a15d99..a38b3c6 100644 --- a/MiraAPI/Events/Vanilla/Meeting/StartMeetingEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/StartMeetingEvent.cs @@ -4,19 +4,11 @@ /// The event that is invoked when a meeting is called. This event is not cancelable. /// This event is called after Mira resets votes, so if you plan on adding votes to a specific player, do it with this event. /// -public class StartMeetingEvent : MiraEvent +/// The instance. +public class StartMeetingEvent(MeetingHud meetingHud) : MiraEvent { /// /// Gets the instance. /// - public MeetingHud MeetingHud { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The instance. - public StartMeetingEvent(MeetingHud meetingHud) - { - MeetingHud = meetingHud; - } + public MeetingHud MeetingHud { get; } = meetingHud; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/AfterVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/AfterVoteEvent.cs index 60a3d36..34df3f9 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/AfterVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/AfterVoteEvent.cs @@ -3,26 +3,17 @@ /// /// Event that is invoked after the local player successfully votes a player or skips. This event is not cancelable. /// -public class AfterVoteEvent : MiraEvent +/// The that was voted on. +/// The player who voted. +public class AfterVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter) : MiraEvent { /// /// Gets the instance of the voter's . /// - public PlayerVoteArea VoteArea { get; } + public PlayerVoteArea VoteArea { get; } = playerVoteArea; /// /// Gets the player who voted. /// - public PlayerControl Player { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The that was voted on. - /// The player who voted. - public AfterVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter) - { - VoteArea = playerVoteArea; - Player = voter; - } + public PlayerControl Player { get; } = voter; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/BeforeVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/BeforeVoteEvent.cs index e6b28f9..9d21b71 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/BeforeVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/BeforeVoteEvent.cs @@ -3,26 +3,17 @@ /// /// Event that is invoked before the local player confirms a vote on a player or when skipping. This event is cancelable. /// -public class BeforeVoteEvent : MiraCancelableEvent +/// The that was voted on. +/// The player who voted. +public class BeforeVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter) : MiraCancelableEvent { /// /// Gets the instance of the voter's . /// - public PlayerVoteArea VoteArea { get; } + public PlayerVoteArea VoteArea { get; } = playerVoteArea; /// /// Gets the player who voted. /// - public PlayerControl Player { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The that was voted on. - /// The player who voted. - public BeforeVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter) - { - VoteArea = playerVoteArea; - Player = voter; - } + public PlayerControl Player { get; } = voter; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs index 988cdc4..952b298 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs @@ -3,24 +3,16 @@ /// /// Checks if voting is complete. If canceled, the default end voting logic will be skipped. /// -public class CheckForEndVotingEvent : MiraCancelableEvent +/// if voting is complete, otherwise. +public class CheckForEndVotingEvent(bool isVotingComplete) : MiraCancelableEvent { /// /// Gets a value indicating whether default voting logic determines that voting is complete. /// - public bool IsVotingComplete { get; } + public bool IsVotingComplete { get; } = isVotingComplete; /// /// Gets or sets a value indicating whether the voting should be forced to end, regardless of the default logic. /// public bool ForceEndVoting { get; set; } - - /// - /// Initializes a new instance of the class. - /// - /// if voting is complete, otherwise. - public CheckForEndVotingEvent(bool isVotingComplete) - { - IsVotingComplete = isVotingComplete; - } } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/DummyVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/DummyVoteEvent.cs index ea3aa69..1bb0bc8 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/DummyVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/DummyVoteEvent.cs @@ -7,38 +7,27 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting; /// /// Invoked before the dummy selects their vote. If canceled, the dummy won't vote. /// -public class DummyVoteEvent : MiraCancelableEvent +/// The voting dummy. +public class DummyVoteEvent(DummyBehaviour dummy) : MiraCancelableEvent { /// /// Gets the dummy that needs to vote. /// - public DummyBehaviour Dummy { get; } + public DummyBehaviour Dummy { get; } = dummy; /// /// Gets the instance of the dummy's . /// - public PlayerVoteData VoteData { get; } + public PlayerVoteData VoteData { get; } = dummy.myPlayer.GetVoteData(); /// /// Gets or sets a value indicating whether the dummy can vote to skip the meeting. /// - public bool CanSkip { get; set; } + public bool CanSkip { get; set; } = true; /// /// Gets or sets a predicate for validating whether the dummy can vote on a player. /// By default, excludes dead and disconnected players. /// - public Predicate PlayerIsValid { get; set; } - - /// - /// Initializes a new instance of the class. - /// - /// The voting dummy. - public DummyVoteEvent(DummyBehaviour dummy) - { - Dummy = dummy; - VoteData = dummy.myPlayer.GetVoteData(); - CanSkip = true; - PlayerIsValid = x => !x.Data.IsDead && !x.Data.Disconnected; - } + public Predicate PlayerIsValid { get; set; } = x => !x.Data.IsDead && !x.Data.Disconnected; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs index 2145b32..7e14a17 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs @@ -4,47 +4,37 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting; /// /// The event that is invoked when Mira handles a vote. This is invoked before Mira's behaviour, so be cautious. -/// If you intend on adding custom vote behaviour, cancel the event and do so. -/// If you are NOT canceling the event, keep in mind that Mira automatically removes a vote and adds the suspect to the list after this event is invoked. /// -public class HandleVoteEvent : MiraCancelableEvent +/// +/// If you intend on adding custom vote behaviour, cancel the event and do so.
+/// If you are NOT canceling the event, keep in mind that Mira automatically removes a vote and adds the suspect to the list after this event is invoked. +///
+/// The voter's . +/// The target's playerId. +public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId) : MiraCancelableEvent { /// /// Gets the instance of the voter's . /// - public PlayerVoteData VoteData { get; } + public PlayerVoteData VoteData { get; } = playerVoteData; /// /// Gets the player who voted. /// - public PlayerControl Player { get; } + public PlayerControl Player { get; } = playerVoteData.Owner; /// /// Gets the player id of the target. /// - public byte TargetId { get; } + public byte TargetId { get; } = targetId; /// /// Gets or sets a value indicating whether to prevent the vote from commencing. /// - public bool PreventVote { get; set; } + public bool PreventVote { get; set; } = false; /// /// Gets the of the target. /// - public NetworkedPlayerInfo TargetPlayerInfo { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The voter's . - /// The target's playerId. - public HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId) - { - VoteData = playerVoteData; - Player = playerVoteData.Owner; - TargetId = targetId; - PreventVote = false; - TargetPlayerInfo = GameData.Instance.GetPlayerById(targetId); - } + public NetworkedPlayerInfo TargetPlayerInfo { get; } = GameData.Instance.GetPlayerById(targetId); } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/MeetingSelectEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/MeetingSelectEvent.cs index 0c3f6d5..aff24f7 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/MeetingSelectEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/MeetingSelectEvent.cs @@ -5,39 +5,28 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting; /// /// The event that is invoked when the player tries to select another player to vote. /// -public class MeetingSelectEvent : MiraEvent +/// The voter's . +/// The target's playerId. +/// Whether the player is allowed to select the target. +public class MeetingSelectEvent(PlayerVoteData playerVoteData, int targetId, bool allowSelect) : MiraEvent { /// /// Gets the instance of the voter's . /// - public PlayerVoteData VoteData { get; } + public PlayerVoteData VoteData { get; } = playerVoteData; /// /// Gets the player id of the target. /// - public int TargetId { get; } + public int TargetId { get; } = targetId; /// /// Gets the of the target. /// - public NetworkedPlayerInfo TargetPlayerInfo { get; } + public NetworkedPlayerInfo TargetPlayerInfo { get; } = GameData.Instance.GetPlayerById((byte)targetId); /// /// Gets or sets a value indicating whether the player is allowed to select the target. /// - public bool AllowSelect { get; set; } - - /// - /// Initializes a new instance of the class. - /// - /// The voter's . - /// The target's playerId. - /// Whether the player is allowed to select the target. - public MeetingSelectEvent(PlayerVoteData playerVoteData, int targetId, bool allowSelect) - { - VoteData = playerVoteData; - TargetId = targetId; - TargetPlayerInfo = GameData.Instance.GetPlayerById((byte)targetId); - AllowSelect = allowSelect; - } + public bool AllowSelect { get; set; } = allowSelect; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/PopulateResultsEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/PopulateResultsEvent.cs index f5e4001..3914722 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/PopulateResultsEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/PopulateResultsEvent.cs @@ -5,21 +5,15 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting; /// /// Called in . -/// Cancelling is NOT advised but if you do plan on cancelling, please ensure you account for displaying ALL player's votes. /// -public class PopulateResultsEvent : MiraCancelableEvent +/// +/// Cancelling is NOT advised but if you do plan on cancelling, please ensure you account for displaying ALL player's votes. +/// +/// The list of s. +public class PopulateResultsEvent(List votes) : MiraCancelableEvent { /// /// Gets a list of networked s. /// - public List Votes { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The list of s. - public PopulateResultsEvent(List votes) - { - Votes = votes; - } + public List Votes { get; } = votes; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs index a61cc51..f31a34f 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs @@ -7,9 +7,6 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting; /// /// Ran after calculating votes and before displaying the results. Only ran on the host. /// -/// -/// Initializes a new instance of the class. -/// /// The list of s that are being processed. /// The player to be exiled. Will be if no player is to be exiled. public class ProcessVotesEvent(List votes, NetworkedPlayerInfo? exiledPlayer = null) : MiraEvent diff --git a/MiraAPI/Events/Vanilla/Player/CompleteHnsTaskEvent.cs b/MiraAPI/Events/Vanilla/Player/CompleteHnsTaskEvent.cs index 5ac7190..7528fc1 100644 --- a/MiraAPI/Events/Vanilla/Player/CompleteHnsTaskEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/CompleteHnsTaskEvent.cs @@ -3,33 +3,23 @@ /// /// The event that is invoked when a player completes a task within Hide and Seek. Non-cancelable. /// -public class CompleteHnsTaskEvent : MiraEvent +/// The currently active. +/// The player who completed the task. +/// The task that the player completed. +public class CompleteHnsTaskEvent(HideAndSeekManager hnsManager, PlayerControl player, PlayerTask task) : MiraEvent { /// /// Gets the instance of the . /// - public PlayerControl Player { get; } + public PlayerControl Player { get; } = player; /// /// Gets the instance of the that the player completed. /// - public PlayerTask Task { get; } + public PlayerTask Task { get; } = task; /// /// Gets the instance of the attached to the game. /// - public HideAndSeekManager HnsManager { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The currently active. - /// The player who completed the task. - /// The task that the player completed. - public CompleteHnsTaskEvent(HideAndSeekManager hnsManager, PlayerControl player, PlayerTask task) - { - HnsManager = hnsManager; - Player = player; - Task = task; - } + public HideAndSeekManager HnsManager { get; } = hnsManager; } diff --git a/MiraAPI/Events/Vanilla/Player/CompleteTaskEvent.cs b/MiraAPI/Events/Vanilla/Player/CompleteTaskEvent.cs index 31fd9d4..7266440 100644 --- a/MiraAPI/Events/Vanilla/Player/CompleteTaskEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/CompleteTaskEvent.cs @@ -3,26 +3,17 @@ /// /// The event that is invoked when a player completes a task. Non cancelable. /// -public class CompleteTaskEvent : MiraEvent +/// The player who completed the task. +/// The task that the player completed. +public class CompleteTaskEvent(PlayerControl player, PlayerTask task) : MiraEvent { /// /// Gets the instance of the . /// - public PlayerControl Player { get; } + public PlayerControl Player { get; } = player; /// /// Gets the instance of the that the player completed. /// - public PlayerTask Task { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The player who completed the task. - /// The task that the player completed. - public CompleteTaskEvent(PlayerControl player, PlayerTask task) - { - Player = player; - Task = task; - } + public PlayerTask Task { get; } = task; } diff --git a/MiraAPI/Events/Vanilla/Player/PlayerDeathEvent.cs b/MiraAPI/Events/Vanilla/Player/PlayerDeathEvent.cs index 3821af4..3441521 100644 --- a/MiraAPI/Events/Vanilla/Player/PlayerDeathEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/PlayerDeathEvent.cs @@ -3,33 +3,23 @@ /// /// Event that is invoked when a player dies. Non cancelable. /// -public class PlayerDeathEvent : MiraEvent +/// The player who died. +/// The reason the player died. +/// The player's , if it exists. +public class PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody? deadBody) : MiraEvent { /// /// Gets the player who died. /// - public PlayerControl Player { get; } + public PlayerControl Player { get; } = player; /// /// Gets the reason the player died. /// - public DeathReason DeathReason { get; } + public DeathReason DeathReason { get; } = reason; /// /// Gets the associated with the player, if any. /// - public DeadBody? DeadBody { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The player who died. - /// The reason the player died. - /// The player's , if it exists. - public PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody? deadBody) - { - Player = player; - DeathReason = reason; - DeadBody = deadBody; - } + public DeadBody? DeadBody { get; } = deadBody; } diff --git a/MiraAPI/Events/Vanilla/Player/PlayerJoinEvent.cs b/MiraAPI/Events/Vanilla/Player/PlayerJoinEvent.cs index ba9bfb5..384f144 100644 --- a/MiraAPI/Events/Vanilla/Player/PlayerJoinEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/PlayerJoinEvent.cs @@ -5,19 +5,11 @@ namespace MiraAPI.Events.Vanilla.Player; /// /// Event that is invoked when a player joins the lobby. Non cancelable. /// -public class PlayerJoinEvent : MiraEvent +/// The data of the player who joined. +public class PlayerJoinEvent(ClientData data) : MiraEvent { /// /// Gets the player who joined. /// - public ClientData ClientData { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The data of the player who joined. - public PlayerJoinEvent(ClientData data) - { - ClientData = data; - } + public ClientData ClientData { get; } = data; } diff --git a/MiraAPI/Events/Vanilla/Player/PlayerLeaveEvent.cs b/MiraAPI/Events/Vanilla/Player/PlayerLeaveEvent.cs index 4607305..11ce0d6 100644 --- a/MiraAPI/Events/Vanilla/Player/PlayerLeaveEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/PlayerLeaveEvent.cs @@ -5,26 +5,17 @@ namespace MiraAPI.Events.Vanilla.Player; /// /// Event that is invoked when a player leaves the game. Non cancelable. /// -public class PlayerLeaveEvent : MiraEvent +/// The data of the player who left. +/// The reason why the player left. +public class PlayerLeaveEvent(ClientData data, DisconnectReasons reason) : MiraEvent { /// /// Gets the player who left. /// - public ClientData ClientData { get; } + public ClientData ClientData { get; } = data; /// /// Gets the reason why the player left. /// - public DisconnectReasons Reason { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The data of the player who left. - /// The reason why the player left. - public PlayerLeaveEvent(ClientData data, DisconnectReasons reason) - { - ClientData = data; - Reason = reason; - } + public DisconnectReasons Reason { get; } = reason; } diff --git a/MiraAPI/Events/Vanilla/Usables/EnterVentEvent.cs b/MiraAPI/Events/Vanilla/Usables/EnterVentEvent.cs index 233e6ee..4d6eaaa 100644 --- a/MiraAPI/Events/Vanilla/Usables/EnterVentEvent.cs +++ b/MiraAPI/Events/Vanilla/Usables/EnterVentEvent.cs @@ -3,26 +3,17 @@ /// /// Event that is invoked when a player enters a vent. This event is cancelable. /// -public class EnterVentEvent : MiraCancelableEvent +/// The that is entering the . +/// The being entered. +public class EnterVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEvent { /// /// Gets the that is entering the . /// - public PlayerControl Player { get; } + public PlayerControl Player { get; } = player; /// /// Gets the that the is entering. /// - public Vent? Vent { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The that is entering the . - /// The being entered. - public EnterVentEvent(PlayerControl player, Vent? vent) - { - Player = player; - Vent = vent; - } + public Vent? Vent { get; } = vent; } diff --git a/MiraAPI/Events/Vanilla/Usables/ExitVentEvent.cs b/MiraAPI/Events/Vanilla/Usables/ExitVentEvent.cs index 6194905..3c0782e 100644 --- a/MiraAPI/Events/Vanilla/Usables/ExitVentEvent.cs +++ b/MiraAPI/Events/Vanilla/Usables/ExitVentEvent.cs @@ -3,26 +3,17 @@ /// /// Event that is invoked when a player exits a vent. This event is cancelable. /// -public class ExitVentEvent : MiraCancelableEvent +/// The who is exiting the . +/// The being exited from. +public class ExitVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEvent { /// /// Gets the that is exiting the . /// - public PlayerControl Player { get; } + public PlayerControl Player { get; } = player; /// /// Gets the that the is exiting. /// - public Vent? Vent { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The who is exiting the . - /// The being exited from. - public ExitVentEvent(PlayerControl player, Vent? vent) - { - Player = player; - Vent = vent; - } + public Vent? Vent { get; } = vent; } diff --git a/MiraAPI/Events/Vanilla/Usables/PlayerCanUseEvent.cs b/MiraAPI/Events/Vanilla/Usables/PlayerCanUseEvent.cs index 9dced79..bc5a06f 100644 --- a/MiraAPI/Events/Vanilla/Usables/PlayerCanUseEvent.cs +++ b/MiraAPI/Events/Vanilla/Usables/PlayerCanUseEvent.cs @@ -3,13 +3,5 @@ /// /// Event for if a can use an from Vanilla Among Us. Will always be ran locally. /// -public class PlayerCanUseEvent : PlayerUseEvent -{ - /// - /// Initializes a new instance of the class. - /// - /// The . - public PlayerCanUseEvent(IUsable usable) : base(usable) - { - } -} +/// The . +public class PlayerCanUseEvent(IUsable usable) : PlayerUseEvent(usable); diff --git a/MiraAPI/Events/Vanilla/Usables/PlayerUseEvent.cs b/MiraAPI/Events/Vanilla/Usables/PlayerUseEvent.cs index 7fc5cd5..e3ce2d0 100644 --- a/MiraAPI/Events/Vanilla/Usables/PlayerUseEvent.cs +++ b/MiraAPI/Events/Vanilla/Usables/PlayerUseEvent.cs @@ -3,32 +3,21 @@ /// /// Event for using a from Vanilla Among Us. Will always be ran locally. /// -public class PlayerUseEvent : MiraCancelableEvent +/// The . +public class PlayerUseEvent(IUsable usable) : MiraCancelableEvent { /// /// Gets the instance of that was used. /// - public IUsable Usable { get; } + public IUsable Usable { get; } = usable; /// /// Gets a value indicating whether the is a , , or . /// - public bool IsPrimaryConsole { get; } + public bool IsPrimaryConsole { get; } = usable.TryCast() || usable.TryCast() || usable.TryCast(); /// /// Gets a value indicating whether the is a . /// - public bool IsVent { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The . - public PlayerUseEvent(IUsable usable) - { - Usable = usable; - - IsPrimaryConsole = usable.TryCast() || usable.TryCast() || usable.TryCast(); - IsVent = usable.TryCast(); - } + public bool IsVent { get; } = usable.TryCast(); } diff --git a/MiraAPI/GameEnd/GameOverManager.cs b/MiraAPI/GameEnd/GameOverManager.cs index 28d2f48..0644cc9 100644 --- a/MiraAPI/GameEnd/GameOverManager.cs +++ b/MiraAPI/GameEnd/GameOverManager.cs @@ -81,9 +81,8 @@ public static class GameOverManager /// Thrown when the type is not registered. public static int GetGameOverId(Type gameOverType) { - if (GameOverIds.TryGetValue(gameOverType, out var id)) - return id; - - throw new ArgumentException($"{gameOverType.FullName} is not a registered custom game over!"); + return GameOverIds.TryGetValue(gameOverType, out var id) + ? id + : throw new ArgumentException($"{gameOverType.FullName} is not a registered custom game over!"); } } diff --git a/MiraAPI/GameModes/.editorconfig b/MiraAPI/GameModes/.editorconfig index 948715b..57cba7e 100644 --- a/MiraAPI/GameModes/.editorconfig +++ b/MiraAPI/GameModes/.editorconfig @@ -1,2 +1,4 @@ [*.cs] -dotnet_diagnostic.CS1591.severity = none \ No newline at end of file + +# 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/CustomGameMode.cs b/MiraAPI/GameModes/CustomGameMode.cs index f4dc43d..f44d006 100644 --- a/MiraAPI/GameModes/CustomGameMode.cs +++ b/MiraAPI/GameModes/CustomGameMode.cs @@ -89,60 +89,87 @@ public abstract class CustomGameMode /// Should Roles Settings be available when this gamemode is selected. /// /// if Role Settings are enabled in this game mode. - public virtual bool AreRoleSettingsEnabled() => true; + public virtual bool AreRoleSettingsEnabled() + { + return true; + } /// /// Should Game Settings be available when this gamemode is selected. /// /// if Game Settings are enabled in this mode. - public virtual bool AreGameSettingsEnabled() => true; + public virtual bool AreGameSettingsEnabled() + { + return true; + } /// /// Custom winner selection. /// /// List of winners or . - public virtual List? CalculateWinners() => null; + public virtual List? CalculateWinners() + { + return null; + } /// /// Show gamemode in . /// /// if the game mode should be shown in the intro cutscene. - public virtual bool ShowGameModeIntroCutscene() => false; + public virtual bool ShowGameModeIntroCutscene() + { + return false; + } /// /// Can Admin be used in this gamemode. /// /// Admin Console. /// if Admin console is enabled. - public virtual bool CanUseMapConsole(MapConsole console) => true; + public virtual bool CanUseMapConsole(MapConsole console) + { + return true; + } /// /// Can a be reported in this gamemode. /// /// Target for reporting. /// if s can be reported. - public virtual bool CanReport(DeadBody body) => true; + public virtual bool CanReport(DeadBody body) + { + return true; + } /// /// Can s be used in this gamemode. /// /// System Console. /// if s are enabled in this mode. - public virtual bool CanUseSystemConsole(SystemConsole console) => true; + public virtual bool CanUseSystemConsole(SystemConsole console) + { + return true; + } /// /// Can tasks be interacted with in this gamemode. /// /// Task console. /// if tasks are enabled in this mode. - public virtual bool CanUseTasks(Console console) => true; + public virtual bool CanUseTasks(Console console) + { + return true; + } /// /// Should the sabotage map be used when attempting to open sabotage overlay. /// /// object. /// if the sabotage map should be shown. - public virtual bool ShouldShowSabotageMap(MapBehaviour map) => true; + public virtual bool ShouldShowSabotageMap(MapBehaviour map) + { + return true; + } /// /// Can a player vent in this gamemode. @@ -150,5 +177,8 @@ public abstract class CustomGameMode /// Target vent. /// Player attempting to vent. /// if venting is enabled in this mode. - public virtual bool CanVent(Vent vent, NetworkedPlayerInfo playerInfo) => true; + public virtual bool CanVent(Vent vent, NetworkedPlayerInfo playerInfo) + { + return true; + } } diff --git a/MiraAPI/GameModes/CustomGameModeManager.cs b/MiraAPI/GameModes/CustomGameModeManager.cs index 3edd028..92eec65 100644 --- a/MiraAPI/GameModes/CustomGameModeManager.cs +++ b/MiraAPI/GameModes/CustomGameModeManager.cs @@ -14,6 +14,10 @@ public static class CustomGameModeManager /// internal static readonly Dictionary GameModes = []; + /// + /// Checks to see if the currently selected gamemode is vanilla. + /// + /// true if there is no custom gamemode selected. public static bool IsDefault() { return ActiveMode?.Id == 0; diff --git a/MiraAPI/GameModes/DefaultMode.cs b/MiraAPI/GameModes/DefaultMode.cs index 83c11ba..47c6c6b 100644 --- a/MiraAPI/GameModes/DefaultMode.cs +++ b/MiraAPI/GameModes/DefaultMode.cs @@ -1,8 +1,16 @@ namespace MiraAPI.GameModes; +/// +/// The default gamemode of Among Us. +/// public class DefaultMode : CustomGameMode { + /// public override string Name => "Default"; + + /// public override string Description => "Default Among Us GameMode"; + + /// public override int Id => 0; } diff --git a/MiraAPI/GameOptions/AbstractOptionGroup.cs b/MiraAPI/GameOptions/AbstractOptionGroup.cs index 01c9e09..9ed2352 100644 --- a/MiraAPI/GameOptions/AbstractOptionGroup.cs +++ b/MiraAPI/GameOptions/AbstractOptionGroup.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Linq; using MiraAPI.Modifiers; using MiraAPI.Roles; @@ -33,10 +34,9 @@ public abstract class AbstractOptionGroup /// /// Gets a value indicating whether the group should be shown in the modifiers menu. /// - // TODO: make this not a boolean -#pragma warning disable S1133 + // Completed: make this not a boolean [Obsolete("Use ParentMenu instead.")] -#pragma warning restore S1133 + [SuppressMessage("Info Code Smell", "S1133:Deprecated code should be removed", Justification = "Retained.")] public virtual bool ShowInModifiersMenu => false; /// @@ -118,11 +118,9 @@ public abstract class AbstractRoleOptionGroup() : AbstractOptionGroup wher get { var role = CustomRoleManager.CustomMiraRoles.FirstOrDefault(x => x.GetType() == OptionableType); - if (role == null) - { - return new(new Color(0.7333f, 0.7333f, 0.7333f, 1)); - } - return new(role.RoleColor, role.Configuration.IconTmp); + return role == null + ? new(new Color(0.7333f, 0.7333f, 0.7333f, 1)) + : new(role.RoleColor, role.Configuration.IconTmp); } } } @@ -133,7 +131,7 @@ public abstract class AbstractRoleOptionGroup() : AbstractOptionGroup wher public enum MenuCategory { /// - /// Placeholder for indexing purposes. Options don't exist in the presset tab. + /// Placeholder for indexing purposes. Options don't exist in the preset tab. /// Preset, diff --git a/MiraAPI/GameOptions/Attributes/ModdedNumberOptionAttribute.cs b/MiraAPI/GameOptions/Attributes/ModdedNumberOptionAttribute.cs index 6ff98dc..6ffe75e 100644 --- a/MiraAPI/GameOptions/Attributes/ModdedNumberOptionAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/ModdedNumberOptionAttribute.cs @@ -42,10 +42,8 @@ public class ModdedNumberOptionAttribute( /// public override object GetValue() { - if (HolderOption is ModdedNumberOption opt) - { - return opt.Value; - } - throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedNumberOption"); + return HolderOption is ModdedNumberOption opt + ? (object)opt.Value + : throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedNumberOption"); } } diff --git a/MiraAPI/GameOptions/Attributes/ModdedToggleOptionAttribute.cs b/MiraAPI/GameOptions/Attributes/ModdedToggleOptionAttribute.cs index 2fccf1f..8f570e6 100644 --- a/MiraAPI/GameOptions/Attributes/ModdedToggleOptionAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/ModdedToggleOptionAttribute.cs @@ -27,10 +27,8 @@ public class ModdedToggleOptionAttribute(string title) : ModdedOptionAttribute(t /// public override object GetValue() { - if (HolderOption is ModdedToggleOption opt) - { - return opt.Value; - } - throw new InvalidOperationException($"Holder option for {Title} is not a ModdedToggleOption."); + return HolderOption is ModdedToggleOption opt + ? (object)opt.Value + : throw new InvalidOperationException($"Holder option for {Title} is not a ModdedToggleOption."); } } diff --git a/MiraAPI/GameOptions/ModdedOptionsManager.cs b/MiraAPI/GameOptions/ModdedOptionsManager.cs index 7dd26ee..d686f50 100644 --- a/MiraAPI/GameOptions/ModdedOptionsManager.cs +++ b/MiraAPI/GameOptions/ModdedOptionsManager.cs @@ -32,13 +32,21 @@ public static class ModdedOptionsManager internal static uint NextId => _nextId++; private static uint _nextId = 1; + /// + /// Pops a message notification of a setting being changed. + /// + /// The game's notification popper. + /// The key of the option that changed. + /// The new value of the option. + /// The color of the notification. + /// The optional sprite of the notification. + /// A flag that indicates if a notification sound should be played. public static void AddSettingsChangeMessage(NotificationPopper notif, StringNames key, string value, Color textColor, TMP_SpriteAsset? sprite, bool playSound = true) { - var item = string.Empty; + string item; var text = textColor.ToTextColor(); - if (sprite != null) - { - item = TranslationController.Instance.GetString( + item = sprite != null + ? TranslationController.Instance.GetString( StringNames.LobbyChangeSettingNotification, string.Concat( ""), "" + value + "" - ); - } - else - { - item = TranslationController.Instance.GetString( + ) + : TranslationController.Instance.GetString( StringNames.LobbyChangeSettingNotification, "" + text + TranslationController.Instance.GetString(key) + "", "" + value + ""); - } notif.SettingsChangeMessageLogic(key, item, playSound); } + [SuppressMessage( + "Major Code Smell", + "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", + Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime." + )] internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo) { if (Activator.CreateInstance(type) is not AbstractOptionGroup group) @@ -80,9 +89,7 @@ public static class ModdedOptionsManager pluginInfo.InternalOptionGroups.Add(group); typeof(OptionGroupSingleton<>).MakeGenericType(type) -#pragma warning disable S3011 - .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! -#pragma warning restore S3011 + .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Message suppression points to here .SetValue(null, group); return true; @@ -211,10 +218,9 @@ public static class ModdedOptionsManager /// /// The original setter method. /// The new object value. -#pragma warning disable CA1707 - [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")] + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention.")] + [SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Harmony naming convention.")] public static void PropertySetterPatch(MethodBase __originalMethod, object value) -#pragma warning restore CA1707 { var attribute = OptionAttributes.First(pair => pair.Key.GetSetMethod() == __originalMethod).Value; attribute.SetValue(value); @@ -226,10 +232,9 @@ public static class ModdedOptionsManager /// The original getter method. /// The result of the property getter. /// so the original getter gets skipped. -#pragma warning disable CA1707 [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")] + [SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Harmony naming convention.")] public static bool PropertyGetterPatch(MethodBase __originalMethod, ref object __result) -#pragma warning restore CA1707 { var attribute = OptionAttributes.First(pair => pair.Key.GetGetMethod() == __originalMethod).Value; __result = attribute.GetValue(); diff --git a/MiraAPI/GameOptions/ModifierOptionGroup.cs b/MiraAPI/GameOptions/ModifierOptionGroup.cs index 3db6566..fa5ed94 100644 --- a/MiraAPI/GameOptions/ModifierOptionGroup.cs +++ b/MiraAPI/GameOptions/ModifierOptionGroup.cs @@ -2,9 +2,7 @@ namespace MiraAPI.GameOptions; -#pragma warning disable CA1852 -internal class ModifierOptionGroup : AbstractOptionGroup -#pragma warning restore CA1852 +internal sealed class ModifierOptionGroup : AbstractOptionGroup { public override string GroupName { get; } @@ -12,6 +10,6 @@ internal class ModifierOptionGroup : AbstractOptionGroup { GroupName = name; Options.AddRange(options); - Options.AddRange(groups.SelectMany(x=>x.Options)); + Options.AddRange(groups.SelectMany(x => x.Options)); } } diff --git a/MiraAPI/GameOptions/OptionGroupSingleton.cs b/MiraAPI/GameOptions/OptionGroupSingleton.cs index a521d7d..919a286 100644 --- a/MiraAPI/GameOptions/OptionGroupSingleton.cs +++ b/MiraAPI/GameOptions/OptionGroupSingleton.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System.Diagnostics.CodeAnalysis; +using System.Linq; namespace MiraAPI.GameOptions; @@ -13,7 +14,6 @@ public static class OptionGroupSingleton where T : AbstractOptionGroup /// /// Gets the instance of the group. /// -#pragma warning disable CA1000 + [SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "This is a utility class to get the instance of a custom option group.")] public static T Instance => _instance ??= ModdedOptionsManager.Groups.OfType().Single(); -#pragma warning restore CA1000 } diff --git a/MiraAPI/GameOptions/OptionNotifConfiguration.cs b/MiraAPI/GameOptions/OptionNotifConfiguration.cs index e16106f..e8e2369 100644 --- a/MiraAPI/GameOptions/OptionNotifConfiguration.cs +++ b/MiraAPI/GameOptions/OptionNotifConfiguration.cs @@ -1,7 +1,9 @@ using System; +using System.Diagnostics.CodeAnalysis; using Il2CppInterop.Runtime.Attributes; using TMPro; using UnityEngine; + namespace MiraAPI.GameOptions; /// @@ -9,14 +11,13 @@ namespace MiraAPI.GameOptions; /// public record struct OptionNotifConfiguration { -#pragma warning disable S1133 - [Obsolete("Default constructor is not supported")] -#pragma warning restore S1133 + [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 public OptionNotifConfiguration() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member { - throw new NotImplementedException("Default constructor is not supported."); + throw new NotImplementedException("Default constructor is not supported. Please use the constructor that takes an AbstractOptionGroup parameter."); } /// diff --git a/MiraAPI/GameOptions/OptionTypes/ModdedEnumOption.cs b/MiraAPI/GameOptions/OptionTypes/ModdedEnumOption.cs index 30809bd..aba6228 100644 --- a/MiraAPI/GameOptions/OptionTypes/ModdedEnumOption.cs +++ b/MiraAPI/GameOptions/OptionTypes/ModdedEnumOption.cs @@ -28,19 +28,17 @@ public class ModdedEnumOption : ModdedOption /// The type. /// An option list of string values to use in place of the name. /// Whether to include this option in the preset or not. - public ModdedEnumOption(string title, int defaultValue, Type enumType, string[]? values = null, bool includeInPreset=true) : base(title, defaultValue, includeInPreset) + public ModdedEnumOption(string title, int defaultValue, Type enumType, string[]? values = null, bool includeInPreset = true) : base(title, defaultValue, includeInPreset) { Values = values ?? Enum.GetNames(enumType); - Data = ScriptableObject.CreateInstance(); - var data = (StringGameSetting)Data; + var data = ScriptableObject.CreateInstance(); data.Title = StringName; data.Type = global::OptionTypes.String; - data.Values = values is null ? - Enum.GetNames(enumType).Select(CustomStringName.CreateAndRegister).ToArray() - : [.. values.Select(CustomStringName.CreateAndRegister)]; - + data.Values = Values.Select(CustomStringName.CreateAndRegister).ToArray(); data.Index = Value; + + Data = data; } /// @@ -53,7 +51,7 @@ public class ModdedEnumOption : ModdedOption stringOption.SetUpFromData(Data, 20); stringOption.OnValueChanged = (Il2CppSystem.Action)ValueChanged; - // SetUpFromData method doesnt work correctly so we must set the values manually + // SetUpFromData method doesn't work correctly so we must set the values manually stringOption.Title = StringName; stringOption.Values = (Data as StringGameSetting)?.Values ?? new Il2CppStructArray(0); stringOption.Value = Value; @@ -127,19 +125,17 @@ public class ModdedEnumOption : ModdedOption where T : Enum /// The default value as an . /// An option list of string values to use in place of the name. /// Whether to include this option in the preset or not. - public ModdedEnumOption(string title, T defaultValue, string[]? values = null, bool includeInPreset=true) : base(title, defaultValue, includeInPreset) + public ModdedEnumOption(string title, T defaultValue, string[]? values = null, bool includeInPreset = true) : base(title, defaultValue, includeInPreset) { Values = values ?? Enum.GetNames(typeof(T)); - Data = ScriptableObject.CreateInstance(); - var data = (StringGameSetting)Data; + var data = ScriptableObject.CreateInstance(); data.Title = StringName; data.Type = global::OptionTypes.String; - data.Values = values is null ? - Enum.GetNames(typeof(T)).Select(CustomStringName.CreateAndRegister).ToArray() - : [.. values.Select(CustomStringName.CreateAndRegister)]; - + data.Values = Values.Select(CustomStringName.CreateAndRegister).ToArray(); data.Index = Convert.ToInt32(Value, NumberFormatInfo.InvariantInfo); + + Data = data; } /// @@ -152,7 +148,7 @@ public class ModdedEnumOption : ModdedOption where T : Enum stringOption.SetUpFromData(Data, 20); stringOption.OnValueChanged = (Il2CppSystem.Action)ValueChanged; - // SetUpFromData method doesnt work correctly so we must set the values manually + // SetUpFromData method doesn't work correctly so we must set the values manually stringOption.Title = StringName; stringOption.Values = (Data as StringGameSetting)?.Values ?? new Il2CppStructArray(0); stringOption.Value = Convert.ToInt32(Value, NumberFormatInfo.InvariantInfo); diff --git a/MiraAPI/GameOptions/OptionTypes/ModdedNumberOption.cs b/MiraAPI/GameOptions/OptionTypes/ModdedNumberOption.cs index 87f4ca9..d22b158 100644 --- a/MiraAPI/GameOptions/OptionTypes/ModdedNumberOption.cs +++ b/MiraAPI/GameOptions/OptionTypes/ModdedNumberOption.cs @@ -138,7 +138,7 @@ public class ModdedNumberOption : ModdedOption SuffixType = suffixType; ZeroWordValue = zeroInfinity ? "∞" : "#"; NegativeWordValue = "#"; - ShiftIncrement = increment != 1f; + ShiftIncrement = Mathf.Approximately(increment, 1f); Value = Mathf.Clamp(defaultValue, min, max); diff --git a/MiraAPI/GameOptions/OptionTypes/ModdedOption.cs b/MiraAPI/GameOptions/OptionTypes/ModdedOption.cs index 4300c4f..34811a6 100644 --- a/MiraAPI/GameOptions/OptionTypes/ModdedOption.cs +++ b/MiraAPI/GameOptions/OptionTypes/ModdedOption.cs @@ -120,7 +120,7 @@ public abstract class ModdedOption : IModdedOption } /// - public void SaveToPreset(ConfigFile presetConfig, bool saveDefault=false) + public void SaveToPreset(ConfigFile presetConfig, bool saveDefault = false) { if (ConfigDefinition is null) { diff --git a/MiraAPI/GameOptions/OptionTypes/ModdedPlayerOption.cs b/MiraAPI/GameOptions/OptionTypes/ModdedPlayerOption.cs index db397bd..654fc79 100644 --- a/MiraAPI/GameOptions/OptionTypes/ModdedPlayerOption.cs +++ b/MiraAPI/GameOptions/OptionTypes/ModdedPlayerOption.cs @@ -85,9 +85,7 @@ public class ModdedPlayerOption : ModdedOption /// A list of filtered players. public System.Collections.Generic.List GetFilteredPlayers() { - return GameData.Instance.AllPlayers.ToArray() - .Where(x => PlayerFilter?.Invoke(x) ?? true) - .ToList(); + return [.. GameData.Instance.AllPlayers.ToArray().Where(x => PlayerFilter?.Invoke(x) ?? true)]; } /// diff --git a/MiraAPI/GameOptions/OptionTypes/ModdedToggleOption.cs b/MiraAPI/GameOptions/OptionTypes/ModdedToggleOption.cs index 55b69b9..27d15a1 100644 --- a/MiraAPI/GameOptions/OptionTypes/ModdedToggleOption.cs +++ b/MiraAPI/GameOptions/OptionTypes/ModdedToggleOption.cs @@ -16,7 +16,7 @@ public class ModdedToggleOption : ModdedOption /// The option title. /// The default value. /// Whether to include this option in the preset or not. - public ModdedToggleOption(string title, bool defaultValue, bool includeInPreset=true) : base(title, defaultValue, includeInPreset) + public ModdedToggleOption(string title, bool defaultValue, bool includeInPreset = true) : base(title, defaultValue, includeInPreset) { Data = ScriptableObject.CreateInstance(); diff --git a/MiraAPI/Hud/CustomActionButton.cs b/MiraAPI/Hud/CustomActionButton.cs index 4c5df0c..6e74b0b 100644 --- a/MiraAPI/Hud/CustomActionButton.cs +++ b/MiraAPI/Hud/CustomActionButton.cs @@ -447,7 +447,10 @@ public abstract class CustomActionButton /// Always by default. /// /// Can the effect be canceled. - public virtual bool IsEffectCancellable() => false; + public virtual bool IsEffectCancellable() + { + return false; + } /// /// When the button is usable, this method is called to determine if the button can be clicked. diff --git a/MiraAPI/Hud/CustomButtonManager.cs b/MiraAPI/Hud/CustomButtonManager.cs index 70ca14b..378c907 100644 --- a/MiraAPI/Hud/CustomButtonManager.cs +++ b/MiraAPI/Hud/CustomButtonManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using MiraAPI.Events.Mira; using MiraAPI.PluginLoading; @@ -21,6 +22,11 @@ public static class CustomButtonManager internal static readonly Dictionary ButtonEventTypes = []; internal static readonly Dictionary ButtonCancelledEventTypes = []; + [SuppressMessage( + "Major Code Smell", + "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", + Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime." + )] internal static bool RegisterButton(Type buttonType, MiraPluginInfo pluginInfo) { if (!buttonType.IsAssignableTo(typeof(CustomActionButton)) || Activator.CreateInstance(buttonType) is not CustomActionButton button) @@ -31,9 +37,7 @@ public static class CustomButtonManager CustomButtons.Add(button); pluginInfo.InternalButtons.Add(button); typeof(CustomButtonSingleton<>).MakeGenericType(buttonType) -#pragma warning disable S3011 - .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! -#pragma warning restore S3011 + .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this .SetValue(null, button); ButtonEventTypes.Add(buttonType, typeof(MiraButtonClickEvent<>).MakeGenericType(buttonType)); diff --git a/MiraAPI/Hud/CustomPlayerMenu.cs b/MiraAPI/Hud/CustomPlayerMenu.cs index fb27f14..c94e355 100644 --- a/MiraAPI/Hud/CustomPlayerMenu.cs +++ b/MiraAPI/Hud/CustomPlayerMenu.cs @@ -10,7 +10,6 @@ using Reactor.Utilities.Extensions; using UnityEngine; using UnityEngine.Events; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member -#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. namespace MiraAPI.Hud; @@ -19,9 +18,9 @@ namespace MiraAPI.Hud; /// /// Used by Il2Cpp. Do not use constructor, this is a . [RegisterInIl2Cpp] -[SuppressMessage("Design", "CA1051:Do not declare visible instance fields", Justification = "Unity Convention")] -[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Unity Convention")] -[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Unity Convention")] +[SuppressMessage("Design", "CA1051:Do not declare visible instance fields", Justification = "Unity Convention.")] +[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Unity Convention.")] +[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Unity Convention.")] public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr) { public ShapeshifterPanel panelPrefab; @@ -69,6 +68,7 @@ public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr) return customMenu; } + [SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity convention.")] private void OnDisable() { ControllerManager.Instance.CloseOverlayMenu(name); diff --git a/MiraAPI/Hud/MultiTargetButton.cs b/MiraAPI/Hud/MultiTargetButton.cs index d52d845..6e4c4b8 100644 --- a/MiraAPI/Hud/MultiTargetButton.cs +++ b/MiraAPI/Hud/MultiTargetButton.cs @@ -38,7 +38,7 @@ public abstract class MultiTargetButton : CustomActionButton where T : MonoBe /// /// Sets the outline of the target . /// - /// The target to set the oultine. + /// The target to set the outline. /// Should the outline be active. public abstract void SetOutline(T target, bool active); @@ -54,10 +54,9 @@ public abstract class MultiTargetButton : CustomActionButton where T : MonoBe } } - Targets = newTargets + Targets = [.. newTargets .Where(IsTargetValid) - .Take(MaxTargets) - .ToArray(); + .Take(MaxTargets)]; Targets.Do(t => SetOutline(t, true)); return base.CanUse() && Targets.Length > 0; diff --git a/MiraAPI/Keybinds/BaseKeybind.cs b/MiraAPI/Keybinds/BaseKeybind.cs index e9407ed..a8b9668 100644 --- a/MiraAPI/Keybinds/BaseKeybind.cs +++ b/MiraAPI/Keybinds/BaseKeybind.cs @@ -9,7 +9,7 @@ namespace MiraAPI.Keybinds; public class BaseKeybind { /// - /// Gets the Rewired assinged for this keybind. + /// Gets the Rewired assigned for this keybind. /// public InputAction? RewiredInputAction { get; internal set; } @@ -38,6 +38,9 @@ public class BaseKeybind Handler = () => { }; } + /// + /// Initializes a new instance of the class. + /// public BaseKeybind() { Handler = () => { }; @@ -67,6 +70,8 @@ public class BaseKeybind /// The to remove. public void RemoveOnActivate(Action action) { +#pragma warning disable CS8601 // Possible null reference assignment. Handler -= action; +#pragma warning restore CS8601 // Possible null reference assignment. } } diff --git a/MiraAPI/Keybinds/KeybindManager.cs b/MiraAPI/Keybinds/KeybindManager.cs index 042322a..055d2ca 100644 --- a/MiraAPI/Keybinds/KeybindManager.cs +++ b/MiraAPI/Keybinds/KeybindManager.cs @@ -15,7 +15,7 @@ public static class KeybindManager /// /// Gets a list of all registered s. /// - public static List Keybinds { get; } = new(); + public static List Keybinds { get; } = []; [HideFromIl2Cpp] internal static Dictionary VanillaKeybinds { get; set; } = []; @@ -61,7 +61,7 @@ public static class KeybindManager { if (!conflicts.TryGetValue(keybind.CurrentKey, out var group)) { - conflicts.Add(keybind.CurrentKey, new List()); + conflicts.Add(keybind.CurrentKey, []); group = conflicts[keybind.CurrentKey]; } @@ -79,7 +79,7 @@ public static class KeybindManager /// Returns all s for a specified keycode. /// /// The key to look for. - /// /// Should only exlusive keybinds be present. + /// /// Should only exclusive keybinds be present. /// The list of s. public static MiraKeybind[] GetKeybindsForKey(KeyboardKeyCode keyCode, bool exclusiveCheck = false) { @@ -92,6 +92,6 @@ public static class KeybindManager } } - return all.ToArray(); + return [.. all]; } } diff --git a/MiraAPI/Keybinds/KeybindUtils.cs b/MiraAPI/Keybinds/KeybindUtils.cs index 7a316be..1ce7f58 100644 --- a/MiraAPI/Keybinds/KeybindUtils.cs +++ b/MiraAPI/Keybinds/KeybindUtils.cs @@ -20,12 +20,7 @@ public static class KeybindUtils /// The currently assigned keycode. public static KeyboardKeyCode GetKeycodeByKeybind(BaseKeybind keybind) { - if (keybind.RewiredInputAction == null) - { - return KeyboardKeyCode.None; - } - - return GetKeycodeByActionId(keybind.RewiredInputAction.id); + return keybind.RewiredInputAction == null ? KeyboardKeyCode.None : GetKeycodeByActionId(keybind.RewiredInputAction.id); } /// diff --git a/MiraAPI/Keybinds/MiraGlobalKeybinds.cs b/MiraAPI/Keybinds/MiraGlobalKeybinds.cs index f945ca9..7e4b21b 100644 --- a/MiraAPI/Keybinds/MiraGlobalKeybinds.cs +++ b/MiraAPI/Keybinds/MiraGlobalKeybinds.cs @@ -20,7 +20,7 @@ public static class MiraGlobalKeybinds public static MiraKeybind SecondaryAbility { get; } = new("Secondary Ability", KeyboardKeyCode.Y); /// - /// Gets the keybind for Tetiary abilities. + /// Gets the keybind for Tertiary abilities. /// public static MiraKeybind TertiaryAbility { get; } = new("Tertiary Ability", KeyboardKeyCode.U); @@ -35,7 +35,7 @@ public static class MiraGlobalKeybinds public static MiraKeybind ModifierSecondaryAbility { get; } = new("Modifier Secondary Ability", KeyboardKeyCode.O); /// - /// Gets the keybind for Tetiary modifier abilities. + /// Gets the keybind for Tertiary modifier abilities. /// public static MiraKeybind ModifierTertiaryAbility { get; } = new("Modifier Tertiary Ability", KeyboardKeyCode.P); } diff --git a/MiraAPI/Keybinds/MiraKeybind.cs b/MiraAPI/Keybinds/MiraKeybind.cs index d2b5847..5eca155 100644 --- a/MiraAPI/Keybinds/MiraKeybind.cs +++ b/MiraAPI/Keybinds/MiraKeybind.cs @@ -6,50 +6,39 @@ namespace MiraAPI.Keybinds; /// /// Represents a registered keybind. /// -public class MiraKeybind : BaseKeybind +/// The name of the keybind. +/// The default keycode. +/// Up to 3 optional s. +/// Is exclusive. +public class MiraKeybind( + string name, + KeyboardKeyCode? defaultKeycode, + ModifierKey[]? modifierKeys = null, + bool exclusive = true) : BaseKeybind(name.ToLower(CultureInfo.InvariantCulture).Replace(' ', '_')) { /// /// Gets name of the keybind. /// - public string Name { get; } + public string Name { get; } = name; /// /// Gets the default keycode of this keybind. /// - public KeyboardKeyCode DefaultKey { get; } + public KeyboardKeyCode DefaultKey { get; } = defaultKeycode ?? KeyboardKeyCode.None; /// /// Gets the s assigned to this keybind. /// Due to Rewired limitations, there can only be 3 s. /// - public ModifierKey[] ModifierKeys { get; } + public ModifierKey[] ModifierKeys { get; } = modifierKeys ?? []; /// /// Gets a value indicating whether this keybind should be checked for conflicts with other exclusive keybinds using the same key. /// - public bool Exclusive { get; } + public bool Exclusive { get; } = exclusive; internal string? SourcePluginName { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// The name of the keybind. - /// The default keycode. - /// Up to 3 optional s. - /// Is exclusive. - public MiraKeybind( - string name, - KeyboardKeyCode? defaultKeycode, - ModifierKey[]? modifierKeys = null, - bool exclusive = true) : base(name.ToLower(CultureInfo.InvariantCulture).Replace(' ', '_')) - { - Name = name; - DefaultKey = defaultKeycode ?? KeyboardKeyCode.None; - ModifierKeys = modifierKeys ?? []; - Exclusive = exclusive; - } - /// public override string ToString() { diff --git a/MiraAPI/Keybinds/VanillaKeybind.cs b/MiraAPI/Keybinds/VanillaKeybind.cs index 5f34288..a6b7350 100644 --- a/MiraAPI/Keybinds/VanillaKeybind.cs +++ b/MiraAPI/Keybinds/VanillaKeybind.cs @@ -8,7 +8,7 @@ namespace MiraAPI.Keybinds; public class VanillaKeybind : BaseKeybind { /// - /// Gets the this keybind is binded to. + /// Gets the this keybind is bound to. /// public ActionButton? Button { get; internal set; } diff --git a/MiraAPI/Keybinds/VanillaKeybindSingleton.cs b/MiraAPI/Keybinds/VanillaKeybindSingleton.cs index 5876fcb..5605d4d 100644 --- a/MiraAPI/Keybinds/VanillaKeybindSingleton.cs +++ b/MiraAPI/Keybinds/VanillaKeybindSingleton.cs @@ -1,17 +1,19 @@ -namespace MiraAPI.Keybinds; +using System.Diagnostics.CodeAnalysis; + +namespace MiraAPI.Keybinds; /// /// Singleton for getting a by . /// -/// type. +/// type. public static class VanillaKeybinding where T : ActionButton { + [SuppressMessage("Major Code Smell", "S2743:Static fields should not be used in generic types", Justification = "The instance holds a reference to the button that defines the class's type parameter.")] private static VanillaKeybind? _instance; /// /// Gets the instance of the . /// -#pragma warning disable CA1000 + [SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "This is a utility class to get the instance of a vanilla keybind.")] public static VanillaKeybind Instance => _instance ??= KeybindManager.VanillaKeybinds[typeof(T)]; -#pragma warning restore CA1000 } diff --git a/MiraAPI/LocalSettings/Attributes/LocalEnumSettingAttribute.cs b/MiraAPI/LocalSettings/Attributes/LocalEnumSettingAttribute.cs index c0608ff..07114e5 100644 --- a/MiraAPI/LocalSettings/Attributes/LocalEnumSettingAttribute.cs +++ b/MiraAPI/LocalSettings/Attributes/LocalEnumSettingAttribute.cs @@ -7,8 +7,9 @@ namespace MiraAPI.LocalSettings.Attributes; /// /// Creates a for the . /// +/// The name of the setting. +/// The description of the setting. /// Optional custom names. -/// [AttributeUsage(AttributeTargets.Property)] public class LocalEnumSettingAttribute( string? name = null, diff --git a/MiraAPI/LocalSettings/Attributes/LocalNumberSettingAttribute.cs b/MiraAPI/LocalSettings/Attributes/LocalNumberSettingAttribute.cs index b5d681c..e1b5047 100644 --- a/MiraAPI/LocalSettings/Attributes/LocalNumberSettingAttribute.cs +++ b/MiraAPI/LocalSettings/Attributes/LocalNumberSettingAttribute.cs @@ -8,11 +8,13 @@ namespace MiraAPI.LocalSettings.Attributes; /// /// Creates a for the . /// +/// The name of the setting. +/// The description of the setting. /// Minimum range. /// Maximum range. /// Increment per use. /// Suffix for the value. -/// Format string used when formating. +/// Format string used when formatting. /// [AttributeUsage(AttributeTargets.Property)] public class LocalNumberSettingAttribute( diff --git a/MiraAPI/LocalSettings/Attributes/LocalSettingAttribute.cs b/MiraAPI/LocalSettings/Attributes/LocalSettingAttribute.cs index 5aaef81..c582f13 100644 --- a/MiraAPI/LocalSettings/Attributes/LocalSettingAttribute.cs +++ b/MiraAPI/LocalSettings/Attributes/LocalSettingAttribute.cs @@ -7,11 +7,13 @@ namespace MiraAPI.LocalSettings.Attributes; /// Base class for all local settings attributes. /// /// The name of the setting. Defaults to entry key. -/// The description of the setting. Defalts to entry description. +/// The description of the setting. Defaults to entry description. [AttributeUsage(AttributeTargets.Property)] public abstract class LocalSettingAttribute( +#pragma warning disable CS9113 // Parameter is unread. string? name = null, string? description = null +#pragma warning restore CS9113 // Parameter is unread. ) : Attribute { /// diff --git a/MiraAPI/LocalSettings/Attributes/LocalSliderSettingAttribute.cs b/MiraAPI/LocalSettings/Attributes/LocalSliderSettingAttribute.cs index 9e14a8e..826df07 100644 --- a/MiraAPI/LocalSettings/Attributes/LocalSliderSettingAttribute.cs +++ b/MiraAPI/LocalSettings/Attributes/LocalSliderSettingAttribute.cs @@ -9,10 +9,14 @@ namespace MiraAPI.LocalSettings.Attributes; /// Creates a for the . /// /// +/// The name of the setting. +/// The description of the setting. /// Minimum range. /// Maximum range. /// Should the value be rounded. /// Suffix for the value. +/// Should display the value next to the name. +/// The format string used for formatting. [AttributeUsage(AttributeTargets.Property)] public class LocalSliderSettingAttribute( string? name = null, diff --git a/MiraAPI/LocalSettings/Attributes/LocalToggleSettingAttribute.cs b/MiraAPI/LocalSettings/Attributes/LocalToggleSettingAttribute.cs index 22ca7aa..fb90f77 100644 --- a/MiraAPI/LocalSettings/Attributes/LocalToggleSettingAttribute.cs +++ b/MiraAPI/LocalSettings/Attributes/LocalToggleSettingAttribute.cs @@ -7,7 +7,6 @@ namespace MiraAPI.LocalSettings.Attributes; /// /// Creates a for the . /// -/// [AttributeUsage(AttributeTargets.Property)] public class LocalToggleSettingAttribute( string? name = null, diff --git a/MiraAPI/LocalSettings/LocalSettingsManager.cs b/MiraAPI/LocalSettings/LocalSettingsManager.cs index 874e258..c1190bb 100644 --- a/MiraAPI/LocalSettings/LocalSettingsManager.cs +++ b/MiraAPI/LocalSettings/LocalSettingsManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using BepInEx.Unity.IL2CPP; @@ -14,6 +15,11 @@ public static class LocalSettingsManager internal static readonly List Tabs = []; internal static readonly List AvailableTabs = []; + [SuppressMessage( + "Major Code Smell", + "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", + Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime." + )] internal static bool RegisterTab(Type type, BasePlugin pluginInfo) { if (Activator.CreateInstance(type, pluginInfo.Config) is not LocalSettingsTab tab) @@ -35,9 +41,7 @@ public static class LocalSettingsManager TypeToTab.Add(type, tab); typeof(LocalSettingsTabSingleton<>).MakeGenericType(type) -#pragma warning disable S3011 - .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! -#pragma warning restore S3011 + .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this .SetValue(null, tab); return true; diff --git a/MiraAPI/LocalSettings/LocalSettingsTab.cs b/MiraAPI/LocalSettings/LocalSettingsTab.cs index 074d7db..41ccc5e 100644 --- a/MiraAPI/LocalSettings/LocalSettingsTab.cs +++ b/MiraAPI/LocalSettings/LocalSettingsTab.cs @@ -84,115 +84,115 @@ public abstract class LocalSettingsTab(ConfigFile config) /// /// Creates the tab and it's content. /// - /// The instace. + /// The instance. /// The created tab . public virtual GameObject CreateTab(OptionsMenuBehaviour instance) { - var tab = Object.Instantiate(instance.transform.FindChild("GeneralTab").gameObject, instance.transform); - tab.name = $"{TabName}Tab"; - tab.transform.DestroyChildren(); - tab.gameObject.SetActive(false); + var tab = Object.Instantiate(instance.transform.FindChild("GeneralTab").gameObject, instance.transform); + tab.name = $"{TabName}Tab"; + tab.transform.DestroyChildren(); + tab.gameObject.SetActive(false); - if (Scroller == null) - { - Scroller = Helpers.CreateScroller(tab.transform, OptionsMenuPatches.MaskCollider); - } + if (Scroller == null) + { + Scroller = Helpers.CreateScroller(tab.transform, OptionsMenuPatches.MaskCollider); + } - if (TabButton != null) - { - TabButton.Content = tab.gameObject; - } + if (TabButton != null) + { + TabButton.Content = tab.gameObject; + } - var generalLabel = instance.transform.FindChild("GeneralTab").FindChild("ControlGroup") - .FindChild("ControlText_TMP").gameObject; - var toggle = instance.transform.FindChild("GeneralTab").FindChild("ChatGroup").FindChild("CensorChatButton").GetComponent(); - var slider = instance.transform.FindChild("GeneralTab").FindChild("SoundGroup").FindChild("SFXSlider").GetComponent(); + var generalLabel = instance.transform.FindChild("GeneralTab").FindChild("ControlGroup") + .FindChild("ControlText_TMP").gameObject; + var toggle = instance.transform.FindChild("GeneralTab").FindChild("ChatGroup").FindChild("CensorChatButton").GetComponent(); + var slider = instance.transform.FindChild("GeneralTab").FindChild("SoundGroup").FindChild("SFXSlider").GetComponent(); - Dictionary> entriesByGroup = new(); - foreach (var entry in Settings) - { - var group = entry.ConfigEntry.Definition.Section; - if (!entriesByGroup.ContainsKey(group)) - entriesByGroup.Add(group, []); + Dictionary> entriesByGroup = []; + foreach (var entry in Settings) + { + var group = entry.ConfigEntry.Definition.Section; + if (!entriesByGroup.ContainsKey(group)) + entriesByGroup.Add(group, []); - entriesByGroup[group].Add(entry); - } + entriesByGroup[group].Add(entry); + } - float contentOffset = 0; - var contentOrder = 1; - var contentIndex = 1; + float contentOffset = 0; + var contentOrder = 1; + var contentIndex = 1; - foreach (var pair in entriesByGroup) - { - if (ShouldCreateLabels) - { - CreateLabel(generalLabel, Scroller.Inner, pair.Key, ref contentOffset); - contentOrder = 1; - contentIndex = 1; - } + foreach (var pair in entriesByGroup) + { + if (ShouldCreateLabels) + { + CreateLabel(generalLabel, Scroller.Inner, pair.Key, ref contentOffset); + contentOrder = 1; + contentIndex = 1; + } - foreach (var setting in pair.Value) - { - var obj = setting.CreateOption( - toggle, - slider, - Scroller.Inner, - ref contentOffset, - ref contentOrder, - contentIndex == pair.Value.Count); + foreach (var setting in pair.Value) + { + var obj = setting.CreateOption( + toggle, + slider, + Scroller.Inner, + ref contentOffset, + ref contentOrder, + contentIndex == pair.Value.Count); - obj!.GetComponentsInChildren(true).Do(x => - { - x.maskInteraction = SpriteMaskInteraction.VisibleInsideMask; - x.sortingOrder = 150; - x.sortingLayerName = "Default"; - }); + obj!.GetComponentsInChildren(true).Do(x => + { + x.maskInteraction = SpriteMaskInteraction.VisibleInsideMask; + x.sortingOrder = 150; + x.sortingLayerName = "Default"; + }); - obj.GetComponentsInChildren(true).Do(x => - { - x.sortingOrder = 151; - x.sortingLayerName = "Default"; - }); + obj.GetComponentsInChildren(true).Do(x => + { + x.sortingOrder = 151; + x.sortingLayerName = "Default"; + }); - obj.GetComponentsInChildren().Do(x => { x.ClickMask = OptionsMenuPatches.MaskCollider; }); + obj.GetComponentsInChildren().Do(x => { x.ClickMask = OptionsMenuPatches.MaskCollider; }); - contentIndex++; - } + contentIndex++; + } - contentOrder = 1; - } + contentOrder = 1; + } - contentIndex = 1; - contentOrder = 1; - foreach (var button in Buttons) - { - var obj = button.CreateButton( - toggle, - Scroller.Inner, - ref contentOffset, - ref contentOrder, - contentIndex == Buttons.Count); + contentIndex = 1; + contentOrder = 1; + foreach (var button in Buttons) + { + var obj = button.CreateButton( + toggle, + Scroller.Inner, + ref contentOffset, + ref contentOrder, + contentIndex == Buttons.Count); - obj!.GetComponentsInChildren(true).Do(x => - { - x.maskInteraction = SpriteMaskInteraction.VisibleInsideMask; - x.sortingOrder = 150; - x.sortingLayerName = "Default"; - }); + obj!.GetComponentsInChildren(true).Do(x => + { + x.maskInteraction = SpriteMaskInteraction.VisibleInsideMask; + x.sortingOrder = 150; + x.sortingLayerName = "Default"; + }); - obj.GetComponentsInChildren(true).Do(x => - { - x.sortingOrder = 151; - x.sortingLayerName = "Default"; - }); + obj.GetComponentsInChildren(true).Do(x => + { + x.sortingOrder = 151; + x.sortingLayerName = "Default"; + }); - obj.GetComponentsInChildren().Do(x => { x.ClickMask = OptionsMenuPatches.MaskCollider; }); + obj.GetComponentsInChildren().Do(x => { x.ClickMask = OptionsMenuPatches.MaskCollider; }); - contentIndex++; - } + contentIndex++; + } - Scroller.SetBounds(new FloatRange(0, (Settings.Count + Buttons.Count) * 0.5f - 5f), new FloatRange(0, 0)); - return tab; + Scroller.SetBounds(new FloatRange(0, (Settings.Count + Buttons.Count) * 0.5f - 5f), new FloatRange(0, 0)); + return tab; } /// @@ -252,8 +252,10 @@ public abstract class LocalSettingsTab(ConfigFile config) { if (!tabButtonObject.Content.gameObject.activeSelf) { - //tabButtonObject.Button.color = TabColor; - //tabButtonObject.Rollover.OutColor = TabColor; +#pragma warning disable S125 // Sections of code should not be commented out + // tabButtonObject.Button.color = TabColor; + // tabButtonObject.Rollover.OutColor = TabColor; +#pragma warning restore S125 // Sections of code should not be commented out } tabButton.transform.localPosition = new Vector3(2.4f, 2.1f - tabOffset, 5.5f); diff --git a/MiraAPI/LocalSettings/LocalSettingsTabSingleton.cs b/MiraAPI/LocalSettings/LocalSettingsTabSingleton.cs index a435fa4..f9d964d 100644 --- a/MiraAPI/LocalSettings/LocalSettingsTabSingleton.cs +++ b/MiraAPI/LocalSettings/LocalSettingsTabSingleton.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System.Diagnostics.CodeAnalysis; +using System.Linq; namespace MiraAPI.LocalSettings; @@ -13,7 +14,6 @@ public static class LocalSettingsTabSingleton where T : LocalSettingsTab /// /// Gets the instance of the setting tab. /// -#pragma warning disable CA1000 + [SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "This is a utility class to get the instance of a local settings tab.")] public static T Instance => _instance ??= LocalSettingsManager.Tabs.OfType().Single(); -#pragma warning restore CA1000 } diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs index 78b0278..9d4fac4 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs @@ -13,40 +13,32 @@ namespace MiraAPI.LocalSettings.SettingTypes; /// /// Local setting class for s. /// -public class LocalEnumSetting : LocalSettingBase +/// The tab to create the setting in. +/// The config entry. +/// The type. +/// The name of the setting. +/// The description of the setting. +/// The optional values array to replace the names. +public class LocalEnumSetting( + Type tab, + ConfigEntryBase configEntry, + Type enumType, + string? name = null, + string? description = null, + string[]? values = null) : LocalSettingBase(tab, configEntry, name, description) { /// /// Gets the type of the setting. /// - public Type EnumType { get; } + public Type EnumType { get; } = enumType; /// /// Gets the values. /// - public string[] Values { get; } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The type. - /// The optional values array to replace the names. - public LocalEnumSetting( - Type tab, - ConfigEntryBase configEntry, - Type enumType, - string? name = null, - string? description = null, - string[]? values = null) - : base(tab, configEntry, name, description) - { - EnumType = enumType; - Values = values ?? Enum + public string[] Values { get; } = values ?? [.. Enum .GetValues(configEntry.SettingType) .Cast() - .Select(x => x.ToDisplayString()) - .ToArray(); - } + .Select(x => x.ToDisplayString())]; /// public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last) diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalNumberSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalNumberSetting.cs index fb86fdc..3f3626f 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalNumberSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalNumberSetting.cs @@ -12,52 +12,43 @@ namespace MiraAPI.LocalSettings.SettingTypes; /// /// Local setting class for numbers. /// -public class LocalNumberSetting : LocalSettingBase +/// The tab to create the setting in. +/// The config entry. +/// The value range. +/// The name of the setting. +/// The description of the setting. +/// The increment per click. +/// The suffix used for formatting. +/// The format string used for formatting. +public class LocalNumberSetting( + Type tab, + ConfigEntryBase configEntry, + string? name = null, + string? description = null, + FloatRange? numberRange = null, + float? increment = null, + MiraNumberSuffixes? suffixType = null, + string? formatString = null) : LocalSettingBase(tab, configEntry, name, description) { /// /// Gets the range of the button. /// - public FloatRange NumberRange { get; } + public FloatRange NumberRange { get; } = numberRange ?? new FloatRange(1, 5); /// /// Gets the increment of the value when button is pressed. /// - public float Increment { get; } + public float Increment { get; } = increment ?? 1; /// /// Gets a format for the text to use to format the number. /// - public string FormatString { get; } + public string FormatString { get; } = formatString ?? "0"; /// /// Gets the suffix for the number value. /// - public MiraNumberSuffixes SuffixType { get; } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The value range. - /// The increment per click. - /// The suffix used for formating. - /// The format string used for formating. - public LocalNumberSetting( - Type tab, - ConfigEntryBase configEntry, - string? name = null, - string? description = null, - FloatRange? numberRange = null, - float? increment = null, - MiraNumberSuffixes? suffixType = null, - string? formatString = null) - : base(tab, configEntry, name, description) - { - SuffixType = suffixType ?? MiraNumberSuffixes.None; - NumberRange = numberRange ?? new FloatRange(1, 5); - Increment = increment ?? 1; - FormatString = formatString ?? "0"; - } + public MiraNumberSuffixes SuffixType { get; } = suffixType ?? MiraNumberSuffixes.None; /// public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last) @@ -139,7 +130,7 @@ public class LocalNumberSetting : LocalSettingBase protected override string GetValueText() { var value = GetValue(); - var formated = Helpers.FormatValue(value, SuffixType, FormatString); - return $"{Name}: {formated}"; + var formatted = Helpers.FormatValue(value, SuffixType, FormatString); + return $"{Name}: {formatted}"; } } diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs index ae6f500..f90b6ec 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs @@ -12,59 +12,50 @@ namespace MiraAPI.LocalSettings.SettingTypes; /// /// Local setting class for sliders. /// -public class LocalSliderSetting : LocalSettingBase +/// The tab to create the setting in. +/// The config entry. +/// The name of the setting. +/// The description of the setting. +/// The value range. +/// The suffix used for formatting. +/// The format string used for formatting. +/// Should the value be rounded. +/// Should display the value next to the name. +public class LocalSliderSetting( + Type tab, + ConfigEntryBase configEntry, + string? name = null, + string? description = null, + FloatRange? sliderRange = null, + bool displayValue = false, + MiraNumberSuffixes? suffixType = null, + string? formatString = null, + bool roundValue = false) : LocalSettingBase(tab, configEntry, name, description) { /// /// Gets the range of the slider. /// - public FloatRange SliderRange { get; } + public FloatRange SliderRange { get; } = sliderRange ?? new FloatRange(0, 100); /// /// Gets a value indicating whether the value should be displayed next to name. /// - public bool DisplayValue { get; } + public bool DisplayValue { get; } = displayValue; /// /// Gets a format for the text to use to format the number. /// - public string FormatString { get; } + public string FormatString { get; } = formatString ?? "0.0"; /// /// Gets a value indicating whether the value should be rounded. /// - public bool RoundValue { get; } + public bool RoundValue { get; } = roundValue; /// /// Gets the suffix for the number value. /// - public MiraNumberSuffixes SuffixType { get; } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The value range. - /// The suffix used for formating. - /// The format string used for formating. - /// Should the value be rounded. - public LocalSliderSetting( - Type tab, - ConfigEntryBase configEntry, - string? name = null, - string? description = null, - FloatRange? sliderRange = null, - bool displayValue = false, - MiraNumberSuffixes? suffixType = null, - string? formatString = null, - bool roundValue = false) - : base(tab, configEntry, name, description) - { - SliderRange = sliderRange ?? new FloatRange(0, 100); - DisplayValue = displayValue; - SuffixType = suffixType ?? MiraNumberSuffixes.None; - FormatString = formatString ?? "0.0"; - RoundValue = roundValue; - } + public MiraNumberSuffixes SuffixType { get; } = suffixType ?? MiraNumberSuffixes.None; /// public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last) @@ -110,9 +101,9 @@ public class LocalSliderSetting : LocalSettingBase if (DisplayValue) { var value = GetValue(); - var formated = Helpers.FormatValue(value, SuffixType, FormatString); - var maxFormated = Helpers.FormatValue(SliderRange.max, SuffixType, FormatString); - return $"{Name}: {formated} / {maxFormated}"; + var formatted = Helpers.FormatValue(value, SuffixType, FormatString); + var maxFormatted = Helpers.FormatValue(SliderRange.max, SuffixType, FormatString); + return $"{Name}: {formatted} / {maxFormatted}"; } return $"{Name}"; diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalToggleSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalToggleSetting.cs index 54cd8ee..7561b6b 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalToggleSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalToggleSetting.cs @@ -12,21 +12,17 @@ namespace MiraAPI.LocalSettings.SettingTypes; /// /// Local setting class for toggles. /// -public class LocalToggleSetting : LocalSettingBase +/// The tab to create the setting in. +/// The config entry. +/// The name of the setting. +/// The description of the setting. +public class LocalToggleSetting( + Type tab, + ConfigEntryBase configEntry, + string? name = null, + string? description = null +) : LocalSettingBase(tab, configEntry, name, description) { - /// - /// Initializes a new instance of the class. - /// - /// - public LocalToggleSetting( - Type tab, - ConfigEntryBase configEntry, - string? name = null, - string? description = null - ) : base(tab, configEntry, name, description) - { - } - /// public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last) { diff --git a/MiraAPI/MiraAPI.csproj b/MiraAPI/MiraAPI.csproj index ec090f0..2da2adb 100644 --- a/MiraAPI/MiraAPI.csproj +++ b/MiraAPI/MiraAPI.csproj @@ -5,16 +5,17 @@ AllOfUs.MiraAPI true true + IDE0031;IDE0032 - + - + - - + + diff --git a/MiraAPI/MiraApiPlugin.cs b/MiraAPI/MiraApiPlugin.cs index 594d927..4dc6457 100644 --- a/MiraAPI/MiraApiPlugin.cs +++ b/MiraAPI/MiraApiPlugin.cs @@ -1,4 +1,5 @@ global using static Reactor.Utilities.Logger; + using System; using BepInEx; using BepInEx.Unity.IL2CPP; diff --git a/MiraAPI/MiraApiSettings.cs b/MiraAPI/MiraApiSettings.cs index fbead71..42d6d39 100644 --- a/MiraAPI/MiraApiSettings.cs +++ b/MiraAPI/MiraApiSettings.cs @@ -71,15 +71,13 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config) /// Gets the scale of the buttons. /// [LocalSliderSetting(min: 0.5f, max: 1.5f, suffixType: MiraNumberSuffixes.Multiplier, formatString: "0.00", displayValue: true)] - public ConfigEntry ButtonUIFactorSlider { get; private set; } = - config.Bind("Visuals/UI", "Button Scale Factor", 0.75f); + public ConfigEntry ButtonUIFactorSlider { get; private set; } = config.Bind("Visuals/UI", "Button Scale Factor", 0.75f); /// /// Gets the fps specified by the player. /// [LocalSliderSetting(min: 60f, max: 240f, suffixType: MiraNumberSuffixes.None, formatString: "0", displayValue: true, roundValue: true)] - public ConfigEntry SetFpsSlider { get; private set; } = - config.Bind("Visuals/UI", "Max FPS", 120f); + public ConfigEntry SetFpsSlider { get; private set; } = config.Bind("Visuals/UI", "Max FPS", 120f); /// /// Gets whether to apply cosmetic changes to the TaskAdder. diff --git a/MiraAPI/Modifiers/BaseModifier.cs b/MiraAPI/Modifiers/BaseModifier.cs index 930cc29..652f86c 100644 --- a/MiraAPI/Modifiers/BaseModifier.cs +++ b/MiraAPI/Modifiers/BaseModifier.cs @@ -78,7 +78,10 @@ public abstract class BaseModifier : IOptionable /// Gets the HUD description for this modifier. Does nothing if is . Required to be visible on UI. /// /// The description string for the HUD. - public virtual string GetDescription() => string.Empty; + public virtual string GetDescription() + { + return string.Empty; + } /// /// Called when the modifier is activated. @@ -127,5 +130,8 @@ public abstract class BaseModifier : IOptionable /// Determines whether the player can vent. /// /// if the player can vent, otherwise. for no effect. - public virtual bool? CanVent() => null; + public virtual bool? CanVent() + { + return null; + } } diff --git a/MiraAPI/Modifiers/ModifierComponent.cs b/MiraAPI/Modifiers/ModifierComponent.cs index 6432b18..612fd75 100644 --- a/MiraAPI/Modifiers/ModifierComponent.cs +++ b/MiraAPI/Modifiers/ModifierComponent.cs @@ -17,6 +17,7 @@ namespace MiraAPI.Modifiers; /// The component for handling s. /// [RegisterInIl2Cpp] +[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity Convention.")] public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) { /// @@ -170,7 +171,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) /// The Type of the e. /// An of s. [HideFromIl2Cpp] - public IEnumerable GetModifiers(Func? predicate=null) where T : BaseModifier + public IEnumerable GetModifiers(Func? predicate = null) where T : BaseModifier { return ActiveModifiers.OfType().Where(x => predicate == null || predicate(x)); } @@ -182,7 +183,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) /// The predicate to check the by. /// An of s. [HideFromIl2Cpp] - public IEnumerable GetModifiers(Type type, Func? predicate=null) + public IEnumerable GetModifiers(Type type, Func? predicate = null) { return ActiveModifiers.Where(x => x.GetType() == type && (predicate == null || predicate(x))); } @@ -194,7 +195,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) /// The predicate to check the by. /// An of s. [HideFromIl2Cpp] - public IEnumerable GetModifiers(uint id, Func? predicate=null) + public IEnumerable GetModifiers(uint id, Func? predicate = null) { var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException( $"Cannot get modifier with id {id} because it is not registered."); @@ -446,20 +447,10 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) [HideFromIl2Cpp] public BaseModifier? AddModifier(Type type, params object[] args) { - BaseModifier? modifier; - if (args.Length > 0) - { - modifier = ModifierFactory.CreateInstance(type, args); - } - else - { - modifier = Activator.CreateInstance(type) as BaseModifier; - if (modifier == null) - { - throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier."); - } - } - + var modifier = args.Length > 0 + ? ModifierFactory.CreateInstance(type, args) + : Activator.CreateInstance(type) as BaseModifier + ?? throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier."); return AddModifier(modifier); } @@ -485,7 +476,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) /// The Type of the . /// if the is present, otherwise. [HideFromIl2Cpp] - public bool HasModifier(Func? predicate=null) where T : BaseModifier + public bool HasModifier(Func? predicate = null) where T : BaseModifier { return ActiveModifiers.Exists(x => x is T modifier && (predicate == null || predicate(modifier))); } @@ -497,7 +488,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) /// The predicate to check the . /// if the is present, otherwise. [HideFromIl2Cpp] - public bool HasModifier(Type type, Func? predicate=null) + public bool HasModifier(Type type, Func? predicate = null) { return ActiveModifiers.Exists(x => x.GetType() == type && (predicate == null || predicate(x))); } @@ -509,7 +500,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) /// The predicate to check the . /// if the is present, otherwise. [HideFromIl2Cpp] - public bool HasModifier(uint id, Func? predicate=null) + public bool HasModifier(uint id, Func? predicate = null) { var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException( $"Cannot get modifier with id {id} because it is not registered."); @@ -536,10 +527,13 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) /// The Type of the . /// if the is present, otherwise. [HideFromIl2Cpp] - public bool HasModifier(bool checkInactive, Func? predicate=null) where T : BaseModifier + public bool HasModifier(bool checkInactive, Func? predicate = null) where T : BaseModifier { return ActiveModifiers.Exists(MatchExpr) || (checkInactive && _toAdd.Exists(MatchExpr)); - bool MatchExpr(BaseModifier bm) => bm is T modifier && (predicate == null || predicate(modifier)); + bool MatchExpr(BaseModifier bm) + { + return bm is T modifier && (predicate == null || predicate(modifier)); + } } /// @@ -550,10 +544,13 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) /// The predicate to check the . /// if the is present, otherwise. [HideFromIl2Cpp] - public bool HasModifier(Type type, bool checkInactive, Func? predicate=null) + public bool HasModifier(Type type, bool checkInactive, Func? predicate = null) { return ActiveModifiers.Exists(MatchExpr) || (checkInactive && _toAdd.Exists(MatchExpr)); - bool MatchExpr(BaseModifier bm) => bm.GetType() == type && (predicate == null || predicate(bm)); + bool MatchExpr(BaseModifier bm) + { + return bm.GetType() == type && (predicate == null || predicate(bm)); + } } /// @@ -564,7 +561,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) /// The predicate to check the . /// if the is present, otherwise. [HideFromIl2Cpp] - public bool HasModifier(uint id, bool checkInactive, Func? predicate=null) + public bool HasModifier(uint id, bool checkInactive, Func? predicate = null) { var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException( $"Cannot get modifier with id {id} because it is not registered."); @@ -582,6 +579,9 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) public bool HasModifier(Guid id, bool checkInactive) { return ActiveModifiers.Exists(MatchExpr) || (checkInactive && _toAdd.Exists(MatchExpr)); - bool MatchExpr(BaseModifier bm) => bm.UniqueId == id; + bool MatchExpr(BaseModifier bm) + { + return bm.UniqueId == id; + } } } diff --git a/MiraAPI/Modifiers/ModifierDisplay/ModifierDisplayComponent.cs b/MiraAPI/Modifiers/ModifierDisplay/ModifierDisplayComponent.cs index e93f477..25a6651 100644 --- a/MiraAPI/Modifiers/ModifierDisplay/ModifierDisplayComponent.cs +++ b/MiraAPI/Modifiers/ModifierDisplay/ModifierDisplayComponent.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Linq; using HarmonyLib; using Il2CppInterop.Runtime.Attributes; @@ -18,6 +19,7 @@ namespace MiraAPI.Modifiers.ModifierDisplay; /// The code used to display s. /// [RegisterInIl2Cpp] +[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity Convention.")] public class ModifierDisplayComponent(nint cppPtr) : MonoBehaviour(cppPtr) { /// diff --git a/MiraAPI/Modifiers/ModifierDisplay/ModifierUiComponent.cs b/MiraAPI/Modifiers/ModifierDisplay/ModifierUiComponent.cs index 66ded67..d767e50 100644 --- a/MiraAPI/Modifiers/ModifierDisplay/ModifierUiComponent.cs +++ b/MiraAPI/Modifiers/ModifierDisplay/ModifierUiComponent.cs @@ -1,4 +1,5 @@ -using Il2CppInterop.Runtime.Attributes; +using System.Diagnostics.CodeAnalysis; +using Il2CppInterop.Runtime.Attributes; using Reactor.Utilities.Attributes; using TMPro; using UnityEngine; @@ -9,6 +10,7 @@ namespace MiraAPI.Modifiers.ModifierDisplay; /// The code placed on every HUD object. Used to handle updating. /// [RegisterInIl2Cpp] +[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity Convention.")] public class ModifierUiComponent(nint cppPtr) : MonoBehaviour(cppPtr) { /// diff --git a/MiraAPI/Modifiers/ModifierManager.cs b/MiraAPI/Modifiers/ModifierManager.cs index c2688a0..1a764ca 100644 --- a/MiraAPI/Modifiers/ModifierManager.cs +++ b/MiraAPI/Modifiers/ModifierManager.cs @@ -57,12 +57,7 @@ public static class ModifierManager /// The ID of the modifier. public static uint? GetModifierTypeId(Type type) { - if (!TypeToIdModifierMap.TryGetValue(type, out var id)) - { - return null; - } - - return id; + return !TypeToIdModifierMap.TryGetValue(type, out var id) ? null : id; } internal static bool RegisterModifier(Type modifierType, MiraPluginInfo info) @@ -121,7 +116,7 @@ public static class ModifierManager // Filter and sort modifiers by descending priority. var modifiers = IdToTypeModifierMap - .Where(x=>x.Value.IsAssignableTo(typeof(GameModifier))) + .Where(x => x.Value.IsAssignableTo(typeof(GameModifier))) .Select(x => Activator.CreateInstance(x.Value) as GameModifier) .OfType() .Where(x => x.GetAmountPerGame() > 0 && x.GetAssignmentChance() > 0) diff --git a/MiraAPI/Modifiers/Types/GameModifier.cs b/MiraAPI/Modifiers/Types/GameModifier.cs index f5ae883..1082f8f 100644 --- a/MiraAPI/Modifiers/Types/GameModifier.cs +++ b/MiraAPI/Modifiers/Types/GameModifier.cs @@ -24,32 +24,47 @@ public abstract class GameModifier : BaseModifier /// Gets the priority at which the modifier will spawn. The higher the value, the higher up on the assignment list. /// /// An value greater than or equal to -1. - public virtual int Priority() => -1; + public virtual int Priority() + { + return -1; + } /// /// Determines whether the modifier is valid on a role. /// /// The role to be checked. /// if the modifier is valid on the role, otherwise . - public virtual bool IsModifierValidOn(RoleBehaviour role) => true; + public virtual bool IsModifierValidOn(RoleBehaviour role) + { + return true; + } /// /// Determines whether the modifier is valid on a role, which runs after players are determined but before the modifiers are given. /// /// The role to be checked. /// if the modifier is valid on the role, otherwise . - public virtual bool IsModifierValidOnPostCheck(RoleBehaviour role) => IsModifierValidOn(role); + public virtual bool IsModifierValidOnPostCheck(RoleBehaviour role) + { + return IsModifierValidOn(role); + } /// /// Determines whether the player won the game with this modifier. The modifier with the highest priority will override other modifiers. /// /// The reason why the game ended. /// if the player won, if they lost. Return to use the player's default win condition. - public virtual bool? DidWin(GameOverReason reason) => null; + public virtual bool? DidWin(GameOverReason reason) + { + return null; + } /// /// Determines whether the modifier can spawn in general, accounting for gamemodes and everything else. /// /// if the modifier is able to spawn, otherwise . - public virtual bool CanSpawnOnCurrentMode() => !GameManager.Instance.IsHideAndSeek(); + public virtual bool CanSpawnOnCurrentMode() + { + return !GameManager.Instance.IsHideAndSeek(); + } } diff --git a/MiraAPI/Networking/Modifiers/AddModifierRpc.cs b/MiraAPI/Networking/Modifiers/AddModifierRpc.cs index d3bcaee..dd225f2 100644 --- a/MiraAPI/Networking/Modifiers/AddModifierRpc.cs +++ b/MiraAPI/Networking/Modifiers/AddModifierRpc.cs @@ -57,19 +57,10 @@ public class AddModifierRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc 0) - { - modifier = ModifierFactory.CreateInstance(type, data.Args); - } - else - { - modifier = Activator.CreateInstance(type) as BaseModifier; - if (modifier == null) - { - throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier."); - } - } + var modifier = data.Args.Length > 0 + ? ModifierFactory.CreateInstance(type, data.Args) + : Activator.CreateInstance(type) as BaseModifier + ?? throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier."); modifier.UniqueId = data.UniqueId; player.AddModifier(modifier); } diff --git a/MiraAPI/Networking/NetData.cs b/MiraAPI/Networking/NetData.cs index ce5de46..aa9a52e 100644 --- a/MiraAPI/Networking/NetData.cs +++ b/MiraAPI/Networking/NetData.cs @@ -21,5 +21,8 @@ public readonly struct NetData(uint id, byte[] data) /// Gets the length of the data in bytes. /// /// An int representing the number of bytes this NetData takes up. - public int GetLength() => 4 + Data.Length; + public int GetLength() + { + return 4 + Data.Length; + } } diff --git a/MiraAPI/Networking/SyncOptionsRpc.cs b/MiraAPI/Networking/SyncOptionsRpc.cs index a80ace3..7b8cc04 100644 --- a/MiraAPI/Networking/SyncOptionsRpc.cs +++ b/MiraAPI/Networking/SyncOptionsRpc.cs @@ -5,7 +5,7 @@ using Reactor.Networking.Rpc; namespace MiraAPI.Networking; -// METHOD RPC DOESNT WORK WITH THE ARRAYS AND STUFF SO THIS IS HOW WE WILL DO IT FOR NOW +// METHOD RPC DOESN'T WORK WITH THE ARRAYS AND STUFF SO THIS IS HOW WE WILL DO IT FOR NOW [RegisterCustomRpc((uint)MiraRpc.SyncGameOptions)] internal sealed class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc(plugin, id) { diff --git a/MiraAPI/Patches/.editorconfig b/MiraAPI/Patches/.editorconfig index 1afcd96..2622fc7 100644 --- a/MiraAPI/Patches/.editorconfig +++ b/MiraAPI/Patches/.editorconfig @@ -1,5 +1,16 @@ [*.{cs,vb}] + +# CA1707: Identifiers should not contain underscores. dotnet_diagnostic.CA1707.severity = none + +# CS1591: Missing XML comment for publicly visible type or member. dotnet_diagnostic.CS1591.severity = none + +# SA1611: Element parameters should be documented. dotnet_diagnostic.SA1611.severity = none -dotnet_diagnostic.SA1615.severity = none \ No newline at end of file + +# SA1615: Element return value should be documented. +dotnet_diagnostic.SA1615.severity = none + +# 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/Accessibility/HudManagerFlashPatches.cs b/MiraAPI/Patches/Accessibility/HudManagerFlashPatches.cs index 2fda4c5..1043709 100644 --- a/MiraAPI/Patches/Accessibility/HudManagerFlashPatches.cs +++ b/MiraAPI/Patches/Accessibility/HudManagerFlashPatches.cs @@ -1,11 +1,14 @@ using System.Collections; +using System.Diagnostics.CodeAnalysis; using BepInEx.Unity.IL2CPP.Utils.Collections; using HarmonyLib; using MiraAPI.LocalSettings; using UnityEngine; namespace MiraAPI.Patches.Accessibility; + [HarmonyPatch] +[SuppressMessage("Style", "IDE0074:Use compound assignment", Justification = "Using compound assignment bypasses Unity lifetime checks.")] public static class HudManagerFlashPatches { [HarmonyPatch(typeof(HudManager), nameof(HudManager.StartReactorFlash))] @@ -37,15 +40,15 @@ public static class HudManagerFlashPatches yield break; } var hudManager = HudManager.Instance; - WaitForSeconds wait = new WaitForSeconds(1f); - bool light = false; + var wait = new WaitForSeconds(1f); + var light = false; hudManager.FullScreen.color = new Color(1f, 0f, 0f, 0.37254903f); while (true) { - var settins = LocalSettingsTabSingleton.Instance; - hudManager.FullScreen.gameObject.SetActive(settins.EnableSabotageFlashes.Value && !hudManager.FullScreen.gameObject.activeSelf); - if (settins.EnableSabotageBlares.Value) + var settings = LocalSettingsTabSingleton.Instance; + hudManager.FullScreen.gameObject.SetActive(settings.EnableSabotageFlashes.Value && !hudManager.FullScreen.gameObject.activeSelf); + if (settings.EnableSabotageBlares.Value) { SoundManager.Instance.PlaySound(ShipStatus.Instance.SabotageSound, false, 1f, null); } diff --git a/MiraAPI/Patches/ChatControllerPatch.cs b/MiraAPI/Patches/ChatControllerPatch.cs index c9a6565..95c388b 100644 --- a/MiraAPI/Patches/ChatControllerPatch.cs +++ b/MiraAPI/Patches/ChatControllerPatch.cs @@ -3,12 +3,10 @@ using UnityEngine; namespace MiraAPI.Patches; -#pragma warning disable SA1629 /// -/// Allows players to paste text into chat. -/// Source: +/// Allows players to paste text into chat.
+/// Source: . ///
-#pragma warning restore SA1629 [HarmonyPatch(typeof(ChatController), nameof(ChatController.Update))] public static class ChatControllerPatch { diff --git a/MiraAPI/Patches/DetectiveNotesMinigamePatch.cs b/MiraAPI/Patches/DetectiveNotesMinigamePatch.cs index a11ec7e..2ac485c 100644 --- a/MiraAPI/Patches/DetectiveNotesMinigamePatch.cs +++ b/MiraAPI/Patches/DetectiveNotesMinigamePatch.cs @@ -30,7 +30,7 @@ public static class DetectiveNotesMinigamePatch var customRoles = CustomRoleManager.CustomRoleBehaviours; foreach (var role in allRoles) { - if (role.TeamType != RoleTeamTypes.Impostor || role.Role == RoleTypes.ImpostorGhost || customRoles.Contains(role) ) + if (role.TeamType != RoleTeamTypes.Impostor || role.Role == RoleTypes.ImpostorGhost || customRoles.Contains(role)) continue; var gameObject = Object.Instantiate(__instance.impostorTypePrefab, __instance.impostorTypeParent); __instance.impostorButton.Add(gameObject); diff --git a/MiraAPI/Patches/Events/CanUsePatches.cs b/MiraAPI/Patches/Events/CanUsePatches.cs index 6206591..311697e 100644 --- a/MiraAPI/Patches/Events/CanUsePatches.cs +++ b/MiraAPI/Patches/Events/CanUsePatches.cs @@ -26,14 +26,14 @@ public static class CanUsePatches [HarmonyPriority(Priority.Last)] [HarmonyPrefix] - public static bool CanUsePatch(Il2CppSystem.Object __instance, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] out bool canUse, [HarmonyArgument(2)] out bool couldUse) + public static bool CanUsePatch(Il2CppSystem.Object __instance, [HarmonyArgument(1)] out bool canUse, [HarmonyArgument(2)] out bool couldUse) { canUse = couldUse = false; - IUsable usable = __instance.Cast(); + IUsable usable = __instance.TryCast()!; if (usable != null) { - var @event = new PlayerCanUseEvent(__instance.Cast()); + var @event = new PlayerCanUseEvent(usable); MiraEventManager.InvokeEvent(@event); return !@event.IsCancelled; diff --git a/MiraAPI/Patches/Events/SabotageEventPatches.cs b/MiraAPI/Patches/Events/SabotageEventPatches.cs index 8df8750..0717d6f 100644 --- a/MiraAPI/Patches/Events/SabotageEventPatches.cs +++ b/MiraAPI/Patches/Events/SabotageEventPatches.cs @@ -12,7 +12,7 @@ public static class SabotageEventPatches { [HarmonyPrefix] [HarmonyPatch(typeof(ShipStatus), nameof(ShipStatus.RpcUpdateSystem), typeof(SystemTypes), typeof(byte))] - public static bool ShipStatusUpdateSystemPrefix(ShipStatus __instance, SystemTypes systemType, byte amount) + public static bool ShipStatusUpdateSystemPrefix(SystemTypes systemType, byte amount) { var @event = new UpdateSystemEvent(systemType, PlayerControl.LocalPlayer, amount); MiraEventManager.InvokeEvent(@event); @@ -21,7 +21,7 @@ public static class SabotageEventPatches [HarmonyPrefix] [HarmonyPatch(typeof(ShipStatus), nameof(ShipStatus.RpcCloseDoorsOfType))] - public static bool ShipStatusCloseDoorsOfTypePrefix(ShipStatus __instance, SystemTypes type) + public static bool ShipStatusCloseDoorsOfTypePrefix(SystemTypes type) { var @event = new CloseDoorsEvent(type); MiraEventManager.InvokeEvent(@event); diff --git a/MiraAPI/Patches/Events/VanillaButtonPatches.cs b/MiraAPI/Patches/Events/VanillaButtonPatches.cs index 71df73f..c95ffe2 100644 --- a/MiraAPI/Patches/Events/VanillaButtonPatches.cs +++ b/MiraAPI/Patches/Events/VanillaButtonPatches.cs @@ -38,13 +38,9 @@ public static class VanillaButtonPatches MiraEventManager.InvokeEvent(new VanillaButtonCancelledEvent(__instance)); } - if (!genericEvent.IsCancelled) - { - return true; - } - - return false; + return !genericEvent.IsCancelled; } + [HarmonyPrefix] [HarmonyPatch(typeof(SecondaryAbilityButton), nameof(SecondaryAbilityButton.DoClick))] public static bool SecondaryDoClickPrefix(AbilityButton __instance) @@ -63,11 +59,6 @@ public static class VanillaButtonPatches MiraEventManager.InvokeEvent(new VanillaButtonCancelledEvent(__instance)); } - if (!genericEvent.IsCancelled) - { - return true; - } - - return false; + return !genericEvent.IsCancelled; } } diff --git a/MiraAPI/Patches/Freeplay/TaskAddButtonPatches.cs b/MiraAPI/Patches/Freeplay/TaskAddButtonPatches.cs index 3e4053e..f9e657d 100644 --- a/MiraAPI/Patches/Freeplay/TaskAddButtonPatches.cs +++ b/MiraAPI/Patches/Freeplay/TaskAddButtonPatches.cs @@ -11,13 +11,11 @@ internal static class TaskAddButtonPatches public static bool StartPrefix(TaskAddButton __instance) { // if this becomes problematic in the future, find a new method. - if (uint.TryParse(__instance.name, out var result)) - { - __instance.Overlay.sprite = __instance.CheckImage; - __instance.Overlay.enabled = PlayerControl.LocalPlayer.HasModifier(result); - return false; - } + if (!uint.TryParse(__instance.name, out var result)) + return true; - return true; + __instance.Overlay.sprite = __instance.CheckImage; + __instance.Overlay.enabled = PlayerControl.LocalPlayer.HasModifier(result); + return false; } } diff --git a/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs b/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs index ad0cabc..9342dce 100644 --- a/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs +++ b/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs @@ -24,7 +24,8 @@ namespace MiraAPI.Patches.Freeplay; public static class TaskAdderPatches { private static Scroller _scroller = null!; - private static Dictionary folders = new(); + private static readonly Dictionary Folders = []; + public static string CrewmateName => TranslationController.Instance.GetString(StringNames.Crewmate); public static string ImpostorName => TranslationController.Instance.GetString(StringNames.Impostor); public static string NeutralName => "Neutral"; @@ -75,11 +76,11 @@ public static class TaskAdderPatches // var neutralFolder = __instance.CreateFolder("Neutral", __instance.Root, 2, Color.gray); var modifiersFolder = __instance.CreateFolder(ModifiersName, __instance.Root, 0, Color.blue); - folders.Clear(); - folders.Add(crewmateFolder.FolderName, crewmateFolder); - folders.Add(impostorFolder.FolderName, impostorFolder); + Folders.Clear(); + Folders.Add(crewmateFolder.FolderName, crewmateFolder); + Folders.Add(impostorFolder.FolderName, impostorFolder); // folders.Add("Neutrals", neutralFolder); - folders.Add(ModifiersName, modifiersFolder); + Folders.Add(ModifiersName, modifiersFolder); int folderIdx = 2; foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins) @@ -92,10 +93,10 @@ public static class TaskAdderPatches { var customRole = role as ICustomRole; var folderName = customRole!.Configuration.FreeplayFolder; - if (!folders.TryGetValue(folderName, out var teamFolder)) + if (!Folders.TryGetValue(folderName, out var teamFolder)) { teamFolder = __instance.CreateFolder(folderName, __instance.Root, folderIdx++, customRole.IntroConfiguration?.IntroTeamColor ?? Color.gray); - folders.Add(folderName, teamFolder); + Folders.Add(folderName, teamFolder); } if (!pluginFolders.TryGetValue(folderName, out var pluginFolder)) @@ -187,14 +188,9 @@ public static class TaskAdderPatches taskFolder3 = folders[systemTypes.ToString()] = Object.Instantiate(__instance.RootFolderPrefab, __instance.transform); taskFolder3.SetFolderColor(TaskFolder.FolderColor.Tan); taskFolder3.gameObject.SetActive(false); - if (systemTypes == SystemTypes.UpperEngine) - { - taskFolder3.FolderName = TranslationController.Instance.GetString(StringNames.Engines); - } - else - { - taskFolder3.FolderName = TranslationController.Instance.GetString(systemTypes); - } + taskFolder3.FolderName = systemTypes == SystemTypes.UpperEngine + ? TranslationController.Instance.GetString(StringNames.Engines) + : TranslationController.Instance.GetString(systemTypes); rootFolder.SubFolders.Add(taskFolder3); } @@ -205,7 +201,6 @@ public static class TaskAdderPatches return false; } - private static TaskFolder CreateFolder(this TaskAdderGame instance, string name, TaskFolder parent, int idx = -1, Color? color = null) { var folder = Object.Instantiate(instance.RootFolderPrefab, instance.transform); @@ -250,9 +245,12 @@ public static class TaskAdderPatches instance.ActiveItems.Add(item.transform); } - private static bool IsChildOf(this TaskFolder child, TaskFolder parent) => parent.SubFolders - .ToArray() - .Any(x => x.FolderName == child.FolderName); + private static bool IsChildOf(this TaskFolder child, TaskFolder parent) + { + return parent.SubFolders + .ToArray() + .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: // true -chip @@ -260,7 +258,7 @@ public static class TaskAdderPatches [HarmonyPatch(nameof(TaskAdderGame.ShowFolder))] public static bool ShowPatch(TaskAdderGame __instance, TaskFolder taskFolder) { - StringBuilder stringBuilder = new StringBuilder(64); + var stringBuilder = new StringBuilder(64); __instance.Hierarchy.Add(taskFolder); foreach (var t in __instance.Hierarchy) { @@ -316,6 +314,7 @@ public static class TaskAdderPatches switch (task.TaskType) { case TaskTypes.DivertPower: +#pragma warning disable IDE0055 // Fix formatting { var targetSystem = task.Cast().TargetSystem; taskAddButton.Text.text = TranslationController.Instance.GetString( @@ -334,9 +333,12 @@ public static class TaskAdderPatches break; } default: + { taskAddButton.Text.text = TranslationController.Instance.GetString(task.TaskType); break; + } +#pragma warning restore IDE0055 // Fix formatting } __instance.AddFileAsChildCustom(taskAddButton, ref num, ref num2, ref num3); @@ -380,7 +382,7 @@ public static class TaskAdderPatches { // I hate you } - if (split is ["Roles", _, _] && folders.Any(x => taskFolder.IsChildOf(x.Value))) + if (split is ["Roles", _, _] && Folders.Any(x => taskFolder.IsChildOf(x.Value))) { var plugin = MiraPluginManager.GetPluginByGuid(split[2]); if (plugin != null) @@ -441,7 +443,7 @@ public static class TaskAdderPatches } } - if (folders.TryGetValue(ModifiersName, out var modifiersFolder) && taskFolder.IsChildOf(modifiersFolder)) + if (Folders.TryGetValue(ModifiersName, out var modifiersFolder) && taskFolder.IsChildOf(modifiersFolder)) { var plugin = MiraPluginManager.GetPluginByGuid(taskFolder.name.Replace("(Clone)", string.Empty)); if (plugin != null) diff --git a/MiraAPI/Patches/GameModes/.editorconfig b/MiraAPI/Patches/GameModes/.editorconfig index d825cc9..8e05860 100644 --- a/MiraAPI/Patches/GameModes/.editorconfig +++ b/MiraAPI/Patches/GameModes/.editorconfig @@ -1,2 +1,4 @@ [*.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/HudManagerPatches.cs b/MiraAPI/Patches/HudManagerPatches.cs index 76adc2c..207aa1d 100644 --- a/MiraAPI/Patches/HudManagerPatches.cs +++ b/MiraAPI/Patches/HudManagerPatches.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using HarmonyLib; using MiraAPI.Hud; using MiraAPI.Keybinds; @@ -27,6 +28,8 @@ public static class HudManagerPatches private static Dictionary vanillaKeybindIcons = []; + [SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "This is internal and will never be used by user code.")] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "This is internal and will never be used by user code.")] internal static List ModdedKeybindIcons = []; public static IEnumerator CoResizeUI() @@ -105,23 +108,28 @@ public static class HudManagerPatches } catch { +#pragma warning disable S125 // Sections of code should not be commented out // Error($"Error arranging child objects in GridArrange: {e}"); +#pragma warning restore S125 // Sections of code should not be commented out } } } } } +#pragma warning disable S125 // Sections of code should not be commented out /* /// - /// Trigger hudstart on current custom gamemode + /// Trigger HudStart on current custom gamemode /// [HarmonyPostfix] [HarmonyPatch(nameof(HudManager.OnGameStart))] public static void GameStartPatch(HudManager __instance) { CustomGameModeManager.ActiveMode?.HudStart(__instance); - }*/ + } + */ +#pragma warning restore S125 // Sections of code should not be commented out /// /// Create custom buttons and arrange them on the hud. diff --git a/MiraAPI/Patches/Keybinds/OptionsMenuBehaviourPatch.cs b/MiraAPI/Patches/Keybinds/OptionsMenuBehaviourPatch.cs index 816ebf4..75cf989 100644 --- a/MiraAPI/Patches/Keybinds/OptionsMenuBehaviourPatch.cs +++ b/MiraAPI/Patches/Keybinds/OptionsMenuBehaviourPatch.cs @@ -9,17 +9,18 @@ public static class OptionsMenuBehaviourPatch { private static ButtonRolloverHandler? _remap_rollover; private static SpriteRenderer? _remap_background; - private static bool _conflicts => KeybindManager.GetConflicts().Count > 0; + + private static bool Conflicts => KeybindManager.GetConflicts().Count > 0; [HarmonyPostfix] [HarmonyPatch(nameof(OptionsMenuBehaviour.Open))] - private static void OpenPostfix(OptionsMenuBehaviour __instance) + private static void OpenPostfix() { _remap_rollover = GameObject.Find("Remap Controls")?.GetComponent()!; try { _remap_background = _remap_rollover.transform.FindChild("Background").GetComponent(); - _remap_background.color = _conflicts ? Color.red : Color.white; + _remap_background.color = Conflicts ? Color.red : Color.white; } catch { @@ -29,7 +30,7 @@ public static class OptionsMenuBehaviourPatch [HarmonyPostfix] [HarmonyPatch(nameof(OptionsMenuBehaviour.Update))] - private static void UpdatePostfix(OptionsMenuBehaviour __instance) + private static void UpdatePostfix() { if (_remap_rollover == null) { @@ -40,8 +41,8 @@ public static class OptionsMenuBehaviourPatch 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; + _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; } } diff --git a/MiraAPI/Patches/LocalSettings/OptionsMenuPatches.cs b/MiraAPI/Patches/LocalSettings/OptionsMenuPatches.cs index a8cab15..b998adb 100644 --- a/MiraAPI/Patches/LocalSettings/OptionsMenuPatches.cs +++ b/MiraAPI/Patches/LocalSettings/OptionsMenuPatches.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using HarmonyLib; using MiraAPI.LocalSettings; @@ -14,11 +15,13 @@ namespace MiraAPI.Patches.LocalSettings; public static class OptionsMenuPatches { internal static OptionsMenuBehaviour? Instance { get; private set; } + [SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] internal static BoxCollider2D MaskCollider = null!; private static SpriteRenderer? background; private static int currentPage = 1; - private static Dictionary> tabButtons = new(); + private static readonly Dictionary> TabButtons = []; /// /// Creates the s and their content. @@ -64,7 +67,7 @@ public static class OptionsMenuPatches MaskCollider.enabled = true; currentPage = 1; - tabButtons.Clear(); + TabButtons.Clear(); float yOffset = 0; int i = 0; int tabIdx = 0; @@ -78,10 +81,10 @@ public static class OptionsMenuPatches button.GetComponent().Content = tab; button.SetActive(page == currentPage); - if (!tabButtons.TryGetValue(page, out var list)) + if (!TabButtons.TryGetValue(page, out var list)) { - tabButtons.Add(page, new()); - list = tabButtons[page]; + TabButtons.Add(page, []); + list = TabButtons[page]; } list.Add(button); yOffset += 0.6f; @@ -96,22 +99,22 @@ public static class OptionsMenuPatches } } - void ChangePage(int increase) + static void ChangePage(int increase) { currentPage += increase; - if (currentPage > tabButtons.Count) + if (currentPage > TabButtons.Count) { currentPage = 1; } if (currentPage < 1) { - currentPage = tabButtons.Count; + currentPage = TabButtons.Count; } } // Create page buttons // TODO: In-game menu has no close button. I tried making one from scratch but failed. Add one later plz - if (tabButtons.Count <= 1) + if (TabButtons.Count <= 1) { return; } @@ -181,7 +184,7 @@ public static class OptionsMenuPatches /// [HarmonyPostfix] [HarmonyPatch(nameof(OptionsMenuBehaviour.Open))] - public static void OpenPostfix(OptionsMenuBehaviour __instance) + public static void OpenPostfix() { LocalSettingsManager.AvailableTabs.ForEach(CustomClose); currentPage = 1; @@ -190,7 +193,7 @@ public static class OptionsMenuPatches private static void UpdatePages() { - foreach (var pages in tabButtons) + foreach (var pages in TabButtons) { pages.Value? .Where(x => x != null) diff --git a/MiraAPI/Patches/Menu/HatsTabPatches.cs b/MiraAPI/Patches/Menu/HatsTabPatches.cs index 43d96c3..cb7b586 100644 --- a/MiraAPI/Patches/Menu/HatsTabPatches.cs +++ b/MiraAPI/Patches/Menu/HatsTabPatches.cs @@ -19,7 +19,7 @@ namespace MiraAPI.Patches.Menu; public static class HatsTabPatches { private static SortedList> sortedHats = []; - private static Dictionary storeNames = []; + private static readonly Dictionary StoreNames = []; private static int currentPage; private static void PreviousPage(HatsTab hatsTab) @@ -57,9 +57,9 @@ public static class HatsTabPatches if (!sortedHats.ContainsKey(hat.StoreName)) sortedHats[hat.StoreName] = []; sortedHats[hat.StoreName].Add(hat); - if (!storeNames.ContainsValue(hat.StoreName)) + if (!StoreNames.ContainsValue(hat.StoreName)) { - storeNames.Add(num, hat.StoreName); + StoreNames.Add(num, hat.StoreName); num++; } } @@ -105,7 +105,7 @@ public static class HatsTabPatches __instance.scroller.Inner.GetComponentsInChildren().Do(x => x.gameObject.DeepDestroy(false)); var groupNameText = __instance.GetComponentInChildren(false); - var group = sortedHats.Where(x => x.Key == storeNames[page]); + var group = sortedHats.Where(x => x.Key == StoreNames[page]); foreach ((string groupName, List hats) in group) { @@ -140,9 +140,9 @@ 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)); - var hatYposition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; - GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), hat); + var hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); + var hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; + GenerateColorChip(__instance, new Vector2(hatXPosition, hatYPosition), hat); hatIndex += 1; yield return null; } diff --git a/MiraAPI/Patches/Menu/MainMenuManagerPatches.cs b/MiraAPI/Patches/Menu/MainMenuManagerPatches.cs index f69e374..4ac5b37 100644 --- a/MiraAPI/Patches/Menu/MainMenuManagerPatches.cs +++ b/MiraAPI/Patches/Menu/MainMenuManagerPatches.cs @@ -17,7 +17,7 @@ public static class MainMenuManagerPatches internal static bool NeedsDeepDestroy { get; private set; } /// - /// A postifix on to load all the addressables registered. + /// A postfix on to load all the addressables registered. /// [HarmonyPatch(nameof(MainMenuManager.Awake))] [HarmonyPostfix] diff --git a/MiraAPI/Patches/Menu/NameplatesTabPatches.cs b/MiraAPI/Patches/Menu/NameplatesTabPatches.cs index 6e96d5f..62cd441 100644 --- a/MiraAPI/Patches/Menu/NameplatesTabPatches.cs +++ b/MiraAPI/Patches/Menu/NameplatesTabPatches.cs @@ -18,12 +18,13 @@ public static class NameplatesTabPatches { private static readonly SortedList> SortedNameplates = new(new ControllableComparer(["vanilla"], [], StringComparer.InvariantCulture)); private static int currentPage; + internal static void AddRange(IEnumerable<(string Key, NamePlateData Visor)> data) { - foreach (var item in data) + foreach (var (key, visor) in data) { - if (!SortedNameplates.ContainsKey(item.Key)) SortedNameplates.Add(item.Key, []); - SortedNameplates[item.Key].Add(item.Visor); + if (!SortedNameplates.ContainsKey(key)) SortedNameplates.Add(key, []); + SortedNameplates[key].Add(visor); } } @@ -107,9 +108,9 @@ public static class NameplatesTabPatches 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; - GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), visor); + float hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); + float hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; + GenerateColorChip(__instance, new Vector2(hatXPosition, hatYPosition), visor); hatIndex += 1; } @@ -138,10 +139,10 @@ public static class NameplatesTabPatches colorChip.Button.ClickMask = __instance.scroller.Hitbox; colorChip.ProductId = namePlate.ProdId; - var x = (NamePlateViewData viewdata) => + var x = (NamePlateViewData viewData) => { - colorChip.transform.GetChild(1).GetComponent().sprite = viewdata?.Image; - // (colorChip as NameplateChip).image.sprite = viewdata?.Image; + colorChip.transform.GetChild(1).GetComponent().sprite = viewData?.Image; + // (colorChip as NameplateChip).image.sprite = viewData?.Image; }; __instance.StartCoroutine(AddressableAssetExtensions.CoLoadAssetAsync(__instance, namePlate.GetAssetReference(), x)); colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f); diff --git a/MiraAPI/Patches/Menu/SkinsTabPatches.cs b/MiraAPI/Patches/Menu/SkinsTabPatches.cs index e1c97a5..5bbae0c 100644 --- a/MiraAPI/Patches/Menu/SkinsTabPatches.cs +++ b/MiraAPI/Patches/Menu/SkinsTabPatches.cs @@ -109,9 +109,9 @@ public static class SkinsTabPatches 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; - GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), skin); + float hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); + float 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 a1627cf..65aac7b 100644 --- a/MiraAPI/Patches/Menu/VisorsTabPatches.cs +++ b/MiraAPI/Patches/Menu/VisorsTabPatches.cs @@ -17,12 +17,13 @@ public static class VisorsTabPatches { private static readonly SortedList> SortedVisors = new(new ControllableComparer(["vanilla"], [], StringComparer.InvariantCulture)); private static int currentPage; + internal static void AddRange(IEnumerable<(string Key, VisorData Visor)> data) { - foreach (var item in data) + foreach (var (key, visor) in data) { - if (!SortedVisors.ContainsKey(item.Key)) SortedVisors.Add(item.Key, []); - SortedVisors[item.Key].Add(item.Visor); + if (!SortedVisors.ContainsKey(key)) SortedVisors.Add(key, []); + SortedVisors[key].Add(visor); } } @@ -106,9 +107,9 @@ public static class VisorsTabPatches 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; - GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), visor); + float hatXPosition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f)); + float hatYPosition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset; + GenerateColorChip(__instance, new Vector2(hatXPosition, hatYPosition), visor); hatIndex += 1; } diff --git a/MiraAPI/Patches/Modifiers/EndGameDidWinPatch.cs b/MiraAPI/Patches/Modifiers/EndGameDidWinPatch.cs index eee933c..a85aefa 100644 --- a/MiraAPI/Patches/Modifiers/EndGameDidWinPatch.cs +++ b/MiraAPI/Patches/Modifiers/EndGameDidWinPatch.cs @@ -52,7 +52,7 @@ internal static class EndGameDidWinPatch } } - public static void Postfix(EndGameResult endGameResult) + public static void Postfix() { EndGameResult.CachedWinners.Clear(); foreach (var winner in CachedWinners) diff --git a/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs b/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs index 2bc615d..8a49e72 100644 --- a/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs +++ b/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs @@ -71,14 +71,14 @@ internal static class GameOptionsMenuPatch [HarmonyPostfix] [HarmonyPatch(nameof(GameOptionsMenu.OnEnable))] - public static void OpenPatch(GameOptionsMenu __instance) + public static void OpenPatch() { HudManager.Instance.PlayerCam.OverrideScreenShakeEnabled = false; } [HarmonyPostfix] [HarmonyPatch(nameof(GameOptionsMenu.OnDisable))] - public static void ClosePatch(GameOptionsMenu __instance) + public static void ClosePatch() { HudManager.Instance.PlayerCam.OverrideScreenShakeEnabled = true; } diff --git a/MiraAPI/Patches/Options/GamePresetsTabPatches.cs b/MiraAPI/Patches/Options/GamePresetsTabPatches.cs index bc6dc3a..f4508e3 100644 --- a/MiraAPI/Patches/Options/GamePresetsTabPatches.cs +++ b/MiraAPI/Patches/Options/GamePresetsTabPatches.cs @@ -3,7 +3,6 @@ using System.IO; using System.Linq; using BepInEx.Configuration; using HarmonyLib; -using MiraAPI.GameOptions; using MiraAPI.PluginLoading; using MiraAPI.Presets; using MiraAPI.Roles; @@ -231,7 +230,7 @@ internal static class GamePresetsTabPatches option.SaveToPreset(presetFile); } - foreach (var role in MenuState.Instance.CurrentMod.InternalRoles.Values.OfType().Where(x=>!x.Configuration.HideSettings)) + foreach (var role in MenuState.Instance.CurrentMod.InternalRoles.Values.OfType().Where(x => !x.Configuration.HideSettings)) { role.SaveToPreset(presetFile); } diff --git a/MiraAPI/Patches/Options/GameSettingMenuPatches.cs b/MiraAPI/Patches/Options/GameSettingMenuPatches.cs index c31b519..d4df499 100644 --- a/MiraAPI/Patches/Options/GameSettingMenuPatches.cs +++ b/MiraAPI/Patches/Options/GameSettingMenuPatches.cs @@ -1,17 +1,4 @@ -using System; -using System.Collections.Generic; -using HarmonyLib; -using MiraAPI.GameOptions; -using MiraAPI.Modifiers; -using MiraAPI.PluginLoading; -using MiraAPI.Presets; -using MiraAPI.Utilities.Assets; -using Reactor.Utilities.Extensions; -using TMPro; -using UnityEngine; -using UnityEngine.Events; -using static UnityEngine.UI.Button; -using Object = UnityEngine.Object; +using HarmonyLib; namespace MiraAPI.Patches.Options; diff --git a/MiraAPI/Patches/Options/LobbyViewPanePatches.cs b/MiraAPI/Patches/Options/LobbyViewPanePatches.cs index 51e2e92..e7f4773 100644 --- a/MiraAPI/Patches/Options/LobbyViewPanePatches.cs +++ b/MiraAPI/Patches/Options/LobbyViewPanePatches.cs @@ -52,7 +52,7 @@ public static class LobbyViewPanePatches { __instance.ChangeTab(ModifiersTabName); })); - ModifiersTabButton.gameObject.SetActive(SelectedModIdx!=0); + ModifiersTabButton.gameObject.SetActive(SelectedModIdx != 0); // Create the next button var nextButton = Object.Instantiate(__instance.BackButton, __instance.BackButton.transform.parent).gameObject; @@ -211,8 +211,7 @@ public static class LobbyViewPanePatches } var color = (i == 0) ? Palette.CrewmateRoleBlue : Palette.ImpostorRoleRed; - if (roleBehaviour is ICustomRole custom && (custom.Team is not ModdedRoleTeams.Crewmate && - custom.Team is not ModdedRoleTeams.Impostor)) + if (roleBehaviour is ICustomRole { Team: not (ModdedRoleTeams.Crewmate or ModdedRoleTeams.Impostor) }) { color = Color.grey; } @@ -584,7 +583,7 @@ public static class LobbyViewPanePatches var filteredOptions = SelectedMod.InternalOptionGroups .Where(x => x.OptionableType == roleType) - .SelectMany(x=>x.Options) + .SelectMany(x => x.Options) .ToList(); for (var i = 0; i < filteredOptions.Count; i++) diff --git a/MiraAPI/Patches/Options/MenuState.cs b/MiraAPI/Patches/Options/MenuState.cs index d459202..a0c46eb 100644 --- a/MiraAPI/Patches/Options/MenuState.cs +++ b/MiraAPI/Patches/Options/MenuState.cs @@ -362,7 +362,7 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr) // Game / Modifier / Custom Settings tab // GST.settingsContainer is same as GST.scrollBar.Inner - if (CurrentMenu != MenuCategory.Preset && CurrentMenu != MenuCategory.Roles) + if (CurrentMenu is not (MenuCategory.Preset or MenuCategory.Roles)) { Gsm.GameSettingsTab.settingsContainer = Gsm.GameSettingsTab.scrollBar.Inner = CurrentContainer.transform; CurrentContainer.SetActive(true); diff --git a/MiraAPI/Patches/Options/NotificationPopperPatch.cs b/MiraAPI/Patches/Options/NotificationPopperPatch.cs index 8024ea4..83e22e5 100644 --- a/MiraAPI/Patches/Options/NotificationPopperPatch.cs +++ b/MiraAPI/Patches/Options/NotificationPopperPatch.cs @@ -14,10 +14,9 @@ public static class NotificationPopperPatch [HarmonyArgument(0)] StringNames key, [HarmonyArgument(1)] int roleCount, [HarmonyArgument(2)] int roleChance, - [HarmonyArgument(3)] RoleTeamTypes teamType, [HarmonyArgument(4)] bool playSound) { - if (CustomRoleManager.CustomRoles.Values.FirstOrDefault(x=>x.StringName==key) is not ICustomRole customRole) + if (CustomRoleManager.CustomRoles.Values.FirstOrDefault(x => x.StringName == key) is not ICustomRole customRole) { return true; } diff --git a/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs b/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs index 0dc8721..4aecf06 100644 --- a/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs +++ b/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs @@ -33,7 +33,7 @@ public static class RoleSettingMenuPatches [HarmonyPostfix] [HarmonyPatch(nameof(RolesSettingsMenu.OnEnable))] - public static void OpenPatch(RolesSettingsMenu __instance) + public static void OpenPatch() { HudManager.Instance.PlayerCam.OverrideScreenShakeEnabled = false; } diff --git a/MiraAPI/Patches/Options/SettingPatches.cs b/MiraAPI/Patches/Options/SettingPatches.cs index 59b956c..e19dac6 100644 --- a/MiraAPI/Patches/Options/SettingPatches.cs +++ b/MiraAPI/Patches/Options/SettingPatches.cs @@ -34,19 +34,23 @@ public static class SettingPatches var custom = ModdedOptionsManager.ModdedOptions.Values.FirstOrDefault(opt => opt.OptionBehaviour != null && opt.OptionBehaviour.Data == __instance); - 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 + 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 { MiraNumberSuffixes.None => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo), MiraNumberSuffixes.Multiplier => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo) + "x", @@ -55,24 +59,6 @@ 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 77b83c2..8876b51 100644 --- a/MiraAPI/Patches/PlayerControlPatches.cs +++ b/MiraAPI/Patches/PlayerControlPatches.cs @@ -119,15 +119,9 @@ internal static class PlayerControlPatches [HarmonyPrefix] [HarmonyPatch(nameof(PlayerControl.RpcMurderPlayer))] [HarmonyPatch(nameof(PlayerControl.MurderPlayer))] - // ReSharper disable once InconsistentNaming - public static bool MurderPlayerPrefix(PlayerControl __instance) + public static bool MurderPlayerPrefix() { - if (LobbyBehaviour.Instance) - { - return false; - } - - return true; + return !LobbyBehaviour.Instance; } [HarmonyPostfix] diff --git a/MiraAPI/Patches/Roles/HudManagerPatches.cs b/MiraAPI/Patches/Roles/HudManagerPatches.cs index 3de9b71..12e1952 100644 --- a/MiraAPI/Patches/Roles/HudManagerPatches.cs +++ b/MiraAPI/Patches/Roles/HudManagerPatches.cs @@ -1,4 +1,5 @@ -using HarmonyLib; +using System.Diagnostics.CodeAnalysis; +using HarmonyLib; using InnerNet; using MiraAPI.Roles; using Reactor.Utilities.Extensions; @@ -12,6 +13,10 @@ namespace MiraAPI.Patches.Roles; public static class HudManagerPatches { // Custom role tab. + [SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] + [SuppressMessage("Usage", "CA2211:Non-constant fields should not be visible", Justification = "Read above.")] + [SuppressMessage("Minor Code Smell", "S1104:Fields should not have public accessibility", Justification = "Read above.")] // why so many warnings??? public static TaskPanelBehaviour? RoleTab; /// @@ -49,7 +54,7 @@ public static class HudManagerPatches /// [HarmonyPostfix] [HarmonyPatch(nameof(HudManager.Update))] - public static void UpdatePostfix(HudManager __instance) + public static void UpdatePostfix() { var local = PlayerControl.LocalPlayer; diff --git a/MiraAPI/Patches/Roles/KillButtonPatches.cs b/MiraAPI/Patches/Roles/KillButtonPatches.cs index 9a00422..2d1bbc0 100644 --- a/MiraAPI/Patches/Roles/KillButtonPatches.cs +++ b/MiraAPI/Patches/Roles/KillButtonPatches.cs @@ -7,7 +7,7 @@ using UnityEngine; namespace MiraAPI.Patches.Roles; /// -/// Fix issues for neutral killers. +/// Fixes issues for neutral killers. /// [HarmonyPatch(typeof(KillButton))] public static class KillButtonPatches @@ -46,7 +46,7 @@ public static class KillButtonPatches } /// - /// Use + /// Use /// instead of from vanilla. /// [HarmonyPrefix] diff --git a/MiraAPI/Patches/Roles/LogicRoleSelectionHnsPatch.cs b/MiraAPI/Patches/Roles/LogicRoleSelectionHnsPatch.cs index c3ed277..f2210ce 100644 --- a/MiraAPI/Patches/Roles/LogicRoleSelectionHnsPatch.cs +++ b/MiraAPI/Patches/Roles/LogicRoleSelectionHnsPatch.cs @@ -32,7 +32,7 @@ public static class LogicRoleSelectionHnsPatch 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))); - List list = new List(); + var list = new List(); if (team == RoleTeamTypes.Crewmate) { Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment"); @@ -105,8 +105,8 @@ public static class LogicRoleSelectionHnsPatch int num2 = 0; while (num2 < teamMax && players.Count > 0) { - PseudoRandomList pseudoRandomList = new PseudoRandomList(AmongUsClient.Instance.GameId); - players._items.Do(x => pseudoRandomList.Add(x)); + var pseudoRandomList = new PseudoRandomList(AmongUsClient.Instance.GameId); + players._items.Do(pseudoRandomList.Add); for (int i = 0; i < GameData.RoundsPlayedInSession; i++) { pseudoRandomList.PickRandom(); diff --git a/MiraAPI/Patches/Roles/NameTagPatch.cs b/MiraAPI/Patches/Roles/NameTagPatch.cs index f373bdf..2eef3a2 100644 --- a/MiraAPI/Patches/Roles/NameTagPatch.cs +++ b/MiraAPI/Patches/Roles/NameTagPatch.cs @@ -33,10 +33,10 @@ public static class NameTagPatch if (!PlayerControl.LocalPlayer || !PlayerControl.LocalPlayer.Data || !PlayerControl.LocalPlayer.Data?.Role || !otherPlayerRole) { __result = Color.white; + return false; } __result = PlayerControl.LocalPlayer.Data?.Role == otherPlayerRole ? otherPlayerRole.NameColor : Color.white; - return false; } } diff --git a/MiraAPI/Patches/Roles/RoleManagerPatches.cs b/MiraAPI/Patches/Roles/RoleManagerPatches.cs index 8d13595..00857a5 100644 --- a/MiraAPI/Patches/Roles/RoleManagerPatches.cs +++ b/MiraAPI/Patches/Roles/RoleManagerPatches.cs @@ -63,21 +63,19 @@ public static class RoleManagerPatches [HarmonyPostfix] [HarmonyPatch(nameof(RoleManager.SelectRoles))] - public static void ModifierSelectionPatches(RoleManager __instance) + public static void ModifierSelectionPatches() { if (!AmongUsClient.Instance.AmHost || !ModifierManager.MiraAssignsModifiers) { return; } - ModifierManager.AssignModifiers( - PlayerControl.AllPlayerControls.ToArray().Where(plr => !plr.Data.IsDead && !plr.Data.Disconnected) - .ToList()); + ModifierManager.AssignModifiers([.. PlayerControl.AllPlayerControls.ToArray().Where(plr => !plr.Data.IsDead && !plr.Data.Disconnected)]); } [HarmonyPrefix] [HarmonyPatch(nameof(RoleManager.AssignRoleOnDeath))] - public static bool AssignRoleOnDeath(RoleManager __instance, [HarmonyArgument(0)] PlayerControl plr) + public static bool AssignRoleOnDeath([HarmonyArgument(0)] PlayerControl plr) { if (!plr || !plr.Data.IsDead) { diff --git a/MiraAPI/Patches/Roles/RoleOptionsCollectionPatch.cs b/MiraAPI/Patches/Roles/RoleOptionsCollectionPatch.cs index d4d80d3..45550ef 100644 --- a/MiraAPI/Patches/Roles/RoleOptionsCollectionPatch.cs +++ b/MiraAPI/Patches/Roles/RoleOptionsCollectionPatch.cs @@ -16,7 +16,7 @@ public static class RoleOptionsCollectionPatch /// [HarmonyPrefix] [HarmonyPatch(nameof(RoleOptionsCollectionV10.AnyRolesEnabled))] - public static bool AnyRolesEnabledPrefix(RoleOptionsCollectionV10 __instance, ref bool __result) + public static bool AnyRolesEnabledPrefix(RoleOptionsCollectionV10 __instance) { foreach (KeyValuePair keyValuePair in __instance.roles) { diff --git a/MiraAPI/Patches/Roles/SabotageButtonPatch.cs b/MiraAPI/Patches/Roles/SabotageButtonPatch.cs index 50c6133..2cc026c 100644 --- a/MiraAPI/Patches/Roles/SabotageButtonPatch.cs +++ b/MiraAPI/Patches/Roles/SabotageButtonPatch.cs @@ -11,7 +11,7 @@ public static class SabotageButtonPatch ///
[HarmonyPatch(nameof(SabotageButton.DoClick))] [HarmonyPrefix] - public static bool DoClickPrefix(SabotageButton __instance) + public static bool DoClickPrefix() { var player = PlayerControl.LocalPlayer; diff --git a/MiraAPI/Patches/Roles/SelectRolesPatch.cs b/MiraAPI/Patches/Roles/SelectRolesPatch.cs index dc51f03..8def5a9 100644 --- a/MiraAPI/Patches/Roles/SelectRolesPatch.cs +++ b/MiraAPI/Patches/Roles/SelectRolesPatch.cs @@ -1,7 +1,8 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; using AmongUs.GameOptions; using HarmonyLib; -using System.Linq; using InnerNet; using MiraAPI.Roles; @@ -10,7 +11,12 @@ namespace MiraAPI.Patches.Roles; [HarmonyPatch(typeof(RoleManager))] public static class SelectRolesPatch { + [SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] + [SuppressMessage("Usage", "CA2211:Non-constant fields should not be visible", Justification = "Read above.")] + [SuppressMessage("Minor Code Smell", "S1104:Fields should not have public accessibility", Justification = "Read above.")] // why so many warnings??? public static bool ApiHandlesRoleSelect = true; + [HarmonyPrefix] [HarmonyPatch(nameof(RoleManager.SelectRoles))] public static bool SelectRoles() @@ -21,10 +27,9 @@ public static class SelectRolesPatch } Il2CppSystem.Collections.Generic.List list = new(); AmongUsClient.Instance.GetAllClients(list); - List list2 = list.ToArray() + List list2 = [.. list.ToArray() .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) - .ToList(); + !c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data)]; foreach (NetworkedPlayerInfo networkedPlayerInfo in GameData.Instance.AllPlayers) { @@ -51,7 +56,7 @@ public static class SelectRolesPatch var source = RoleManager.Instance.AllRoles.ToArray() .Where(role => role.TeamType == team && !RoleManager.IsGhostRole(role.Role) && CustomRoleUtils.CanSpawnOnCurrentMode(role)); - List list = new List(); + var list = new List(); IRoleOptionsCollection roleOptions = opts.RoleOptions; // Assign guaranteed roles first, just like the vanilla selector. This is @@ -71,8 +76,7 @@ public static class SelectRolesPatch // another player and, more importantly, leaves the fallback count wrong. list.Clear(); foreach (var role in source.Where(x => - roleOptions.GetChancePerGame(x.Role) > 0 && - roleOptions.GetChancePerGame(x.Role) < 100) + roleOptions.GetChancePerGame(x.Role) is > 0 and < 100) .Select(role => role.Role)) { for (var i = 0; i < roleOptions.GetNumPerGame(role); i++) diff --git a/MiraAPI/Patches/Roles/TaskPanelPatch.cs b/MiraAPI/Patches/Roles/TaskPanelPatch.cs index a08445a..09877e5 100644 --- a/MiraAPI/Patches/Roles/TaskPanelPatch.cs +++ b/MiraAPI/Patches/Roles/TaskPanelPatch.cs @@ -8,7 +8,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 overriden every frame. + /// 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. /// [HarmonyPrefix] diff --git a/MiraAPI/Patches/ServerDropdownPatch.cs b/MiraAPI/Patches/ServerDropdownPatch.cs index 7749c9b..2c91560 100644 --- a/MiraAPI/Patches/ServerDropdownPatch.cs +++ b/MiraAPI/Patches/ServerDropdownPatch.cs @@ -15,7 +15,7 @@ public static class ServerDropdownPatch region.TranslateName == other.TranslateName && region.PingServer == other.PingServer && region.TargetServer == other.TargetServer && - region.Servers.All(s=>other.Servers.Any(x=>x.Equals(s))); + region.Servers.All(s => other.Servers.Any(x => x.Equals(s))); } public static bool Prefix(ServerDropdown __instance) diff --git a/MiraAPI/Patches/Stubs/MinigameStubs.cs b/MiraAPI/Patches/Stubs/MinigameStubs.cs index 4c2628f..b2e62cd 100644 --- a/MiraAPI/Patches/Stubs/MinigameStubs.cs +++ b/MiraAPI/Patches/Stubs/MinigameStubs.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using HarmonyLib; namespace MiraAPI.Patches.Stubs; @@ -7,6 +8,7 @@ namespace MiraAPI.Patches.Stubs; /// Reverse patches for s. /// [HarmonyPatch] +[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Stub parameters.")] public static class MinigameStubs { /// diff --git a/MiraAPI/Patches/Stubs/RoleBehaviourStubs.cs b/MiraAPI/Patches/Stubs/RoleBehaviourStubs.cs index 8743f3b..69b4089 100644 --- a/MiraAPI/Patches/Stubs/RoleBehaviourStubs.cs +++ b/MiraAPI/Patches/Stubs/RoleBehaviourStubs.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using HarmonyLib; using Hazel; using Il2CppSystem.Text; @@ -9,6 +10,7 @@ namespace MiraAPI.Patches.Stubs; /// Stub methods for the class. Needed because of Il2Cpp limitations on injected classes. /// [HarmonyPatch] +[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Stub parameters.")] public static class RoleBehaviourStubs { /// @@ -283,6 +285,8 @@ public static class RoleBehaviourStubs /// Stub method for . /// /// The object. + /// The rpc message id. + /// The used to parse the message. [HarmonyReversePatch] [HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.HandleRoleRpc))] [MethodImpl(MethodImplOptions.NoInlining)] @@ -295,6 +299,9 @@ public static class RoleBehaviourStubs /// Stub method for . /// /// The object. + /// The to apply the special setup to. + /// The killer. + /// The victim. [HarmonyReversePatch] [HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.KillAnimSpecialSetup))] [MethodImpl(MethodImplOptions.NoInlining)] diff --git a/MiraAPI/Patches/TmpAwakePatch.cs b/MiraAPI/Patches/TmpAwakePatch.cs index 9405e01..853c557 100644 --- a/MiraAPI/Patches/TmpAwakePatch.cs +++ b/MiraAPI/Patches/TmpAwakePatch.cs @@ -3,6 +3,7 @@ using MiraAPI.Utilities.Assets; using TMPro; namespace MiraAPI.Patches; + [HarmonyPatch] public static class TmpAwakePatch { diff --git a/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs b/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs index 1d8c1e9..08d1ee6 100644 --- a/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs +++ b/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs @@ -51,12 +51,14 @@ internal static class DummyBehaviourPatches yield break; } - List potentialSuspects = new(); - potentialSuspects.AddRange(PlayerControl.AllPlayerControls - .ToArray() - .Where(p => p != dummy.myPlayer) - .Where(p => dummyVoteEvent.PlayerIsValid(p)) - .Select(p => p.PlayerId)); + List potentialSuspects = + [ + .. PlayerControl.AllPlayerControls + .ToArray() + .Where(p => p != dummy.myPlayer) + .Where(p => dummyVoteEvent.PlayerIsValid(p)) + .Select(p => p.PlayerId), + ]; if (dummyVoteEvent.CanSkip) { diff --git a/MiraAPI/Patches/Voting/MeetingHudPatches.cs b/MiraAPI/Patches/Voting/MeetingHudPatches.cs index 7a4338a..b848555 100644 --- a/MiraAPI/Patches/Voting/MeetingHudPatches.cs +++ b/MiraAPI/Patches/Voting/MeetingHudPatches.cs @@ -12,7 +12,7 @@ using MiraAPI.Voting; namespace MiraAPI.Patches.Voting; [HarmonyPatch(typeof(MeetingHud))] -[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony Convention")] +[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony Convention.")] internal static class MeetingHudPatches { [HarmonyPrefix] @@ -105,7 +105,7 @@ internal static class MeetingHudPatches [HarmonyPrefix] [HarmonyPatch(nameof(MeetingHud.Select))] - public static bool SelectPatch(MeetingHud __instance, int suspectStateIdx) + public static bool SelectPatch(int suspectStateIdx) { var voteData = PlayerControl.LocalPlayer.GetVoteData(); @@ -141,7 +141,7 @@ internal static class MeetingHudPatches continue; } - voteData.Votes.RemoveAll(x=>x.Suspect==pc.PlayerId); + voteData.Votes.RemoveAll(x => x.Suspect == pc.PlayerId); voteData.VotesRemaining += 1; VotingUtils.RpcRemoveVote(PlayerControl.LocalPlayer, player.PlayerId, pc.PlayerId); @@ -205,9 +205,9 @@ internal static class MeetingHudPatches [HarmonyPrefix] [HarmonyPatch(nameof(MeetingHud.PopulateResults))] - public static bool PopulateResultsPatch(MeetingHud __instance, ref Il2CppStructArray states) + public static bool PopulateResultsPatch(ref Il2CppStructArray states) { - var votes = states.Select(x=> new CustomVote(x.VoterId, x.VotedForId)).ToList(); + var votes = states.Select(x => new CustomVote(x.VoterId, x.VotedForId)).ToList(); VotingUtils.HandlePopulateResults(votes); return false; @@ -217,7 +217,7 @@ internal static class MeetingHudPatches [HarmonyPrefix] [HarmonyPatch(nameof(MeetingHud.CmdCastVote))] // Although this method is inlined in MeetingHud.Confirm, the next patch fixes that. - public static bool CmdCastVoteOverridePatch(MeetingHud __instance, byte playerId, byte suspectIdx) + public static bool CmdCastVoteOverridePatch(byte playerId, byte suspectIdx) { VotingUtils.RpcCastVote(PlayerControl.LocalPlayer, playerId, suspectIdx); return false; diff --git a/MiraAPI/PluginLoading/IMiraPlugin.cs b/MiraAPI/PluginLoading/IMiraPlugin.cs index a29dd4c..14f58b7 100644 --- a/MiraAPI/PluginLoading/IMiraPlugin.cs +++ b/MiraAPI/PluginLoading/IMiraPlugin.cs @@ -9,9 +9,9 @@ namespace MiraAPI.PluginLoading; public interface IMiraPlugin { /// - /// Gets or sets a value indicating whether to display the plugin in the options menu. + /// Gets a value indicating whether to display the plugin in the options menu. /// - public virtual bool DisplayOnOptionsMenu => true; + virtual bool DisplayOnOptionsMenu => true; /// /// Gets the name to display on the options menu. @@ -22,39 +22,39 @@ public interface IMiraPlugin /// Gets the abbreviated name to display for other mods to pick up. /// /// The text for the plugin. - public virtual string GetAbbreviatedModName() + virtual string GetAbbreviatedModName() { - return new(OptionsTitleText.Where(c => !char.IsLower(c) && !char.IsWhiteSpace(c)).ToArray()); + return new([.. OptionsTitleText.Where(c => !char.IsLower(c) && !char.IsWhiteSpace(c))]); } /// /// Gets the name for the first custom category in the game options menu, if any. /// - public virtual string CustomOptionMenuNameOne => "Custom Category 1"; + virtual string CustomOptionMenuNameOne => "Custom Category 1"; /// /// Gets the name for the second custom category in the game options menu, if any. /// - public virtual string CustomOptionMenuNameTwo => "Custom Category 2"; + virtual string CustomOptionMenuNameTwo => "Custom Category 2"; /// /// Gets the description for the second custom category in the game options menu, if any. /// - public virtual string ModifierMenuDescription => "Configure modifiers and their settings here!"; + virtual string ModifierMenuDescription => "Configure modifiers and their settings here!"; /// /// Gets the description for the first custom category in the game options menu, if any. /// - public virtual string CustomOptionMenuOneDescription => "Apply game settings for this mod!"; + virtual string CustomOptionMenuOneDescription => "Apply game settings for this mod!"; /// /// Gets the description for the second custom category in the game options menu, if any. /// - public virtual string CustomOptionMenuTwoDescription => "Apply game settings for this mod!"; + virtual string CustomOptionMenuTwoDescription => "Apply game settings for this mod!"; /// /// Gets the for the plugin. /// /// The for the plugin. - public ConfigFile GetConfigFile(); + ConfigFile GetConfigFile(); } diff --git a/MiraAPI/PluginLoading/MiraPluginInfo.cs b/MiraAPI/PluginLoading/MiraPluginInfo.cs index db030b0..4c170f9 100644 --- a/MiraAPI/PluginLoading/MiraPluginInfo.cs +++ b/MiraAPI/PluginLoading/MiraPluginInfo.cs @@ -56,12 +56,12 @@ public class MiraPluginInfo internal void SavePublicCollections() { - Presets = [..InternalPresets]; - Modifiers = [..InternalModifiers]; - OptionGroups = [..InternalOptionGroups]; - Options = [..InternalOptions]; + Presets = [.. InternalPresets]; + Modifiers = [.. InternalModifiers]; + OptionGroups = [.. InternalOptionGroups]; + Options = [.. InternalOptions]; Roles = new ReadOnlyDictionary(InternalRoles); - Buttons = [..InternalButtons]; + Buttons = [.. InternalButtons]; } internal List InternalPresets { get; } = []; diff --git a/MiraAPI/PluginLoading/MiraPluginManager.cs b/MiraAPI/PluginLoading/MiraPluginManager.cs index e662859..8d385b5 100644 --- a/MiraAPI/PluginLoading/MiraPluginManager.cs +++ b/MiraAPI/PluginLoading/MiraPluginManager.cs @@ -17,7 +17,6 @@ using MiraAPI.Keybinds; using MiraAPI.LocalSettings; using MiraAPI.LocalSettings.Attributes; using MiraAPI.Modifiers; -using MiraAPI.Patches.Options; using MiraAPI.Presets; using MiraAPI.Roles; using MiraAPI.Utilities; diff --git a/MiraAPI/Presets/OptionPreset.cs b/MiraAPI/Presets/OptionPreset.cs index 11b6d75..82d4888 100644 --- a/MiraAPI/Presets/OptionPreset.cs +++ b/MiraAPI/Presets/OptionPreset.cs @@ -10,47 +10,39 @@ namespace MiraAPI.Presets; /// /// Represents a preset of game options that can be applied to the game. /// -public class OptionPreset +/// +/// Initializes a new instance of the class with the specified name and configuration file. +/// +/// The name of the preset. +/// The plugin associated with the preset. +/// The configuration file for the preset. +public class OptionPreset(string name, MiraPluginInfo plugin, ConfigFile presetConfig) { /// /// Gets the name of the preset. /// - public string Name { get; } + public string Name { get; } = name; /// /// Gets the plugin associated with the preset. /// - public MiraPluginInfo Plugin { get; } + public MiraPluginInfo Plugin { get; } = plugin; /// /// Gets the of the plugin associated with the preset. /// - public ConfigFile PluginConfig { get; } + public ConfigFile PluginConfig { get; } = plugin.PluginConfig; /// /// Gets the for the preset. /// - public ConfigFile PresetConfig { get; } + public ConfigFile PresetConfig { get; } = presetConfig; /// /// Gets or sets the button associated with the preset in the UI. /// public GameObject? PresetButton { get; set; } - /// - /// Initializes a new instance of the class with the specified name and configuration file. - /// - /// The name of the preset. - /// The plugin associated with the preset. - /// The configuration file for the preset. - public OptionPreset(string name, MiraPluginInfo plugin, ConfigFile presetConfig) - { - Name = name; - Plugin = plugin; - PluginConfig = plugin.PluginConfig; - PresetConfig = presetConfig; - } - /// /// Loads the preset by applying the values from the preset configuration to the plugin configuration. /// @@ -80,9 +72,11 @@ public class OptionPreset { 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/PresetManager.cs b/MiraAPI/Presets/PresetManager.cs index f753db5..2abe74f 100644 --- a/MiraAPI/Presets/PresetManager.cs +++ b/MiraAPI/Presets/PresetManager.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using BepInEx.Configuration; @@ -55,9 +56,10 @@ public static class PresetManager /// Loads the s for the specified plugin by reading the s from the preset directory. /// /// The plugin for which the s should be loaded. + [SuppressMessage("Style", "IDE0031:Use null propagation", Justification = "Using null propagation bypasses Unity's lifetime checks.")] public static void LoadPresets(MiraPluginInfo plugin) { - foreach (var btn in plugin.InternalPresets.Select(x=>x.PresetButton)) + foreach (var btn in plugin.InternalPresets.Select(x => x.PresetButton)) { if (btn != null) { @@ -87,12 +89,12 @@ public static class PresetManager SaveOnConfigSet = false, }; - foreach (var option in plugin.InternalOptions.Where(x=>x.IncludeInPreset)) + foreach (var option in plugin.InternalOptions.Where(x => x.IncludeInPreset)) { option.Bind(presetConfig); } - foreach (var role in plugin.InternalRoles.Values.OfType().Where(x=>!x.Configuration.HideSettings)) + foreach (var role in plugin.InternalRoles.Values.OfType().Where(x => !x.Configuration.HideSettings)) { role.BindConfig(presetConfig); } @@ -101,7 +103,7 @@ public static class PresetManager plugin.InternalPresets.Add(new OptionPreset(presetName, plugin, presetConfig)); } - plugin.Presets = [..plugin.InternalPresets]; + plugin.Presets = [.. plugin.InternalPresets]; } /// @@ -109,15 +111,17 @@ public static class PresetManager /// public static void LoadMasterPreset() { - /*foreach (var btn in plugin.InternalPresets.Select(x=>x.PresetButton)) - { - if (btn != null) - { - Object.DestroyImmediate(btn); - } - } +#pragma warning disable S125 // Sections of code should not be commented out + /*foreach (var btn in plugin.InternalPresets.Select(x => x.PresetButton)) + { + if (btn != null) + { + Object.DestroyImmediate(btn); + } + } - plugin.InternalPresets.Clear();*/ + plugin.InternalPresets.Clear();*/ +#pragma warning restore S125 // Sections of code should not be commented out if (!Directory.Exists(PresetDirectory)) { Directory.CreateDirectory(PresetDirectory); @@ -133,19 +137,22 @@ public static class PresetManager { var fileName = Path.GetFileName(file); Info($"Loading preset file {fileName}"); + +#pragma warning disable S125 // Sections of code should not be commented out // var presetName = Path.GetFileNameWithoutExtension(file); +#pragma warning restore S125 // Sections of code should not be commented out var presetConfig = new ConfigFile(file, false) { SaveOnConfigSet = false, }; foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins) { - foreach (var option in plugin.InternalOptions.Where(x=>x.IncludeInPreset)) + foreach (var option in plugin.InternalOptions.Where(x => x.IncludeInPreset)) { option.Bind(presetConfig); } - foreach (var role in plugin.InternalRoles.Values.OfType().Where(x=>!x.Configuration.HideSettings)) + foreach (var role in plugin.InternalRoles.Values.OfType().Where(x => !x.Configuration.HideSettings)) { role.BindConfig(presetConfig); } @@ -153,8 +160,10 @@ public static class PresetManager presetConfig.Save(); +#pragma warning disable S125 // Sections of code should not be commented out // InternalMasterPresets.Add(new OptionPreset(presetName, plugin, presetConfig)); +#pragma warning restore S125 // Sections of code should not be commented out } - MasterPresets = [..InternalMasterPresets]; + MasterPresets = [.. InternalMasterPresets]; } } diff --git a/MiraAPI/Presets/SavePresetPopup.cs b/MiraAPI/Presets/SavePresetPopup.cs index 87959e7..271c330 100644 --- a/MiraAPI/Presets/SavePresetPopup.cs +++ b/MiraAPI/Presets/SavePresetPopup.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using MiraAPI.Utilities; using MiraAPI.Utilities.Assets; using Reactor.Utilities.Attributes; @@ -10,18 +11,15 @@ using UnityEngine.UI; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member [RegisterInIl2Cpp] -#pragma warning disable S3903 -#pragma warning disable CA1050 +// 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.")] public class SavePresetPopup(nint cppPtr) : Minigame(cppPtr) -#pragma warning restore CA1050 -#pragma warning restore S3903 { -#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. private TextMeshPro textBoxText; private TextBoxTMP textBox; private Action onSave; -#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. // Cleanup holder object public void OnDestroy() @@ -34,7 +32,9 @@ 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(); @@ -80,7 +80,7 @@ public class SavePresetPopup(nint cppPtr) : Minigame(cppPtr) public static void CreatePopup(Action saveAction) { - // Because innerscuff doesnt account for Z value in Close animation + // Because innerscuff doesn't account for Z value in Close animation var holder = new GameObject("PopupHolder") { transform = diff --git a/MiraAPI/Roles/CustomRoleConfiguration.cs b/MiraAPI/Roles/CustomRoleConfiguration.cs index f756fed..1fb8312 100644 --- a/MiraAPI/Roles/CustomRoleConfiguration.cs +++ b/MiraAPI/Roles/CustomRoleConfiguration.cs @@ -5,6 +5,8 @@ using MiraAPI.Patches.Freeplay; using MiraAPI.Utilities.Assets; using TMPro; using UnityEngine; +using System.Diagnostics.CodeAnalysis; + namespace MiraAPI.Roles; /// @@ -12,9 +14,8 @@ namespace MiraAPI.Roles; /// public record struct CustomRoleConfiguration { -#pragma warning disable S1133 [Obsolete("Default constructor is not supported. Please use the constructor that takes an ICustomRole parameter.")] -#pragma warning restore S1133 + [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 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 6c6760b..c5d62b2 100644 --- a/MiraAPI/Roles/CustomRoleManager.cs +++ b/MiraAPI/Roles/CustomRoleManager.cs @@ -75,8 +75,8 @@ public static class CustomRoleManager RoleManager.GhostRoles.Add(role.Role); } - CustomRoleBehaviours = CustomRoles.Values.ToList(); - CustomMiraRoles = CustomRoles.Values.OfType().ToList(); + CustomRoleBehaviours = [.. CustomRoles.Values]; + CustomMiraRoles = [.. CustomRoles.Values.OfType()]; } internal static void RegisterRoleTypes(List roles, MiraPluginInfo pluginInfo) diff --git a/MiraAPI/Roles/CustomRoleUtils.cs b/MiraAPI/Roles/CustomRoleUtils.cs index 08c5cd4..6d09171 100644 --- a/MiraAPI/Roles/CustomRoleUtils.cs +++ b/MiraAPI/Roles/CustomRoleUtils.cs @@ -21,18 +21,17 @@ public static class CustomRoleUtils /// if the is able to spawn, otherwise . public static bool CanSpawnOnCurrentMode(RoleBehaviour role) { - if (role is ICustomRole custom) - { - return custom.CanSpawnOnCurrentMode(); - } - - if (GameManager.Instance.IsHideAndSeek()) - { - return role.Role is RoleTypes.Engineer || role.Role is RoleTypes.Impostor; - } - return true; + return role is ICustomRole custom + ? custom.CanSpawnOnCurrentMode() + : !GameManager.Instance.IsHideAndSeek() || role.Role is RoleTypes.Engineer or RoleTypes.Impostor; } + /// + /// Retrieves a flattened list of possible roles and their selection chances based on the provided assignment data. + /// + /// The list of role assignment configurations to process. + /// An optional filter to apply to the assignment data. If null, all roles in the list are processed. + /// A list of tuples containing the role type and its corresponding chance, duplicated according to each role's configured count. public static List<(ushort RoleType, int Chance)> GetPossibleRoles( List assignmentData, Func? predicate = null) @@ -50,6 +49,11 @@ public static class CustomRoleUtils return roles; } + /// + /// Generates the role assignment data for a specific role type using the current game options. + /// + /// The type of the role to retrieve assignment data for. + /// A instance containing the role behaviour, its maximum count per game, and its selection chance. public static RoleManager.RoleAssignmentData GetAssignData(RoleTypes roleType) { var currentGameOptions = GameOptionsManager.Instance.CurrentGameOptions; @@ -64,12 +68,15 @@ public static class CustomRoleUtils return assignmentData; } + /// + /// Retrieves the registered behaviour for a given role type. + /// + /// The type of the role to find. + /// The matching if found; otherwise, null. public static RoleBehaviour? GetRegisteredRole(RoleTypes roleType) { // we want to prioritize the custom roles because the role has the right RoleColour/TeamColor - var role = CustomRoleManager.AllRoles.FirstOrDefault(x => x.Role == roleType); - - return role; + return CustomRoleManager.AllRoles.FirstOrDefault(x => x.Role == roleType); } /// @@ -77,21 +84,30 @@ public static class CustomRoleUtils /// /// An of s. // ReSharper disable once MemberCanBePrivate.Global - public static IEnumerable GetActiveRoles() => PlayerControl.AllPlayerControls.ToArray().Select(x => x.Data.Role); + public static IEnumerable GetActiveRoles() + { + return PlayerControl.AllPlayerControls.ToArray().Select(x => x.Data.Role); + } /// /// Gets all active in-game roles in a certain team. /// /// The team you would like to check for. /// A list of roles with the team. - public static IEnumerable GetActiveRolesOfTeam(ModdedRoleTeams team) => GetActiveRoles().Where(x => x is ICustomRole customRole && customRole.Team == team); + public static IEnumerable GetActiveRolesOfTeam(ModdedRoleTeams team) + { + return GetActiveRoles().Where(x => x is ICustomRole customRole && customRole.Team == team); + } /// /// Gets all active in-game roles. /// /// The you would like to check for. /// An of s. - public static IEnumerable GetActiveRolesOfType() where T : RoleBehaviour => GetActiveRoles().OfType(); + public static IEnumerable GetActiveRolesOfType() where T : RoleBehaviour + { + return GetActiveRoles().OfType(); + } /// /// Creates a for the Role Tab. @@ -115,12 +131,7 @@ public static class CustomRoleUtils public static LoadableAsset? GetIntroSound(RoleTypes roleType) { var role = CustomRoleManager.AllRoles.FirstOrDefault(role => role.Role == roleType); - if (role is ICustomRole customRole) - { - return customRole.Configuration.IntroSound; - } - - return new PreloadedAsset(role!.IntroSound); + return role is ICustomRole customRole ? customRole.Configuration.IntroSound : new PreloadedAsset(role!.IntroSound); } /// diff --git a/MiraAPI/Roles/ICustomRole.cs b/MiraAPI/Roles/ICustomRole.cs index c0c97be..a789838 100644 --- a/MiraAPI/Roles/ICustomRole.cs +++ b/MiraAPI/Roles/ICustomRole.cs @@ -80,7 +80,7 @@ public interface ICustomRole : IOptionable /// Binds the configuration options for this role to the provided ConfigFile. /// /// The ConfigFile to bind the options to. - public virtual void BindConfig(ConfigFile config) + virtual void BindConfig(ConfigFile config) { config.Bind(NumConfigDefinition, Configuration.DefaultRoleCount); config.Bind(ChanceConfigDefinition, Configuration.DefaultChance); @@ -91,7 +91,7 @@ public interface ICustomRole : IOptionable /// /// The to save the preset configuration to. /// Whether to use the default values for the configuration. - public virtual void SaveToPreset(ConfigFile presetConfig, bool useDefault=false) + virtual void SaveToPreset(ConfigFile presetConfig, bool useDefault = false) { BindConfig(presetConfig); presetConfig[NumConfigDefinition].BoxedValue = useDefault ? Configuration.DefaultRoleCount : GetCount(); @@ -102,7 +102,7 @@ public interface ICustomRole : IOptionable /// Loads the role's configuration from a preset . /// /// The containing the preset configuration. - public virtual void LoadFromPreset(ConfigFile presetConfig) + virtual void LoadFromPreset(ConfigFile presetConfig) { if (presetConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry numEntry)) { @@ -119,40 +119,31 @@ public interface ICustomRole : IOptionable /// Gets the role chance option. /// /// The role chance option. - public virtual int? GetChance() + virtual int? GetChance() { - if (!Configuration.CanModifyChance) - { - return Configuration.DefaultChance; - } - - if (ParentMod.PluginConfig.TryGetEntry(ChanceConfigDefinition, out ConfigEntry entry)) - { - return Mathf.Clamp(entry.Value, 0, 100); - } - - return null; + return !Configuration.CanModifyChance + ? Configuration.DefaultChance + : ParentMod.PluginConfig.TryGetEntry(ChanceConfigDefinition, out ConfigEntry entry) + ? Mathf.Clamp(entry.Value, 0, 100) + : null; } /// /// Gets the role count option. /// /// The role count option. - public virtual int? GetCount() + virtual int? GetCount() { - if (ParentMod.PluginConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry entry)) - { - return Mathf.Clamp(entry.Value, 0, Configuration.MaxRoleCount); - } - - return null; + return ParentMod.PluginConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry entry) + ? Mathf.Clamp(entry.Value, 0, Configuration.MaxRoleCount) + : null; } /// /// Sets the role chance option. /// /// The chance between 0 and 100. - public virtual void SetChance(int chance) + virtual void SetChance(int chance) { if (!Configuration.CanModifyChance) { @@ -173,7 +164,7 @@ public interface ICustomRole : IOptionable /// Sets the role count option. /// /// The amount of this role between zero and its MaxRoleCount in the Configuration. - public virtual void SetCount(int count) + virtual void SetCount(int count) { if (ParentMod.PluginConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry entry)) { @@ -189,7 +180,7 @@ public interface ICustomRole : IOptionable /// /// The player with the role. /// Whether they can see the role (name color) or not. - public virtual bool CanLocalPlayerSeeRole(PlayerControl player) + virtual bool CanLocalPlayerSeeRole(PlayerControl player) { return (PlayerControl.LocalPlayer.Data.Role.IsImpostor && player.Data.Role.IsImpostor) || PlayerControl.LocalPlayer.Data.IsDead; } @@ -200,7 +191,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. - public virtual bool SetupIntroTeam(IntroCutscene instance, ref Il2CppSystem.Collections.Generic.List yourTeam) + virtual bool SetupIntroTeam(IntroCutscene instance, ref Il2CppSystem.Collections.Generic.List yourTeam) { if (Team == ModdedRoleTeams.Custom) { @@ -228,7 +219,10 @@ public interface ICustomRole : IOptionable /// Get the custom Role Tab text for this role. /// /// A with the role tab text. - StringBuilder SetTabText() => CustomRoleUtils.CreateForRole(this); + StringBuilder SetTabText() + { + return CustomRoleUtils.CreateForRole(this); + } /// /// Determine whether a given can be applied to this role. @@ -244,10 +238,13 @@ 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 . - public virtual bool CanSpawnOnCurrentMode() => !GameManager.Instance.IsHideAndSeek(); + virtual bool CanSpawnOnCurrentMode() + { + return !GameManager.Instance.IsHideAndSeek(); + } /// /// Gets the function that determines whether the role should be toggled on or off in the game settings. /// - public virtual Func VisibleInSettings => () => true; + virtual Func VisibleInSettings => () => true; } diff --git a/MiraAPI/Roles/RoleId.cs b/MiraAPI/Roles/RoleId.cs index 189682b..ea0c2f3 100644 --- a/MiraAPI/Roles/RoleId.cs +++ b/MiraAPI/Roles/RoleId.cs @@ -15,12 +15,9 @@ public static class RoleId /// Thrown when the role is not registered. public static ushort Get() where T : ICustomRole { - if (!CustomRoleManager.RoleIds.TryGetValue(typeof(T), out var roleId)) - { - throw new InvalidOperationException($"Role {typeof(T)} is not registered"); - } - - return roleId; + return !CustomRoleManager.RoleIds.TryGetValue(typeof(T), out var roleId) + ? throw new InvalidOperationException($"Role {typeof(T)} is not registered") + : roleId; } /// @@ -31,11 +28,8 @@ public static class RoleId /// Thrown when the role is not registered. public static ushort Get(Type type) { - if (!CustomRoleManager.RoleIds.TryGetValue(type, out var roleId)) - { - throw new InvalidOperationException($"Role {type} is not registered"); - } - - return roleId; + return !CustomRoleManager.RoleIds.TryGetValue(type, out var roleId) + ? throw new InvalidOperationException($"Role {type} is not registered") + : roleId; } } diff --git a/MiraAPI/Utilities/Assets/AddressablesLoader.cs b/MiraAPI/Utilities/Assets/AddressablesLoader.cs index 7acf73d..d2533c6 100644 --- a/MiraAPI/Utilities/Assets/AddressablesLoader.cs +++ b/MiraAPI/Utilities/Assets/AddressablesLoader.cs @@ -163,16 +163,16 @@ public static class AddressablesLoader [HideFromIl2Cpp] internal static IEnumerator LoadCosmetics() { - while (!AmongUsClient.Instance || CatalogLocations.Select(x=>x.Location).Any(x=>!LoadedLocations.Contains(x))) yield return null; + while (!AmongUsClient.Instance || CatalogLocations.Select(x => x.Location).Any(x => !LoadedLocations.Contains(x))) yield return null; var hatBehaviours = DiscoverData(RegisteredHatKeys); - hatBehaviours = hatBehaviours.OrderBy(x => x.StoreName).ToList(); + hatBehaviours = [.. hatBehaviours.OrderBy(x => x.StoreName)]; var skinBehaviours = DiscoverData(RegisteredSkinKeys); - skinBehaviours = skinBehaviours.OrderBy(x => x.StoreName).ToList(); + skinBehaviours = [.. skinBehaviours.OrderBy(x => x.StoreName)]; var namePlateBehaviours = DiscoverAndReportData(RegisteredNameplateKeys); - namePlateBehaviours = namePlateBehaviours.OrderBy(x => x.Category).ToList(); + namePlateBehaviours = [.. namePlateBehaviours.OrderBy(x => x.Category)]; var visorBehaviours = DiscoverAndReportData(RegisteredVisorKeys); - visorBehaviours = visorBehaviours.OrderBy(x => x.Category).ToList(); + visorBehaviours = [.. visorBehaviours.OrderBy(x => x.Category)]; var hatData = new List(); hatData.AddRange(HatManager.Instance.allHats); @@ -187,12 +187,12 @@ public static class AddressablesLoader var visorData = new List(); visorData.AddRange(HatManager.Instance.allVisors); VisorsTabPatches.AddRange(visorBehaviours); - HatManager.Instance.allVisors = PrepareArray(visorData, visorBehaviours.Select(x=>x.Data).ToList()); + HatManager.Instance.allVisors = PrepareArray(visorData, [.. visorBehaviours.Select(x => x.Data)]); var namePlateData = new List(); namePlateData.AddRange(HatManager.Instance.allNamePlates); NameplatesTabPatches.AddRange(namePlateBehaviours); - HatManager.Instance.allNamePlates = PrepareArray(namePlateData, namePlateBehaviours.Select(x => x.Data).ToList()); + HatManager.Instance.allNamePlates = PrepareArray(namePlateData, [.. namePlateBehaviours.Select(x => x.Data)]); } private static T[] PrepareArray(List data, List behaviours) where T : CosmeticData @@ -203,7 +203,7 @@ public static class AddressablesLoader behaviours[i].displayOrder = count + i; data.Add(behaviours[i]); } - return data.ToArray(); + return [.. data]; } private static List DiscoverData(List tags) diff --git a/MiraAPI/Utilities/Assets/LoadableBundleAsset.cs b/MiraAPI/Utilities/Assets/LoadableBundleAsset.cs index 3476a9a..99a9c4c 100644 --- a/MiraAPI/Utilities/Assets/LoadableBundleAsset.cs +++ b/MiraAPI/Utilities/Assets/LoadableBundleAsset.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using Reactor.Utilities.Extensions; using UnityEngine; @@ -17,6 +18,7 @@ public class LoadableBundleAsset(string name, AssetBundle bundle) : LoadableA /// /// The asset. /// The asset did not load properly. + [SuppressMessage("Style", "IDE0029:Use coalesce expression", Justification = "Null coalescing bypasses Unity lifetime checks.")] public override T LoadAsset() { if (LoadedAsset != null) @@ -26,11 +28,6 @@ public class LoadableBundleAsset(string name, AssetBundle bundle) : LoadableA LoadedAsset = bundle.LoadAsset(name); - if (LoadedAsset == null) - { - throw new InvalidOperationException($"INVALID ASSET: {name}"); - } - - return LoadedAsset; + return LoadedAsset == null ? throw new InvalidOperationException($"INVALID ASSET: {name}") : LoadedAsset; } } diff --git a/MiraAPI/Utilities/Assets/LoadableResourceAsset.cs b/MiraAPI/Utilities/Assets/LoadableResourceAsset.cs index 5678997..4fffd2f 100644 --- a/MiraAPI/Utilities/Assets/LoadableResourceAsset.cs +++ b/MiraAPI/Utilities/Assets/LoadableResourceAsset.cs @@ -8,18 +8,18 @@ namespace MiraAPI.Utilities.Assets; /// /// The path to the embedded resource. /// The pixels per unit for the loaded sprite. -public class LoadableResourceAsset(string path, float pixelsPerUnit=100f) : LoadableAsset +public class LoadableResourceAsset(string path, float pixelsPerUnit = 100f) : LoadableAsset { private readonly Assembly _assembly = Assembly.GetCallingAssembly(); /// public override Sprite LoadAsset() { - if (LoadedAsset) + if (!LoadedAsset) { - return LoadedAsset!; + LoadedAsset = SpriteTools.LoadSpriteFromPath(path, _assembly, pixelsPerUnit); } - return LoadedAsset = SpriteTools.LoadSpriteFromPath(path, _assembly, pixelsPerUnit); + return LoadedAsset!; } } diff --git a/MiraAPI/Utilities/Assets/TmpSpriteUtils.cs b/MiraAPI/Utilities/Assets/TmpSpriteUtils.cs index 518e4ac..8b9bf9f 100644 --- a/MiraAPI/Utilities/Assets/TmpSpriteUtils.cs +++ b/MiraAPI/Utilities/Assets/TmpSpriteUtils.cs @@ -1,18 +1,43 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Reactor.Utilities.Extensions; using TMPro; using UnityEngine; namespace MiraAPI.Utilities.Assets; + +/// +/// Utility class for dynamically generating and managing TextMeshPro sprite assets. +/// public static class TmpSpriteUtils { private static Shader _spriteShader; - private static Dictionary LoadedSprites = []; - public static TMP_SpriteAsset AssetHolder; + private static readonly Dictionary LoadedSprites = []; + + [SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] + internal static TMP_SpriteAsset AssetHolder; + + /// + /// Creates and caches a from a given Unity . + /// + /// The Unity sprite to convert into a TMP sprite asset. + /// The unique name for the sprite asset, used for caching and inline rich text tags. + /// The scale applied to the sprite. Defaults to 1. + /// The generated or previously cached . public static TMP_SpriteAsset CreateSpriteAsset(Sprite sprite, string assetName, float scale = 1) { return CreateSpriteAsset(sprite.texture, sprite.rect, assetName, scale); } + + /// + /// Creates and caches a from a source texture and a specific region. + /// + /// The source containing the sprite. + /// The specific region of the texture to use. + /// The unique name for the sprite asset, used for caching and inline rich text tags. + /// The scale applied to the sprite. Defaults to 1. + /// The generated or previously cached . public static TMP_SpriteAsset CreateSpriteAsset(Texture2D sourceTexture, Rect rect, string assetName, float scale = 1) { if (LoadedSprites.TryGetValue(assetName, out var existingAsset)) @@ -26,6 +51,7 @@ public static class TmpSpriteUtils AssetHolder.DontUnload().DontDestroy(); AssetHolder.fallbackSpriteAssets = new(); } + TMP_SpriteAsset spriteAsset = ScriptableObject.CreateInstance(); spriteAsset.name = assetName; spriteAsset.spriteSheet = sourceTexture; @@ -40,9 +66,11 @@ public static class TmpSpriteUtils name = assetName + " Material", }; material.SetTexture(ShaderUtilities.ID_MainTex, sourceTexture); - // TODO: Using these values, the icons will NOT clip through chatboxes. However, this breaks quite literally every other tmp text that isn't masked. Please fix this if a good solution is found. + // TODO: Using these values, the icons will NOT clip through chat boxes. However, this breaks quite literally every other tmp text that isn't masked. Please fix this if a good solution is found. +#pragma warning disable S125 // Sections of code should not be commented out /*material.SetFloat(ShaderUtilities.ID_StencilComp, 4); material.SetFloat(ShaderUtilities.ID_StencilID, 1);*/ +#pragma warning restore S125 // Sections of code should not be commented out material.SetFloat(ShaderUtilities.ID_StencilComp, 0); material.SetFloat(ShaderUtilities.ID_StencilID, 0); material.SetFloat(ShaderUtilities.ID_StencilOp, 0); @@ -65,9 +93,16 @@ public static class TmpSpriteUtils return spriteAsset; } + /// + /// Constructs a with calculated offsets and adds it to the provided . + /// + /// The target sprite asset to add the sprite information to. + /// The texture rect dimensions used to calculate width, height, and offsets. + /// The name assigned to the sprite, used to generate its hash code. + /// The visual scale applied to the sprite rendering. private static void AddSpriteToAsset(TMP_SpriteAsset spriteAsset, Rect rect, string spriteName, float scale) { - TMP_Sprite newSprite = new TMP_Sprite + var newSprite = new TMP_Sprite { name = spriteName, hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteName), diff --git a/MiraAPI/Utilities/ColorExtensions.cs b/MiraAPI/Utilities/ColorExtensions.cs index 0bf4ebf..4d83852 100644 --- a/MiraAPI/Utilities/ColorExtensions.cs +++ b/MiraAPI/Utilities/ColorExtensions.cs @@ -14,10 +14,19 @@ public static class ColorExtensions /// Luminance value between 0 and 1. public static float GetRelativeLuminance(this Color color) { - var r = color.r <= 0.03928f ? color.r / 12.92f : Mathf.Pow((color.r + 0.055f) / 1.055f, 2.4f); - var g = color.g <= 0.03928f ? color.g / 12.92f : Mathf.Pow((color.g + 0.055f) / 1.055f, 2.4f); - var b = color.b <= 0.03928f ? color.b / 12.92f : Mathf.Pow((color.b + 0.055f) / 1.055f, 2.4f); - return (0.2126f * r) + (0.7152f * g) + (0.0722f * b); + return (0.2126f * Linearize(color.r)) + + (0.7152f * Linearize(color.g)) + + (0.0722f * Linearize(color.b)); + } + + /// + /// Linearizes an sRGB component into linear space. + /// + /// The component to linearize. + /// The linearized result. + public static float Linearize(float c) + { + return c <= 0.03928f ? c / 12.92f : Mathf.Pow((c + 0.055f) / 1.055f, 2.4f); } /// diff --git a/MiraAPI/Utilities/ControllableComparer.cs b/MiraAPI/Utilities/ControllableComparer.cs index 8c7806c..c7d3c43 100644 --- a/MiraAPI/Utilities/ControllableComparer.cs +++ b/MiraAPI/Utilities/ControllableComparer.cs @@ -1,22 +1,18 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace MiraAPI.Utilities; -internal sealed class ControllableComparer : IComparer where T : IComparable +internal sealed class ControllableComparer(T[] forcedToBottom, T[] forcedToTop, IComparer fallbackComparer) : IComparer where T : IComparable { - private readonly T[] _forcedToBottom; - private readonly T[] _forcedToTop; - private readonly IComparer _fallbackComparer; - public ControllableComparer(T[] forcedToBottom, T[] forcedToTop, IComparer fallbackComparer) - { - _forcedToBottom = forcedToBottom; - _forcedToTop = forcedToTop; - _fallbackComparer = fallbackComparer; - } + 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))) @@ -24,11 +20,13 @@ internal sealed class ControllableComparer : IComparer where T : IComparab if (_forcedToBottom.Contains(x)) return 1; + if (_forcedToBottom.Contains(y)) return -1; if (_forcedToTop.Contains(x)) return -1; + if (_forcedToTop.Contains(y)) return 1; diff --git a/MiraAPI/Utilities/Extensions.cs b/MiraAPI/Utilities/Extensions.cs index 53e395e..666dbdf 100644 --- a/MiraAPI/Utilities/Extensions.cs +++ b/MiraAPI/Utilities/Extensions.cs @@ -2,6 +2,7 @@ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; @@ -77,14 +78,7 @@ public static class Extensions TaskTypes taskType = self.TaskType; float realtimeSinceStartup = Time.realtimeSinceStartup - self.timeOpened; PlayerTask myTask = self.MyTask; - if (myTask != null) - { - isComplete = myTask.IsComplete; - } - else - { - isComplete = false; - } + isComplete = myTask != null && myTask.IsComplete; analytics.MinigameClosed(data, taskType, realtimeSinceStartup, isComplete); self.StartCoroutine(self.CoDestroySelf()); } @@ -137,26 +131,17 @@ public static class Extensions /// /// Returns a random element from the specified sequence. /// - /// - /// The sequence to select an element from. - /// - /// - /// The type of elements in the sequence. - /// - /// - /// A randomly selected element from . - /// - /// - /// Thrown when is empty. - /// + /// The sequence to select an element from. + /// The type of elements in the sequence. + /// A randomly selected element from . + /// Thrown when is empty. public static T RandomSnapshot(this IEnumerable input) { var list = input.ToList(); - if (list.Count == 0) - throw new InvalidOperationException("Cannot get random element from an empty collection."); - - return list[UnityEngine.Random.Range(0, list.Count)]; + return list.Count == 0 + ? throw new InvalidOperationException("Cannot get random element from an empty collection.") + : list[UnityEngine.Random.Range(0, list.Count)]; } /// @@ -164,14 +149,20 @@ public static class Extensions /// /// The . /// The player's . - public static PlayerControl? GetPlayer(this PlayerVoteArea state) => GameData.Instance.GetPlayerById(state.TargetPlayerId)?.Object; + public static PlayerControl? GetPlayer(this PlayerVoteArea state) + { + return GameData.Instance.GetPlayerById(state.TargetPlayerId)?.Object; + } /// /// Gets an representing the amount of tasks a player has left. /// /// The player. /// A count of how many tasks the player has left. - public static int GetTasksLeft(this PlayerControl player) => player.Data.Tasks.ToArray().Count(x => !x.Complete); + public static int GetTasksLeft(this PlayerControl player) + { + return player.Data.Tasks.ToArray().Count(x => !x.Complete); + } /// /// Checks if a is the game's host. @@ -226,9 +217,13 @@ public static class Extensions /// /// The to destroy. /// Whether to run the garbage collector immediately. + [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Unclear, but please shut up.")] public static void DeepDestroy(this GameObject obj, bool clearGc = true) { obj.Destroy(); +#pragma warning disable S125 // Sections of code should not be commented out + // Nuke(obj, clearGc); +#pragma warning restore S125 // Sections of code should not be commented out } /// @@ -269,6 +264,9 @@ public static class Extensions } } + // Left 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.")] private static IEnumerator Nuke(GameObject? go, bool clearGc) { if (go == null) @@ -359,6 +357,7 @@ public static class Extensions /// /// Clears up the Garbage Collector manually if necessary. /// + [SuppressMessage("Critical Code Smell", "S1215:\"GC.Collect\" should not be called", Justification = "Usage of GC.Collect is intentionally brought on by the user.")] public static void ClearGarbageCollector() { Resources.UnloadUnusedAssets(); diff --git a/MiraAPI/Utilities/Helpers.cs b/MiraAPI/Utilities/Helpers.cs index 9f66817..02e200a 100644 --- a/MiraAPI/Utilities/Helpers.cs +++ b/MiraAPI/Utilities/Helpers.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using HarmonyLib; @@ -42,6 +43,7 @@ public static class Helpers /// Gets the move next of an on . /// /// Where the should be parented to. + /// The name of the method being searched for. /// THe corresponding method to patch. public static MethodBase? GetStateMachineMoveNext(string methodName) { @@ -49,7 +51,7 @@ public static class Helpers var showRoleStateMachine = typeof(T) .GetNestedTypes() - .FirstOrDefault(x=>x.Name.Contains(methodName)); + .FirstOrDefault(x => x.Name.Contains(methodName)); if (showRoleStateMachine == null) { @@ -285,9 +287,9 @@ public static class Helpers { var results = new Il2CppSystem.Collections.Generic.List(); Physics2D.OverlapCircle(source, radius, filter, results); - return results.ToArray() + return [.. results.ToArray() .Where(collider2D => collider2D.CompareTag("DeadBody")) - .Select(collider2D => collider2D.GetComponent()).ToList(); + .Select(collider2D => collider2D.GetComponent())]; } /// @@ -304,9 +306,9 @@ public static class Helpers { var results = new Il2CppSystem.Collections.Generic.List(); Physics2D.OverlapCircle(source, radius, filter, results); - return results.ToArray() + return [.. results.ToArray() .Where(collider2D => colliderTag == null || collider2D.CompareTag(colliderTag)) - .Select(collider2D => collider2D.GetComponent()).ToList(); + .Select(collider2D => collider2D.GetComponent())]; } /// @@ -323,20 +325,17 @@ public static class Helpers { var newList = GetNearestObjectsOfType(source, radius, CreateFilter(Constants.NotShipMask)); - if (!ignoreColliders) - { - return newList; - } - - return (from player in newList - let vector = player.GetTruePosition() - source - let magnitude = vector.magnitude - where !PhysicsHelpers.AnyNonTriggersBetween( - source, - vector.normalized, - magnitude, - Constants.ShipAndObjectsMask) - select player).ToList(); + return !ignoreColliders + ? newList + : [.. from player in newList + let vector = player.GetTruePosition() - source + let magnitude = vector.magnitude + where !PhysicsHelpers.AnyNonTriggersBetween( + source, + vector.normalized, + magnitude, + Constants.ShipAndObjectsMask) + select player]; } /// @@ -361,7 +360,7 @@ public static class Helpers var myPos = source.GetTruePosition(); var players = GetClosestPlayers(myPos, distance, ignoreColliders); - return ignoreSource ? players.Where(plr => plr.PlayerId != source.PlayerId).ToList() : players; + return ignoreSource ? [.. players.Where(plr => plr.PlayerId != source.PlayerId)] : players; } /// @@ -402,17 +401,11 @@ public static class Helpers { var magnitude2 = (a.GetTruePosition() - source).magnitude; var magnitude3 = (b.GetTruePosition() - source).magnitude; - if (magnitude2 > magnitude3) - { - return 1; - } - - if (magnitude2 < magnitude3) - { - return -1; - } - - return 0; + return magnitude2 > magnitude3 + ? 1 + : magnitude2 < magnitude3 + ? -1 + : 0; }); return outputList; } @@ -503,17 +496,16 @@ public static class Helpers /// The random string. public static string RandomString(int length, string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") { - return new string(Enumerable.Repeat(chars, length) - .Select(s => s[Random.RandomRangeInt(0, s.Length)]).ToArray()); + return new string([.. Enumerable.Repeat(chars, length).Select(s => s[Random.RandomRangeInt(0, s.Length)])]); } /// - /// Returns the formated value using the specified suffix and format string. + /// Returns the formatted value using the specified suffix and format string. /// /// The value to format. /// The suffix to add. /// The format string to use to format. - /// The formated value. + /// The formatted value. public static string FormatValue(float value, MiraNumberSuffixes suffix = MiraNumberSuffixes.None, string formatString = "0.0") { return suffix switch @@ -534,11 +526,7 @@ public static class Helpers /// The 's name. public static string GetRoleName(this RoleBehaviour role) { - if (role is ICustomRole custom) - { - return custom.RoleName; - } - return role.NiceName; + return role is ICustomRole custom ? custom.RoleName : role.NiceName; } /// @@ -546,6 +534,7 @@ public static class Helpers /// /// The to check. /// The 's blacklist status. + [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Intentionally unused because the main intent is for it to be used by dependent mods to add to a blacklist.")] public static bool IsRoleBlacklisted(this RoleBehaviour role) { // This should be patchable by mods when a vanilla role is meant to be replaced by a custom role. diff --git a/MiraAPI/Utilities/ShaderID.cs b/MiraAPI/Utilities/ShaderID.cs index 3ef92e6..20a5bf9 100644 --- a/MiraAPI/Utilities/ShaderID.cs +++ b/MiraAPI/Utilities/ShaderID.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using UnityEngine; -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member namespace MiraAPI.Utilities; @@ -11,6 +10,11 @@ public static class ShaderID { private static readonly Dictionary Cache = []; + /// + /// Retrieves the cached shader property ID for the specified name. If it is not cached, it registers and caches the ID before returning it. + /// + /// The name of the shader property to look up. + /// The integer ID of the shader property. public static int Get(string name) { if (Cache.TryGetValue(name, out var id)) @@ -23,81 +27,233 @@ public static class ShaderID return id; } - // For player shader + // For player shaders + + /// + /// The shader property ID for "_BodyColor". + /// public static readonly int BodyColor = Shader.PropertyToID("_BodyColor"); + + /// + /// The shader property ID for "_BackColor". + /// public static readonly int BackColor = Shader.PropertyToID("_BackColor"); + + /// + /// The shader property ID for "_VisorColor". + /// public static readonly int VisorColor = Shader.PropertyToID("_VisorColor"); // Main texture, very obviously used in any shader with a texture + + /// + /// The shader property ID for "_MainTex". + /// public static readonly int MainTex = Shader.PropertyToID("_MainTex"); // Any masking stuff, like MeetingHud bubbles + + /// + /// The shader property ID for "_Mask". + /// public static readonly int Mask = Shader.PropertyToID("_Mask"); + + /// + /// The shader property ID for "_MaskComp". + /// public static readonly int MaskComp = Shader.PropertyToID("_MaskComp"); + + /// + /// The shader property ID for "_MaskLayer". + /// public static readonly int MaskLayer = Shader.PropertyToID("_MaskLayer"); + + /// + /// The shader property ID for "_Stencil". + /// public static readonly int Stencil = Shader.PropertyToID("_Stencil"); + + /// + /// The shader property ID for "_StencilComp". + /// public static readonly int StencilComp = Shader.PropertyToID("_StencilComp"); // Used in many tasks + + /// + /// The shader property ID for "_Color". + /// public static readonly int Color = Shader.PropertyToID("_Color"); // Has 2 uses in the game, provided for convenience + + /// + /// The shader property ID for "_Opacity". + /// public static readonly int Opacity = Shader.PropertyToID("_Opacity"); // Used once in CooldownHelpers, once in PowerBarMining + + /// + /// The shader property ID for "_NormalizedUvs". + /// public static readonly int NormalizedUvs = Shader.PropertyToID("_NormalizedUvs"); // Used in many consoles + + /// + /// The shader property ID for "_Outline". + /// public static readonly int Outline = Shader.PropertyToID("_Outline"); + + /// + /// The shader property ID for "_OutlineColor". + /// public static readonly int OutlineColor = Shader.PropertyToID("_OutlineColor"); // Used in some consoles + + /// + /// The shader property ID for "_AddColor". + /// public static readonly int AddColor = Shader.PropertyToID("_AddColor"); // Has some uses in various locations + + /// + /// The shader property ID for "_Percent". + /// public static readonly int Percent = Shader.PropertyToID("_Percent"); + + /// + /// The shader property ID for "_PercentY". + /// public static readonly int PercentY = Shader.PropertyToID("_PercentY"); + + /// + /// The shader property ID for "_Desat". + /// public static readonly int Desat = Shader.PropertyToID("_Desat"); // Used in LightSource + + /// + /// The shader property ID for "_PlayerRadius". + /// public static readonly int PlayerRadius = Shader.PropertyToID("_PlayerRadius"); + + /// + /// The shader property ID for "_LightRadius". + /// public static readonly int LightRadius = Shader.PropertyToID("_LightRadius"); + + /// + /// The shader property ID for "_LightOffset". + /// public static readonly int LightOffset = Shader.PropertyToID("_LightOffset"); + + /// + /// The shader property ID for "_FlashlightSize". + /// public static readonly int FlashlightSize = Shader.PropertyToID("_FlashlightSize"); + + /// + /// The shader property ID for "_FlashlightAngle". + /// public static readonly int FlashlightAngle = Shader.PropertyToID("_FlashlightAngle"); // Used once for LightSourceGpuRenderer + + /// + /// The shader property ID for "_DepthCompressionValue". + /// public static readonly int DepthCompressionValue = Shader.PropertyToID("_DepthCompressionValue"); // Used in ProgressTracker + + /// + /// The shader property ID for "_Buckets". + /// public static readonly int Buckets = Shader.PropertyToID("_Buckets"); + + /// + /// The shader property ID for "_FullBuckets". + /// public static readonly int FullBuckets = Shader.PropertyToID("_FullBuckets"); // Used once in IntroCutscene and EndGameManager + + /// + /// The shader property ID for "_Rad". + /// public static readonly int Rad = Shader.PropertyToID("_Rad"); // Used only once for Quick Chat + + /// + /// The shader property ID for "_FaceColor". + /// public static readonly int FaceColor = Shader.PropertyToID("_FaceColor"); // Used for NavigationMinigame + + /// + /// The shader property ID for "_CrossHair". + /// public static readonly int CrossHair = Shader.PropertyToID("_CrossHair"); + + /// + /// The shader property ID for "_CrossColor". + /// public static readonly int CrossColor = Shader.PropertyToID("_CrossColor"); // Used for both SurveillanceMinigame (Planet and Normal) + + /// + /// The shader property ID for "_Center". + /// public static readonly int Center = Shader.PropertyToID("_Center"); + + /// + /// The shader property ID for "_Color2". + /// public static readonly int Color2 = Shader.PropertyToID("_Color2"); // Used in ReactorShipRoom + + /// + /// The shader property ID for "_Speed". + /// public static readonly int Speed = Shader.PropertyToID("_Speed"); // Used only once in CourseMinigame + + /// + /// The shader property ID for "_AltTex". + /// public static readonly int AltTex = Shader.PropertyToID("_AltTex"); + + /// + /// The shader property ID for "_Perc". + /// public static readonly int Perc = Shader.PropertyToID("_Perc"); // Used once in TextMarquee + + /// + /// The shader property ID for "_VertexOffsetX". + /// public static readonly int VertexOffsetX = Shader.PropertyToID("_VertexOffsetX"); + + /// + /// The shader property ID for "_VertexOffsetY". + /// public static readonly int VertexOffsetY = Shader.PropertyToID("_VertexOffsetY"); // Used in VertLineBehaviour + + /// + /// The shader property ID for "_Fade". + /// public static readonly int Fade = Shader.PropertyToID("_Fade"); } diff --git a/MiraAPI/Utilities/StateMachineWrapper.cs b/MiraAPI/Utilities/StateMachineWrapper.cs index 3c05334..1321ec1 100644 --- a/MiraAPI/Utilities/StateMachineWrapper.cs +++ b/MiraAPI/Utilities/StateMachineWrapper.cs @@ -53,19 +53,28 @@ public class StateMachineWrapper where T : Il2CppObjectBase /// Gets the current state of the state machine. /// /// The current state as an integer. - public int GetState() => (int)_stateProperty.GetValue(_stateMachine)!; + public int GetState() + { + return (int)_stateProperty.GetValue(_stateMachine)!; + } /// /// Sets the current state of the state machine. /// /// The new state to use. - public void SetState(int newState) => _stateProperty.SetValue(_stateMachine, newState); + public void SetState(int newState) + { + _stateProperty.SetValue(_stateMachine, newState); + } /// /// Sets the newest yield return of the state machine. /// /// The new return to use. - public void SetRecentReturn(Object newReturn) => _currentProperty.SetValue(_stateMachine, newReturn); + public void SetRecentReturn(Object newReturn) + { + _currentProperty.SetValue(_stateMachine, newReturn); + } /// /// Gets a parameter of type from the state machine by its name. diff --git a/MiraAPI/Voting/PlayerVoteData.cs b/MiraAPI/Voting/PlayerVoteData.cs index 0e52078..45ab8b7 100644 --- a/MiraAPI/Voting/PlayerVoteData.cs +++ b/MiraAPI/Voting/PlayerVoteData.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Il2CppInterop.Runtime.Attributes; using Reactor.Utilities.Attributes; using UnityEngine; @@ -34,6 +35,7 @@ public class PlayerVoteData(nint cppPtr) : MonoBehaviour(cppPtr) private int _votesRemaining = 1; + [SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity convention.")] private void Awake() { Owner = GetComponent(); @@ -78,7 +80,7 @@ public class PlayerVoteData(nint cppPtr) : MonoBehaviour(cppPtr) /// The target's playerId. public void RemovePlayerVote(byte playerId) { - Votes.Remove(Votes.Find(x=>x.Suspect==playerId)); + Votes.Remove(Votes.Find(x => x.Suspect == playerId)); } /// diff --git a/MiraAPI/Voting/VotingUtils.cs b/MiraAPI/Voting/VotingUtils.cs index fb117e4..b463ca2 100644 --- a/MiraAPI/Voting/VotingUtils.cs +++ b/MiraAPI/Voting/VotingUtils.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using MiraAPI.Events; using MiraAPI.Events.Vanilla.Meeting.Voting; @@ -107,6 +108,11 @@ public static class VotingUtils /// The id of the player who casted the vote. /// The voted player's id. [MethodRpc((uint)MiraRpc.CastVote)] + [SuppressMessage( + "Style", + "IDE0060:Remove unused parameter", + Justification = "Required parameter: The MethodRpc system mandates an InnerNetObject (or its derived class) as the first parameter for sender context, even if unused in the method body." + )] public static void RpcCastVote(PlayerControl source, byte srcPlayerId, byte suspectPlayerId) { CustomCastVote(srcPlayerId, suspectPlayerId); @@ -168,7 +174,7 @@ public static class VotingUtils { var dictionary = new Dictionary(); - foreach (var vote in votes.Select(v=>v.Suspect)) + foreach (var vote in votes.Select(v => v.Suspect)) { if (!dictionary.TryAdd(vote, 1)) { @@ -198,7 +204,7 @@ public static class VotingUtils /// The list of s. public static void HandlePopulateResults(List votes) { - PopulateResultsEvent @event = new PopulateResultsEvent(votes); + var @event = new PopulateResultsEvent(votes); MiraEventManager.InvokeEvent(@event); if (@event.IsCancelled)