Merge branch 'dev' into mira-events-dev

This commit is contained in:
David Higueros committed 2026-11-08 22:41:18 -07:00
commit ecb43716ce
80 files changed
+742 -607

No files matched your search

+5 -11
View File
@@ -5,20 +5,14 @@ using UnityEngine;
namespace MiraAPI.Example;
[RegisterCustomColors]
[RegisterCustomColors("color.")]
public static class ExampleColors
{
public static CustomColor Cerulean { get; } = new("color.cerulean", new Color(0.0f, 0.48f, 0.65f))
{
ColorBrightness = CustomColorBrightness.Lighter,
};
public static CustomColor Cerulean { get; } = new("cerulean", new Color(0.0f, 0.48f, 0.65f), CustomColorBrightness.Lighter);
public static CustomColor Rose { get; } = new("color.rose", new Color(0.98f, 0.26f, 0.62f));
public static CustomColor Rose { get; } = new("rose", new Color(0.98f, 0.26f, 0.62f), CustomColorBrightness.Lighter);
public static CustomColor Gold { get; } = new("color.gold", new Color(1.0f, 0.84f, 0.0f));
public static CustomColor Gold { get; } = new("gold", new Color(1.0f, 0.84f, 0.0f), CustomColorBrightness.Lighter);
public static VariableColor Rainbow { get; } = new("color.rainbow", t => new HsbColor(MathUtilities.PingPong(t, 1f, 0.3f), 1f, 1f))
{
ColorBrightness = CustomColorBrightness.Lighter,
};
public static VariableColor Rainbow { get; } = new("rainbow", t => new HsbColor(MathUtilities.PingPong(t, 1f, 0.3f), 1f, 1f), CustomColorBrightness.Lighter);
}
+1
View File
@@ -14,6 +14,7 @@ using Reactor.Utilities;
namespace MiraAPI.Example;
[RegisterEventContainer]
public static class ExampleEventHandlers
{
public static void Initialize()
+3
View File
@@ -26,6 +26,9 @@ public partial class ExamplePlugin : BasePlugin, IMiraPlugin
public string OptionsTitleText { get; } = "Mira API\nExample Mod";
public string CustomOptionMenuNameTwo { get; } = "Example Options";
/// <inheritdoc />
public bool ForceRegisterEvents => false;
public ConfigFile GetConfigFile()
{
return Config;
+81 -41
View File
@@ -1,4 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using System;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
@@ -8,45 +9,44 @@ namespace MiraAPI.Colors;
/// <summary>
/// Represents a custom color with a main color and a shadow color.
/// </summary>
/// <param name="name">The name of the option.</param>
/// <param name="nameId">The name of the option as a <see cref="StringNames"/> value.</param>
/// <param name="rawId">The name of the option as a <see cref="string"/> value.</param>
/// <param name="mainColor">The main color.</param>
/// <param name="shadowColor">The shadow color.</param>
/// <param name="brightness">The brightness type of the color.</param>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Internal code.")]
[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1513:Closing brace should be followed by blank line", Justification = "Looks weird.")]
public class CustomColor(StringNames name, Color32 mainColor, Color32 shadowColor)
public class CustomColor(StringNames? nameId, string? rawId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness)
{
/// <summary>
/// Gets or sets the main color.
/// </summary>
public Color32 MainColor
{
get;
set
{
field = value;
InternalMainColor = value;
}
}
= mainColor;
private StringNames? name = nameId;
private CustomColorBrightness colorBrightness = brightness;
/// <summary>
/// Gets or sets the shadow color.
/// Gets the main color.
/// </summary>
public Color32 ShadowColor
{
get;
set
{
field = value;
InternalShadowColor = value;
}
}
= shadowColor;
public Color32 MainColor => mainColor;
/// <summary>
/// Gets or sets the name of the color.
/// Gets the shadow color.
/// </summary>
public StringNames Name { get; set; } = name;
public Color32 ShadowColor => shadowColor;
/// <summary>
/// Gets the name of the color.
/// </summary>
public StringNames Name
{
get
{
if (!name.HasValue && !string.IsNullOrEmpty(RawId))
name = MiraLocaleManager.GetOrCreateLocaleString(RawId);
return name.GetValueOrDefault();
}
internal set
{
name = value;
}
}
/// <summary>
/// Gets the id of the color.
@@ -54,28 +54,68 @@ public class CustomColor(StringNames name, Color32 mainColor, Color32 shadowColo
public int ColorId { get; internal set; } = -1;
/// <summary>
/// Gets or sets whether the color is lighter or darker. Can be used to help with colorblind stuff.
/// Gets or sets whether the color is lighter or darker.
/// </summary>
public CustomColorBrightness ColorBrightness { get; set; } = CustomColorBrightness.Darker;
public CustomColorBrightness ColorBrightness
{
get => colorBrightness;
[Obsolete("Use the constructor to set ColorBrightness instead. This will be removed in a future version.")]
set => colorBrightness = value;
}
internal string? RawId = rawId;
internal Color InternalMainColor = mainColor;
internal Color InternalShadowColor = shadowColor;
/// <inheritdoc cref="CustomColor"/>
public CustomColor(StringNames name, Color32 mainColor)
: this(name, mainColor, mainColor.DarkenAbsolute(60))
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(StringNames nameId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness)
: this(nameId, null, mainColor, shadowColor, brightness)
{
}
/// <inheritdoc cref="CustomColor"/>
public CustomColor(string name, Color32 mainColor)
: this(name, mainColor, mainColor.DarkenAbsolute(60))
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(StringNames nameId, Color32 mainColor, CustomColorBrightness brightness)
: this(nameId, null, mainColor, mainColor.DarkenAbsolute(60), brightness)
{
}
/// <inheritdoc cref="CustomColor"/>
public CustomColor(string name, Color32 mainColor, Color32 shadowColor)
: this(MiraLocaleManager.GetOrCreateLocaleString(name), mainColor, shadowColor)
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(string rawId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness)
: this(null, rawId, mainColor, shadowColor, brightness)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(string rawId, Color32 mainColor, CustomColorBrightness brightness)
: this(null, rawId, mainColor, mainColor.DarkenAbsolute(60), brightness)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public CustomColor(StringNames nameId, Color32 mainColor, Color32 shadowColor)
: this(nameId, null, mainColor, shadowColor, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public CustomColor(StringNames nameId, Color32 mainColor)
: this(nameId, null, mainColor, mainColor.DarkenAbsolute(60), CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public CustomColor(string rawId, Color32 mainColor, Color32 shadowColor)
: this(null, rawId, mainColor, shadowColor, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public CustomColor(string rawId, Color32 mainColor)
: this(null, rawId, mainColor, mainColor.DarkenAbsolute(60), CustomColorBrightness.Darker)
{
}
}
+52 -4
View File
@@ -1,7 +1,11 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Colors;
@@ -16,9 +20,8 @@ public static class PaletteManager
/// </summary>
public static CustomColor[] RegisteredColors => [.. CustomColors];
internal static readonly List<CustomColor> CustomColors = [];
internal static readonly HashSet<StringNames> VariableColorNames = [];
private static readonly List<CustomColor> CustomColors = [];
private static readonly HashSet<StringNames> VariableColorNames = [];
private static readonly CustomColorBrightness[] ColorBrightnessMap =
[
CustomColorBrightness.Darker, // Red
@@ -43,6 +46,49 @@ public static class PaletteManager
private static int originalLength;
internal static bool RegisterColors(Type type, MiraPluginInfo miraPlugin)
{
if (!type.TryGetCustomAttribute<RegisterCustomColorsAttribute>(out var attribute))
{
return false;
}
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers))
{
if (!property.PropertyType.IsAssignableTo(typeof(CustomColor)))
{
continue;
}
if (property.GetValue(null) is not CustomColor color)
{
Error($"Color property {property.Name} in {type.Name} is not a CustomColor.");
continue;
}
if (!string.IsNullOrEmpty(color.RawId) && !string.IsNullOrEmpty(attribute.IdPrefix))
{
color.Name = MiraLocaleManager.GetOrCreateLocaleString(attribute.IdPrefix + color.RawId);
}
CustomColors.Add(color);
if (color is VariableColor)
VariableColorNames.Add(color.Name);
}
if (!miraPlugin.DebugMode)
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers)
.Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(CustomColor))))
{
Error($"{field.Name} is a field, not a property. Use properties for colors.");
}
return true;
}
internal static void RegisterAllColors()
{
originalLength = Palette.PlayerColors.Length;
@@ -50,7 +96,9 @@ public static class PaletteManager
var colors = CustomColors.Select(x => x.MainColor).ToArray();
var shadowColors = CustomColors.Select(x => x.ShadowColor).ToArray();
var stringNames = CustomColors.Select(x => x.Name).ToArray();
var newColorId = originalLength;
foreach (var color in CustomColors)
{
color.ColorId = newColorId++;
@@ -5,5 +5,20 @@ namespace MiraAPI.Colors;
/// <summary>
/// Used to mark a class for <see cref="CustomColor"/> registration.
/// </summary>
/// <param name="idPrefix">The group translation ID prefix to attach to color names before registration.</param>
[AttributeUsage(AttributeTargets.Class)]
public class RegisterCustomColorsAttribute : Attribute;
public class RegisterCustomColorsAttribute(string idPrefix) : Attribute
{
/// <summary>
/// Gets the translation ID prefix for all of the colors within the container type.
/// </summary>
public string IdPrefix => idPrefix;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterCustomColorsAttribute"/> class.
/// </summary>
public RegisterCustomColorsAttribute()
: this(string.Empty)
{
}
}
+109 -17
View File
@@ -1,6 +1,5 @@
using System;
using MiraAPI.LocalSettings;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
@@ -9,40 +8,133 @@ namespace MiraAPI.Colors;
/// <summary>
/// Represents a dynamic custom color that changes over time.
/// </summary>
/// <param name="name">The name of the color.</param>
/// <param name="nameId">The name of the option as a <see cref="StringNames"/> value.</param>
/// <param name="rawId">The name of the option as a <see cref="string"/> value.</param>
/// <param name="mainEvaluator">The function to evaluate the dynamic main color.</param>
/// <param name="shadowEvaluator">The function to evaluate the dynamic shadow color.</param>
/// <param name="mainColor">The static main color used when dynamic colors are disabled.</param>
/// <param name="shadowColor">The static shadow color used when dynamic colors are disabled.</param>
/// <param name="defaultTime">The default time that is used to automatically fill in the static colors when the latter is not provided.</param>
public sealed class VariableColor(StringNames name, Func<float, Color> mainEvaluator, Func<float, Color>? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f)
: CustomColor(name, mainColor ?? mainEvaluator(defaultTime), shadowColor ?? shadowEvaluator?.Invoke(defaultTime) ?? (mainColor ?? mainEvaluator(defaultTime)).DarkenAbsolute(60))
/// <param name="brightness">The brightness type of the color.</param>
public sealed class VariableColor(
StringNames? nameId,
string? rawId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
Color32? mainColor,
Color32? shadowColor,
float defaultTime,
CustomColorBrightness brightness)
: CustomColor(
nameId,
rawId,
mainColor ?? mainEvaluator(defaultTime),
shadowColor ?? shadowEvaluator?.Invoke(defaultTime) ?? (mainColor ?? mainEvaluator(defaultTime)).DarkenAbsolute(60),
brightness)
{
/// <summary>
/// Gets or sets a delegate that takes in a time value and returns the dynamic main color.
/// Gets a delegate that takes in a time value and returns the dynamic main color.
/// </summary>
public Func<float, Color> MainEvaluator { get; set; } = mainEvaluator;
public Func<float, Color> MainEvaluator => mainEvaluator;
/// <summary>
/// Gets or sets a delegate that takes in a time value and returns the dynamic shadow color.
/// Gets a delegate that takes in a time value and returns the dynamic shadow color.
/// </summary>
public Func<float, Color> ShadowEvaluator { get; set; } = shadowEvaluator ?? (t => mainEvaluator(t).DarkenAbsolute(0.24f));
public Func<float, Color> ShadowEvaluator { get; } = shadowEvaluator ?? (t => mainEvaluator(t).DarkenAbsolute(0.24f));
/// <inheritdoc cref="VariableColor"/>
public VariableColor(StringNames name, Func<float, Color> mainEvaluator, Color32? mainColor = null, float defaultTime = 0f)
: this(name, mainEvaluator, null, mainColor, null, defaultTime)
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor"/>
public VariableColor(string name, Func<float, Color> mainEvaluator, Color32? mainColor = null, float defaultTime = 0f)
: this(name, mainEvaluator, null, mainColor, null, defaultTime)
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, null, mainColor, null, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor"/>
public VariableColor(string name, Func<float, Color> mainEvaluator, Func<float, Color>? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f)
: this(MiraLocaleManager.GetOrCreateLocaleString(name), mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime)
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, null, mainColor, null, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
Color32? mainColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, null, mainColor, null, defaultTime, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
Color32? mainColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, null, mainColor, null, defaultTime, CustomColorBrightness.Darker)
{
}
@@ -13,7 +13,7 @@ public sealed class MiraButtonCancelledEvent<T>(T button) : MiraEvent
/// <summary>
/// Gets the <see cref="CustomActionButton"/> whose click was cancelled.
/// </summary>
public T Button { get; } = button;
public T Button => button;
}
/// <summary>
@@ -25,5 +25,5 @@ public sealed class MiraButtonCancelledEvent(CustomActionButton button) : MiraEv
/// <summary>
/// Gets the <see cref="CustomActionButton"/> whose click was cancelled.
/// </summary>
public CustomActionButton Button { get; } = button;
public CustomActionButton Button => button;
}
+3 -3
View File
@@ -14,12 +14,12 @@ public class MiraButtonClickEvent<T>(T button, MiraButtonClickEvent genericClick
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
/// </summary>
public T Button { get; } = button;
public T Button => button;
/// <summary>
/// Gets the generic <see cref="MiraButtonClickEvent"/> that is invoked before this button-specific event.
/// </summary>
public MiraButtonClickEvent GenericClickEvent { get; } = genericClickEvent;
public MiraButtonClickEvent GenericClickEvent => genericClickEvent;
}
/// <summary>
@@ -31,5 +31,5 @@ public class MiraButtonClickEvent(CustomActionButton button) : MiraCancelableEve
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
/// </summary>
public CustomActionButton Button { get; } = button;
public CustomActionButton Button => button;
}
@@ -12,10 +12,10 @@ public class UiButtonPostResetEvent(GameObject topUiRow, GameObject secondUiRow)
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the very top UI row.
/// </summary>
public GameObject MainTopUiRow { get; } = topUiRow;
public GameObject MainTopUiRow => topUiRow;
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the second top UI row.
/// </summary>
public GameObject SecondTopUiRow { get; } = secondUiRow;
public GameObject SecondTopUiRow => secondUiRow;
}
+24
View File
@@ -333,4 +333,28 @@ public static class MiraEventManager
EventHandlersToLoad.Clear();
}
internal static void RegisterEvents(Type type, IMiraPlugin miraPlugin)
{
if (!miraPlugin.ForceRegisterEvents && !type.IsDefined<RegisterEventContainerAttribute>())
{
return;
}
foreach (var method in type.GetMethods(MiraPluginManager.DeclaredStaticMembers))
{
if (!method.TryGetCustomAttribute<RegisterEventAttribute>(out var eventAttribute))
continue;
var parameters = method.GetParameters();
if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent)))
{
Error($"Invalid event registration method {method.Name} in {type.Name}");
continue;
}
RegisterEventHandler(method, eventAttribute.Priority, eventAttribute.InvokeOnSubtype);
}
}
}
+2 -2
View File
@@ -13,13 +13,13 @@ public class RegisterEventAttribute(int priority, bool invokeOnSubtype) : Attrib
/// <summary>
/// Gets the priority of the event. Lower values are called first.
/// </summary>
public int Priority { get; } = priority;
public int Priority => priority;
/// <summary>
/// Gets a value indicating whether the event handler should also be
/// triggered by subclasses of the <see cref="MiraEvent"/> type of the handler.
/// </summary>
public bool InvokeOnSubtype { get; } = invokeOnSubtype;
public bool InvokeOnSubtype => invokeOnSubtype;
/// <inheritdoc cref="RegisterEventAttribute"/>
public RegisterEventAttribute(int priority)
@@ -0,0 +1,9 @@
using System;
namespace MiraAPI.Events;
/// <summary>
/// Register a container of <see cref="MiraEvent"/>s.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class RegisterEventContainerAttribute : Attribute;
@@ -14,33 +14,33 @@ public class AfterMurderEvent(PlayerControl source, PlayerControl target, Player
/// <summary>
/// Gets the <see cref="PlayerControl"/> that killed the <see cref="Target"/>.
/// </summary>
public PlayerControl Source { get; } = source;
public PlayerControl Source => source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was killed.
/// </summary>
public PlayerControl Target { get; } = target;
public PlayerControl Target => target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was framed, if any.
/// </summary>
public PlayerControl? Framed { get; } = framed;
public PlayerControl? Framed => framed;
/// <summary>
/// Gets a value indicating whether the murder was done indirectly.
/// This is commonly used to prevent the <see cref="Source"/> <see cref="PlayerControl"/> from being killed.
/// </summary>
public bool IsIndirectAttack { get; } = isIndirect;
public bool IsIndirectAttack => isIndirect;
/// <summary>
/// Gets a value indicating whether the murder was able to bypass protective roles or general defense, such as <see cref="GuardianAngelRole"/>.
/// </summary>
public bool IgnoreDefense { get; } = ignoreDefense;
public bool IgnoreDefense => ignoreDefense;
/// <summary>
/// Gets the <see cref="Target"/>'s <see cref="DeadBody"/>, if it exists.
/// </summary>
public DeadBody? DeadBody { get; } = deadBody;
public DeadBody? DeadBody => deadBody;
/// <summary>
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
@@ -9,5 +9,5 @@ public class BeforeGameEndEvent(GameOverReason reason) : MiraCancelableEvent
/// <summary>
/// Gets the reason for the game end.
/// </summary>
public GameOverReason Reason { get; } = reason;
public GameOverReason Reason => reason;
}
@@ -17,22 +17,22 @@ public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is killing the <see cref="Target"/>.
/// </summary>
public PlayerControl Source { get; } = source;
public PlayerControl Source => source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being killed.
/// </summary>
public PlayerControl Target { get; } = target;
public PlayerControl Target => target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being framed, if any.
/// </summary>
public PlayerControl? Framed { get; } = framed;
public PlayerControl? Framed => framed;
/// <summary>
/// Gets whether the murder was meant to be done in a meeting, via an enum.
/// </summary>
public MeetingCheck InMeeting { get; } = inMeeting;
public MeetingCheck InMeeting => inMeeting;
/// <summary>
/// Gets or sets a value indicating whether the murder is done indirectly.
@@ -9,5 +9,5 @@ public class BeforeRoundStartEvent(bool triggeredByIntro) : MiraCancelableEvent
/// <summary>
/// Gets a value indicating whether the event was triggered by the <see cref="IntroCutscene"/> or <see cref="ExileController"/>.
/// </summary>
public bool TriggeredByIntro { get; } = triggeredByIntro;
public bool TriggeredByIntro => triggeredByIntro;
}
@@ -9,5 +9,5 @@ public class GameEndEvent(EndGameManager manager) : MiraEvent
/// <summary>
/// Gets the <see cref="global::EndGameManager"/> instance.
/// </summary>
public EndGameManager EndGameManager { get; } = manager;
public EndGameManager EndGameManager => manager;
}
@@ -9,5 +9,5 @@ public class IntroBeginEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; } = introCutscene;
public IntroCutscene IntroCutscene => introCutscene;
}
@@ -9,5 +9,5 @@ public class IntroEndEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; } = introCutscene;
public IntroCutscene IntroCutscene => introCutscene;
}
@@ -9,5 +9,5 @@ public class IntroRoleRevealEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; } = introCutscene;
public IntroCutscene IntroCutscene => introCutscene;
}
@@ -10,5 +10,5 @@ public class RoundStartEvent(bool triggeredByIntro) : MiraEvent
/// <summary>
/// Gets a value indicating whether the event was triggered by the <see cref="IntroCutscene"/> or <see cref="ExileController"/>.
/// </summary>
public bool TriggeredByIntro { get; } = triggeredByIntro;
public bool TriggeredByIntro => triggeredByIntro;
}
@@ -12,10 +12,10 @@ public class SetRoleEvent(PlayerControl player, RoleTypes role) : MiraEvent
/// <summary>
/// Gets the <see cref="PlayerControl"/> whose role was changed.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the role that the player was set to.
/// </summary>
public RoleTypes Role { get; } = role;
public RoleTypes Role => role;
}
@@ -13,7 +13,7 @@ public sealed class VanillaButtonCancelledEvent<T>(T button) : MiraEvent
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> whose click was cancelled.
/// </summary>
public T Button { get; } = button;
public T Button => button;
}
/// <summary>
@@ -25,5 +25,5 @@ public sealed class VanillaButtonCancelledEvent(AbilityButton button) : MiraEven
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> whose click was cancelled.
/// </summary>
public AbilityButton Button { get; } = button;
public AbilityButton Button => button;
}
@@ -14,12 +14,12 @@ public sealed class VanillaButtonClickEvent<T>(T button, VanillaButtonClickEvent
/// <summary>
/// Gets the vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public T Button { get; } = button;
public T Button => button;
/// <summary>
/// Gets the generic <see cref="VanillaButtonClickEvent"/> that is invoked before this button-specific event.
/// </summary>
public VanillaButtonClickEvent GenericClickEvent { get; } = genericClickEvent;
public VanillaButtonClickEvent GenericClickEvent => genericClickEvent;
}
/// <summary>
@@ -33,15 +33,15 @@ public sealed class VanillaButtonClickEvent(AbilityButton button, PlayerControl?
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public AbilityButton Button { get; } = button;
public AbilityButton Button => button;
/// <summary>
/// Gets the target <see cref="PlayerControl"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public PlayerControl? PlayerTarget { get; } = playerTarget;
public PlayerControl? PlayerTarget => playerTarget;
/// <summary>
/// Gets the target <see cref="Vent"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public Vent? VentTarget { get; } = ventTarget;
public Vent? VentTarget => ventTarget;
}
@@ -9,5 +9,5 @@ public class CloseDoorsEvent(SystemTypes room) : MiraCancelableEvent
/// <summary>
/// Gets the room that the doors were closed in.
/// </summary>
public SystemTypes Room { get; } = room;
public SystemTypes Room => room;
}
@@ -9,5 +9,5 @@ public class PlayerOpenSabotageEvent(MapBehaviour mapBehaviour) : MiraCancelable
/// <summary>
/// Gets the <see cref="global::MapBehaviour"/>.
/// </summary>
public MapBehaviour MapBehaviour { get; } = mapBehaviour;
public MapBehaviour MapBehaviour => mapBehaviour;
}
@@ -11,15 +11,15 @@ public class UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byt
/// <summary>
/// Gets the type of system that will be updated.
/// </summary>
public SystemTypes SystemType { get; } = systemType;
public SystemTypes SystemType => systemType;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is updating the system.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the byte amount the system is being updated by.
/// </summary>
public byte Amount { get; } = amount;
public byte Amount => amount;
}
@@ -9,5 +9,5 @@ public class EjectionEvent(ExileController controller) : MiraEvent
/// <summary>
/// Gets the <see cref="global::ExileController"/> instance.
/// </summary>
public ExileController ExileController { get; } = controller;
public ExileController ExileController => controller;
}
@@ -9,5 +9,5 @@ public class EndMeetingEvent(MeetingHud meetingHud) : MiraEvent
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; } = meetingHud;
public MeetingHud MeetingHud => meetingHud;
}
@@ -12,15 +12,15 @@ public class ReportBodyEvent(PlayerControl reporter, NetworkedPlayerInfo? target
/// <summary>
/// Gets the player that is reporting the body.
/// </summary>
public PlayerControl Reporter { get; } = reporter;
public PlayerControl Reporter => reporter;
/// <summary>
/// Gets the player that is being reported. Will be <see langword="null"/> for emergency meeting.
/// </summary>
public NetworkedPlayerInfo? Target { get; } = target;
public NetworkedPlayerInfo? Target => target;
/// <summary>
/// Gets the <see cref="DeadBody"/> that is being reported. Will be <see langword="null"/> for emergency meeting.
/// </summary>
public DeadBody? Body { get; } = body;
public DeadBody? Body => body;
}
@@ -10,5 +10,5 @@ public class StartMeetingEvent(MeetingHud meetingHud) : MiraEvent
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; } = meetingHud;
public MeetingHud MeetingHud => meetingHud;
}
@@ -10,10 +10,10 @@ public class AfterVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter)
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteArea"/>.
/// </summary>
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
public PlayerVoteArea VoteArea => playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; } = voter;
public PlayerControl Player => voter;
}
@@ -10,10 +10,10 @@ public class BeforeVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter)
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteArea"/>.
/// </summary>
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
public PlayerVoteArea VoteArea => playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; } = voter;
public PlayerControl Player => voter;
}
@@ -9,7 +9,7 @@ public class CheckForEndVotingEvent(bool isVotingComplete) : MiraCancelableEvent
/// <summary>
/// Gets a value indicating whether default voting logic determines that voting is complete.
/// </summary>
public bool IsVotingComplete { get; } = isVotingComplete;
public bool IsVotingComplete => isVotingComplete;
/// <summary>
/// Gets or sets a value indicating whether the voting should be forced to end, regardless of the default logic.
@@ -13,12 +13,12 @@ public class DummyVoteEvent(DummyBehaviour dummy) : MiraCancelableEvent
/// <summary>
/// Gets the dummy that needs to vote.
/// </summary>
public DummyBehaviour Dummy { get; } = dummy;
public DummyBehaviour Dummy => dummy;
/// <summary>
/// Gets the instance of the dummy's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; } = dummy.myPlayer.GetVoteData();
public PlayerVoteData VoteData => dummy.myPlayer.GetVoteData();
/// <summary>
/// Gets or sets a value indicating whether the dummy can vote to skip the meeting.
@@ -17,18 +17,18 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; } = playerVoteData;
public PlayerVoteData VoteData => playerVoteData;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public byte TargetId => targetId;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; } = playerVoteData.Owner;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public byte TargetId { get; } = targetId;
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
/// </summary>
@@ -13,12 +13,12 @@ public class MeetingSelectEvent(PlayerVoteData playerVoteData, int targetId, boo
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; } = playerVoteData;
public PlayerVoteData VoteData => playerVoteData;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public int TargetId { get; } = targetId;
public int TargetId => targetId;
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
@@ -15,5 +15,5 @@ public class PopulateResultsEvent(List<CustomVote> votes) : MiraCancelableEvent
/// <summary>
/// Gets a list of networked <see cref="CustomVote"/>s.
/// </summary>
public List<CustomVote> Votes { get; } = votes;
public List<CustomVote> Votes => votes;
}
@@ -27,7 +27,7 @@ public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exil
/// <summary>
/// Gets the list of <see cref="CustomVote"/>s that are being processed.
/// </summary>
public List<CustomVote> Votes { get; } = votes;
public List<CustomVote> Votes => votes;
/// <summary>
/// Gets or sets a value indicating whether an overruling was done. Normally set by judge but can be overwritten.
@@ -9,5 +9,5 @@ public class VotingCompleteEvent(MeetingHud meetingHud) : MiraEvent
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; } = meetingHud;
public MeetingHud MeetingHud => meetingHud;
}
@@ -11,15 +11,15 @@ public class CompleteHnsTaskEvent(HideAndSeekManager hnsManager, PlayerControl p
/// <summary>
/// Gets the instance of the <see cref="PlayerControl"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task { get; } = task;
public PlayerTask Task => task;
/// <summary>
/// Gets the instance of the <see cref="HideAndSeekManager"/> attached to the game.
/// </summary>
public HideAndSeekManager HnsManager { get; } = hnsManager;
public HideAndSeekManager HnsManager => hnsManager;
}
@@ -10,10 +10,10 @@ public class CompleteTaskEvent(PlayerControl player, PlayerTask task) : MiraEven
/// <summary>
/// Gets the instance of the <see cref="PlayerControl"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task { get; } = task;
public PlayerTask Task => task;
}
@@ -11,15 +11,15 @@ public class PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody
/// <summary>
/// Gets the player who died.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the reason the player died.
/// </summary>
public DeathReason DeathReason { get; } = reason;
public DeathReason DeathReason => reason;
/// <summary>
/// Gets the <see cref="global::DeadBody"/> associated with the player, if any.
/// </summary>
public DeadBody? DeadBody { get; } = deadBody;
public DeadBody? DeadBody => deadBody;
}
@@ -11,5 +11,5 @@ public class PlayerJoinEvent(ClientData data) : MiraEvent
/// <summary>
/// Gets the player who joined.
/// </summary>
public ClientData ClientData { get; } = data;
public ClientData ClientData => data;
}
@@ -12,10 +12,10 @@ public class PlayerLeaveEvent(ClientData data, DisconnectReasons reason) : MiraE
/// <summary>
/// Gets the player who left.
/// </summary>
public ClientData ClientData { get; } = data;
public ClientData ClientData => data;
/// <summary>
/// Gets the reason why the player left.
/// </summary>
public DisconnectReasons Reason { get; } = reason;
public DisconnectReasons Reason => reason;
}
@@ -10,10 +10,10 @@ public class EnterVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEv
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is entering the <see cref="Vent"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is entering.
/// </summary>
public Vent? Vent { get; } = vent;
public Vent? Vent => vent;
}
@@ -10,10 +10,10 @@ public class ExitVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEve
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is exiting the <see cref="Vent"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is exiting.
/// </summary>
public Vent? Vent { get; } = vent;
public Vent? Vent => vent;
}
@@ -9,7 +9,7 @@ public class PlayerUseEvent(IUsable usable) : MiraCancelableEvent
/// <summary>
/// Gets the instance of <see cref="IUsable"/> that was used.
/// </summary>
public IUsable Usable { get; } = usable;
public IUsable Usable => usable;
/// <summary>
/// Gets a value indicating whether the <see cref="Usable"/> is a <see cref="Console"/>, <see cref="MapConsole"/>, or <see cref="SystemConsole"/>.
+1 -7
View File
@@ -14,13 +14,7 @@ public static class GameOverManager
private static int nextId = Enum.GetNames<GameOverReason>().Length;
/// <summary>
/// Register a <see cref="CustomGameOver"/>.
/// </summary>
/// <param name="gameOverType">Type of the <see cref="CustomGameOver"/>.</param>
/// <exception cref="ArgumentException">Thrown when the type is not a subclass of <see cref="CustomGameOver"/>, is abstract, or does not have a parameterless constructor.</exception>
/// <returns><see langword="true"/> if the game over was registered successfully, <see langword="false"/> otherwise.</returns>
public static bool RegisterGameOver(Type gameOverType)
internal static bool RegisterGameOver(Type gameOverType)
{
if (!typeof(CustomGameOver).IsAssignableFrom(gameOverType))
{
+1 -10
View File
@@ -19,23 +19,14 @@ public static class CustomGameModeManager
return ++lastId;
}
/// <summary>
/// Register gamemode from type.
/// </summary>
/// <param name="gameModeType">Type of gamemode class, should inherit from <see cref="AbstractGameMode"/>.</param>
/// <param name="pluginInfo">The custom plugin info of the mod.</param>
/// <returns>Whether the gamemode was successfully registered.</returns>
internal static bool RegisterGameMode(Type gameModeType, MiraPluginInfo pluginInfo)
{
if (!typeof(AbstractGameMode).IsAssignableFrom(gameModeType))
{
Warning($"{gameModeType.Name} does not inherit CustomGameMode!");
return false;
}
var instance = Activator.CreateInstance(gameModeType);
if (instance is not AbstractGameMode mode)
if (Activator.CreateInstance(gameModeType) is not AbstractGameMode mode)
{
Error($"Failed to create instance of {gameModeType.Name}");
return false;
+2 -2
View File
@@ -3,6 +3,6 @@ namespace System.Runtime.CompilerServices;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)]
internal sealed class CollectionBuilderAttribute(Type builderType, string methodName) : Attribute
{
public Type BuilderType { get; } = builderType;
public string MethodName { get; } = methodName;
public Type BuilderType => builderType;
public string MethodName => methodName;
}
+51 -34
View File
@@ -66,25 +66,17 @@ public static class ModdedOptionsManager
notif.SettingsChangeMessageLogic(key, item, playSound);
}
internal static bool RegisterGroup(Type type)
{
if (TypeToGroup.ContainsKey(type))
{
Error($"Group {type.Name} already exists.");
return false;
}
if (Activator.CreateInstance(type) is not AbstractOptionGroup group)
{
return false;
}
RegisterGroupInternal(group, type);
return true;
}
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo)
{
if (!type.IsAssignableTo(typeof(AbstractOptionGroup)))
{
return false;
}
if (TypeToGroup.ContainsKey(type))
{
Error($"Group {type.Name} already exists.");
@@ -110,24 +102,49 @@ public static class ModdedOptionsManager
pluginInfo.InternalOptionGroups.Add(group);
RegisterGroupInternal(group, type);
return true;
}
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
private static void RegisterGroupInternal(AbstractOptionGroup group, Type type)
{
Groups.Add(group);
TypeToGroup.Add(type, group);
typeof(OptionGroupSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
.SetValue(null, group);
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers))
{
if (property.PropertyType.IsAssignableTo(typeof(IModdedOption)))
{
RegisterPropertyOption(type, property, pluginInfo);
continue;
}
if (property.PropertyType.IsAssignableTo(typeof(IModdedOptionList)))
{
RegisterPropertyOptionList(type, property, pluginInfo);
continue;
}
if (property.TryGetCustomAttribute<ModdedOptionAttribute>(out var attribute))
{
RegisterAttributeOption(type, attribute, property, pluginInfo);
continue;
}
if (property.TryGetCustomAttribute<ModdedOptionListAttribute>(out var listAttr))
{
RegisterAttributeOptionList(type, listAttr, property, pluginInfo);
}
}
foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers)
.Where(f => !MiraPluginManager.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.");
}
return true;
}
internal static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
private static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (!TypeToGroup.TryGetValue(type, out var group))
{
@@ -144,7 +161,7 @@ public static class ModdedOptionsManager
RegisterOption(option, group, property.Name, pluginInfo);
}
internal static void RegisterAttributeOption(
private static void RegisterAttributeOption(
Type type,
ModdedOptionAttribute attribute,
PropertyInfo property,
@@ -209,7 +226,7 @@ public static class ModdedOptionsManager
RegisterOption(option, group, property.Name, pluginInfo);
}
internal static void RegisterPropertyOptionList(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
private static void RegisterPropertyOptionList(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (!TypeToGroup.TryGetValue(type, out var group))
{
@@ -231,7 +248,7 @@ public static class ModdedOptionsManager
}
}
internal static void RegisterAttributeOptionList(
private static void RegisterAttributeOptionList(
Type type,
ModdedOptionListAttribute attribute,
PropertyInfo property,
@@ -342,7 +359,7 @@ public static class ModdedOptionsManager
}
}
internal static void RegisterOption(
private static void RegisterOption(
IModdedOption option,
AbstractOptionGroup group,
string propertyName,
@@ -363,9 +380,9 @@ public static class ModdedOptionsManager
{
var chunks = ModdedOptions.Values.Select(option => option.GetNetData()).ChunkNetData(1000);
while (chunks.Count > 0)
while (chunks.TryDequeue(out var netData))
{
Rpc<SyncOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, chunks.Dequeue()));
Rpc<SyncGameOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData));
}
}
@@ -162,7 +162,7 @@ public abstract class ModdedOption<T> : IModdedOption
entry.Value = _value;
}
Rpc<SyncOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, new MiraOptionNetData(true, [GetNetData()]), true);
Rpc<SyncGameOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, new MiraOptionNetData(true, [GetNetData()]), true);
}
OnValueChanged(_value);
+1
View File
@@ -45,6 +45,7 @@ public static class CustomButtonManager
CustomButtons.Add(button);
pluginInfo.InternalButtons.Add(button);
typeof(CustomButtonSingleton<>).MakeGenericType(buttonType)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this
.SetValue(null, button);
+1 -1
View File
@@ -22,7 +22,7 @@ public abstract class MultiTargetButton<T> : CustomActionButton
/// <summary>
/// Gets the maximum amount of targets the button can have.
/// </summary>
public virtual int MaxTargets { get; } = int.MaxValue;
public virtual int MaxTargets => int.MaxValue;
/// <inheritdoc cref="CustomActionButton{T}.IsTargetValid"/>
public virtual bool IsTargetValid(T target)
+48 -8
View File
@@ -2,6 +2,8 @@ using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using MiraAPI.PluginLoading;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using Rewired;
@@ -76,6 +78,42 @@ public static class KeybindManager
}
}
internal static bool RegisterKeybinds(Type type, IMiraPlugin plugin)
{
if (!type.IsDefined<RegisterCustomKeybindsAttribute>())
{
return false;
}
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers))
{
if (property.PropertyType != typeof(MiraKeybind))
{
continue;
}
if (property.GetValue(null) is not MiraKeybind keybind)
{
Error($"Keybind property {property.Name} in {type.Name} is not a MiraKeybind.");
continue;
}
Keybinds.Add(keybind);
keybind.SourcePluginName = plugin.OptionsTitleText.Translate();
}
if (!plugin.DebugMode)
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers)
.Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(MiraKeybind))))
{
Error($"{field.Name} is a field, not a property. Use properties for keybinds.");
}
return true;
}
/// <summary>
/// Returns all conflicts where <see cref="MiraKeybind"/>s use the same key.
/// </summary>
@@ -89,16 +127,18 @@ public static class KeybindManager
if (key == KeyboardKeyCode.None) continue;
var all = GetKeybindsForKey(key, true);
if (all.Length > 1)
if (all.Length <= 1)
{
if (!conflicts.TryGetValue(key, out var group))
{
group = [];
conflicts.Add(key, group);
}
if (!group.Contains(keybind)) group.Add(keybind);
continue;
}
if (!conflicts.TryGetValue(key, out var group))
{
group = [];
conflicts.Add(key, group);
}
if (!group.Contains(keybind)) group.Add(keybind);
}
return conflicts;
+2 -2
View File
@@ -15,7 +15,7 @@ public class MiraKeybind(string name, KeyboardKeyCode? defaultKeycode, ModifierK
/// <summary>
/// Gets name of the keybind.
/// </summary>
public string Name { get; } = name;
public string Name => name;
/// <summary>
/// Gets the default keycode of this keybind.
@@ -37,7 +37,7 @@ public class MiraKeybind(string name, KeyboardKeyCode? defaultKeycode, ModifierK
/// Gets a value indicating whether this keybind should be checked for conflicts with other exclusive keybinds using the same key.
/// Active exclusive controller bindings take priority over vanilla actions during gameplay.
/// </summary>
public bool Exclusive { get; } = exclusive;
public bool Exclusive => exclusive;
internal string? SourcePluginName { get; set; }
@@ -6,6 +6,4 @@ namespace MiraAPI.LocalSettings.Attributes;
/// Attribute for local setting buttons.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class LocalSettingsButtonAttribute : Attribute
{
}
public class LocalSettingsButtonAttribute : Attribute;
+59 -7
View File
@@ -1,8 +1,13 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using MiraAPI.LocalSettings.Attributes;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
namespace MiraAPI.LocalSettings;
@@ -19,9 +24,9 @@ public static class LocalSettingsManager
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
internal static bool RegisterTab(Type type, BasePlugin pluginInfo)
internal static bool RegisterLocalTabs(Type type, BasePlugin pluginInfo)
{
if (Activator.CreateInstance(type, pluginInfo.Config) is not LocalSettingsTab tab)
if (!type.IsAssignableTo(typeof(LocalSettingsTab)))
{
return false;
}
@@ -32,17 +37,64 @@ public static class LocalSettingsManager
return false;
}
Tabs.Add(tab);
if (tab.ShouldCreateButton)
if (Activator.CreateInstance(type, pluginInfo.Config) is not LocalSettingsTab tabInstance)
{
AvailableTabs.Add(tab);
return false;
}
TypeToTab.Add(type, tab);
Tabs.Add(tabInstance);
if (tabInstance.ShouldCreateButton)
{
AvailableTabs.Add(tabInstance);
}
TypeToTab.Add(type, tabInstance);
typeof(LocalSettingsTabSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this
.SetValue(null, tab);
.SetValue(null, tabInstance);
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers))
{
if (property.IsDefined<LocalSettingsButtonAttribute>())
{
if (property.GetValue(tabInstance) is not LocalSettingsButton button)
{
Error($"Option property {property.Name} in {type.Name} has to be a settings button.");
continue;
}
button.Tab = tabInstance;
tabInstance.Buttons.Add(button);
continue;
}
if (!property.TryGetCustomAttribute<LocalSettingAttribute>(out var attribute))
{
continue;
}
if (!typeof(ConfigEntryBase).IsAssignableFrom(property.PropertyType))
{
continue;
}
if (property.GetValue(tabInstance) is not ConfigEntryBase configEntry)
{
Error($"Option property {property.Name} in {type.Name} has to be a config entry.");
continue;
}
attribute.CreateSetting(type, configEntry);
}
foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers)
.Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f)
&& (f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) || f.FieldType.IsAssignableTo(typeof(LocalSettingsButton)))))
{
Error($"{field.Name} is a field, not a property. Use properties for local settings or buttons.");
}
return true;
}
@@ -31,7 +31,7 @@ public class LocalEnumSetting(
/// <summary>
/// Gets the <see cref="Enum"/> type of the setting.
/// </summary>
public Type EnumType { get; } = enumType;
public Type EnumType => enumType;
/// <summary>
/// Gets the <see langword="enum"/> values.
@@ -41,7 +41,7 @@ public class LocalSliderSetting(
/// <summary>
/// Gets a value indicating whether the value should be displayed next to name.
/// </summary>
public bool DisplayValue { get; } = displayValue;
public bool DisplayValue => displayValue;
/// <summary>
/// Gets a format for the text to use to format the number.
@@ -51,7 +51,7 @@ public class LocalSliderSetting(
/// <summary>
/// Gets a value indicating whether the value should be rounded.
/// </summary>
public bool RoundValue { get; } = roundValue;
public bool RoundValue => roundValue;
/// <summary>
/// Gets the suffix for the number value.
@@ -13,12 +13,12 @@ namespace MiraAPI.MeetingAbilities;
public static class MeetingButtonManager
{
/// <summary>
/// Gets a list if==of all registered <see cref="TargetedMeetingButton"/>.
/// Gets a list of all registered <see cref="TargetedMeetingButton"/>.
/// </summary>
public static List<TargetedMeetingButton> TargetedButtons { get; internal set; } = [];
/// <summary>
/// Gets a list if==of all registered <see cref="MeetingActionButton"/>.
/// Gets a list of all registered <see cref="MeetingActionButton"/>.
/// </summary>
public static List<MeetingActionButton> UntargetedButtons { get; internal set; } = [];
@@ -64,7 +64,7 @@ public abstract class TargetedMeetingButton
/// <summary>
/// Gets the <see cref="MeetingButtonUsesMode"/> for this button.
/// </summary>
public virtual MeetingButtonUsesMode UsesMode { get; } = MeetingButtonUsesMode.PerGame;
public virtual MeetingButtonUsesMode UsesMode => MeetingButtonUsesMode.PerGame;
/// <summary>
/// Determines if the button is enabled.
-7
View File
@@ -5,7 +5,6 @@
<PackageId>AllOfUs.MiraAPI</PackageId>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>IDE0031;IDE0032</NoWarn>
</PropertyGroup>
<ItemGroup>
@@ -16,11 +15,5 @@
<EmbeddedResource Include="Resources\**\*.*" />
</ItemGroup>
<ItemGroup>
<EditorConfigFiles Remove="GameModes\.editorconfig" />
<EditorConfigFiles Remove="Patches\GameModes\.editorconfig" />
<EditorConfigFiles Remove="Patches\.editorconfig" />
</ItemGroup>
<Import Project="../AmongUs.props" />
</Project>
+6 -3
View File
@@ -8,7 +8,6 @@ using MiraAPI.Patches;
using MiraAPI.Patches.Roles;
using MiraAPI.PluginLoading;
using MiraAPI.Translation;
using MiraAPI.VanillaEvents;
using Reactor;
using Reactor.Localization;
using Reactor.Networking;
@@ -41,6 +40,12 @@ public partial class MiraApiPlugin : BasePlugin, IMiraPlugin
/// <inheritdoc />
public bool DisplayOnOptionsMenu => false;
/// <inheritdoc />
public bool DebugMode => IsDevBuild;
/// <inheritdoc />
public bool ForceRegisterEvents => false;
/// <summary>
/// Gets a value indicating whether the current device is running Starlight (on mobile).
/// </summary>
@@ -93,8 +98,6 @@ public partial class MiraApiPlugin : BasePlugin, IMiraPlugin
"Dictates the unit of distance used in numeric option displays representing a distance.");
Harmony.PatchAll();
RoleOptionsCollectionPatch.PatchRoleMethods(Harmony);
UiResetEvents.Initialize();
JudgeEvents.Initialize();
ReactorCredits.Register("Mira API", Version, IsDevBuild, ReactorCredits.AlwaysShow);
+1 -1
View File
@@ -110,7 +110,7 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config)
/// <returns>The coroutine that resizes the UI.</returns>
public static IEnumerator CoResizeSettingsUI()
{
while (!HudManager.Instance || !MiraHudHelper.UiGrid || !MiraHudHelper.ExtraUiGrid)
while (!HudManager.InstanceExists || !MiraHudHelper.UiGrid || !MiraHudHelper.ExtraUiGrid)
{
yield return null;
}
+8 -5
View File
@@ -68,11 +68,14 @@ public static class ModifierManager
return false;
}
IdToTypeModifierMap.Add(GetNextTypeId(), modifierType);
TypeToIdModifierMap.Add(modifierType, _nextTypeId);
var id = GetNextTypeId();
IdToTypeModifierMap.Add(id, modifierType);
TypeToIdModifierMap.Add(modifierType, id);
BaseModifier modifier;
if (modifierType.GetConstructor(Type.EmptyTypes) != null)
var ctor = modifierType.GetConstructor(Type.EmptyTypes);
if (ctor != null)
{
modifier = (BaseModifier)Activator.CreateInstance(modifierType)!;
}
@@ -90,7 +93,7 @@ public static class ModifierManager
return true;
}
if (modifierType.GetConstructor(Type.EmptyTypes) == null)
if (ctor == null)
{
Error($"Game Modifier {modifierType.FullName} does not have a parameterless constructor!");
return false;
@@ -103,7 +106,7 @@ public static class ModifierManager
PrioritiesToIdsMap[priority] = list = [];
}
list.Add(_nextTypeId);
list.Add(id);
return true;
}
+2 -2
View File
@@ -10,12 +10,12 @@ public readonly struct NetData(uint id, byte[] data)
/// <summary>
/// Gets the ID of the data.
/// </summary>
public uint Id { get; } = id;
public uint Id => id;
/// <summary>
/// Gets the byte[] data.
/// </summary>
public byte[] Data { get; } = data;
public byte[] Data => data;
/// <summary>
/// Gets the length of the data in bytes.
+32 -15
View File
@@ -1,27 +1,24 @@
using Hazel;
using MiraAPI.GameOptions;
using MiraAPI.Roles;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
namespace MiraAPI.Networking;
internal readonly struct MiraOptionNetData(bool showNotif, NetData[] data)
{
public bool ShouldShowNotifications => showNotif;
public NetData[] Data => data;
}
// METHOD RPC DOESN'T WORK WITH THE ARRAYS AND STUFF SO THIS IS HOW WE WILL DO IT FOR NOW
[RegisterCustomRpc((uint)MiraRpc.SyncGameOptions)]
#pragma warning disable SA1515 // Single-line comment should be preceded by blank line (Justification: ReSharper suppression.)
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by Reactor.)
internal sealed class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, MiraOptionNetData>(plugin, id)
#pragma warning restore SA1515 // Single-line comment should be preceded by blank line
internal abstract class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, MiraOptionNetData>(plugin, id)
{
public override RpcLocalHandling LocalHandling => RpcLocalHandling.None;
public override void Write(MessageWriter writer, MiraOptionNetData data)
{
/*if (data == null)
{
writer.WritePacked(0U);
return;
}*/
var info = data.Data;
writer.Write(data.ShouldShowNotifications);
writer.WritePacked((uint)info.Length);
@@ -46,14 +43,34 @@ internal sealed class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCust
return new MiraOptionNetData(shouldShowNotif, data);
}
}
[RegisterCustomRpc((uint)MiraRpc.SyncGameOptions)]
#pragma warning disable SA1515 // Single-line comment should be preceded by blank line (Justification: ReSharper suppression.)
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by Reactor.)
internal sealed class SyncGameOptionsRpc(MiraApiPlugin plugin, uint id) : SyncOptionsRpc(plugin, id)
#pragma warning restore SA1515 // Single-line comment should be preceded by blank line
{
public override void Handle(PlayerControl innerNetObject, MiraOptionNetData data)
{
if (AmongUsClient.Instance.HostId != innerNetObject.OwnerId)
if (AmongUsClient.Instance.HostId == innerNetObject.OwnerId)
{
return;
ModdedOptionsManager.HandleSyncOptions(data.ShouldShowNotifications, data.Data ?? []);
}
}
}
[RegisterCustomRpc((uint)MiraRpc.SyncRoleOptions)]
#pragma warning disable SA1515 // Single-line comment should be preceded by blank line (Justification: ReSharper suppression.)
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by Reactor.)
internal sealed class SyncRoleOptionsRpc(MiraApiPlugin plugin, uint id) : SyncOptionsRpc(plugin, id)
#pragma warning restore SA1515 // Single-line comment should be preceded by blank line
{
public override void Handle(PlayerControl innerNetObject, MiraOptionNetData data)
{
if (AmongUsClient.Instance.HostId == innerNetObject.OwnerId)
{
CustomRoleManager.HandleSyncRoleOptions(data.ShouldShowNotifications, data.Data ?? []);
}
ModdedOptionsManager.HandleSyncOptions(data.ShouldShowNotifications, data.Data ?? []);
}
}
-64
View File
@@ -1,64 +0,0 @@
using Hazel;
using MiraAPI.Roles;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
namespace MiraAPI.Networking;
internal readonly struct MiraOptionNetData(bool showNotif, NetData[] data)
{
public bool ShouldShowNotifications { get; } = showNotif;
public NetData[] Data { get; } = data;
}
[RegisterCustomRpc((uint)MiraRpc.SyncRoleOptions)]
#pragma warning disable SA1515 // Single-line comment should be preceded by blank line (Justification: ReSharper suppression.)
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by Reactor.)
internal sealed class SyncRoleOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, MiraOptionNetData>(plugin, id)
#pragma warning restore SA1515 // Single-line comment should be preceded by blank line
{
public override RpcLocalHandling LocalHandling => RpcLocalHandling.None;
public override void Write(MessageWriter writer, MiraOptionNetData data)
{
/*if (data == null)
{
writer.WritePacked(0U);
return;
}*/
var info = data.Data;
writer.Write(data.ShouldShowNotifications);
writer.WritePacked((uint)info.Length);
foreach (var netData in info)
{
writer.WritePacked(netData.Id);
writer.WriteBytesAndSize(netData.Data);
}
}
public override MiraOptionNetData Read(MessageReader reader)
{
var shouldShowNotif = reader.ReadBoolean();
var length = reader.ReadPackedUInt32();
var data = new NetData[length];
for (var i = 0; i < length; i++)
{
var dataId = reader.ReadPackedUInt32();
var bytes = reader.ReadBytesAndSize();
data[i] = new NetData(dataId, bytes);
}
return new MiraOptionNetData(shouldShowNotif, data);
}
public override void Handle(PlayerControl innerNetObject, MiraOptionNetData data)
{
if (AmongUsClient.Instance.HostId != innerNetObject.OwnerId)
{
return;
}
CustomRoleManager.HandleSyncRoleOptions(data.ShouldShowNotifications, data.Data ?? []);
}
}
+6 -6
View File
@@ -962,13 +962,13 @@ public static class RoleGuidePatches
private sealed class DetailedPanel(string title, string category, string modId, RoleBehaviour? role, GameModifier? modifier, uint typeId)
{
public string Title => title;
public string Category => category;
public string ModId => modId;
public RoleBehaviour? Role => role;
public GameModifier? Modifier => modifier;
public uint TypeId => typeId;
public MatchInfoRolePanel? Panel { get; set; }
public string Title { get; } = title;
public string Category { get; } = category;
public string ModId { get; } = modId;
public RoleBehaviour? Role { get; } = role;
public GameModifier? Modifier { get; } = modifier;
public uint TypeId { get; } = typeId;
public int Amount { get; set; }
public int Chance { get; set; }
public float Likelihood { get; set; }
+19 -1
View File
@@ -1,6 +1,8 @@
using System.Globalization;
using System;
using System.Globalization;
using System.Linq;
using BepInEx.Configuration;
using MiraAPI.Events;
namespace MiraAPI.PluginLoading;
@@ -58,6 +60,22 @@ public interface IMiraPlugin
/// </summary>
string CustomOptionMenuTwoDescription => "Apply game settings for this mod!";
/// <summary>
/// Gets a value indicating whether the plugin is in debug mode.
/// </summary>
bool DebugMode => false;
/// <summary>
/// Gets a value indicating whether the plugin relies on the legacy global event scanning system.
/// </summary>
/// <remarks>
/// This property defaults to true to maintain backwards compatibility.
/// To upgrade your mod, apply the <see cref="RegisterEventContainerAttribute"/> to any class
/// containing events, and then override this property to return <see langword="false"/>.
/// </remarks>
[Obsolete("Global event scanning is deprecated. Add [RegisterEventContainer] to your event classes and override this property to false.")]
bool ForceRegisterEvents => true;
/// <summary>
/// Gets the <see cref="ConfigFile"/> for the plugin.
/// </summary>
+13 -1
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using BepInEx;
using BepInEx.Configuration;
using MiraAPI.Events;
@@ -19,12 +20,13 @@ namespace MiraAPI.PluginLoading;
/// </summary>
public class MiraPluginInfo
{
internal MiraPluginInfo(IMiraPlugin miraPlugin, PluginInfo info)
internal MiraPluginInfo(IMiraPlugin miraPlugin, PluginInfo info, Assembly assembly)
{
MiraPlugin = miraPlugin;
PluginConfig = miraPlugin.GetConfigFile();
PluginInfo = info;
PluginId = info.Metadata.GUID;
PluginAssembly = assembly;
}
/// <summary>
@@ -47,6 +49,16 @@ public class MiraPluginInfo
/// </summary>
public ConfigFile PluginConfig { get; }
/// <summary>
/// Gets the plugin's <see cref="Assembly"/>.
/// </summary>
public Assembly PluginAssembly { get; }
/// <summary>
/// Gets a value indicating whether the plugin is in debug mode.
/// </summary>
public bool DebugMode => MiraPlugin.DebugMode;
/// <summary>
/// Gets a <see cref="IReadOnlyCollection{T}"/> of this <see cref="IMiraPlugin"/>'s <see cref="BaseModifier"/>s. This is not safe for <see cref="BaseModifier"/>s with constructors.
/// </summary>
+59 -236
View File
@@ -9,24 +9,19 @@ using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using MiraAPI.Colors;
using MiraAPI.Events;
using MiraAPI.GameEnd;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.Hud;
using MiraAPI.Keybinds;
using MiraAPI.LocalSettings;
using MiraAPI.LocalSettings.Attributes;
using MiraAPI.MeetingAbilities;
using MiraAPI.Modifiers;
using MiraAPI.Presets;
using MiraAPI.Roles;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using Reactor.Networking;
namespace MiraAPI.PluginLoading;
@@ -40,10 +35,10 @@ public sealed class 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;
internal const BindingFlags DeclaredInstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
internal const BindingFlags DeclaredStaticMembers = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
private readonly Dictionary<Assembly, MiraPluginInfo> _registeredPlugins = [];
private readonly Dictionary<string, MiraPluginInfo> _registeredPlugins = [];
internal MiraPluginInfo[] RegisteredPlugins { get; private set; } = [];
internal MiraPluginInfo[] RegisteredPluginsWithOptions { get; private set; } = [];
@@ -54,6 +49,16 @@ public sealed class MiraPluginManager
internal static ConfigFile MiraApiConfig { get; private set; } = null!;
internal static MiraPluginInfo MiraApiPluginInfo { get; private set; } = null!;
/// <summary>
/// Get a mira plugin by its GUID.
/// </summary>
/// <param name="pluginId">The plugin GUID.</param>
/// <returns>A <see cref="MiraPluginInfo"/>.</returns>
public static MiraPluginInfo? GetPluginByGuid(string pluginId)
{
return Instance._registeredPlugins.GetValueOrDefault(pluginId);
}
internal void Initialize(BasePlugin miraApiPlugin, IMiraPlugin apiPlugin)
{
CustomGameModeManager.RegisterDefaultMode();
@@ -105,7 +110,7 @@ public sealed class MiraPluginManager
private MiraPluginInfo RegisterPlugin(Assembly assembly, IMiraPlugin plugin, PluginInfo pluginInfo, BasePlugin basePlugin, bool isMira)
{
var info = new MiraPluginInfo(plugin, pluginInfo);
var info = new MiraPluginInfo(plugin, pluginInfo, assembly);
var roles = new List<Type>();
var oldConfigSetting = info.PluginConfig.SaveOnConfigSet;
@@ -118,7 +123,7 @@ public sealed class MiraPluginManager
info.InternalOptionGroups.Sort((x, y) => x.GroupPriority.CompareTo(y.GroupPriority));
QueuedRoleRegistrations.Add(info, roles);
_registeredPlugins.Add(assembly, info);
_registeredPlugins.Add(pluginInfo.Metadata.GUID, info);
info.SavePublicCollections();
PresetManager.CreateDefaultPreset(info);
@@ -127,39 +132,54 @@ public sealed class MiraPluginManager
return info;
}
private static bool IsAutoPropertyBackingField(FieldInfo field)
internal static bool IsAutoPropertyBackingField(FieldInfo field)
{
return field.IsDefined<CompilerGeneratedAttribute>(false) &&
field.Name.Contains(">k__BackingField", StringComparison.Ordinal);
field.Name.Contains(">k__BackingField", StringComparison.Ordinal);
}
[SuppressMessage("Minor Code Smell", "S3626:Jump statements should not be redundant", Justification = "Code consistency.")]
private static void ProcessAssemblyTypes(Assembly assembly, MiraPluginInfo info, BasePlugin basePlugin, IMiraPlugin plugin, List<Type> roles, bool isMira)
{
if (plugin.ForceRegisterEvents)
{
Warning("For optimisation reasons, MiraAPI no longer automatically searches every type for events. Please use RegisterEventsAttribute moving forward.");
}
foreach (var type in assembly.GetTypes())
{
if ((isMira && type.IsAbstract) || type.IsDefined<MiraIgnoreAttribute>())
continue;
RegisterEventHandlers(type);
RegisterEvents(type, plugin);
if (RegisterEventType(type, info))
continue;
if (RegisterModifier(type, info))
continue;
if (RegisterOptions(type, info))
continue;
if (RegisterLocalTabs(type, basePlugin))
continue;
if (RegisterColors(type, info))
continue;
if (RegisterRole(type, info, roles))
continue;
if (RegisterModifier(type, info))
continue;
if (RegisterButton(type, info))
continue;
if (RegisterKeybinds(type, plugin))
continue;
if (RegisterGameModeAttribute(type, info))
continue;
if (RegisterGameOver(type))
continue;
@@ -168,36 +188,18 @@ public sealed class MiraPluginManager
if (RegisterTargetedMeetingAbility(type, info))
continue;
if (RegisterGameModeAttribute(type, info))
continue;
if (!RegisterColorClasses(type))
RegisterKeybinds(type, plugin);
}
}
private static void RegisterEventHandlers(Type type)
private static void RegisterEvents(Type type, IMiraPlugin miraPlugin)
{
foreach (var method in AccessTools.GetDeclaredMethods(type))
try
{
if (!method.TryGetCustomAttribute<RegisterEventAttribute>(out var eventAttribute))
continue;
if (!method.IsStatic)
{
Error($"Event handler method {method.Name} in {type.Name} must be static.");
continue;
}
var parameters = method.GetParameters();
if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent)))
{
Error($"Invalid event handler registration: method {method.Name} in {type.Name}");
continue;
}
MiraEventManager.RegisterEventHandler(method, eventAttribute.Priority, eventAttribute.InvokeOnSubtype);
MiraEventManager.RegisterEvents(type, miraPlugin);
}
catch (Exception e)
{
Error($"Failed to register events in {type.Name}: {e}");
}
}
@@ -214,16 +216,6 @@ public sealed class MiraPluginManager
}
}
/// <summary>
/// Get a mira plugin by its GUID.
/// </summary>
/// <param name="pluginId">The plugin GUID.</param>
/// <returns>A <see cref="MiraPluginInfo"/>.</returns>
public static MiraPluginInfo? GetPluginByGuid(string pluginId)
{
return Instance._registeredPlugins.Values.FirstOrDefault(plugin => plugin.PluginId == pluginId);
}
private static bool RegisterGameOver(Type type)
{
try
@@ -241,54 +233,7 @@ public sealed class MiraPluginManager
{
try
{
if (!type.IsAssignableTo(typeof(AbstractOptionGroup)))
{
return false;
}
if (!ModdedOptionsManager.RegisterGroup(type, pluginInfo))
{
return false;
}
foreach (var property in type.GetProperties(DeclaredInstanceMembers))
{
if (property.IsDefined<MiraIgnoreAttribute>())
continue;
if (property.PropertyType.IsAssignableTo(typeof(IModdedOption)))
{
ModdedOptionsManager.RegisterPropertyOption(type, property, pluginInfo);
continue;
}
if (property.PropertyType.IsAssignableTo(typeof(IModdedOptionList)))
{
ModdedOptionsManager.RegisterPropertyOptionList(type, property, pluginInfo);
continue;
}
var attribute = property.GetCustomAttribute<ModdedOptionAttribute>();
if (attribute != null)
{
ModdedOptionsManager.RegisterAttributeOption(type, attribute, property, pluginInfo);
continue;
}
var listAttr = property.GetCustomAttribute<ModdedOptionListAttribute>();
if (listAttr != null)
{
ModdedOptionsManager.RegisterAttributeOptionList(type, listAttr, property, pluginInfo);
}
}
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.");
}
return true;
return ModdedOptionsManager.RegisterGroup(type, pluginInfo);
}
catch (Exception e)
{
@@ -302,19 +247,7 @@ public sealed class MiraPluginManager
{
try
{
if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type)))
{
return false;
}
if (!ModList.GetById(pluginInfo.PluginId).IsRequiredOnAllClients)
{
Error("Custom roles are only supported on all clients.");
return false;
}
roles.Add(type);
return true;
return CustomRoleManager.RegisterRole(type, pluginInfo, roles);
}
catch (Exception e)
{
@@ -324,46 +257,11 @@ public sealed class MiraPluginManager
return false;
}
private static bool RegisterColorClasses(Type type)
private static bool RegisterColors(Type type, MiraPluginInfo miraPlugin)
{
try
{
if (type.GetCustomAttribute<RegisterCustomColorsAttribute>() == null)
{
return false;
}
if (!type.IsStatic())
{
Error($"Color class {type.Name} must be static.");
return false;
}
foreach (var property in type.GetProperties(DeclaredStaticMembers))
{
if (!property.PropertyType.IsAssignableTo(typeof(CustomColor)))
{
continue;
}
if (property.GetValue(null) is not CustomColor color)
{
Error($"Color property {property.Name} in {type.Name} is not a CustomColor.");
continue;
}
PaletteManager.CustomColors.Add(color);
if (color is VariableColor)
PaletteManager.VariableColorNames.Add(color.Name);
}
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;
return PaletteManager.RegisterColors(type, miraPlugin);
}
catch (Exception e)
{
@@ -382,8 +280,9 @@ public sealed class MiraPluginManager
catch (Exception e)
{
Error($"Failed to register modifier {type.Name}: {e}");
return false;
}
return false;
}
private static bool RegisterButton(Type type, MiraPluginInfo pluginInfo)
@@ -404,8 +303,7 @@ public sealed class MiraPluginManager
{
try
{
if (typeof(AbstractGameMode).IsAssignableFrom(type))
return CustomGameModeManager.RegisterGameMode(type, pluginInfo);
return CustomGameModeManager.RegisterGameMode(type, pluginInfo);
}
catch (Exception e)
{
@@ -419,55 +317,7 @@ public sealed class MiraPluginManager
{
try
{
if (!type.IsAssignableTo(typeof(LocalSettingsTab)))
{
return false;
}
if (!LocalSettingsManager.RegisterTab(type, pluginInfo))
{
return false;
}
if (!LocalSettingsManager.TypeToTab.TryGetValue(type, out var tabInstance))
{
return false;
}
foreach (var property in type.GetProperties(DeclaredInstanceMembers))
{
if (property.IsDefined<LocalSettingsButtonAttribute>() &&
property.PropertyType.IsAssignableTo(typeof(LocalSettingsButton)))
{
var button = property.GetValue(tabInstance) as LocalSettingsButton;
button!.Tab = tabInstance;
tabInstance.Buttons.Add(button);
continue;
}
if (!typeof(ConfigEntryBase).IsAssignableFrom(property.PropertyType))
{
continue;
}
if (property.GetValue(tabInstance) is not ConfigEntryBase configEntry)
{
Error($"Option property {property.Name} in {type.Name} has to be a config entry.");
continue;
}
if (property.TryGetCustomAttribute<LocalSettingAttribute>(out var attribute))
{
attribute.CreateSetting(type, configEntry);
}
}
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.");
}
return true;
return LocalSettingsManager.RegisterLocalTabs(type, pluginInfo);
}
catch (Exception e)
{
@@ -477,47 +327,18 @@ public sealed class MiraPluginManager
return false;
}
private static void RegisterKeybinds(Type type, IMiraPlugin plugin)
private static bool RegisterKeybinds(Type type, IMiraPlugin plugin)
{
try
{
if (!type.IsDefined<RegisterCustomKeybindsAttribute>())
{
return;
}
if (!type.IsStatic())
{
Error($"Keybinds class {type.Name} must be static.");
return;
}
foreach (var property in type.GetProperties(DeclaredStaticMembers))
{
if (property.PropertyType != typeof(MiraKeybind))
{
continue;
}
if (property.GetValue(null) is not MiraKeybind keybind)
{
Error($"Keybind property {property.Name} in {type.Name} is not a MiraKeybind.");
continue;
}
KeybindManager.Keybinds.Add(keybind);
keybind.SourcePluginName = plugin.OptionsTitleText.Translate();
}
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.");
}
return KeybindManager.RegisterKeybinds(type, plugin);
}
catch (Exception e)
{
Error($"Failed to register keybind class {type.Name}: {e}");
}
return false;
}
private static bool RegisterMeetingAbility(Type type, MiraPluginInfo info)
@@ -529,8 +350,9 @@ public sealed class MiraPluginManager
catch (Exception e)
{
Error($"Failed to register meeting ability {type.Name}: {e}");
return false;
}
return false;
}
private static bool RegisterTargetedMeetingAbility(Type type, MiraPluginInfo info)
@@ -542,7 +364,8 @@ public sealed class MiraPluginManager
catch (Exception e)
{
Error($"Failed to register targeted meeting ability {type.Name}: {e}");
return false;
}
return false;
}
}
+4 -4
View File
@@ -18,22 +18,22 @@ public class OptionPreset(string name, MiraPluginInfo plugin, ConfigFile presetC
/// <summary>
/// Gets the name of the preset.
/// </summary>
public string Name { get; } = name;
public string Name => name;
/// <summary>
/// Gets the plugin associated with the preset.
/// </summary>
public MiraPluginInfo Plugin { get; } = plugin;
public MiraPluginInfo Plugin => plugin;
/// <summary>
/// Gets the <see cref="ConfigFile"/> of the plugin associated with the preset.
/// </summary>
public ConfigFile PluginConfig { get; } = plugin.PluginConfig;
public ConfigFile PluginConfig => plugin.PluginConfig;
/// <summary>
/// Gets the <see cref="ConfigFile"/> for the preset.
/// </summary>
public ConfigFile PresetConfig { get; } = presetConfig;
public ConfigFile PresetConfig => presetConfig;
/// <summary>
/// Gets or sets the button associated with the preset in the UI.
+20 -2
View File
@@ -10,6 +10,7 @@ using MiraAPI.PluginLoading;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Networking;
using Reactor.Networking.Rpc;
using Reactor.Utilities.Extensions;
using TMPro;
@@ -118,6 +119,23 @@ public static class CustomRoleManager
pluginInfo.PluginConfig.SaveOnConfigSet = oldConfigSetting;
}
internal static bool RegisterRole(Type type, MiraPluginInfo miraPlugin, List<Type> roles)
{
if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type)))
{
return false;
}
if (!ModList.GetById(miraPlugin.PluginId).IsRequiredOnAllClients)
{
Error("Custom roles are only supported on all clients.");
return false;
}
roles.Add(type);
return true;
}
private static RoleBehaviour? RegisterRole(Type roleType, MiraPluginInfo parentMod)
{
if (!(typeof(RoleBehaviour).IsAssignableFrom(roleType) && typeof(ICustomRole).IsAssignableFrom(roleType)))
@@ -278,9 +296,9 @@ public static class CustomRoleManager
.Select(x => ((ICustomRole)x).GetNetData())
.ChunkNetData(1000);
while (data.Count > 0)
while (data.TryDequeue(out var netData))
{
Rpc<SyncRoleOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, data.Dequeue()));
Rpc<SyncRoleOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData));
}
}
+6 -6
View File
@@ -31,13 +31,13 @@ internal sealed class GuideOptionPage(
IReadOnlyList<string> modSearchTerms,
List<GuideOptionEntry> entries)
{
public AbstractOptionGroup Group { get; } = group;
public AbstractOptionGroup Group => group;
public List<AbstractOptionGroup> Groups { get; } = [group];
public string Title { get; } = title;
public string Title => title;
public LoadableAsset<Sprite> Sprite { get; } = group.Sprite;
public LoadableAsset<Sprite> Sprite => group.Sprite;
public int Order { get; set; } = order;
@@ -45,13 +45,13 @@ internal sealed class GuideOptionPage(
public uint GroupPriority { get; set; } = groupPriority;
public int Columns { get; } = columns;
public int Columns => columns;
public string ModAbbreviation { get; } = modAbbreviation;
public string ModAbbreviation => modAbbreviation;
public HashSet<string> ModSearchTerms { get; } = new(modSearchTerms, StringComparer.OrdinalIgnoreCase);
public List<GuideOptionEntry> Entries { get; } = entries;
public List<GuideOptionEntry> Entries => entries;
}
internal static class GuideOptionPages
+3 -7
View File
@@ -4,15 +4,11 @@ using MiraAPI.Roles;
namespace MiraAPI.VanillaEvents;
[RegisterEventContainer]
internal static class JudgeEvents
{
public static void Initialize()
{
// This is required because MiraAPI isn't an IMiraPlugin (besides in the gamemodes branch)
MiraEventManager.RegisterEventHandler<ProcessVotesEvent>(ProcessVotesEventHandler, -1000);
}
private static void ProcessVotesEventHandler(ProcessVotesEvent @event)
[RegisterEvent(-1000)]
public static void ProcessVotesEventHandler(ProcessVotesEvent @event)
{
if (!MeetingHud.Instance.TryGetWinningOverrule(
out var judgeOverrule,
+9 -12
View File
@@ -5,17 +5,11 @@ using MiraAPI.LocalSettings;
namespace MiraAPI.VanillaEvents;
[RegisterEventContainer]
internal static class UiResetEvents
{
public static void Initialize()
{
MiraEventManager.RegisterEventHandler<UiButtonResetEvent>(ResetButtonParents);
MiraEventManager.RegisterEventHandler<UiButtonPostResetEvent>(PlaceWikiButton, -900);
MiraEventManager.RegisterEventHandler<UiButtonPostResetEvent>(PlaceSubmergedButton, -800);
MiraEventManager.RegisterEventHandler<UiButtonPostResetEvent>(PlaceModifierUi, -700);
}
private static void ResetButtonParents(UiButtonResetEvent _)
[RegisterEvent]
public static void ResetButtonParents(UiButtonResetEvent _)
{
var wikiButton = MiraHudHelper.VanillaMatchInfoButton;
var subButton = MiraHudHelper.SubmergedFloorButton;
@@ -36,7 +30,8 @@ internal static class UiResetEvents
}
}
private static void PlaceWikiButton(UiButtonPostResetEvent @event)
[RegisterEvent(-900)]
public static void PlaceWikiButton(UiButtonPostResetEvent @event)
{
var wikiButton = MiraHudHelper.VanillaMatchInfoButton;
if (!wikiButton)
@@ -50,7 +45,8 @@ internal static class UiResetEvents
wikiButton.transform.SetParent(opts.WikiOnBottomRow.Value ? secondRow.transform : firstRow.transform);
}
private static void PlaceSubmergedButton(UiButtonPostResetEvent @event)
[RegisterEvent(-800)]
public static void PlaceSubmergedButton(UiButtonPostResetEvent @event)
{
var subButton = MiraHudHelper.SubmergedFloorButton;
if (!subButton)
@@ -62,7 +58,8 @@ internal static class UiResetEvents
subButton.transform.SetParent(secondRow.transform);
}
private static void PlaceModifierUi(UiButtonPostResetEvent @event)
[RegisterEvent(-700)]
public static void PlaceModifierUi(UiButtonPostResetEvent @event)
{
var modDisplay = MiraHudHelper.ModifierDisplayOnRight ? MiraHudHelper.ModifierDisplayObject : null!;
if (!modDisplay)