Merge branch 'dev' into 2025.3.25

This commit is contained in:
XtraCube committed 2025-04-05 14:32:26 -04:00
commit a3fc847d07
15 files changed
+277 -133

No files matched your search

+25 -21
View File
@@ -21,7 +21,7 @@ public static class MiraEventManager
public static bool InvokeEvent<T>(T eventInstance) where T : MiraEvent
{
EventWrappers.TryGetValue(typeof(T), out var handlers);
if (handlers == null)
if (handlers == null || handlers.Count == 0)
{
return false;
}
@@ -43,7 +43,7 @@ public static class MiraEventManager
public static bool InvokeEvent(MiraEvent eventInstance, Type type)
{
EventWrappers.TryGetValue(type, out var handlers);
if (handlers == null)
if (handlers == null || handlers.Count == 0)
{
return false;
}
@@ -61,47 +61,51 @@ public static class MiraEventManager
/// </summary>
/// <param name="type">The type of event.</param>
/// <param name="methodInfo">The MethodInfo of the event handler.</param>
/// <param name="priority">The priority of the event handler. Higher values are called first.</param>
/// <param name="priority">The priority of the event handler. Lower values are called first.</param>
public static void RegisterEventHandler(Type type, MethodInfo methodInfo, int priority = 0)
{
if (!type.IsSubclassOf(typeof(MiraEvent)))
{
Logger<MiraApiPlugin>.Error($"Type must be a subclass of MiraEvent: {nameof(type)}");
Logger<MiraApiPlugin>.Error($"Type must be a subclass of MiraEvent: {type.FullName}");
return;
}
if (!EventWrappers.TryGetValue(type, out var handlers))
{
handlers = [];
EventWrappers.Add(type, handlers);
}
EventWrappers.TryAdd(type, []);
var handlers = EventWrappers[type];
var @delegate = Delegate.CreateDelegate(typeof(Action<>).MakeGenericType(type), methodInfo);
handlers.Add(new MiraEventWrapper(@delegate, priority));
var eventWrapper = new MiraEventWrapper(@delegate, priority);
var index = handlers.BinarySearch(eventWrapper, Comparer<MiraEventWrapper>.Create((a, b) => a.Priority.CompareTo(b.Priority)));
if (index < 0)
{
index = ~index;
}
handlers.Insert(index, eventWrapper);
}
/// <summary>
/// Register an event.
/// </summary>
/// <param name="handler">The callback method/handler for the event.</param>
/// <param name="priority">The priority of the event handler. Higher values are called first.</param>
/// <param name="priority">The priority of the event handler. Lower values are called first.</param>
/// <typeparam name="T">Type of event.</typeparam>
public static void RegisterEventHandler<T>(Action<T> handler, int priority = 0) where T : MiraEvent
{
if (!EventWrappers.ContainsKey(typeof(T)))
{
EventWrappers.Add(typeof(T), []);
}
EventWrappers.TryAdd(typeof(T), []);
var handlers = EventWrappers[typeof(T)];
handlers.Add(new MiraEventWrapper(handler, priority));
}
var eventWrapper = new MiraEventWrapper(handler, priority);
internal static void SortAllHandlers()
{
foreach (var handlers in EventWrappers.Values)
var index = handlers.BinarySearch(eventWrapper, Comparer<MiraEventWrapper>.Create((a, b) => a.Priority.CompareTo(b.Priority)));
if (index < 0)
{
handlers.Sort((a, b) => a.Priority.CompareTo(b.Priority));
index = ~index;
}
handlers.Insert(index, eventWrapper);
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ public class MiraEventWrapper
public Delegate EventHandler { get; }
/// <summary>
/// Gets the priority of the handler. Higher values are called first.
/// Gets the priority of the handler. Lower values are called first.
/// </summary>
public int Priority { get; }
+2 -2
View File
@@ -9,14 +9,14 @@ namespace MiraAPI.Events;
public class RegisterEventAttribute : Attribute
{
/// <summary>
/// Gets the priority of the event.
/// Gets the priority of the event. Lower values are called first.
/// </summary>
public int Priority { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEventAttribute"/> class.
/// </summary>
/// <param name="priority">The priority of the event.</param>
/// <param name="priority">The priority of the event. Lower values are called first.</param>
public RegisterEventAttribute(int priority = 0)
{
Priority = priority;
+24 -18
View File
@@ -417,9 +417,12 @@ public abstract class CustomActionButton
/// <param name="playerControl">The local PlayerControl.</param>
public virtual void FixedUpdateHandler(PlayerControl playerControl)
{
if (Timer >= 0 && !TimerPaused)
if (Timer >= 0)
{
Timer -= Time.deltaTime;
if (!TimerPaused)
{
Timer -= Time.deltaTime;
}
}
else if (HasEffect && EffectActive)
{
@@ -428,25 +431,28 @@ public abstract class CustomActionButton
OnEffectEnd();
}
if (CanUse())
if (Button)
{
Button?.SetEnabled();
}
else
{
Button?.SetDisabled();
}
if (CanUse())
{
Button.SetEnabled();
}
else
{
Button.SetDisabled();
}
if (EffectActive)
{
Button?.SetFillUp(Timer, EffectDuration);
if (EffectActive)
{
Button.SetFillUp(Timer, EffectDuration);
Button!.cooldownTimerText.text = Mathf.CeilToInt(Timer).ToString(NumberFormatInfo.InvariantInfo);
Button!.cooldownTimerText.gameObject.SetActive(true);
}
else
{
Button?.SetCoolDown(Timer, Cooldown);
Button.cooldownTimerText.text = Mathf.CeilToInt(Timer).ToString(NumberFormatInfo.InvariantInfo);
Button.cooldownTimerText.gameObject.SetActive(true);
}
else
{
Button.SetCoolDown(Timer, Cooldown);
}
}
FixedUpdate(playerControl);
+12 -3
View File
@@ -1,4 +1,6 @@
using BepInEx.Unity.IL2CPP;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using BepInEx.Unity.IL2CPP;
namespace MiraAPI;
@@ -13,7 +15,14 @@ public static class ModCompatibility
public const string SubmergedId = "Submerged";
/// <summary>
/// Gets a value indicating whether the Submerged mod is loaded.
/// Checks if the Submerged mod is loaded.
/// </summary>
public static bool SubmergedLoaded => IL2CPPChainloader.Instance.Plugins.TryGetValue(SubmergedId, out _);
/// <param name="submergedAssembly">Submerged mod assembly if loaded, null otherwise.</param>
/// <returns>True if the Submerged mod is loaded, false otherwise.</returns>
public static bool SubmergedLoaded([NotNullWhen(true)] out Assembly? submergedAssembly)
{
var result = IL2CPPChainloader.Instance.Plugins.TryGetValue(SubmergedId, out var plugin);
submergedAssembly = result ? plugin?.Instance.GetType().Assembly : null;
return result;
}
}
+62 -3
View File
@@ -67,14 +67,18 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
private void FixedUpdate()
{
var removed = _toRemove.Count > 0;
foreach (var modifier in _toRemove.ToArray())
{
_toRemove.Remove(modifier);
modifier.OnDeactivate();
Modifiers.Remove(modifier);
}
var added = _toAdd.Count > 0;
foreach (var modifier in _toAdd.ToArray())
{
_toAdd.Remove(modifier);
Modifiers.Add(modifier);
modifier.Initialized = true;
modifier.OnActivate();
@@ -85,14 +89,12 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
}
}
if (_toAdd.Count > 0 || _toRemove.Count > 0)
if (removed || added)
{
if (_player.AmOwner && HudManager.InstanceExists)
{
HudManager.Instance.SetHudActive(_player, _player.Data.Role, HudManager.Instance.TaskPanel.isActiveAndEnabled);
}
_toAdd.Clear();
_toRemove.Clear();
ActiveModifiers = Modifiers.ToImmutableList();
}
@@ -507,4 +509,61 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
{
return ActiveModifiers.Exists(x => x.UniqueId == id);
}
/// <summary>
/// Checks if a player has an active modifier by its type.
/// </summary>
/// <param name="checkInactive">Whether to check inactive modifiers (those pending to be added).</param>
/// <param name="predicate">The predicate to check the modifier.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>True if the Modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier<T>(bool checkInactive, Func<T, bool>? predicate=null) where T : BaseModifier
{
return ActiveModifiers.Exists(MatchExpr) || (checkInactive && _toAdd.Exists(MatchExpr));
bool MatchExpr(BaseModifier bm) => bm is T modifier && (predicate == null || predicate(modifier));
}
/// <summary>
/// Checks if a player has an active modifier by its type.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="checkInactive">Whether to check inactive modifiers (those pending to be added).</param>
/// <param name="predicate">The predicate to check the modifier.</param>
/// <returns>True if the Modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier(Type type, bool checkInactive, Func<BaseModifier, bool>? predicate=null)
{
return ActiveModifiers.Exists(MatchExpr) || (checkInactive && _toAdd.Exists(MatchExpr));
bool MatchExpr(BaseModifier bm) => bm.GetType() == type && (predicate == null || predicate(bm));
}
/// <summary>
/// Checks if a player has an active modifier by its type ID.
/// </summary>
/// <param name="id">The modifier's type ID.</param>
/// <param name="checkInactive">Whether to check inactive modifiers (those pending to be added).</param>
/// <param name="predicate">The predicate to check the modifier.</param>
/// <returns>True if the modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier(uint id, bool checkInactive, Func<BaseModifier, bool>? predicate=null)
{
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
$"Cannot get modifier with id {id} because it is not registered.");
return HasModifier(type, checkInactive, predicate);
}
/// <summary>
/// Checks if a player has an active modifier by its unique ID.
/// </summary>
/// <param name="id">The modifier's guid.</param>
/// <param name="checkInactive">Whether to check inactive modifiers (those pending to be added).</param>
/// <returns>True if the modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier(Guid id, bool checkInactive)
{
return ActiveModifiers.Exists(MatchExpr) || (checkInactive && _toAdd.Exists(MatchExpr));
bool MatchExpr(BaseModifier bm) => bm.UniqueId == id;
}
}
+11 -11
View File
@@ -180,6 +180,17 @@ public static class ModifierExtensions
return player.GetModifierComponent().HasModifier(typeId, predicate);
}
/// <summary>
/// Checks if the player has a specific modifier by its GUID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="uniqueId">The unique ID of the modifier.</param>
/// <returns>True if the player has the modifier, false otherwise.</returns>
public static bool HasModifier(this PlayerControl player, Guid uniqueId)
{
return player.GetModifierComponent().HasModifier(uniqueId);
}
/// <summary>
/// Clears all modifiers from a player.
/// </summary>
@@ -204,17 +215,6 @@ public static class ModifierExtensions
}
}
/// <summary>
/// Checks if the player has a specific modifier by its GUID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="uniqueId">The unique ID of the modifier.</param>
/// <returns>True if the player has the modifier, false otherwise.</returns>
public static bool HasModifier(this PlayerControl player, Guid uniqueId)
{
return player.GetModifierComponent().HasModifier(uniqueId);
}
/// <summary>
/// Tries to get a modifier by its type.
/// </summary>
+39 -50
View File
@@ -103,68 +103,57 @@ public static class ModifierManager
{
var rand = new Random();
foreach (var priority in PrioritiesToIdsMap.Keys.OrderByDescending(x => x))
// Filter and sort modifiers by descending priority.
var modifiers = IdToTypeModifierMap
.Where(x=>x.Value.IsAssignableTo(typeof(GameModifier)))
.Select(x => Activator.CreateInstance(x.Value) as GameModifier)
.OfType<GameModifier>()
.Where(x => x.GetAmountPerGame() > 0 && x.GetAssignmentChance() > 0)
.OrderByDescending(x => x.Priority())
.ToArray();
foreach (var modifier in modifiers)
{
var filteredModifiers = new List<uint>();
var assignments = modifier.GetAmountPerGame();
foreach (var id in PrioritiesToIdsMap[priority])
var validPlayers = plrs.Where(x => IsGameModifierValid(x, modifier, modifier.TypeId)).ToList();
if (validPlayers.Count == 0)
{
var mod = Activator.CreateInstance(IdToTypeModifierMap[id]) as GameModifier;
var chance = Math.Clamp(mod!.GetAssignmentChance(), 0, 100);
var count = mod.GetAmountPerGame();
if (chance == 0 || count == 0)
{
continue;
}
var maxCount = plrs.Count(x => IsGameModifierValid(x, mod, id));
if (maxCount == 0)
{
Logger<MiraApiPlugin>.Warning($"No players are valid for {mod.ModifierName}");
continue;
}
var num = Math.Clamp(count, 0, maxCount);
for (var i = 0; i < num; i++)
{
var randomNum = rand.Next(100);
if (randomNum < chance)
{
filteredModifiers.Add(id);
}
}
}
if (filteredModifiers.Count == 0)
{
Logger<MiraApiPlugin>.Warning($"No filtered modifiers for priority {priority}");
Logger<MiraApiPlugin>.Warning($"No valid players for modifier {modifier.ModifierName}");
continue;
}
var shuffledList = filteredModifiers.Randomize();
assignments = Math.Min(assignments, validPlayers.Count);
var availablePlayers = new List<PlayerControl>(validPlayers);
if (shuffledList.Count > plrs.Count)
for (var i = 0; i < assignments; i++)
{
shuffledList = shuffledList.GetRange(0, plrs.Count);
}
foreach (var id in shuffledList)
{
var mod = Activator.CreateInstance(IdToTypeModifierMap[id]) as GameModifier;
var plr = plrs.Where(x => IsGameModifierValid(x, mod!, id)).Random();
if (!plr || plr == null)
var chance = Math.Clamp(modifier.GetAssignmentChance(), 0, 100);
if (rand.Next(100) >= chance)
{
Logger<MiraApiPlugin>.Warning($"Somehow valid players for modifier {mod!.ModifierName} disappeared");
continue;
}
else
var candidates = availablePlayers
.Where(x => IsGameModifierValid(x, modifier, modifier.TypeId))
.ToList();
if (candidates.Count == 0)
{
plr.RpcAddModifier(id);
Logger<MiraApiPlugin>.Warning(
$"No available players for modifier {modifier.ModifierName} at assignment {i + 1}");
break;
}
var plr = candidates.Random();
if (plr == null)
{
Logger<MiraApiPlugin>.Warning($"Valid player for modifier {modifier.ModifierName} disappeared");
continue;
}
plr.RpcAddModifier(modifier.TypeId);
availablePlayers.Remove(plr);
}
}
}
@@ -0,0 +1,15 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
namespace MiraAPI.Patches.Events;
[HarmonyPatch(typeof(SpawnInMinigame), nameof(SpawnInMinigame.Close))]
internal static class SpawnInMinigamePatch
{
public static void Postfix()
{
var @event = new RoundStartEvent(false);
MiraEventManager.InvokeEvent(@event);
}
}
@@ -0,0 +1,31 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
namespace MiraAPI.Patches.Events;
[HarmonyPatch]
internal static class SubmergedSpawnGamePatch
{
public static bool Prepare()
{
return ModCompatibility.SubmergedLoaded(out _);
}
public static IEnumerable<MethodBase> TargetMethods()
{
if (ModCompatibility.SubmergedLoaded(out var subAss) &&
subAss.GetType("Submerged.SpawnIn.SubmarineSelectSpawn") is { } selectSpawn)
{
yield return AccessTools.Method(selectSpawn, "OnDestroy");
}
}
public static void Postfix()
{
var @event = new RoundStartEvent(false);
MiraEventManager.InvokeEvent(@event);
}
}
@@ -2,13 +2,15 @@
using HarmonyLib;
using MiraAPI.Modifiers;
using MiraAPI.Modifiers.Types;
using MiraAPI.Utilities;
using Reactor.Utilities;
namespace MiraAPI.Patches.Modifiers;
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CoEndGame))]
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnGameEnd))]
public static class EndGameDidWinPatch
{
public static void Prefix()
public static void Postfix()
{
var gameOverReason = EndGameResult.CachedGameOverReason;
EndGameResult.CachedWinners.Clear();
@@ -17,18 +19,26 @@ public static class EndGameDidWinPatch
for (var i = 0; i < GameData.Instance.PlayerCount; i++)
{
var networkedPlayerInfo = players[i];
if (networkedPlayerInfo == null)
if (!networkedPlayerInfo)
{
continue;
}
var didWin = networkedPlayerInfo.Role.DidWin(gameOverReason);
var modifierWin = networkedPlayerInfo.Object?.GetModifierComponent().GetModifiers<GameModifier>()
.FirstOrDefault(x => x.DidWin(gameOverReason) != null)?.DidWin(gameOverReason);
if (modifierWin != null)
bool? modifierDidWin = null;
foreach (var modifier in networkedPlayerInfo.Object.GetModifiers<GameModifier>().OrderByDescending(x => x.Priority()))
{
didWin = modifierWin.Value;
var result = modifier.DidWin(gameOverReason);
if (!result.HasValue) continue;
modifierDidWin = result.Value;
break;
}
if (modifierDidWin.HasValue)
{
didWin = modifierDidWin.Value;
}
if (didWin)
+3 -13
View File
@@ -12,7 +12,7 @@ namespace MiraAPI.Patches.Roles;
/// Patches for custom ejection messages.
/// </summary>
[HarmonyPatch(typeof(ExileController))]
public static class EjectionPatches
internal static class EjectionPatches
{
[HarmonyPostfix]
[HarmonyPatch(nameof(ExileController.Begin))]
@@ -35,19 +35,9 @@ public static class EjectionPatches
__instance.completeString = role.GetCustomEjectionMessage(__instance.initData.networkedPlayer);
}
[HarmonyPatch]
internal static class WrapUpPatch
[HarmonyPatch(typeof(ExileController), nameof(ExileController.WrapUp))]
public static class WrapUpPatch
{
public static IEnumerable<MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(ExileController), nameof(ExileController.WrapUp));
yield return AccessTools.Method(typeof(AirshipExileController), nameof(AirshipExileController.WrapUpAndSpawn));
if (ModCompatibility.SubmergedLoaded && AccessTools.TypeByName("Submerged.ExileCutscene.SubmergedExileController") is { } type)
{
yield return AccessTools.Method(type, "WrapUpAndSpawn");
}
}
public static void Postfix()
{
var @event = new RoundStartEvent(false);
+34 -2
View File
@@ -35,24 +35,56 @@ internal static class MeetingHudPatches
modifier.OnMeetingStart();
}
}
var @event = new StartMeetingEvent(__instance);
MiraEventManager.InvokeEvent(@event);
}
[HarmonyPostfix]
[HarmonyPatch(nameof(MeetingHud.OnDestroy))]
public static void MeetingHudOnDestroyPatch(MeetingHud __instance)
public static void OnDestroyPatch(MeetingHud __instance)
{
MiraEventManager.InvokeEvent(new EndMeetingEvent(__instance));
}
[HarmonyPostfix]
[HarmonyPatch(nameof(MeetingHud.VotingComplete))]
public static void MeetingHudVotingCompletePatch(MeetingHud __instance)
public static void VotingCompletePatch(MeetingHud __instance)
{
MiraEventManager.InvokeEvent(new VotingCompleteEvent(__instance));
}
// this is necessary because the actual ForceSkipAll method is inlined.
[HarmonyPrefix]
[HarmonyPatch(nameof(MeetingHud.Update))]
public static void ForceSkipPatch(MeetingHud __instance)
{
if (__instance.state is not (MeetingHud.VoteStates.NotVoted or MeetingHud.VoteStates.Voted))
{
return;
}
var logicOptionsNormal = GameManager.Instance.LogicOptions.Cast<LogicOptionsNormal>();
var votingTime = logicOptionsNormal.GetVotingTime();
if (votingTime <= 0)
{
return;
}
var num2 = __instance.discussionTimer - logicOptionsNormal.GetDiscussionTime();
if (!AmongUsClient.Instance.AmHost || num2 < votingTime)
{
return;
}
foreach (var plr in PlayerControl.AllPlayerControls)
{
var voteData = plr.GetVoteData();
voteData.SetRemainingVotes(0);
}
}
[HarmonyPrefix]
[HarmonyPatch(nameof(MeetingHud.Select))]
public static bool SelectPatch(MeetingHud __instance, int suspectStateIdx)
@@ -109,7 +109,6 @@ public sealed class MiraPluginManager
Logger<MiraApiPlugin>.Info($"Registering mod {pluginInfo.Metadata.GUID} with Mira API.");
};
IL2CPPChainloader.Instance.Finished += PaletteManager.RegisterAllColors;
IL2CPPChainloader.Instance.Finished += MiraEventManager.SortAllHandlers;
IL2CPPChainloader.Instance.Finished += () =>
{
CustomButtonManager.Buttons = new ReadOnlyCollection<CustomActionButton>(CustomButtonManager.CustomButtons);
+1 -1
View File
@@ -19,7 +19,7 @@ public static class Helpers
/// <returns>A list of alive players.</returns>
public static List<PlayerControl> GetAlivePlayers()
{
return PlayerControl.AllPlayerControls.ToArray().Where(x => !x.Data.IsDead).ToList();
return [.. GameData.Instance.AllPlayers.ToArray().Where(x => !x.IsDead && !x.Disconnected && x.Object).Select(x=>x.Object)];
}
/// <summary>