Merge branch 'dev' into no-boxing

This commit is contained in:
Az committed 2026-11-13 00:59:50 -05:00
commit 4272c2e383
20 files changed
+430 -166

No files matched your search

+1 -1
View File
@@ -40,7 +40,7 @@ public class ChameleonRole : CrewmateRole, ICustomRole
return;
}
if (Player.MyPhysics.Velocity.magnitude > 0)
if (Player.MyPhysics.Velocity.sqrMagnitude > 0)
{
var rend = Player.cosmetics.currentBodySprite.BodySprite;
var tmp = Player.cosmetics.nameText;
+5 -7
View File
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HarmonyLib;
@@ -45,11 +46,8 @@ public static class PaletteManager
private static int originalLength;
internal static bool RegisterColors(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterColors(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var miraPlugin = context.MiraPlugin;
if (!type.TryGetCustomAttribute<RegisterCustomColorsAttribute>(out var attribute))
{
return false;
@@ -79,11 +77,11 @@ public static class PaletteManager
VariableColorNames.Add(color.Name);
}
if (!miraPlugin.DebugMode)
if (!context.MiraPlugin.DebugMode)
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers)
.Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(CustomColor))))
.Where(f => !f.IsAutoPropertyBackingField() && f.FieldType.IsAssignableTo(typeof(CustomColor))))
{
Error($"{field.Name} is a field, not a property. Use properties for colors.");
}
+11 -17
View File
@@ -84,27 +84,24 @@ public static class MiraEventManager
return true;
}
internal static bool RegisterEventType(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterEventType(Type type, in MiraPluginManager.RegistrationContext context)
{
var eventType = context.Type;
var pluginInfo = context.PluginInfo;
if (eventType.IsAbstract || !eventType.IsSubclassOf(typeof(MiraEvent)))
if (type.IsAbstract || !type.IsSubclassOf(typeof(MiraEvent)))
{
return false;
}
AddTypeToTracked(eventType);
AddTypeToTracked(type);
// subtypes are added to their supertypes, regardless of which were added first
TrackedEventTypes[eventType].UnionWith(InternalEventTypes.Where(x => x.IsSubclassOfWithGeneric(eventType)));
foreach (var supertype in InternalEventTypes.Where(x => eventType.IsSubclassOfWithGeneric(x)))
TrackedEventTypes[type].UnionWith(InternalEventTypes.Where(x => x.IsSubclassOfWithGeneric(type)));
foreach (var supertype in InternalEventTypes.Where(x => type.IsSubclassOfWithGeneric(x)))
{
AddTypeToTracked(supertype, eventType);
AddTypeToTracked(supertype, type);
}
pluginInfo.InternalEventTypes.Add(eventType);
InternalEventTypes.Add(eventType);
context.PluginInfo.InternalEventTypes.Add(type);
InternalEventTypes.Add(type);
return true;
}
@@ -343,14 +340,11 @@ public static class MiraEventManager
EventHandlersToLoad.Clear();
}
internal static bool RegisterEvents(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterEvents(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var miraPlugin = context.MiraPlugin;
var hasContainerAttribute = type.IsDefined<RegisterEventContainerAttribute>();
if (!miraPlugin.ForceRegisterEvents && !hasContainerAttribute)
if (!context.MiraPlugin.ForceRegisterEvents && !hasContainerAttribute)
{
return false;
}
@@ -368,7 +362,7 @@ public static class MiraEventManager
continue;
}
RegisterEventHandler(method, eventAttribute.Priority, eventAttribute.InvokeOnSubtype);
RegisterEventHandler(parameters[0].ParameterType, method, eventAttribute.Priority, eventAttribute.InvokeOnSubtype);
}
return hasContainerAttribute;
+1 -3
View File
@@ -15,10 +15,8 @@ public static class GameOverManager
private static int nextId = Enum.GetNames<GameOverReason>().Length;
internal static bool RegisterGameOver(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterGameOver(Type type, in MiraPluginManager.RegistrationContext _)
{
var type = context.Type;
if (!typeof(CustomGameOver).IsAssignableFrom(type))
{
return false;
+2 -5
View File
@@ -19,11 +19,8 @@ public static class CustomGameModeManager
return ++lastId;
}
internal static bool RegisterGameMode(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterGameMode(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!typeof(AbstractGameMode).IsAssignableFrom(type))
{
return false;
@@ -41,7 +38,7 @@ public static class CustomGameModeManager
var id = GetNextId();
mode.ID = id;
IdToModeMap.Add(id, mode);
pluginInfo.GameModes.Add(id, mode);
context.PluginInfo.GameModes.Add(id, mode);
GameModeOption.AddOption(mode);
return true;
}
+16 -30
View File
@@ -43,6 +43,7 @@ public static class ModdedOptionsManager
internal static readonly Dictionary<Type, List<AbstractOptionGroup>> GameModeOptionGroups = [];
internal static readonly Dictionary<uint, IModdedOption> ModdedOptions = [];
internal static readonly List<AbstractOptionGroup> Groups = [];
internal static readonly Comparer<AbstractOptionGroup> Comparer = Comparer<AbstractOptionGroup>.Create((x, y) => x.GroupPriority.CompareTo(y.GroupPriority));
internal static uint NextId => _nextId++;
private static uint _nextId = 1;
@@ -70,15 +71,8 @@ public static class ModdedOptionsManager
notif.SettingsChangeMessageLogic(key, item, playSound);
}
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
internal static bool RegisterGroup(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterGroup(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!type.IsAssignableTo(typeof(AbstractOptionGroup)))
{
return false;
@@ -107,13 +101,13 @@ public static class ModdedOptionsManager
}
}
var pluginInfo = context.PluginInfo;
pluginInfo.InternalOptionGroups.Add(group);
Groups.Add(group);
typeof(OptionGroupSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression refers to this
.SetValue(null, group);
Helpers.SetInstance(typeof(OptionGroupSingleton<>), type, group);
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers))
{
@@ -121,13 +115,13 @@ public static class ModdedOptionsManager
if (propType.IsAssignableTo(OptionType))
{
RegisterPropertyOption(type, property, pluginInfo, group);
RegisterPropertyOption(type, group, property, pluginInfo);
continue;
}
if (propType.IsAssignableTo(OptionListType))
{
RegisterPropertyOptionList(type, property, pluginInfo, group);
RegisterPropertyOptionList(type, group, property, pluginInfo);
continue;
}
@@ -137,13 +131,13 @@ public static class ModdedOptionsManager
{
if (attr is ModdedOptionAttribute moddedAttr)
{
RegisterAttributeOption(type, moddedAttr, property, pluginInfo, propType, attributes, group);
RegisterAttributeOption(type, group, moddedAttr, property, pluginInfo, propType, attributes);
break;
}
if (attr is ModdedOptionListAttribute listAttr)
{
RegisterAttributeOptionList(type, listAttr, property, pluginInfo, propType, attributes, group);
RegisterAttributeOptionList(type, group, listAttr, property, pluginInfo, propType, attributes);
break;
}
}
@@ -153,7 +147,7 @@ public static class ModdedOptionsManager
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers)
.Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f)
.Where(f => !f.IsAutoPropertyBackingField()
&& (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IBaseModdedOptionList)))))
{
Error($"{field.Name} is a field, not a property. Use properties for options.");
@@ -188,11 +182,7 @@ public static class ModdedOptionsManager
lookup[toPatch.MethodHandle] = attribute;
}
private static void RegisterPropertyOption(
Type type,
PropertyInfo property,
MiraPluginInfo pluginInfo,
AbstractOptionGroup group)
private static void RegisterPropertyOption(Type type, AbstractOptionGroup group, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (property.GetValue(group) is not IModdedOption option)
{
@@ -205,12 +195,12 @@ public static class ModdedOptionsManager
private static void RegisterAttributeOption(
Type type,
AbstractOptionGroup group,
ModdedOptionAttribute attribute,
PropertyInfo property,
MiraPluginInfo pluginInfo,
Type propType,
object[] attributes,
AbstractOptionGroup group)
object[] attributes)
{
if (!OptionAttributes.Add(property))
{
@@ -253,11 +243,7 @@ public static class ModdedOptionsManager
RegisterOption(type, option, group, property.Name, pluginInfo);
}
private static void RegisterPropertyOptionList(
Type type,
PropertyInfo property,
MiraPluginInfo pluginInfo,
AbstractOptionGroup group)
private static void RegisterPropertyOptionList(Type type, AbstractOptionGroup group, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (property.GetValue(group) is not IBaseModdedOptionList optionList)
{
@@ -275,12 +261,12 @@ public static class ModdedOptionsManager
private static void RegisterAttributeOptionList(
Type type,
AbstractOptionGroup group,
ModdedOptionListAttribute attribute,
PropertyInfo property,
MiraPluginInfo pluginInfo,
Type propType,
object[] attributes,
AbstractOptionGroup group)
object[] attributes)
{
if (!OptionAttributes.Add(property))
{
+9 -19
View File
@@ -1,10 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using MiraAPI.Events.Mira;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
namespace MiraAPI.Hud;
@@ -32,38 +31,29 @@ public static class CustomButtonManager
internal static readonly Dictionary<Type, Type> ButtonEventTypes = [];
internal static readonly Dictionary<Type, Type> ButtonCancelledEventTypes = [];
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
internal static bool RegisterButton(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterButton(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!type.IsAssignableTo(typeof(CustomActionButton)) || Activator.CreateInstance(type) is not CustomActionButton button)
{
return false;
}
context.PluginInfo.InternalButtons.Add(button);
CustomButtons.Add(button);
pluginInfo.InternalButtons.Add(button);
typeof(CustomButtonSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this
.SetValue(null, button);
ButtonEventTypes.Add(type, typeof(MiraButtonClickEvent<>).MakeGenericType(type));
ButtonCancelledEventTypes.Add(type, typeof(MiraButtonCancelledEvent<>).MakeGenericType(type));
Helpers.SetInstance(typeof(CustomButtonSingleton<>), type, button);
return true;
}
internal static void RegisterAllButtons()
{
// Save all buttons into a read-only collection for easy access
Buttons = new ReadOnlyCollection<CustomActionButton>(CustomButtonManager.CustomButtons);
EventTypes = new ReadOnlyDictionary<Type, Type>(CustomButtonManager.ButtonEventTypes);
CancelledEventTypes = new ReadOnlyDictionary<Type, Type>(CustomButtonManager.ButtonCancelledEventTypes);
Buttons = new ReadOnlyCollection<CustomActionButton>(CustomButtons);
EventTypes = new ReadOnlyDictionary<Type, Type>(ButtonEventTypes);
CancelledEventTypes = new ReadOnlyDictionary<Type, Type>(ButtonCancelledEventTypes);
}
}
+13 -5
View File
@@ -23,6 +23,15 @@ public static class KeybindManager
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
internal static readonly Dictionary<Type, VanillaKeybind> VanillaKeybinds = [];
internal static void SetKeybind<T>(int keybindId)
where T : ActionButton
{
var type = typeof(T);
var bind = new VanillaKeybind(keybindId);
VanillaKeybinds[type] = bind;
Helpers.SetInstance(typeof(VanillaKeybinding<>), type, bind);
}
internal static void RewiredInit()
{
try
@@ -78,16 +87,15 @@ public static class KeybindManager
}
}
internal static bool RegisterKeybinds(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterKeybinds(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var miraPlugin = context.MiraPlugin;
if (!type.IsDefined<RegisterCustomKeybindsAttribute>())
{
return false;
}
var miraPlugin = context.MiraPlugin;
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers))
{
if (!property.PropertyType.IsAssignableTo(typeof(MiraKeybind)))
@@ -109,7 +117,7 @@ public static class KeybindManager
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers)
.Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(MiraKeybind))))
.Where(f => !f.IsAutoPropertyBackingField() && f.FieldType.IsAssignableTo(typeof(MiraKeybind))))
{
Error($"{field.Name} is a field, not a property. Use properties for keybinds.");
}
+7 -15
View File
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using BepInEx.Configuration;
using MiraAPI.LocalSettings.Attributes;
using MiraAPI.PluginLoading;
@@ -19,15 +17,8 @@ public static class LocalSettingsManager
internal static readonly List<LocalSettingsTab> Tabs = [];
internal static readonly List<LocalSettingsTab> AvailableTabs = [];
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
internal static bool RegisterLocalTabs(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterLocalTabs(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var basePlugin = context.BasePlugin;
if (!type.IsAssignableTo(typeof(LocalSettingsTab)))
{
return false;
@@ -39,7 +30,7 @@ public static class LocalSettingsManager
return false;
}
if (Activator.CreateInstance(type, basePlugin.Config) is not LocalSettingsTab tabInstance)
if (Activator.CreateInstance(type, context.BasePlugin.Config) is not LocalSettingsTab tabInstance)
{
return false;
}
@@ -53,9 +44,7 @@ public static class LocalSettingsManager
TypeToTab.Add(type, tabInstance);
typeof(LocalSettingsTabSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this
.SetValue(null, tabInstance);
Helpers.SetInstance(typeof(LocalSettingsTabSingleton<>), type, tabInstance);
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers))
{
@@ -91,8 +80,11 @@ public static class LocalSettingsManager
attribute.CreateSetting(type, configEntry);
}
if (!context.MiraPlugin.DebugMode)
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers)
.Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f)
.Where(f => !f.IsAutoPropertyBackingField()
&& (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.");
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Components;
using UnityEngine;
@@ -22,34 +23,30 @@ public static class MeetingButtonManager
/// </summary>
public static List<MeetingActionButton> UntargetedButtons { get; internal set; } = [];
internal static bool RegisterTargetedMeetingButton(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterTargetedMeetingButton(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!typeof(TargetedMeetingButton).IsAssignableFrom(type))
{
return false;
}
var button = (Activator.CreateInstance(type) as TargetedMeetingButton)!;
pluginInfo.InternalTargetedMeetingButtons.Add(button);
context.PluginInfo.InternalTargetedMeetingButtons.Add(button);
TargetedButtons.Add(button);
Helpers.SetInstance(typeof(TargetedMeetingButtonSingleton<>), type, button);
return true;
}
internal static bool RegisterMeetingButton(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterMeetingButton(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!typeof(MeetingActionButton).IsAssignableFrom(type))
{
return false;
}
var button = (Activator.CreateInstance(type) as MeetingActionButton)!;
pluginInfo.InternalMeetingButtons.Add(button);
context.PluginInfo.InternalMeetingButtons.Add(button);
UntargetedButtons.Add(button);
return true;
}
+2 -5
View File
@@ -67,11 +67,8 @@ public static class ModifierManager
Modifiers = new ReadOnlyCollection<BaseModifier>(InternalModifiers);
}
internal static bool RegisterModifier(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterModifier(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!typeof(BaseModifier).IsAssignableFrom(type))
{
return false;
@@ -94,7 +91,7 @@ public static class ModifierManager
modifier = (BaseModifier)FormatterServices.GetUninitializedObject(type);
}
pluginInfo.InternalModifiers.Add(modifier);
context.PluginInfo.InternalModifiers.Add(modifier);
InternalModifiers.Add(modifier);
if (modifier is not GameModifier gameModifier)
+6 -6
View File
@@ -21,11 +21,11 @@ public static class KeybindMenuPatch
_registered = true;
// Set these here right after input manager initializes
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);
KeybindManager.SetKeybind<KillButton>(8);
KeybindManager.SetKeybind<UseButton>(6);
KeybindManager.SetKeybind<ReportButton>(7);
KeybindManager.SetKeybind<VentButton>(50);
KeybindManager.SetKeybind<SabotageButton>(4);
KeybindManager.SetKeybind<AbilityButton>(49);
}
}
@@ -1,4 +1,5 @@
using System.Linq;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Utilities;
@@ -9,6 +10,8 @@ namespace MiraAPI.Patches.Options;
[HarmonyPatch(typeof(PlayerOption))]
public static class PlayerOptionPatches
{
private static readonly Comparer<NetworkedPlayerInfo> Comparer = Comparer<NetworkedPlayerInfo>.Create((a, b) => a.PlayerId.CompareTo(b.PlayerId));
// Updates the list of players according to the filter.
[HarmonyPrefix]
[HarmonyPatch(nameof(PlayerOption.FixedUpdate))]
@@ -26,7 +29,7 @@ public static class PlayerOptionPatches
var filteredPlayers = moddedPlrOpt.GetFilteredPlayers();
if (filteredPlayers.Count != __instance.Values.Count)
{
filteredPlayers.Sort((a, b) => a.PlayerId.CompareTo(b.PlayerId));
filteredPlayers.Sort(Comparer);
moddedPlrOpt.Values = filteredPlayers;
__instance.Values = filteredPlayers.ToIl2CppList();
+1 -1
View File
@@ -119,7 +119,7 @@ public class MiraPluginInfo
Modifiers = [.. InternalModifiers];
OptionGroups = [.. InternalOptionGroups];
Options = [.. InternalOptions];
Roles = new ReadOnlyDictionary<ushort, RoleBehaviour>(InternalRoles);
Roles = new(InternalRoles);
Buttons = [.. InternalButtons];
MeetingButtons = [.. InternalMeetingButtons];
TargetedMeetingButtons = [.. InternalTargetedMeetingButtons];
+37 -23
View File
@@ -4,7 +4,6 @@ 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;
@@ -30,9 +29,9 @@ namespace MiraAPI.PluginLoading;
[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
{
internal delegate bool TypeRegistrationHandler(in RegistrationContext context);
internal delegate bool TypeRegistrationHandler(Type type, in RegistrationContext context);
internal readonly record struct RegistrationContext(Type Type, MiraPluginInfo PluginInfo, IMiraPlugin MiraPlugin, BasePlugin BasePlugin, List<Type> Roles);
internal readonly record struct RegistrationContext(MiraPluginInfo PluginInfo, IMiraPlugin MiraPlugin, BasePlugin BasePlugin, List<Type> Roles);
private MiraPluginManager()
{
@@ -69,6 +68,15 @@ public sealed class MiraPluginManager
("targeted meeting ability", MeetingButtonManager.RegisterTargetedMeetingButton),
];
private static readonly (string LogContext, Action Handler)[] RegistrationFinalisers =
[
("color", PaletteManager.RegisterAllColors),
("button", CustomButtonManager.RegisterAllButtons),
("modifier", ModifierManager.RegisterAllModifiers),
("event", MiraEventManager.OnLoadFinalize),
("plugin", Instance.FinaliseLoading),
];
/// <summary>
/// Get a mira plugin by its GUID.
/// </summary>
@@ -111,18 +119,28 @@ public sealed class MiraPluginManager
IL2CPPChainloader.Instance.Finished += () =>
{
PaletteManager.RegisterAllColors();
CustomButtonManager.RegisterAllButtons();
ModifierManager.RegisterAllModifiers();
MiraEventManager.OnLoadFinalize();
// Cache all the registered plugins into an array for easy access
RegisteredPlugins = [.. _registeredPlugins.Values];
RegisteredPluginsWithOptions = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu)];
PluginsWithOptionsOrGameModes = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu || m.GameModes.Count > 0)];
foreach (var (logContext, handler) in RegistrationFinalisers)
{
try
{
handler();
}
catch (Exception e)
{
Error($"Failed to finalise {logContext} registry: {e}");
}
}
};
}
private void FinaliseLoading()
{
// Cache all the registered plugins into an array for easy access
RegisteredPlugins = [.. _registeredPlugins.Values];
RegisteredPluginsWithOptions = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu)];
PluginsWithOptionsOrGameModes = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu || m.GameModes.Count > 0)];
}
private MiraPluginInfo RegisterPlugin(Assembly assembly, IMiraPlugin plugin, PluginInfo pluginInfo, BasePlugin basePlugin, bool isMira)
{
var info = new MiraPluginInfo(plugin, pluginInfo, assembly);
@@ -136,23 +154,19 @@ public sealed class MiraPluginManager
info.PluginConfig.Save();
info.PluginConfig.SaveOnConfigSet = oldConfigSetting;
info.InternalOptionGroups.Sort((x, y) => x.GroupPriority.CompareTo(y.GroupPriority));
info.InternalOptionGroups.Sort(ModdedOptionsManager.Comparer);
QueuedRoleRegistrations.Add(info, roles);
_registeredPlugins.Add(pluginInfo.Metadata.GUID, info);
info.SavePublicCollections();
PresetManager.CreateDefaultPreset(info);
PresetManager.LoadPresets(info);
return info;
}
internal 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)
{
if (plugin.ForceRegisterEvents)
@@ -160,23 +174,23 @@ public sealed class MiraPluginManager
Warning("For optimisation reasons, MiraAPI no longer automatically searches every type for events. Please use RegisterEventContainerAttribute moving forward.");
}
var context = new RegistrationContext(info, plugin, basePlugin, roles);
foreach (var type in assembly.GetTypes())
{
if ((isMira && type.IsAbstract) || type.IsDefined<MiraIgnoreAttribute>())
continue;
var context = new RegistrationContext(type, info, plugin, basePlugin, roles);
foreach (var (logContext, handler) in RegistrationHandlers)
{
try
{
if (handler(in context))
if (handler(type, in context))
break;
}
catch (Exception e)
{
Error($"Failed to register {logContext} {type.Name}: {e}");
Error($"Failed to register {logContext} in {type.Name}: {e}");
}
}
}
+5 -7
View File
@@ -119,24 +119,20 @@ public static class CustomRoleManager
pluginInfo.PluginConfig.SaveOnConfigSet = oldConfigSetting;
}
internal static bool RegisterRole(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterRole(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
var roles = context.Roles;
if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type)))
{
return false;
}
if (!ModList.GetById(pluginInfo.PluginId).IsRequiredOnAllClients)
if (!ModList.GetById(context.PluginInfo.PluginId).IsRequiredOnAllClients)
{
Error("Custom roles are only supported on all clients.");
return false;
}
roles.Add(type);
context.Roles.Add(type);
return true;
}
@@ -216,6 +212,8 @@ public static class CustomRoleManager
CustomRoles.Add(roleId, roleBehaviour);
Helpers.SetInstance(typeof(CustomRoleSingleton<>), roleType, roleBehaviour);
if (customRole.Configuration.HideSettings)
{
return roleBehaviour;
+76
View File
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace MiraAPI.Utilities;
/// <summary>
/// Defines a method that a type implements to compare two objects using extra contextual information.
/// </summary>
/// <typeparam name="TValue">The type of objects to compare.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
public interface IComparer<in TValue, in TParam>
{
/// <summary>
/// When overridden in a derived class, performs a comparison of two objects of the
/// same type using the provided context and returns a value indicating whether one
/// object is less than, equal or greater than the other.
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <param name="context">The extra information to aid in the comparison.</param>
/// <returns>
/// A signed integer that indicates the relative values of x and y, as shown in the
/// following table.<br/><br/>
/// Value – Meaning<br/>
/// Less than zero – x is less than y.<br/>
/// Zero – x equals y.<br/>
/// Greater than zero – x is greater than y.<br/>
/// </returns>
int Compare(TValue? x, TValue? y, TParam? context);
}
/// <summary>
/// Provides a base class for implementations of the <see cref="IComparer{TValue, TParam}"/>
/// generic interface.
/// </summary>
/// <typeparam name="TValue">The type of objects to compare.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
[SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "Mimics Comparer<T> design.")]
public abstract class Comparer<TValue, TParam> : IComparer<TValue, TParam>
{
/// <summary>
/// Gets a default contextual comparer that ignores the parameter and falls back to standard comparison.
/// </summary>
public static Comparer<TValue, TParam> Default { get; } = new DefaultComparer();
/// <summary>
/// Creates a contextual comparer by using the specified comparison delegate.
/// </summary>
/// <param name="comparison">The comparison to use.</param>
/// <returns>The new comparer.</returns>
public static Comparer<TValue, TParam> Create(Func<TValue?, TValue?, TParam?, int>? comparison)
{
ArgumentNullException.ThrowIfNull(comparison);
return new FuncComparer(comparison);
}
/// <inheritdoc/>
public abstract int Compare(TValue? x, TValue? y, TParam? context);
private sealed class DefaultComparer : Comparer<TValue, TParam>
{
public override int Compare(TValue? x, TValue? y, TParam? context)
{
return Comparer<TValue>.Default.Compare(x, y);
}
}
private sealed class FuncComparer(Func<TValue?, TValue?, TParam?, int> comparison) : Comparer<TValue, TParam>
{
public override int Compare(TValue? x, TValue? y, TParam? context)
{
return comparison(x, y, context);
}
}
}
@@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace MiraAPI.Utilities;
/// <summary>
/// Provides extension methods to integrate <see cref="IComparer{TValue, TParam}"/> with standard .NET collections and LINQ.
/// </summary>
public static class ContextualComparerExtensions
{
private readonly struct BoundComparer<T, TParam>(IComparer<T, TParam> comparer, TParam? context) : IComparer<T>
{
public int Compare(T? x, T? y)
{
return comparer.Compare(x, y, context);
}
}
/// <summary>
/// Binds a context parameter to a contextual comparer, returning a standard <see cref="IComparer{T}"/>.
/// </summary>
/// <typeparam name="T">The type of objects to compare.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
/// <param name="comparer">The contextual comparer.</param>
/// <param name="context">The context to bind to the comparer.</param>
/// <returns>A standard comparer that implicitly uses the provided context.</returns>
/// <exception cref="ArgumentNullException"><paramref name="comparer"/> is null.</exception>
public static IComparer<T> Bind<T, TParam>(this IComparer<T, TParam> comparer, TParam? context)
{
ArgumentNullException.ThrowIfNull(comparer);
return new BoundComparer<T, TParam>(comparer, context);
}
/// <summary>
/// Sorts the elements in the entire <see cref="List{T}"/> using the specified contextual comparer and context.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
/// <param name="list">The list to sort.</param>
/// <param name="comparer">The contextual comparer to use when comparing elements.</param>
/// <param name="context">The context to aid in the comparison.</param>
/// <exception cref="ArgumentNullException"><paramref name="list"/> or <paramref name="comparer"/> is null.</exception>
public static void Sort<T, TParam>(this List<T> list, IComparer<T, TParam> comparer, TParam? context)
{
ArgumentNullException.ThrowIfNull(list);
list.Sort(comparer.Bind(context));
}
/// <summary>
/// Sorts the elements in an entire one-dimensional array using the specified contextual comparer and context.
/// </summary>
/// <typeparam name="T">The type of elements in the array.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
/// <param name="array">The one-dimensional array to sort.</param>
/// <param name="comparer">The contextual comparer to use when comparing elements.</param>
/// <param name="context">The context to aid in the comparison.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> or <paramref name="comparer"/> is null.</exception>
public static void Sort<T, TParam>(this T[] array, IComparer<T, TParam> comparer, TParam? context)
{
ArgumentNullException.ThrowIfNull(array);
Array.Sort(array, comparer.Bind(context));
}
/// <summary>
/// Searches the entire sorted <see cref="List{T}"/> for an element using the specified contextual comparer and context,
/// and returns the zero-based index of the element.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
/// <param name="list">The sorted list to search.</param>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <param name="comparer">The contextual comparer to use when comparing elements.</param>
/// <param name="context">The context to aid in the comparison.</param>
/// <returns>
/// The zero-based index of item in the sorted list, if item is found; otherwise, a negative number that is the
/// bitwise complement of the index of the next element that is larger than item or, if there is no larger element,
/// the bitwise complement of Count.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="list"/> or <paramref name="comparer"/> is null.</exception>
public static int BinarySearch<T, TParam>(this List<T> list, T item, IComparer<T, TParam> comparer, TParam? context)
{
ArgumentNullException.ThrowIfNull(list);
return list.BinarySearch(item, comparer.Bind(context));
}
/// <summary>
/// Searches an entire one-dimensional sorted array for a specific element using the specified contextual comparer and context.
/// </summary>
/// <typeparam name="T">The type of elements in the array.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
/// <param name="array">The sorted one-dimensional array to search.</param>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <param name="comparer">The contextual comparer to use when comparing elements.</param>
/// <param name="context">The context to aid in the comparison.</param>
/// <returns>
/// The index of the specified value in the specified array, if value is found; otherwise, a negative number.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="array"/> or <paramref name="comparer"/> is null.</exception>
public static int BinarySearch<T, TParam>(this T[] array, T item, IComparer<T, TParam> comparer, TParam? context)
{
ArgumentNullException.ThrowIfNull(array);
return Array.BinarySearch(array, item, comparer.Bind(context));
}
/// <summary>
/// Sorts the elements of a sequence in ascending order according to a key and a contextual comparer.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
/// <param name="source">A sequence of values to order.</param>
/// <param name="keySelector">A function to extract a key from an element.</param>
/// <param name="comparer">The contextual comparer to compare keys.</param>
/// <param name="context">The context to aid in the comparison.</param>
/// <returns>An <see cref="IOrderedEnumerable{TElement}"/> whose elements are sorted according to a key.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/>, <paramref name="keySelector"/>, or <paramref name="comparer"/> is null.</exception>
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey, TParam>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey, TParam> comparer,
TParam? context)
{
return source.OrderBy(keySelector, comparer.Bind(context));
}
/// <summary>
/// Sorts the elements of a sequence in descending order according to a key and a contextual comparer.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
/// <param name="source">A sequence of values to order.</param>
/// <param name="keySelector">A function to extract a key from an element.</param>
/// <param name="comparer">The contextual comparer to compare keys.</param>
/// <param name="context">The context to aid in the comparison.</param>
/// <returns>An <see cref="IOrderedEnumerable{TElement}"/> whose elements are sorted in descending order according to a key.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/>, <paramref name="keySelector"/>, or <paramref name="comparer"/> is null.</exception>
public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey, TParam>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey, TParam> comparer,
TParam? context)
{
return source.OrderByDescending(keySelector, comparer.Bind(context));
}
/// <summary>
/// Performs a subsequent ordering of the elements in a sequence in ascending order according to a key and a contextual comparer.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
/// <param name="source">An <see cref="IOrderedEnumerable{TElement}"/> that contains elements to sort.</param>
/// <param name="keySelector">A function to extract a key from an element.</param>
/// <param name="comparer">The contextual comparer to compare keys.</param>
/// <param name="context">The context to aid in the comparison.</param>
/// <returns>An <see cref="IOrderedEnumerable{TElement}"/> whose elements are sorted according to a key.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/>, <paramref name="keySelector"/>, or <paramref name="comparer"/> is null.</exception>
public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey, TParam>(
this IOrderedEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey, TParam> comparer,
TParam? context)
{
return source.ThenBy(keySelector, comparer.Bind(context));
}
/// <summary>
/// Performs a subsequent ordering of the elements in a sequence in descending order, according to a key and a contextual comparer.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>
/// <typeparam name="TParam">The type of the context.</typeparam>
/// <param name="source">An <see cref="IOrderedEnumerable{TElement}"/> that contains elements to sort.</param>
/// <param name="keySelector">A function to extract a key from an element.</param>
/// <param name="comparer">The contextual comparer to compare keys.</param>
/// <param name="context">The context to aid in the comparison.</param>
/// <returns>An <see cref="IOrderedEnumerable{TElement}"/> whose elements are sorted in descending order according to a key.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/>, <paramref name="keySelector"/>, or <paramref name="comparer"/> is null.</exception>
public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey, TParam>(
this IOrderedEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey, TParam> comparer,
TParam? context)
{
return source.ThenByDescending(keySelector, comparer.Bind(context));
}
}
+12
View File
@@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
@@ -937,4 +938,15 @@ public static class Extensions
result = obj.TryCast<T>();
return result != null;
}
/// <summary>
/// Checks if a field is auto-generated by the compiler.
/// </summary>
/// <param name="field">The <see cref="FieldInfo"/> to check.</param>
/// <returns>true if the field was auto-generated; otherwise false.</returns>
public static bool IsAutoPropertyBackingField(this FieldInfo field)
{
return field.IsDefined<CompilerGeneratedAttribute>(false) &&
field.Name.Contains(">k__BackingField", StringComparison.Ordinal);
}
}
+25 -10
View File
@@ -31,6 +31,12 @@ internal readonly record struct AdvancedSettingsRow(string Title, string Value,
/// </summary>
public static class Helpers
{
[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 const BindingFlags StaticInstanceFlags = BindingFlags.Static | BindingFlags.NonPublic;
internal const float MatchInfoGuideBaseScale = 1.3f;
private static NumberOption? _advancedSettingsRowPrefab;
@@ -435,6 +441,17 @@ public static class Helpers
];
}
private static readonly Comparer<PlayerControl, Vector2> PlayerPosComparer = Comparer<PlayerControl, Vector2>.Create((a, b, source) =>
{
var magnitude2 = (a!.GetTruePosition() - source).sqrMagnitude;
var magnitude3 = (b!.GetTruePosition() - source).sqrMagnitude;
return magnitude2 > magnitude3
? 1
: magnitude2 < magnitude3
? -1
: 0;
});
/// <summary>
/// Gets the closest <see cref="PlayerControl"/>s to a specific <see cref="PlayerControl"/>.
/// </summary>
@@ -493,16 +510,7 @@ public static class Helpers
Constants.ShipAndObjectsMask))
select playerControl);
outputList.Sort((a, b) =>
{
var magnitude2 = (a.GetTruePosition() - source).magnitude;
var magnitude3 = (b.GetTruePosition() - source).magnitude;
return magnitude2 > magnitude3
? 1
: magnitude2 < magnitude3
? -1
: 0;
});
outputList.Sort(PlayerPosComparer, source);
return outputList;
}
@@ -1254,4 +1262,11 @@ public static class Helpers
panel.roleCount.fontMaterial.SetFloat(panel.STENCIL_NAME, 50f);
panel.roleIcon.transform.localScale = new Vector3(3.5f, 3.5f, 1f);
}
internal static void SetInstance(Type openGeneric, Type typeParam, object value)
{
openGeneric.MakeGenericType(typeParam)
.GetField("_instance", StaticInstanceFlags)! // Suppression message refers to this
.SetValue(null, value);
}
}