formatting + squeezing out some more performance

this is very nitpicky, but better be overly conscious about it early iykwim

some changes were whacked from pietro's faster load time branch
This commit is contained in:
Az committed 2026-11-04 01:38:33 -05:00
1 parent 0e5d94400a
commit b3900576d6
27 files changed
+256 -217

No files matched your search

@@ -29,6 +29,11 @@ public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target
/// </summary>
public PlayerControl? Framed { get; } = framed;
/// <summary>
/// Gets whether the murder was meant to be done in a meeting, via an enum.
/// </summary>
public MeetingCheck InMeeting { get; } = inMeeting;
/// <summary>
/// Gets or sets a value indicating whether the murder is done indirectly.
/// This is commonly used to prevent the <see cref="Source"/> <see cref="PlayerControl"/> from being killed.
@@ -40,11 +45,6 @@ public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target
/// </summary>
public bool IgnoreDefense { get; set; } = ignoreDefense;
/// <summary>
/// Gets whether the murder was meant to be done in a meeting, via an enum.
/// </summary>
public MeetingCheck InMeeting { get; } = inMeeting;
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
@@ -14,5 +14,5 @@ public class CheckForEndVotingEvent(bool isVotingComplete) : MiraCancelableEvent
/// <summary>
/// Gets or sets a value indicating whether the voting should be forced to end, regardless of the default logic.
/// </summary>
public bool ForceEndVoting { get; set; }
public bool ForceEndVoting { get; set; } = false;
}
@@ -29,11 +29,6 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool
/// </summary>
public byte TargetId { get; } = targetId;
/// <summary>
/// Gets or sets a value indicating whether to prevent the vote from commencing.
/// </summary>
public bool PreventVote { get; set; } = false;
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
/// </summary>
@@ -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.
/// </summary>
public bool IsOverruling { get; set; } = isOverruling;
/// <summary>
/// Gets or sets a value indicating whether to prevent the vote from commencing.
/// </summary>
public bool PreventVote { get; set; } = false;
}
@@ -12,7 +12,7 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting;
/// <param name="exiledPlayer">The player to be exiled. Will be <see langword="null"/> if no player is to be exiled.</param>
public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exiledPlayer = null) : MiraEvent
{
private readonly List<CustomVote> originalVotes = [.. votes];
private readonly CustomVote[] originalVotes = [.. votes];
/// <summary>
/// Gets a value indicating whether the exiled player has been modified by the event.
@@ -48,6 +48,9 @@ public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exil
get;
set
{
if (field == value)
return;
field = value;
ExiledPlayerModified = true;
}
-1
View File
@@ -29,7 +29,6 @@ public static class GameOverManager
if (gameOverType.IsAbstract)
{
Error("The type must not be abstract.");
return false;
}
+6 -6
View File
@@ -12,13 +12,13 @@ public static class CustomGameModeManager
{
internal static readonly Dictionary<uint, AbstractGameMode> IdToModeMap = [];
private static uint lastId;
private static uint GetNextId()
{
return ++LastId;
return ++lastId;
}
private static uint LastId { get; set; }
/// <summary>
/// Register gamemode from type.
/// </summary>
@@ -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()
+3 -4
View File
@@ -17,6 +17,8 @@ namespace MiraAPI.GameModes;
/// The game mode option.
/// </summary>
[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
{
/// <summary>
@@ -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)
@@ -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;
/// <param name="roleType">Optional parameter to specify a role Type.</param>
/// <param name="modeType">Optional parameter to specify a game mode Type.</param>
[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, Type? roleType = null, Type? modeType = null) : PropertyOptionAttribute
{
internal IModdedOption? HolderOption { get; set; }
internal Type ValueType { get; set; }
internal IModdedOption? HolderOption;
internal Type ValueType;
/// <summary>
/// Gets the title of the option.
@@ -12,11 +12,13 @@ namespace MiraAPI.GameOptions.Attributes;
/// </summary>
/// <param name="title">The title of the options.</param>
[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) : PropertyOptionAttribute
{
internal IModdedOptionList? HolderOptionList { get; set; }
internal IList? Value { get; set; }
internal Type ValueType { get; set; }
internal IModdedOptionList? HolderOptionList;
internal IList? Value;
internal Type ValueType;
/// <summary>
/// Gets the title of the options.
@@ -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
/// <summary>
/// Gets or sets the <see cref="Color"/> for the text on the options pop-up.
/// </summary>
[HideFromIl2Cpp]
public Color PopUpTextColor { get; set; }
}
@@ -6,7 +6,7 @@ using MiraAPI.Utilities;
namespace MiraAPI.HnsReimplemented.Options;
/// <summary>
/// Gets or sets the crewmate options for Hide and Seek.
/// Crewmate options for Hide and Seek.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.)
public class HnsCrewmateOptions : AbstractOptionGroup<HideAndSeekMode>
@@ -15,9 +15,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup<HideAndSeekMode>
public override string GroupName => "Crewmates";
/// <summary>
/// Gets or sets the player speed.
/// Gets the player speed.
/// </summary>
public ModdedNumberOption PlayerSpeed { get; set; } = new(
public ModdedNumberOption PlayerSpeed { get; } = new(
"Player Speed",
1f,
0.5f,
@@ -29,9 +29,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup<HideAndSeekMode>
"0.00");
/// <summary>
/// Gets or sets the hiding time.
/// Gets the hiding time.
/// </summary>
public ModdedNumberOption HidingTime { get; set; } = new(
public ModdedNumberOption HidingTime { get; } = new(
"Hiding Time",
200,
160,
@@ -42,9 +42,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup<HideAndSeekMode>
MiraNumberSuffixes.Seconds);
/// <summary>
/// Gets or sets the limits of a crewmate's vision.
/// Gets the limits of a crewmate's vision.
/// </summary>
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<HideAndSeekMode>
"0.00");
/// <summary>
/// Gets or sets a flag that toggles flashlight vision.
/// Gets a flag that toggles flashlight vision.
/// </summary>
public ModdedToggleOption FlashlightMode { get; set; } = new(
public ModdedToggleOption FlashlightMode { get; } = new(
"Flashlight Mode",
true);
/// <summary>
/// Gets or sets the range of a crewmate's flashlight.
/// Gets the range of a crewmate's flashlight.
/// </summary>
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<HideAndSeekMode>
};
/// <summary>
/// Gets or sets the maximum number of times a crewmate can vent.
/// Gets the maximum number of times a crewmate can vent.
/// </summary>
public ModdedNumberOption MaxVentUses { get; set; } = new(
public ModdedNumberOption MaxVentUses { get; } = new(
"Max Vent Uses",
1,
0,
@@ -92,9 +92,9 @@ public class HnsCrewmateOptions : AbstractOptionGroup<HideAndSeekMode>
MiraNumberSuffixes.None);
/// <summary>
/// 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.
/// </summary>
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<HideAndSeekMode>
};
/// <summary>
/// Gets or sets the visibility of player names.
/// Gets the visibility of player names.
/// </summary>
public ModdedToggleOption ShowNames { get; set; } = new(
public ModdedToggleOption ShowNames { get; } = new(
"Show Names",
false);
}
@@ -6,7 +6,7 @@ using MiraAPI.Utilities;
namespace MiraAPI.HnsReimplemented.Options;
/// <summary>
/// Gets or sets the Final Hide options for Hide and Seek.
/// Final Hide options for Hide and Seek.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.)
public class HnsFinalHideOptions : AbstractOptionGroup<HideAndSeekMode>
@@ -15,9 +15,9 @@ public class HnsFinalHideOptions : AbstractOptionGroup<HideAndSeekMode>
public override string GroupName => "Final Hide";
/// <summary>
/// Gets or sets the duration of the Final Hide phase.
/// Gets the duration of the Final Hide phase.
/// </summary>
public ModdedNumberOption FinalHideTime { get; set; } = new(
public ModdedNumberOption FinalHideTime { get; } = new(
"Hiding Time",
50,
30,
@@ -28,9 +28,9 @@ public class HnsFinalHideOptions : AbstractOptionGroup<HideAndSeekMode>
MiraNumberSuffixes.Seconds);
/// <summary>
/// Gets or sets the Seeker's speed when the Final Hide phase begins.
/// Gets the Seeker's speed when the Final Hide phase begins.
/// </summary>
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<HideAndSeekMode>
"0.00");
/// <summary>
/// Gets or sets whether the Seeker sees the Final hide player pings.
/// Gets whether the Seeker sees the Final hide player pings.
/// </summary>
public ModdedToggleOption FinalHidePings { get; set; } = new(
public ModdedToggleOption FinalHidePings { get; } = new(
"Final Hide Pings",
true);
/// <summary>
/// Gets or sets the interval between each ping.
/// Gets the interval between each ping.
/// </summary>
public ModdedNumberOption PingInterval { get; set; } = new(
public ModdedNumberOption PingInterval { get; } = new(
"Ping Interval",
6,
3,
@@ -62,9 +62,9 @@ public class HnsFinalHideOptions : AbstractOptionGroup<HideAndSeekMode>
MiraNumberSuffixes.Seconds);
/// <summary>
/// Gets or sets whether the Seeker can see players on an admin map.
/// Gets whether the Seeker can see players on an admin map.
/// </summary>
public ModdedToggleOption FinalHideSeekMap { get; set; } = new(
public ModdedToggleOption FinalHideSeekMap { get; } = new(
"Final Hide Seek Map",
true);
}
@@ -6,7 +6,7 @@ using MiraAPI.Utilities;
namespace MiraAPI.HnsReimplemented.Options;
/// <summary>
/// Gets or sets the seeker settings on Hide and Seek.
/// Seeker settings on Hide and Seek.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.)
public class HnsImpostorOptions : AbstractOptionGroup<HideAndSeekMode>
@@ -15,15 +15,15 @@ public class HnsImpostorOptions : AbstractOptionGroup<HideAndSeekMode>
public override string GroupName => "Impostors";
/// <summary>
/// Gets or sets the player who will be the seeker.
/// Gets the player who will be the seeker.
/// </summary>
public ModdedPlayerOption SelectedSeeker { get; set; } = new(
public ModdedPlayerOption SelectedSeeker { get; } = new(
"Forced Impostor");
/// <summary>
/// Gets or sets the range of a seeker's vision.
/// Gets the range of a seeker's vision.
/// </summary>
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<HideAndSeekMode>
"0.00");
/// <summary>
/// Gets or sets the range of a seeker's flashlight.
/// Gets the range of a seeker's flashlight.
/// </summary>
public ModdedNumberOption ImpostorFlashlightSize { get; set; } = new(
public ModdedNumberOption ImpostorFlashlightSize { get; } = new(
"Impostor Flashlight Size",
0.35f,
0.1f,
@@ -6,7 +6,7 @@ using MiraAPI.Utilities;
namespace MiraAPI.HnsReimplemented.Options;
/// <summary>
/// Gets or sets the task options for Hide and Seek.
/// Task options for Hide and Seek.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.)
public class HnsTaskOptions : AbstractOptionGroup<HideAndSeekMode>
@@ -15,9 +15,9 @@ public class HnsTaskOptions : AbstractOptionGroup<HideAndSeekMode>
public override string GroupName => "Tasks";
/// <summary>
/// Gets or sets the umber of common tasks.
/// Gets the umber of common tasks.
/// </summary>
public ModdedNumberOption CommonTasks { get; set; } = new(
public ModdedNumberOption CommonTasks { get; } = new(
"# Common Tasks",
1,
0,
@@ -28,9 +28,9 @@ public class HnsTaskOptions : AbstractOptionGroup<HideAndSeekMode>
MiraNumberSuffixes.None);
/// <summary>
/// Gets or sets the number of long tasks.
/// Gets the number of long tasks.
/// </summary>
public ModdedNumberOption LongTasks { get; set; } = new(
public ModdedNumberOption LongTasks { get; } = new(
"# Long Tasks",
1,
0,
@@ -41,9 +41,9 @@ public class HnsTaskOptions : AbstractOptionGroup<HideAndSeekMode>
MiraNumberSuffixes.None);
/// <summary>
/// Gets or sets the number of short tasks.
/// Gets the number of short tasks.
/// </summary>
public ModdedNumberOption ShortTasks { get; set; } = new(
public ModdedNumberOption ShortTasks { get; } = new(
"# Short Tasks",
2,
0,
+4 -3
View File
@@ -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
/// </summary>
public static List<MiraKeybind> Keybinds { get; } = [];
[HideFromIl2Cpp]
internal static Dictionary<Type, VanillaKeybind> 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<Type, VanillaKeybind> VanillaKeybinds = [];
internal static void RewiredInit()
{
+7 -7
View File
@@ -74,7 +74,7 @@ public abstract class LocalSettingsTab(ConfigFile config)
/// </summary>
protected int TabIndex => LocalSettingsManager.Tabs.IndexOf(this) + 10;
private Scroller? Scroller { get; set; }
private Scroller? scroller;
/// <summary>
/// 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;
}
+1 -3
View File
@@ -61,7 +61,6 @@ public partial class MiraApiPlugin : BasePlugin, IMiraPlugin
/// </summary>
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<SortingGroups> 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());
+12 -17
View File
@@ -28,19 +28,16 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
public ImmutableList<BaseModifier> ActiveModifiers { get; private set; } = ImmutableList<BaseModifier>.Empty;
private readonly List<BaseModifier> _toRemove = [];
private readonly List<BaseModifier> _toAdd = [];
private readonly List<BaseModifier> _modifiers = [];
private ModifierDisplayComponent? ModifierDisplay { get; set; }
[HideFromIl2Cpp]
private List<BaseModifier> 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);
}
}
}
+6 -11
View File
@@ -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<Type, VanillaKeybind>
{
{ 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);
}
}
+24 -24
View File
@@ -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<TextTranslatorTMP>().Destroy();
// create modifiers button
ModifiersTabButton = Object.Instantiate(__instance.rolesTabButton, __instance.rolesTabButton.transform.parent);
ModifiersTabButton.buttonText.gameObject.GetComponent<TextTranslatorTMP>().Destroy();
ModifiersTabButton.name = "ModifiersTabButton";
var pos = ModifiersTabButton.transform.localPosition;
modifiersTabButton = Object.Instantiate(__instance.rolesTabButton, __instance.rolesTabButton.transform.parent);
modifiersTabButton.buttonText.gameObject.GetComponent<TextTranslatorTMP>().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;
@@ -25,12 +25,12 @@ namespace MiraAPI.Patches.Options;
[HarmonyPatch(typeof(RolesSettingsMenu))]
public static class RoleSettingMenuPatches
{
private static Dictionary<RoleOptionsGroup, bool> RoleGroupHidden { get; set; } = [];
private static readonly Dictionary<RoleOptionsGroup, bool> RoleGroupHidden = [];
private static float ScrollerNum { get; set; } = 0.522f;
private static RoleBehaviour? currentRole;
private static List<IModdedOption>? currentRoleOptions;
private static RoleBehaviour? CurrentRole { get; set; }
private static List<IModdedOption>? 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<RoleOptionSetting>(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<TextTranslatorTMP>().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;
+54 -57
View File
@@ -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;
/// <summary>
/// Mira Plugin manager.
/// </summary>
[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<Assembly, MiraPluginInfo> _registeredPlugins = [];
internal MiraPluginInfo[] RegisteredPlugins { get; private set; } = [];
@@ -40,24 +50,25 @@ public sealed class MiraPluginManager
internal MiraPluginInfo[] PluginsWithOptionsOrGameModes { get; private set; } = [];
internal Dictionary<MiraPluginInfo, List<Type>> 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<Type> roles, bool isMira)
private static bool IsAutoPropertyBackingField(FieldInfo field)
{
return field.IsDefined<CompilerGeneratedAttribute>(false) &&
field.Name.Contains(">k__BackingField", StringComparison.Ordinal);
}
private static void ProcessAssemblyTypes(Assembly assembly, MiraPluginInfo info, BasePlugin basePlugin, IMiraPlugin plugin, List<Type> 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<RegisterEventAttribute>();
if (eventAttribute == null)
if (!method.TryGetCustomAttribute<RegisterEventAttribute>(out var eventAttribute))
continue;
if (!method.IsStatic)
@@ -221,17 +235,11 @@ public sealed class MiraPluginManager
return false;
}
foreach (var property in type.GetProperties())
foreach (var property in type.GetProperties(DeclaredInstanceMembers))
{
if (property.IsDefined<MiraIgnoreAttribute>())
continue;
if (property.GetMethod?.IsStatic == true)
{
Error($"Non-ignored option property {property.Name} in {type.Name} must not be static.");
continue;
}
if (property.PropertyType.IsAssignableTo(typeof(IModdedOption)))
{
ModdedOptionsManager.RegisterPropertyOption(type, property, pluginInfo);
@@ -258,8 +266,8 @@ public sealed class MiraPluginManager
}
}
foreach (var field in type.GetFields()
.Where(f => f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IModdedOptionList))))
foreach (var field in type.GetFields(DeclaredInstanceMembers)
.Where(f => !IsAutoPropertyBackingField(f) && (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IModdedOptionList)))))
{
Error($"{field.Name} is a field, not a property. Use properties for options.");
}
@@ -274,9 +282,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<Type> roles)
{
role = null;
try
{
if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type)))
@@ -290,7 +297,7 @@ public sealed class MiraPluginManager
return false;
}
role = type;
roles.Add(type);
return true;
}
catch (Exception e)
@@ -301,22 +308,22 @@ public sealed class MiraPluginManager
return false;
}
private static void RegisterColorClasses(Type type)
private static bool RegisterColorClasses(Type type)
{
try
{
if (type.GetCustomAttribute<RegisterCustomColorsAttribute>() == 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)))
{
@@ -335,15 +342,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)
@@ -402,13 +413,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<LocalSettingsButtonAttribute>() &&
property.PropertyType.IsAssignableTo(typeof(LocalSettingsButton)))
{
@@ -423,26 +434,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<LocalSettingAttribute>();
if (attribute != null)
if (property.TryGetCustomAttribute<LocalSettingAttribute>(out var attribute))
{
attribute.CreateSetting(type, configEntry);
}
}
foreach (var field in type.GetFields().Where(f => f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) && f.IsDefined<LocalSettingAttribute>()))
foreach (var field in type.GetFields(DeclaredInstanceMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) && f.IsDefined<LocalSettingAttribute>()))
{
Error($"{field.Name} is a field, not a property. Use properties for local settings.");
}
@@ -457,7 +461,7 @@ public sealed class MiraPluginManager
return false;
}
private static void RegisterKeybinds(Type type, BasePlugin source)
private static void RegisterKeybinds(Type type, IMiraPlugin plugin)
{
try
{
@@ -472,7 +476,7 @@ public sealed class MiraPluginManager
return;
}
foreach (var property in type.GetProperties())
foreach (var property in type.GetProperties(DeclaredStaticMembers))
{
if (property.PropertyType != typeof(MiraKeybind))
{
@@ -486,17 +490,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.");
}
+9
View File
@@ -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;
/// </summary>
public static class AudioTools
{
private static readonly Dictionary<(Assembly Assembly, string Path), AudioClip> AudioClipCache = [];
/// <summary>
/// Loads and returns an audio clip from a resource path using the specified <see cref="Assembly"/>.
/// </summary>
@@ -23,6 +26,11 @@ public static class AudioTools
/// <exception cref="MissingManifestResourceException">Stream failed to load. Check if the name of your asset was correct.</exception>
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;
}
@@ -19,7 +19,17 @@ public class LoadableAddressableAssets<T>(string key)
/// <summary>
/// Gets or sets reference to the loaded asset. Intended to be used for caching purposes.
/// </summary>
protected List<T>? LoadedAssets { get; set; }
protected List<T>? LoadedAssets
{
get;
set
{
field = value;
loaded = value?.AsReadOnly();
}
}
private ReadOnlyCollection<T>? loaded;
/// <summary>
/// Initializes a new instance of the <see cref="LoadableAddressableAssets{T}"/> class, with added garbageCollector logic,
@@ -42,7 +52,7 @@ public class LoadableAddressableAssets<T>(string key)
{
if (LoadedAssets != null)
{
return LoadedAssets.AsReadOnly();
return loaded!;
}
var locations = Addressables.LoadResourceLocationsAsync(key).WaitForCompletion();
@@ -62,6 +72,6 @@ public class LoadableAddressableAssets<T>(string key)
_gcAction?.Invoke(this);
GC.EndNoGCRegion();
return LoadedAssets.AsReadOnly();
return loaded!;
}
}
+1 -1
View File
@@ -37,7 +37,7 @@ public abstract class LoadableAsset<T>
/// <returns>True if the asset was unloaded, false otherwise.</returns>
public virtual bool UnloadAsset()
{
if (LoadedAsset == null || !LoadedAsset)
if (LoadedAsset == null)
{
return false;
}
+17 -1
View File
@@ -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;
/// </summary>
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 = [];
/// <summary>
/// Loads and returns a texture from a resource path using the specified <see cref="Assembly"/>.
/// </summary>
@@ -19,11 +23,16 @@ public static class SpriteTools
/// <exception cref="ArgumentException">Thrown when the resource cannot be found in the specified <see cref="Assembly"/>.</exception>
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
/// <returns>A <see cref="Sprite"/> object created from the texture loaded from the specified resource path.</returns>
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;
}
}
+14
View File
@@ -858,4 +858,18 @@ public static class Extensions
{
return Attribute.IsDefined(element, typeof(T));
}
/// <summary>
/// Attempts to get a specified custom attribute on an element.
/// </summary>
/// <typeparam name="T">The type of the attribute.</typeparam>
/// <param name="member">The member to get the attribute from.</param>
/// <param name="attribute">If the method returns true, a non-null reference to the attribute.</param>
/// <returns>true if the member has the specified attribute; otherwise false.</returns>
public static bool TryGetCustomAttribute<T>(this MemberInfo member, [NotNullWhen(true)] out T? attribute)
where T : Attribute
{
attribute = member.GetCustomAttribute<T>();
return attribute != null;
}
}