diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index ad0f7544..50db579b 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -5,6 +5,8 @@ on: ["workflow_dispatch", "push", "pull_request"] jobs: build: runs-on: ubuntu-22.04 + permissions: + id-token: write steps: - uses: actions/checkout@v4 with: @@ -38,14 +40,21 @@ jobs: with: name: AllOfUs.MiraAPI.nupkg path: MiraAPI/bin/Release/AllOfUs.MiraAPI.*.nupkg - + - uses: softprops/action-gh-release@v2 if: github.ref_type == 'tag' with: draft: true files: MiraAPI/bin/Release/net6.0/MiraAPI.dll - + + - name: NuGet login + if: github.ref_type == 'tag' + uses: NuGet/login@v1 + id: login + with: + user: xtracube + - name: Push NuGet package if: github.ref_type == 'tag' run: | - dotnet nuget push MiraAPI/bin/Release/AllOfUs.MiraAPI.*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }} \ No newline at end of file + dotnet nuget push MiraAPI/bin/Release/AllOfUs.MiraAPI.*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ steps.login.outputs.NUGET_API_KEY }} diff --git a/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs index 4441391a..61dd2648 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs @@ -29,6 +29,11 @@ public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target /// public PlayerControl? Framed { get; } = framed; + /// + /// Gets whether the murder was meant to be done in a meeting, via an enum. + /// + public MeetingCheck InMeeting { get; } = inMeeting; + /// /// Gets or sets a value indicating whether the murder is done indirectly. /// This is commonly used to prevent the from being killed. @@ -40,11 +45,6 @@ public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target /// public bool IgnoreDefense { get; set; } = ignoreDefense; - /// - /// Gets whether the murder was meant to be done in a meeting, via an enum. - /// - public MeetingCheck InMeeting { get; } = inMeeting; - /// /// Initializes a new instance of the class. /// diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs index 952b2988..656ef44f 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs @@ -14,5 +14,5 @@ public class CheckForEndVotingEvent(bool isVotingComplete) : MiraCancelableEvent /// /// Gets or sets a value indicating whether the voting should be forced to end, regardless of the default logic. /// - public bool ForceEndVoting { get; set; } + public bool ForceEndVoting { get; set; } = false; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs index 0c67e88e..5d3008d6 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs @@ -29,11 +29,6 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool /// public byte TargetId { get; } = targetId; - /// - /// Gets or sets a value indicating whether to prevent the vote from commencing. - /// - public bool PreventVote { get; set; } = false; - /// /// Gets the of the target. /// @@ -43,4 +38,9 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool /// Gets or sets a value indicating whether the vote event is an Overrule caused by a Judge. /// public bool IsOverruling { get; set; } = isOverruling; + + /// + /// Gets or sets a value indicating whether to prevent the vote from commencing. + /// + public bool PreventVote { get; set; } = false; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs index 043ec56c..40a7f1a5 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs @@ -12,7 +12,7 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting; /// The player to be exiled. Will be if no player is to be exiled. public class ProcessVotesEvent(List votes, NetworkedPlayerInfo? exiledPlayer = null) : MiraEvent { - private readonly List originalVotes = [.. votes]; + private readonly CustomVote[] originalVotes = [.. votes]; /// /// Gets a value indicating whether the exiled player has been modified by the event. @@ -48,6 +48,9 @@ public class ProcessVotesEvent(List votes, NetworkedPlayerInfo? exil get; set { + if (field == value) + return; + field = value; ExiledPlayerModified = true; } diff --git a/MiraAPI/GameEnd/GameOverManager.cs b/MiraAPI/GameEnd/GameOverManager.cs index bde0aa8d..f536c49b 100644 --- a/MiraAPI/GameEnd/GameOverManager.cs +++ b/MiraAPI/GameEnd/GameOverManager.cs @@ -29,7 +29,6 @@ public static class GameOverManager if (gameOverType.IsAbstract) { - Error("The type must not be abstract."); return false; } diff --git a/MiraAPI/GameModes/CustomGameModeManager.cs b/MiraAPI/GameModes/CustomGameModeManager.cs index f43fc0de..d5678012 100644 --- a/MiraAPI/GameModes/CustomGameModeManager.cs +++ b/MiraAPI/GameModes/CustomGameModeManager.cs @@ -12,13 +12,13 @@ public static class CustomGameModeManager { internal static readonly Dictionary IdToModeMap = []; + private static uint lastId; + private static uint GetNextId() { - return ++LastId; + return ++lastId; } - private static uint LastId { get; set; } - /// /// Register gamemode from type. /// @@ -45,8 +45,8 @@ public static class CustomGameModeManager return true; IdToModeMap.Add(GetNextId(), mode); - pluginInfo.GameModes.Add(LastId, mode); - mode.ID = LastId; + pluginInfo.GameModes.Add(lastId, mode); + mode.ID = lastId; GameModeOption.AddOption(mode); return true; } @@ -121,7 +121,7 @@ public static class CustomGameModeManager IdToModeMap.Add(1, hnsMode); hnsMode.ID = 1; GameModeOption.AddOption(hnsMode); - LastId++; + lastId++; } internal static void GetAndSetGameMode() diff --git a/MiraAPI/GameModes/GameModeOption.cs b/MiraAPI/GameModes/GameModeOption.cs index 56b63ac7..79fccb28 100644 --- a/MiraAPI/GameModes/GameModeOption.cs +++ b/MiraAPI/GameModes/GameModeOption.cs @@ -17,6 +17,8 @@ namespace MiraAPI.GameModes; /// The game mode option. /// [HarmonyPatch] +[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.")] // why so many warnings??? public static class GameModeOption { /// @@ -47,10 +49,7 @@ public static class GameModeOption [0] = MiraLocaleManager.GetOrCreateLocaleString("MiraApi.Gamemode.Classic"), }; - internal static StringOption OptionBehaviour { get; set; } = null!; - - [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.")] // why so many warnings??? + internal static StringOption OptionBehaviour = null!; internal static int LastValue; internal static void AddOption(AbstractGameMode mode) diff --git a/MiraAPI/GameOptions/Attributes/ModdedOptionAttribute.cs b/MiraAPI/GameOptions/Attributes/ModdedOptionAttribute.cs index 0287a524..3ff1f434 100644 --- a/MiraAPI/GameOptions/Attributes/ModdedOptionAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/ModdedOptionAttribute.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace MiraAPI.GameOptions.Attributes; @@ -10,10 +11,12 @@ namespace MiraAPI.GameOptions.Attributes; /// Optional parameter to specify a role Type. /// Optional parameter to specify a game mode Type. [AttributeUsage(AttributeTargets.Property)] +[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.")] // why so many warnings??? public abstract class ModdedOptionAttribute(string? title = null, Type? roleType = null, Type? modeType = null) : PropertyOptionAttribute { - internal IModdedOption? HolderOption { get; set; } - internal Type ValueType { get; set; } + internal IModdedOption? HolderOption; + internal Type ValueType; /// /// Gets the role type of the option. diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs index 5205c8c7..34215b14 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Text.RegularExpressions; @@ -11,12 +12,14 @@ namespace MiraAPI.GameOptions.Attributes; /// /// The title of the options. [AttributeUsage(AttributeTargets.Property)] +[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.")] // why so many warnings??? public abstract class ModdedOptionListAttribute(string? title = null) : PropertyOptionAttribute { - internal IModdedOptionList? HolderOptionList { get; set; } - internal IList? Value { get; set; } - internal Type ValueType { get; set; } - internal string[] Titles { get; set; } + internal IModdedOptionList? HolderOptionList; + internal IList? Value; + internal Type ValueType; + internal string[] Titles; private static readonly Regex FormatParams = new(@"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout); diff --git a/MiraAPI/GameOptions/OptionNotifConfiguration.cs b/MiraAPI/GameOptions/OptionNotifConfiguration.cs index aa021282..8df65557 100644 --- a/MiraAPI/GameOptions/OptionNotifConfiguration.cs +++ b/MiraAPI/GameOptions/OptionNotifConfiguration.cs @@ -1,6 +1,5 @@ using System; using System.Diagnostics.CodeAnalysis; -using Il2CppInterop.Runtime.Attributes; using TMPro; using UnityEngine; @@ -49,6 +48,5 @@ public record struct OptionNotifConfiguration /// /// Gets or sets the for the text on the options pop-up. /// - [HideFromIl2Cpp] public Color PopUpTextColor { get; set; } } diff --git a/MiraAPI/HnsReimplemented/Options/HnsCrewmateOptions.cs b/MiraAPI/HnsReimplemented/Options/HnsCrewmateOptions.cs index 949cf541..2093c545 100644 --- a/MiraAPI/HnsReimplemented/Options/HnsCrewmateOptions.cs +++ b/MiraAPI/HnsReimplemented/Options/HnsCrewmateOptions.cs @@ -6,7 +6,7 @@ using MiraAPI.Utilities; namespace MiraAPI.HnsReimplemented.Options; /// -/// Gets or sets the crewmate options for Hide and Seek. +/// Crewmate options for Hide and Seek. /// // ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) public class HnsCrewmateOptions : AbstractOptionGroup @@ -15,9 +15,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup public override string GroupName => "Crewmates"; /// - /// Gets or sets the player speed. + /// Gets the player speed. /// - public ModdedNumberOption PlayerSpeed { get; set; } = new( + public ModdedNumberOption PlayerSpeed { get; } = new( "Player Speed", 1f, 0.5f, @@ -29,9 +29,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup "0.00"); /// - /// Gets or sets the hiding time. + /// Gets the hiding time. /// - public ModdedNumberOption HidingTime { get; set; } = new( + public ModdedNumberOption HidingTime { get; } = new( "Hiding Time", 200, 160, @@ -42,9 +42,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup MiraNumberSuffixes.Seconds); /// - /// Gets or sets the limits of a crewmate's vision. + /// Gets the limits of a crewmate's vision. /// - public ModdedNumberOption CrewmateVision { get; set; } = new( + public ModdedNumberOption CrewmateVision { get; } = new( "Crewmate Vision", 0.6f, 0.25f, @@ -56,16 +56,16 @@ public class HnsCrewmateOptions : AbstractOptionGroup "0.00"); /// - /// Gets or sets a flag that toggles flashlight vision. + /// Gets a flag that toggles flashlight vision. /// - public ModdedToggleOption FlashlightMode { get; set; } = new( + public ModdedToggleOption FlashlightMode { get; } = new( "Flashlight Mode", true); /// - /// Gets or sets the range of a crewmate's flashlight. + /// Gets the range of a crewmate's flashlight. /// - public ModdedNumberOption CrewmateFlashlightSize { get; set; } = new( + public ModdedNumberOption CrewmateFlashlightSize { get; } = new( "Crewmate Flashlight Size", 0.35f, 0.1f, @@ -79,9 +79,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup }; /// - /// Gets or sets the maximum number of times a crewmate can vent. + /// Gets the maximum number of times a crewmate can vent. /// - public ModdedNumberOption MaxVentUses { get; set; } = new( + public ModdedNumberOption MaxVentUses { get; } = new( "Max Vent Uses", 1, 0, @@ -92,9 +92,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup MiraNumberSuffixes.None); /// - /// Gets or sets the maximum amount of time a crewmate can spend inside a vent. + /// Gets the maximum amount of time a crewmate can spend inside a vent. /// - public ModdedNumberOption MaxTimeInVent { get; set; } = new( + public ModdedNumberOption MaxTimeInVent { get; } = new( "Max Time in Vent", 3, 1, @@ -108,9 +108,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup }; /// - /// Gets or sets the visibility of player names. + /// Gets the visibility of player names. /// - public ModdedToggleOption ShowNames { get; set; } = new( + public ModdedToggleOption ShowNames { get; } = new( "Show Names", false); } diff --git a/MiraAPI/HnsReimplemented/Options/HnsFinalHideOptions.cs b/MiraAPI/HnsReimplemented/Options/HnsFinalHideOptions.cs index ab6d393e..e7739eaa 100644 --- a/MiraAPI/HnsReimplemented/Options/HnsFinalHideOptions.cs +++ b/MiraAPI/HnsReimplemented/Options/HnsFinalHideOptions.cs @@ -6,7 +6,7 @@ using MiraAPI.Utilities; namespace MiraAPI.HnsReimplemented.Options; /// -/// Gets or sets the Final Hide options for Hide and Seek. +/// Final Hide options for Hide and Seek. /// // ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) public class HnsFinalHideOptions : AbstractOptionGroup @@ -15,9 +15,9 @@ public class HnsFinalHideOptions : AbstractOptionGroup public override string GroupName => "Final Hide"; /// - /// Gets or sets the duration of the Final Hide phase. + /// Gets the duration of the Final Hide phase. /// - public ModdedNumberOption FinalHideTime { get; set; } = new( + public ModdedNumberOption FinalHideTime { get; } = new( "Hiding Time", 50, 30, @@ -28,9 +28,9 @@ public class HnsFinalHideOptions : AbstractOptionGroup MiraNumberSuffixes.Seconds); /// - /// Gets or sets the Seeker's speed when the Final Hide phase begins. + /// Gets the Seeker's speed when the Final Hide phase begins. /// - public ModdedNumberOption FinalHideImpostorSpeed { get; set; } = new( + public ModdedNumberOption FinalHideImpostorSpeed { get; } = new( "Final Hide Impostor Speed", 1.2f, 1f, @@ -42,16 +42,16 @@ public class HnsFinalHideOptions : AbstractOptionGroup "0.00"); /// - /// Gets or sets whether the Seeker sees the Final hide player pings. + /// Gets whether the Seeker sees the Final hide player pings. /// - public ModdedToggleOption FinalHidePings { get; set; } = new( + public ModdedToggleOption FinalHidePings { get; } = new( "Final Hide Pings", true); /// - /// Gets or sets the interval between each ping. + /// Gets the interval between each ping. /// - public ModdedNumberOption PingInterval { get; set; } = new( + public ModdedNumberOption PingInterval { get; } = new( "Ping Interval", 6, 3, @@ -62,9 +62,9 @@ public class HnsFinalHideOptions : AbstractOptionGroup MiraNumberSuffixes.Seconds); /// - /// Gets or sets whether the Seeker can see players on an admin map. + /// Gets whether the Seeker can see players on an admin map. /// - public ModdedToggleOption FinalHideSeekMap { get; set; } = new( + public ModdedToggleOption FinalHideSeekMap { get; } = new( "Final Hide Seek Map", true); } diff --git a/MiraAPI/HnsReimplemented/Options/HnsImpostorOptions.cs b/MiraAPI/HnsReimplemented/Options/HnsImpostorOptions.cs index 15da3ff8..c2df43bc 100644 --- a/MiraAPI/HnsReimplemented/Options/HnsImpostorOptions.cs +++ b/MiraAPI/HnsReimplemented/Options/HnsImpostorOptions.cs @@ -6,7 +6,7 @@ using MiraAPI.Utilities; namespace MiraAPI.HnsReimplemented.Options; /// -/// Gets or sets the seeker settings on Hide and Seek. +/// Seeker settings on Hide and Seek. /// // ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) public class HnsImpostorOptions : AbstractOptionGroup @@ -15,15 +15,15 @@ public class HnsImpostorOptions : AbstractOptionGroup public override string GroupName => "Impostors"; /// - /// Gets or sets the player who will be the seeker. + /// Gets the player who will be the seeker. /// - public ModdedPlayerOption SelectedSeeker { get; set; } = new( + public ModdedPlayerOption SelectedSeeker { get; } = new( "Forced Impostor"); /// - /// Gets or sets the range of a seeker's vision. + /// Gets the range of a seeker's vision. /// - public ModdedNumberOption ImpostorVision { get; set; } = new( + public ModdedNumberOption ImpostorVision { get; } = new( "Impostor Vision", 0.6f, 0.25f, @@ -35,9 +35,9 @@ public class HnsImpostorOptions : AbstractOptionGroup "0.00"); /// - /// Gets or sets the range of a seeker's flashlight. + /// Gets the range of a seeker's flashlight. /// - public ModdedNumberOption ImpostorFlashlightSize { get; set; } = new( + public ModdedNumberOption ImpostorFlashlightSize { get; } = new( "Impostor Flashlight Size", 0.35f, 0.1f, diff --git a/MiraAPI/HnsReimplemented/Options/HnsTaskOptions.cs b/MiraAPI/HnsReimplemented/Options/HnsTaskOptions.cs index dddd7043..723de1ab 100644 --- a/MiraAPI/HnsReimplemented/Options/HnsTaskOptions.cs +++ b/MiraAPI/HnsReimplemented/Options/HnsTaskOptions.cs @@ -6,7 +6,7 @@ using MiraAPI.Utilities; namespace MiraAPI.HnsReimplemented.Options; /// -/// Gets or sets the task options for Hide and Seek. +/// Task options for Hide and Seek. /// // ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.) public class HnsTaskOptions : AbstractOptionGroup @@ -15,9 +15,9 @@ public class HnsTaskOptions : AbstractOptionGroup public override string GroupName => "Tasks"; /// - /// Gets or sets the umber of common tasks. + /// Gets the umber of common tasks. /// - public ModdedNumberOption CommonTasks { get; set; } = new( + public ModdedNumberOption CommonTasks { get; } = new( "# Common Tasks", 1, 0, @@ -28,9 +28,9 @@ public class HnsTaskOptions : AbstractOptionGroup MiraNumberSuffixes.None); /// - /// Gets or sets the number of long tasks. + /// Gets the number of long tasks. /// - public ModdedNumberOption LongTasks { get; set; } = new( + public ModdedNumberOption LongTasks { get; } = new( "# Long Tasks", 1, 0, @@ -41,9 +41,9 @@ public class HnsTaskOptions : AbstractOptionGroup MiraNumberSuffixes.None); /// - /// Gets or sets the number of short tasks. + /// Gets the number of short tasks. /// - public ModdedNumberOption ShortTasks { get; set; } = new( + public ModdedNumberOption ShortTasks { get; } = new( "# Short Tasks", 2, 0, diff --git a/MiraAPI/Keybinds/KeybindManager.cs b/MiraAPI/Keybinds/KeybindManager.cs index 143863e8..b3097e14 100644 --- a/MiraAPI/Keybinds/KeybindManager.cs +++ b/MiraAPI/Keybinds/KeybindManager.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; -using Il2CppInterop.Runtime.Attributes; using MiraAPI.Utilities; using Rewired; @@ -17,8 +17,9 @@ public static class KeybindManager /// public static List Keybinds { get; } = []; - [HideFromIl2Cpp] - internal static Dictionary VanillaKeybinds { get; 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 readonly Dictionary VanillaKeybinds = []; internal static void RewiredInit() { diff --git a/MiraAPI/LocalSettings/LocalSettingsTab.cs b/MiraAPI/LocalSettings/LocalSettingsTab.cs index e92f2cf4..f5b22e77 100644 --- a/MiraAPI/LocalSettings/LocalSettingsTab.cs +++ b/MiraAPI/LocalSettings/LocalSettingsTab.cs @@ -74,7 +74,7 @@ public abstract class LocalSettingsTab(ConfigFile config) /// protected int TabIndex => LocalSettingsManager.Tabs.IndexOf(this) + 10; - private Scroller? Scroller { get; set; } + private Scroller? scroller; /// /// Invoked when an option value is changed. @@ -119,9 +119,9 @@ public abstract class LocalSettingsTab(ConfigFile config) tab.transform.DestroyChildren(); tab.gameObject.SetActive(false); - if (Scroller == null) + if (scroller == null) { - Scroller = Helpers.CreateScroller(tab.transform, OptionsMenuPatches.MaskCollider); + scroller = Helpers.CreateScroller(tab.transform, OptionsMenuPatches.MaskCollider); } if (TabButton != null) @@ -152,7 +152,7 @@ public abstract class LocalSettingsTab(ConfigFile config) { if (ShouldCreateLabels) { - CreateLabel(generalLabel, Scroller.Inner, pair.Key, ref contentOffset); + CreateLabel(generalLabel, scroller.Inner, pair.Key, ref contentOffset); contentOrder = 1; contentIndex = 1; } @@ -162,7 +162,7 @@ public abstract class LocalSettingsTab(ConfigFile config) var obj = setting.CreateOption( toggle, slider, - Scroller.Inner, + scroller.Inner, ref contentOffset, ref contentOrder, contentIndex == pair.Value.Count); @@ -194,7 +194,7 @@ public abstract class LocalSettingsTab(ConfigFile config) { var obj = button.CreateButton( toggle, - Scroller.Inner, + scroller.Inner, ref contentOffset, ref contentOrder, contentIndex == Buttons.Count); @@ -217,7 +217,7 @@ public abstract class LocalSettingsTab(ConfigFile config) contentIndex++; } - Scroller.SetBounds(new FloatRange(0, (Settings.Count + Buttons.Count) * 0.5f - 5f), new FloatRange(0, 0)); + scroller.SetBounds(new FloatRange(0, (Settings.Count + Buttons.Count) * 0.5f - 5f), new FloatRange(0, 0)); return tab; } diff --git a/MiraAPI/MiraApiPlugin.cs b/MiraAPI/MiraApiPlugin.cs index 5def08da..dc926b2e 100644 --- a/MiraAPI/MiraApiPlugin.cs +++ b/MiraAPI/MiraApiPlugin.cs @@ -61,7 +61,6 @@ public partial class MiraApiPlugin : BasePlugin, IMiraPlugin /// public static bool IsDevBuild => Version.Contains("ci", StringComparison.OrdinalIgnoreCase) || Version.Contains("dev", StringComparison.OrdinalIgnoreCase); - private static MiraPluginManager? PluginManager { get; set; } internal Harmony Harmony { get; } = new(Id); internal static ConfigEntry WikiSortingGroup { get; private set; } @@ -99,8 +98,7 @@ public partial class MiraApiPlugin : BasePlugin, IMiraPlugin ReactorCredits.Register("Mira API", Version, IsDevBuild, ReactorCredits.AlwaysShow); - PluginManager = new MiraPluginManager(); - PluginManager.Initialize(this, this); + MiraPluginManager.Instance.Initialize(this, this); MiraLocaleManager.Register("mira.api", typeof(MiraApiPlugin).Assembly); LocalizationManager.Register(new MiraLocalizationProvider()); diff --git a/MiraAPI/Modifiers/ModifierComponent.cs b/MiraAPI/Modifiers/ModifierComponent.cs index 9ebfc827..241799e7 100644 --- a/MiraAPI/Modifiers/ModifierComponent.cs +++ b/MiraAPI/Modifiers/ModifierComponent.cs @@ -28,19 +28,16 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) public ImmutableList ActiveModifiers { get; private set; } = ImmutableList.Empty; private readonly List _toRemove = []; - private readonly List _toAdd = []; + private readonly List _modifiers = []; - private ModifierDisplayComponent? ModifierDisplay { get; set; } - - [HideFromIl2Cpp] - private List Modifiers { get; set; } = []; + private ModifierDisplayComponent? modifierDisplay; private PlayerControl _player = null!; internal void ClearModifiers() { - _toRemove.AddRange(Modifiers); + _toRemove.AddRange(_modifiers); } private void Awake() @@ -55,15 +52,13 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) ModifierExtensions.ModifierComponents.Add(_player, this); - Modifiers = []; - if (!_player.AmOwner) { return; } - ModifierDisplay = ModifierDisplayComponent.CreateDisplay(); - ModifierDisplay?.UpdateModifiersList(Modifiers); + modifierDisplay = ModifierDisplayComponent.CreateDisplay(); + modifierDisplay?.UpdateModifiersList(_modifiers); } private void FixedUpdate() @@ -81,14 +76,14 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) Error($"Error while deactivating modifier {modifier.ModifierName}: {e}"); } - Modifiers.Remove(modifier); + _modifiers.Remove(modifier); } var added = _toAdd.Count > 0; foreach (var modifier in _toAdd.ToArray()) { _toAdd.Remove(modifier); - Modifiers.Add(modifier); + _modifiers.Add(modifier); modifier.Initialized = true; try { @@ -109,10 +104,10 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) { if (_player.AmOwner && HudManager.InstanceExists) { - ModifierDisplay?.UpdateModifiersList(Modifiers); + modifierDisplay?.UpdateModifiersList(_modifiers); } - ActiveModifiers = Modifiers.ToImmutableList(); + ActiveModifiers = _modifiers.ToImmutableList(); } foreach (var modifier in ActiveModifiers) @@ -127,7 +122,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) } } - if (_player.AmOwner && ModifierDisplay && HudManager.InstanceExists) + if (_player.AmOwner && modifierDisplay && HudManager.InstanceExists) { var taskPanelOpen = HudManager.Instance.TaskPanel.open; var roleTabOpen = HudManagerPatches.RoleTab != null && HudManagerPatches.RoleTab.open; @@ -135,11 +130,11 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr) if (leftSideHud && (taskPanelOpen || roleTabOpen)) { - ModifierDisplay!.gameObject.SetActive(false); + modifierDisplay!.gameObject.SetActive(false); } else { - ModifierDisplay!.gameObject.SetActive(MeetingHud.Instance || HudManager.Instance.TaskPanel.isActiveAndEnabled); + modifierDisplay!.gameObject.SetActive(MeetingHud.Instance || HudManager.Instance.TaskPanel.isActiveAndEnabled); } } } diff --git a/MiraAPI/Patches/Keybinds/KeybindsPatch.cs b/MiraAPI/Patches/Keybinds/KeybindsPatch.cs index e7acf891..0fea5793 100644 --- a/MiraAPI/Patches/Keybinds/KeybindsPatch.cs +++ b/MiraAPI/Patches/Keybinds/KeybindsPatch.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using HarmonyLib; using MiraAPI.Keybinds; using Rewired; @@ -23,14 +21,11 @@ public static class KeybindMenuPatch _registered = true; // Set these here right after input manager initializes - KeybindManager.VanillaKeybinds = new Dictionary - { - { typeof(KillButton), new VanillaKeybind(8) }, - { typeof(UseButton), new VanillaKeybind(6) }, - { typeof(ReportButton), new VanillaKeybind(7) }, - { typeof(VentButton), new VanillaKeybind(50) }, - { typeof(SabotageButton), new VanillaKeybind(4) }, - { typeof(AbilityButton), new VanillaKeybind(49) }, - }; + KeybindManager.VanillaKeybinds[typeof(KillButton)] = new VanillaKeybind(8); + KeybindManager.VanillaKeybinds[typeof(UseButton)] = new VanillaKeybind(6); + KeybindManager.VanillaKeybinds[typeof(ReportButton)] = new VanillaKeybind(7); + KeybindManager.VanillaKeybinds[typeof(VentButton)] = new VanillaKeybind(50); + KeybindManager.VanillaKeybinds[typeof(SabotageButton)] = new VanillaKeybind(4); + KeybindManager.VanillaKeybinds[typeof(AbilityButton)] = new VanillaKeybind(49); } } diff --git a/MiraAPI/Patches/Options/LobbyViewPanePatches.cs b/MiraAPI/Patches/Options/LobbyViewPanePatches.cs index ee26a263..c77f93d1 100644 --- a/MiraAPI/Patches/Options/LobbyViewPanePatches.cs +++ b/MiraAPI/Patches/Options/LobbyViewPanePatches.cs @@ -22,15 +22,15 @@ namespace MiraAPI.Patches.Options; [HarmonyPatch(typeof(LobbyViewSettingsPane))] public static class LobbyViewPanePatches { - private static int SelectedModIdx { get; set; } + private static int selectedModIdx; private static MiraPluginInfo[] Plugins => MiraPluginManager.Instance.RegisteredPluginsWithOptions; - private static MiraPluginInfo? SelectedMod => SelectedModIdx == 0 + private static MiraPluginInfo? SelectedMod => selectedModIdx == 0 ? null - : Plugins[SelectedModIdx - 1]; + : Plugins[selectedModIdx - 1]; - private static PassiveButton? ModifiersTabButton { get; set; } + private static PassiveButton? modifiersTabButton; internal static StringNames ModifiersTabName { get; } = MiraLocaleManager.GetOrCreateLocaleString("ModifiersTab"); private static AbstractGameMode? GetCustomGamemode() @@ -71,20 +71,20 @@ public static class LobbyViewPanePatches __instance.gameModeText.GetComponent().Destroy(); // create modifiers button - ModifiersTabButton = Object.Instantiate(__instance.rolesTabButton, __instance.rolesTabButton.transform.parent); - ModifiersTabButton.buttonText.gameObject.GetComponent().Destroy(); - ModifiersTabButton.name = "ModifiersTabButton"; - var pos = ModifiersTabButton.transform.localPosition; + modifiersTabButton = Object.Instantiate(__instance.rolesTabButton, __instance.rolesTabButton.transform.parent); + modifiersTabButton.buttonText.gameObject.GetComponent().Destroy(); + modifiersTabButton.name = "ModifiersTabButton"; + var pos = modifiersTabButton.transform.localPosition; pos.x = 2.1f; - ModifiersTabButton.transform.localPosition = pos; - ModifiersTabButton.buttonText.text = "Modifiers".Translate(); - ModifiersTabButton.OnClick = new Button.ButtonClickedEvent(); - ModifiersTabButton.OnClick.AddListener( + modifiersTabButton.transform.localPosition = pos; + modifiersTabButton.buttonText.text = "Modifiers".Translate(); + modifiersTabButton.OnClick = new Button.ButtonClickedEvent(); + modifiersTabButton.OnClick.AddListener( (UnityAction)(() => { __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; @@ -106,10 +106,10 @@ public static class LobbyViewPanePatches passiveButton.OnClick.AddListener( (UnityAction)(() => { - SelectedModIdx += 1; - if (SelectedModIdx > Plugins.Length) + selectedModIdx += 1; + if (selectedModIdx > Plugins.Length) { - SelectedModIdx = 0; + selectedModIdx = 0; } Refresh(__instance); @@ -128,10 +128,10 @@ public static class LobbyViewPanePatches passiveButton2.OnClick.AddListener( (UnityAction)(() => { - SelectedModIdx -= 1; - if (SelectedModIdx < 0) + selectedModIdx -= 1; + if (selectedModIdx < 0) { - SelectedModIdx = Plugins.Length; + selectedModIdx = Plugins.Length; } Refresh(__instance); @@ -143,7 +143,7 @@ public static class LobbyViewPanePatches if (SelectedMod == null) { var cgm = GetCustomGamemode(); - ModifiersTabButton?.gameObject.SetActive(false); + modifiersTabButton?.gameObject.SetActive(false); menu.rolesTabButton.gameObject.SetActive(cgm is null or { ShowNormalRoleSettings: true }); menu.gameModeText.text = cgm is null ? MiraLocaleManager.Get("MiraApi.Gamemode.Classic") : cgm.ColoredName; } @@ -154,7 +154,7 @@ public static class LobbyViewPanePatches var showRolesButton = SelectedMod.InternalOptionGroups.Any(r => r.ParentMenu is MenuCategory.Roles || r.OptionableType?.IsAssignableTo(typeof(ICustomRole)) == true); - ModifiersTabButton?.gameObject.SetActive(showModifierButton); + modifiersTabButton?.gameObject.SetActive(showModifierButton); menu.rolesTabButton.gameObject.SetActive(showRolesButton); menu.gameModeText.text = SelectedMod.PluginInfo.Metadata.Name; } @@ -171,14 +171,14 @@ public static class LobbyViewPanePatches { if (__instance.currentTab != ModifiersTabName || SelectedMod == null) { - ModifiersTabButton?.SelectButton(false); + modifiersTabButton?.SelectButton(false); return; } __instance.taskTabButton.SelectButton(false); __instance.rolesTabButton.SelectButton(false); - ModifiersTabButton?.SelectButton(true); + modifiersTabButton?.SelectButton(true); var filteredGroups = SelectedMod.InternalOptionGroups .Where(x => x.GroupVisible() && (x.ParentMenu is MenuCategory.Modifiers || (x.OptionableType != null && x.OptionableType.IsAssignableTo(typeof(BaseModifier))))); @@ -218,7 +218,7 @@ public static class LobbyViewPanePatches [HarmonyPatch(nameof(LobbyViewSettingsPane.DrawRolesTab))] public static bool DrawRolesTabPatch(LobbyViewSettingsPane __instance) { - if (SelectedModIdx == 0) + if (selectedModIdx == 0) { var num = 0.95f; var num2 = -6.53f; diff --git a/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs b/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs index a7bfb166..3d2ed2ec 100644 --- a/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs +++ b/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs @@ -25,12 +25,12 @@ namespace MiraAPI.Patches.Options; [HarmonyPatch(typeof(RolesSettingsMenu))] public static class RoleSettingMenuPatches { - private static Dictionary RoleGroupHidden { get; set; } = []; + private static readonly Dictionary RoleGroupHidden = []; - private static float ScrollerNum { get; set; } = 0.522f; + private static RoleBehaviour? currentRole; + private static List? currentRoleOptions; - private static RoleBehaviour? CurrentRole { get; set; } - private static List? CurrentRoleOptions { get; set; } + private static float scrollerNum = 0.522f; [HarmonyPostfix] [HarmonyPatch(nameof(RolesSettingsMenu.OnEnable))] @@ -41,8 +41,8 @@ public static class RoleSettingMenuPatches private static IEnumerator CoQuotaTabPatch(RolesSettingsMenu roleMenu) { - CurrentRole = null; - CurrentRoleOptions = null; + currentRole = null; + currentRoleOptions = null; roleMenu.QuotaTabSelectables.Clear(); roleMenu.roleChances.Clear(); @@ -171,7 +171,7 @@ public static class RoleSettingMenuPatches } else { - ScrollerNum = 0.522f; + scrollerNum = 0.522f; var num4 = 0; var roleOptionSettings = roleMenu.scrollBar.Inner.GetComponentsInChildren(false); @@ -288,7 +288,7 @@ public static class RoleSettingMenuPatches categoryHeaderMasked.Background.size.y); categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f; - categoryHeaderMasked.transform.localPosition = new Vector3(-0.44f, ScrollerNum, -2f); + categoryHeaderMasked.transform.localPosition = new Vector3(-0.44f, scrollerNum, -2f); categoryHeaderMasked.gameObject.SetActive(true); quotaInst.gameObject.SetActive(!RoleGroupHidden[group]); @@ -300,7 +300,7 @@ public static class RoleSettingMenuPatches newText.transform.localPosition = new Vector3(2.6249f, -0.165f, 0f); newText.gameObject.GetComponent().Destroy(); - ScrollerNum -= 0.422f; + scrollerNum -= 0.422f; if (!RoleGroupHidden[group]) { @@ -351,7 +351,7 @@ public static class RoleSettingMenuPatches if (RoleGroupHidden.TryGetValue(group, out var value) && !value) { - ScrollerNum -= 0.4f; + scrollerNum -= 0.4f; } } } @@ -428,7 +428,7 @@ public static class RoleSettingMenuPatches } scroller.Inner = isRolesConfig ? menu.AdvancedRolesSettings.transform : menu.RoleChancesSettings.transform; - scroller.SetYBoundsMax(-ScrollerNum - 2); + scroller.SetYBoundsMax(-scrollerNum - 2); } // TODO: turn this into a fixed update @@ -437,11 +437,11 @@ public static class RoleSettingMenuPatches public static bool UpdatePatch(RolesSettingsMenu __instance) { if (MenuState.Instance.CurrentModIdx == 0) return true; - if (CurrentRole == null || CurrentRoleOptions == null) return false; + if (currentRole == null || currentRoleOptions == null) return false; - var hasImage = CurrentRole.RoleScreenshot != null; + var hasImage = currentRole.RoleScreenshot != null; var num = hasImage ? -0.872f : -1; - foreach (var opt in CurrentRoleOptions) + foreach (var opt in currentRoleOptions) { if (opt.OptionBehaviour == null) continue; @@ -508,7 +508,7 @@ public static class RoleSettingMenuPatches optBehaviour.gameObject.Destroy(); } - CurrentRole = role; + currentRole = role; __instance.advancedSettingChildren.Clear(); // TODO: create sub groups under the role settings. @@ -547,7 +547,7 @@ public static class RoleSettingMenuPatches newOpt.Initialize(); } - CurrentRoleOptions = filteredOptions; + currentRoleOptions = filteredOptions; } [HarmonyPrefix] @@ -698,7 +698,7 @@ public static class RoleSettingMenuPatches Vector3.zero, Quaternion.identity, __instance.RoleChancesSettings.transform); - roleOptionSetting.transform.localPosition = new Vector3(-0.1f, ScrollerNum, -2f); + roleOptionSetting.transform.localPosition = new Vector3(-0.1f, scrollerNum, -2f); roleOptionSetting.SetRole(GameOptionsManager.Instance.CurrentGameOptions.RoleOptions, role, 20); roleOptionSetting.titleText.text = role.GetRoleName(); @@ -767,7 +767,7 @@ public static class RoleSettingMenuPatches if (index < MenuState.Instance.CurrentMod.InternalRoles.Count - 1) { - ScrollerNum -= 0.43f; + scrollerNum -= 0.43f; } return roleOptionSetting; diff --git a/MiraAPI/PluginLoading/MiraPluginManager.cs b/MiraAPI/PluginLoading/MiraPluginManager.cs index beb82873..c6e1b00e 100644 --- a/MiraAPI/PluginLoading/MiraPluginManager.cs +++ b/MiraAPI/PluginLoading/MiraPluginManager.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using BepInEx.Unity.IL2CPP; @@ -31,8 +33,16 @@ namespace MiraAPI.PluginLoading; /// /// Mira Plugin manager. /// +[SuppressMessage("Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Intended behaviour.")] public sealed class MiraPluginManager { + private MiraPluginManager() + { + } + + private const BindingFlags DeclaredInstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + private const BindingFlags DeclaredStaticMembers = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + private readonly Dictionary _registeredPlugins = []; internal MiraPluginInfo[] RegisteredPlugins { get; private set; } = []; @@ -40,24 +50,25 @@ public sealed class MiraPluginManager internal MiraPluginInfo[] PluginsWithOptionsOrGameModes { get; private set; } = []; internal Dictionary> QueuedRoleRegistrations { get; } = []; - internal static MiraPluginManager Instance { get; private set; } = new(); + internal static MiraPluginManager Instance { get; } = new(); internal static ConfigFile MiraApiConfig { get; private set; } = null!; internal static MiraPluginInfo MiraApiPluginInfo { get; private set; } = null!; internal void Initialize(BasePlugin miraApiPlugin, IMiraPlugin apiPlugin) { - Instance = this; CustomGameModeManager.RegisterDefaultMode(); CustomGameModeManager.GetAndSetGameMode(); if (IL2CPPChainloader.Instance.Plugins.TryGetValue(MiraApiPlugin.Id, out var newPlugin)) { + var registrationTimer = Stopwatch.StartNew(); var info = RegisterPlugin(typeof(MiraPluginManager).Assembly, apiPlugin, newPlugin, miraApiPlugin, true); MiraApiConfig = info.PluginConfig; MiraApiPluginInfo = info; - Info($"Registering Mira API as mod."); + registrationTimer.Stop(); + Info($"Registering Mira API as mod in {registrationTimer.ElapsedMilliseconds}ms."); } IL2CPPChainloader.Instance.PluginLoad += (pluginInfo, assembly, plugin) => @@ -67,8 +78,10 @@ public sealed class MiraPluginManager return; } + var registrationTimer = Stopwatch.StartNew(); RegisterPlugin(assembly, miraPlugin, pluginInfo, plugin, false); - Info($"Registering mod {pluginInfo.Metadata.GUID} with Mira API."); + registrationTimer.Stop(); + Info($"Registering mod {pluginInfo.Metadata.Name} with Mira API in {registrationTimer.ElapsedMilliseconds}ms."); }; IL2CPPChainloader.Instance.Finished += () => @@ -97,7 +110,7 @@ public sealed class MiraPluginManager var oldConfigSetting = info.PluginConfig.SaveOnConfigSet; info.PluginConfig.SaveOnConfigSet = false; - ProcessAssemblyTypes(assembly, info, basePlugin, roles, isMira); + ProcessAssemblyTypes(assembly, info, basePlugin, plugin, roles, isMira); info.PluginConfig.Save(); info.PluginConfig.SaveOnConfigSet = oldConfigSetting; @@ -113,7 +126,13 @@ public sealed class MiraPluginManager return info; } - private static void ProcessAssemblyTypes(Assembly assembly, MiraPluginInfo info, BasePlugin basePlugin, List roles, bool isMira) + private static bool IsAutoPropertyBackingField(FieldInfo field) + { + return field.IsDefined(false) && + field.Name.Contains(">k__BackingField", StringComparison.Ordinal); + } + + private static void ProcessAssemblyTypes(Assembly assembly, MiraPluginInfo info, BasePlugin basePlugin, IMiraPlugin plugin, List roles, bool isMira) { foreach (var type in assembly.GetTypes()) { @@ -131,11 +150,8 @@ public sealed class MiraPluginManager if (RegisterLocalTabs(type, basePlugin)) continue; - if (RegisterRole(type, info, out var role)) - { - roles.Add(role); + if (RegisterRole(type, info, roles)) continue; - } if (RegisterButton(type, info)) continue; @@ -152,8 +168,8 @@ public sealed class MiraPluginManager if (RegisterGameModeAttribute(type, info)) continue; - RegisterColorClasses(type); - RegisterKeybinds(type, basePlugin); + if (!RegisterColorClasses(type)) + RegisterKeybinds(type, plugin); } } @@ -161,9 +177,7 @@ public sealed class MiraPluginManager { foreach (var method in AccessTools.GetDeclaredMethods(type)) { - var eventAttribute = method.GetCustomAttribute(); - - if (eventAttribute == null) + if (!method.TryGetCustomAttribute(out var eventAttribute)) continue; if (!method.IsStatic) @@ -224,25 +238,17 @@ public sealed class MiraPluginManager return false; } - foreach (var property in type.GetProperties()) + foreach (var property in type.GetProperties(DeclaredInstanceMembers)) { if (property.IsDefined()) continue; - var getter = property.GetMethod; - - if (getter == null) + if (property.GetMethod == null) { Error($"Non-ignored option property {property.Name} in {type.Name} must at least have a getter."); continue; } - if (getter.IsStatic) - { - Error($"Non-ignored option property {property.Name} in {type.Name} must not be static."); - continue; - } - var propType = property.PropertyType; if (propType.IsAssignableTo(OptionType)) @@ -275,8 +281,8 @@ public sealed class MiraPluginManager } } - foreach (var field in type.GetFields() - .Where(f => f.FieldType.IsAssignableTo(OptionType) || f.FieldType.IsAssignableTo(OptionListType))) + foreach (var field in type.GetFields(DeclaredInstanceMembers) + .Where(f => !IsAutoPropertyBackingField(f) && (f.FieldType.IsAssignableTo(OptionType) || f.FieldType.IsAssignableTo(OptionListType)))) { Error($"{field.Name} is a field, not a property. Use properties for options."); } @@ -291,9 +297,8 @@ public sealed class MiraPluginManager return false; } - private static bool RegisterRole(Type type, MiraPluginInfo pluginInfo, [NotNullWhen(true)] out Type? role) + private static bool RegisterRole(Type type, MiraPluginInfo pluginInfo, List roles) { - role = null; try { if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type))) @@ -307,7 +312,7 @@ public sealed class MiraPluginManager return false; } - role = type; + roles.Add(type); return true; } catch (Exception e) @@ -318,22 +323,22 @@ public sealed class MiraPluginManager return false; } - private static void RegisterColorClasses(Type type) + private static bool RegisterColorClasses(Type type) { try { if (type.GetCustomAttribute() == null) { - return; + return false; } if (!type.IsStatic()) { Error($"Color class {type.Name} must be static."); - return; + return false; } - foreach (var property in type.GetProperties()) + foreach (var property in type.GetProperties(DeclaredStaticMembers)) { if (!property.PropertyType.IsAssignableTo(typeof(CustomColor))) { @@ -352,15 +357,19 @@ public sealed class MiraPluginManager PaletteManager.VariableColorNames.Add(color.Name); } - foreach (var field in type.GetFields().Where(f => f.FieldType.IsAssignableTo(typeof(CustomColor)))) + foreach (var field in type.GetFields(DeclaredStaticMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(CustomColor)))) { Error($"{field.Name} is a field, not a property. Use properties for colors."); } + + return true; } catch (Exception e) { Error($"Failed to register color class {type.Name}: {e}"); } + + return false; } private static bool RegisterModifier(Type type, MiraPluginInfo info) @@ -419,13 +428,13 @@ public sealed class MiraPluginManager return false; } - foreach (var property in type.GetProperties()) + if (!LocalSettingsManager.TypeToTab.TryGetValue(type, out var tabInstance)) { - if (LocalSettingsManager.TypeToTab[type] is not { } tabInstance) - { - continue; - } + return false; + } + foreach (var property in type.GetProperties(DeclaredInstanceMembers)) + { if (property.IsDefined() && property.PropertyType.IsAssignableTo(typeof(LocalSettingsButton))) { @@ -440,26 +449,19 @@ public sealed class MiraPluginManager continue; } - if (property.GetMethod?.IsStatic == true) - { - Error($"Option property {property.Name} in {type.Name} must not be static."); - continue; - } - if (property.GetValue(tabInstance) is not ConfigEntryBase configEntry) { Error($"Option property {property.Name} in {type.Name} has to be a config entry."); continue; } - var attribute = property.GetCustomAttribute(); - if (attribute != null) + if (property.TryGetCustomAttribute(out var attribute)) { attribute.CreateSetting(type, configEntry); } } - foreach (var field in type.GetFields().Where(f => f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) && f.IsDefined())) + foreach (var field in type.GetFields(DeclaredInstanceMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) && f.IsDefined())) { Error($"{field.Name} is a field, not a property. Use properties for local settings."); } @@ -474,7 +476,7 @@ public sealed class MiraPluginManager return false; } - private static void RegisterKeybinds(Type type, BasePlugin source) + private static void RegisterKeybinds(Type type, IMiraPlugin plugin) { try { @@ -489,7 +491,7 @@ public sealed class MiraPluginManager return; } - foreach (var property in type.GetProperties()) + foreach (var property in type.GetProperties(DeclaredStaticMembers)) { if (property.PropertyType != typeof(MiraKeybind)) { @@ -503,17 +505,10 @@ public sealed class MiraPluginManager } KeybindManager.Keybinds.Add(keybind); - if (source is IMiraPlugin miraPlugin) - { - keybind.SourcePluginName = miraPlugin.OptionsTitleText.Translate(); - } - else if (source is MiraApiPlugin) - { - keybind.SourcePluginName = "MiraAPI"; - } + keybind.SourcePluginName = plugin.OptionsTitleText.Translate(); } - foreach (var field in type.GetFields().Where(f => f.FieldType.IsAssignableTo(typeof(MiraKeybind)))) + foreach (var field in type.GetFields(DeclaredStaticMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(MiraKeybind)))) { Error($"{field.Name} is a field, not a property. Use properties for keybinds."); } diff --git a/MiraAPI/Utilities/Assets/AudioTools.cs b/MiraAPI/Utilities/Assets/AudioTools.cs index 075b65c1..d8802eb9 100644 --- a/MiraAPI/Utilities/Assets/AudioTools.cs +++ b/MiraAPI/Utilities/Assets/AudioTools.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Reflection; using System.Resources; @@ -13,6 +14,8 @@ namespace MiraAPI.Utilities.Assets; /// public static class AudioTools { + private static readonly Dictionary<(Assembly Assembly, string Path), AudioClip> AudioClipCache = []; + /// /// Loads and returns an audio clip from a resource path using the specified . /// @@ -23,6 +26,11 @@ public static class AudioTools /// Stream failed to load. Check if the name of your asset was correct. public static AudioClip LoadAudioFromResources(string resourcePath, Assembly assembly) { + if (AudioClipCache.TryGetValue((assembly, resourcePath), out var cachedClip) && cachedClip != null) + { + return cachedClip; + } + using var assetStream = assembly.GetManifestResourceStream(resourcePath) ?? throw new MissingManifestResourceException($"Stream failed to load. Check if the asset name is correct: {resourcePath}"); @@ -93,6 +101,7 @@ public static class AudioTools var audioClip = AudioClip.Create(resourcePath, samples.Length / channels, channels, sampleRate, false); audioClip.SetData(samples, 0); + AudioClipCache[(assembly, resourcePath)] = audioClip; return audioClip; } diff --git a/MiraAPI/Utilities/Assets/LoadableAddressableAssets.cs b/MiraAPI/Utilities/Assets/LoadableAddressableAssets.cs index ab20265c..d8197c83 100644 --- a/MiraAPI/Utilities/Assets/LoadableAddressableAssets.cs +++ b/MiraAPI/Utilities/Assets/LoadableAddressableAssets.cs @@ -19,7 +19,17 @@ public class LoadableAddressableAssets(string key) /// /// Gets or sets reference to the loaded asset. Intended to be used for caching purposes. /// - protected List? LoadedAssets { get; set; } + protected List? LoadedAssets + { + get; + set + { + field = value; + loaded = value?.AsReadOnly(); + } + } + + private ReadOnlyCollection? loaded; /// /// Initializes a new instance of the class, with added garbageCollector logic, @@ -42,7 +52,7 @@ public class LoadableAddressableAssets(string key) { if (LoadedAssets != null) { - return LoadedAssets.AsReadOnly(); + return loaded!; } var locations = Addressables.LoadResourceLocationsAsync(key).WaitForCompletion(); @@ -62,6 +72,6 @@ public class LoadableAddressableAssets(string key) _gcAction?.Invoke(this); GC.EndNoGCRegion(); - return LoadedAssets.AsReadOnly(); + return loaded!; } } diff --git a/MiraAPI/Utilities/Assets/LoadableAsset.cs b/MiraAPI/Utilities/Assets/LoadableAsset.cs index 28c77095..dea91e71 100644 --- a/MiraAPI/Utilities/Assets/LoadableAsset.cs +++ b/MiraAPI/Utilities/Assets/LoadableAsset.cs @@ -37,7 +37,7 @@ public abstract class LoadableAsset /// True if the asset was unloaded, false otherwise. public virtual bool UnloadAsset() { - if (LoadedAsset == null || !LoadedAsset) + if (LoadedAsset == null) { return false; } diff --git a/MiraAPI/Utilities/Assets/SpriteTools.cs b/MiraAPI/Utilities/Assets/SpriteTools.cs index 05ebcfce..b197fc90 100644 --- a/MiraAPI/Utilities/Assets/SpriteTools.cs +++ b/MiraAPI/Utilities/Assets/SpriteTools.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Reflection; using Reactor.Utilities.Extensions; using UnityEngine; @@ -10,6 +11,9 @@ namespace MiraAPI.Utilities.Assets; /// public static class SpriteTools { + private static readonly Dictionary<(Assembly Assembly, string ResourcePath), Texture2D> TextureCache = []; + private static readonly Dictionary<(Assembly Assembly, string ResourcePath, float PixelsPerUnit), Sprite> SpriteCache = []; + /// /// Loads and returns a texture from a resource path using the specified . /// @@ -19,11 +23,16 @@ public static class SpriteTools /// Thrown when the resource cannot be found in the specified . public static Texture2D LoadTextureFromResourcePath(string resourcePath, Assembly assembly) { + if (TextureCache.TryGetValue((assembly, resourcePath), out var cachedTexture) && cachedTexture != null) + { + return cachedTexture; + } + var tex = new Texture2D(1, 1, TextureFormat.ARGB32, false) { wrapMode = TextureWrapMode.Clamp, }; - var myStream = assembly.GetManifestResourceStream(resourcePath); + using var myStream = assembly.GetManifestResourceStream(resourcePath); if (myStream != null) { var buttonTexture = myStream.ReadFully(); @@ -35,6 +44,7 @@ public static class SpriteTools } tex.name = resourcePath; + TextureCache[(assembly, resourcePath)] = tex; return tex; } @@ -47,6 +57,11 @@ public static class SpriteTools /// A object created from the texture loaded from the specified resource path. public static Sprite LoadSpriteFromPath(string resourcePath, Assembly assembly, float pixelsPerUnit) { + if (SpriteCache.TryGetValue((assembly, resourcePath, pixelsPerUnit), out var cachedSprite) && cachedSprite != null) + { + return cachedSprite; + } + var tex = LoadTextureFromResourcePath(resourcePath, assembly); var sprite = Sprite.Create( tex, @@ -56,6 +71,7 @@ public static class SpriteTools 0, SpriteMeshType.FullRect); sprite.name = resourcePath; + SpriteCache[(assembly, resourcePath, pixelsPerUnit)] = sprite; return sprite; } } diff --git a/MiraAPI/Utilities/Extensions.cs b/MiraAPI/Utilities/Extensions.cs index bbc627db..868bef17 100644 --- a/MiraAPI/Utilities/Extensions.cs +++ b/MiraAPI/Utilities/Extensions.cs @@ -858,4 +858,18 @@ public static class Extensions { return Attribute.IsDefined(element, typeof(T)); } + + /// + /// Attempts to get a specified custom attribute on an element. + /// + /// The type of the attribute. + /// The member to get the attribute from. + /// If the method returns true, a non-null reference to the attribute. + /// true if the member has the specified attribute; otherwise false. + public static bool TryGetCustomAttribute(this MemberInfo member, [NotNullWhen(true)] out T? attribute) + where T : Attribute + { + attribute = member.GetCustomAttribute(); + return attribute != null; + } }