mirror of
https://github.com/All-Of-Us-Mods/MiraAPI.git
synced 2026-10-20 01:46:15 +00:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d1d1891a8 | ||
|
|
531a799a24 | ||
|
|
3e6eb49d93 | ||
|
|
a3fc847d07 | ||
|
|
ddfad0752d | ||
|
|
f1846375ca | ||
|
|
fcb693e899 | ||
|
|
21bec074fa | ||
|
|
31ffe6274c | ||
|
|
aef4d6daf1 | ||
|
|
bd0aa68cb8 | ||
|
|
f43a542134 | ||
|
|
efd176f7a4 | ||
|
|
b2fabdb139 | ||
|
|
3a36acd131 | ||
|
|
8c763e2a57 | ||
|
|
ce330325e4 | ||
|
|
89cd32d4a4 | ||
|
|
f0e37daf0e | ||
|
|
a5ddec48c8 | ||
|
|
5f4461f7e5 | ||
|
|
5e2ca191ba | ||
|
|
a0d3afc7c7 | ||
|
|
3cd7acbc70 | ||
|
|
31132e6e65 | ||
|
|
1a53e2b045 | ||
|
|
be46ee7329 | ||
|
|
75a15dc090 | ||
|
|
cffb104392 |
No files matched your search
+2
-2
@@ -2,10 +2,10 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Reactor" Version="2.3.1" />
|
||||
<PackageReference Include="BepInEx.Unity.IL2CPP" Version="6.0.0-be.697" Private="false" ExcludeAssets="runtime;native" />
|
||||
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2024.10.29" PrivateAssets="all" />
|
||||
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2025.3.25" PrivateAssets="all" />
|
||||
|
||||
<PackageReference Include="BepInEx.AutoPlugin" Version="1.1.0" PrivateAssets="all" />
|
||||
<PackageReference Include="BepInEx.IL2CPP.MSBuild" Version="2.0.1" PrivateAssets="all" ExcludeAssets="runtime" />
|
||||
<PackageReference Include="BepInEx.IL2CPP.MSBuild" Version="2.1.0-rc.1" PrivateAssets="all" ExcludeAssets="runtime" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="Copy" AfterTargets="Build" Condition="'$(AmongUs)' != ''">
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556" PrivateAssets="all" />
|
||||
<AdditionalFiles Include="$(MSBuildThisFileDirectory)\stylecop.json" Link="stylecop.json" Visible="false" />
|
||||
|
||||
<PackageReference Include="SonarAnalyzer.CSharp" Version="9.32.0.97167">
|
||||
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.7.0.110445">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
</PackageReference>
|
||||
|
||||
@@ -9,10 +9,7 @@ using MiraAPI.Events.Vanilla.Player;
|
||||
using MiraAPI.Example.Buttons.Freezer;
|
||||
using MiraAPI.Example.Roles;
|
||||
using MiraAPI.Utilities;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using Reactor.Utilities;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Example;
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using AmongUs.GameOptions;
|
||||
using MiraAPI.Roles;
|
||||
using Reactor.Utilities;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
|
||||
@@ -19,6 +20,12 @@ public class ChameloenRole : CrewmateRole, ICustomRole
|
||||
IntroSound = CustomRoleUtils.GetIntroSound(RoleTypes.Shapeshifter),
|
||||
};
|
||||
|
||||
public override void Initialize(PlayerControl player)
|
||||
{
|
||||
Player = player;
|
||||
Logger<ExamplePlugin>.Error("Initializing ChamelonRole for player: " + player.PlayerId);
|
||||
}
|
||||
|
||||
public void PlayerControlFixedUpdate(PlayerControl playerControl)
|
||||
{
|
||||
if (playerControl.MyPhysics.Velocity.magnitude > 0)
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace MiraAPI.Events.Vanilla.Gameplay;
|
||||
|
||||
/// <summary>
|
||||
/// The event that is invoked when the intro cutscene has finished playing.
|
||||
/// </summary>
|
||||
public class IntroEndEvent(IntroCutscene introCutscene) : MiraEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the instance of the IntroCutscene.
|
||||
/// </summary>
|
||||
public IntroCutscene IntroCutscene { get; } = introCutscene;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace MiraAPI.Events.Vanilla.Gameplay;
|
||||
|
||||
/// <summary>
|
||||
/// Start Round event, invoked on IntroCutscene.OnDestroy and ExileController.WrapUp.
|
||||
/// </summary>
|
||||
public class RoundStartEvent : MiraEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the event was triggered by the IntroCutscene or ExileController.
|
||||
/// </summary>
|
||||
public bool TriggeredByIntro { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RoundStartEvent"/> class.
|
||||
/// </summary>
|
||||
/// <param name="triggeredByIntro">Whether the event was triggered by the intro or not.</param>
|
||||
public RoundStartEvent(bool triggeredByIntro)
|
||||
{
|
||||
TriggeredByIntro = triggeredByIntro;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace MiraAPI.Events.Vanilla.Meeting;
|
||||
|
||||
/// <summary>
|
||||
/// The event that is invoked when the meeting has ended.
|
||||
/// </summary>
|
||||
public class EndMeetingEvent(MeetingHud meetingHud) : MiraEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the MeetingHud instance.
|
||||
/// </summary>
|
||||
public MeetingHud MeetingHud { get; } = meetingHud;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace MiraAPI.Events.Vanilla.Meeting.Voting;
|
||||
|
||||
/// <summary>
|
||||
/// The event that is invoked when the voting phase of a meeting is complete.
|
||||
/// </summary>
|
||||
/// <param name="meetingHud">The MeetingHud instance.</param>
|
||||
public class VotingCompleteEvent(MeetingHud meetingHud) : MiraEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the MeetingHud instance.
|
||||
/// </summary>
|
||||
public MeetingHud MeetingHud { get; } = meetingHud;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -16,6 +16,7 @@ namespace MiraAPI;
|
||||
[BepInAutoPlugin("mira.api", "MiraAPI")]
|
||||
[BepInProcess("Among Us.exe")]
|
||||
[BepInDependency(ReactorPlugin.Id)]
|
||||
[BepInDependency(ModCompatibility.SubmergedId, BepInDependency.DependencyFlags.SoftDependency)]
|
||||
[ReactorModFlags(ModFlags.RequireOnAllClients)]
|
||||
public partial class MiraApiPlugin : BasePlugin
|
||||
{
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using BepInEx.Unity.IL2CPP;
|
||||
|
||||
namespace MiraAPI;
|
||||
|
||||
/// <summary>
|
||||
/// Mod compatibility tools.
|
||||
/// </summary>
|
||||
public static class ModCompatibility
|
||||
{
|
||||
/// <summary>
|
||||
/// The ID for the Submerged mod.
|
||||
/// </summary>
|
||||
public const string SubmergedId = "Submerged";
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the Submerged mod is loaded.
|
||||
/// </summary>
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,13 @@ public abstract class BaseModifier : IOptionable
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when a meeting starts.
|
||||
/// </summary>
|
||||
public virtual void OnMeetingStart()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the player can vent.
|
||||
/// </summary>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using AmongUs.Data;
|
||||
using AmongUs.GameOptions;
|
||||
using Assets.CoreScripts;
|
||||
using BepInEx.Unity.IL2CPP.Utils;
|
||||
@@ -96,7 +97,7 @@ public static class CustomMurderRpc
|
||||
var flag = PlayerControl.LocalPlayer.Data.Role.Role == RoleTypes.GuardianAngel;
|
||||
if (flag && PlayerControl.LocalPlayer.Data.PlayerId == target.protectedByGuardianId)
|
||||
{
|
||||
StatsManager.Instance.IncrementStat(StringNames.StatsGuardianAngelCrewmatesProtected);
|
||||
DataManager.Player.Stats.IncrementStat(StatID.Role_GuardianAngel_CrewmatesProtected);
|
||||
AchievementManager.Instance.OnProtectACrewmate();
|
||||
}
|
||||
|
||||
@@ -127,14 +128,14 @@ public static class CustomMurderRpc
|
||||
DebugAnalytics.Instance.Analytics.Kill(target.Data, source.Data);
|
||||
if (source.AmOwner)
|
||||
{
|
||||
StatsManager.Instance.IncrementStat(
|
||||
DataManager.Player.Stats.IncrementStat(
|
||||
GameManager.Instance.IsHideAndSeek()
|
||||
? StringNames.StatsImpostorKills_HideAndSeek
|
||||
: StringNames.StatsImpostorKills);
|
||||
? StatID.HideAndSeek_ImpostorKills
|
||||
: StatID.ImpostorKills);
|
||||
|
||||
if (source.CurrentOutfitType == PlayerOutfitType.Shapeshifted)
|
||||
{
|
||||
StatsManager.Instance.IncrementStat(StringNames.StatsShapeshifterShiftedKills);
|
||||
DataManager.Player.Stats.IncrementStat(StatID.Role_Shapeshifter_ShiftedKills);
|
||||
}
|
||||
|
||||
if (Constants.ShouldPlaySfx() && playKillSound)
|
||||
@@ -152,7 +153,7 @@ public static class CustomMurderRpc
|
||||
target.gameObject.layer = LayerMask.NameToLayer("Ghost");
|
||||
if (target.AmOwner)
|
||||
{
|
||||
StatsManager.Instance.IncrementStat(StringNames.StatsTimesMurdered);
|
||||
DataManager.Player.Stats.IncrementStat(StatID.TimesMurdered);
|
||||
if (Minigame.Instance)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ namespace MiraAPI.Patches.Freeplay;
|
||||
[HarmonyPatch(typeof(TaskAdderGame))]
|
||||
internal static class TaskAdderPatches
|
||||
{
|
||||
private static Scroller? _scroller;
|
||||
private static Scroller _scroller = null!;
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(nameof(TaskAdderGame.Begin))]
|
||||
@@ -293,9 +293,9 @@ internal static class TaskAdderPatches
|
||||
chip.GetComponent<SpriteRenderer>().maskInteraction = SpriteMaskInteraction.VisibleInsideMask;
|
||||
}
|
||||
|
||||
if (_scroller && _scroller != null)
|
||||
if (_scroller)
|
||||
{
|
||||
_scroller.CalculateAndSetYBounds(__instance.ActiveItems.Count, 6, 3, 1f);
|
||||
_scroller.CalculateAndSetYBounds(__instance.ActiveItems.Count, 6, 5, 1.4f);
|
||||
_scroller.SetYBoundsMin(0.0f);
|
||||
_scroller.ScrollToTop();
|
||||
}
|
||||
|
||||
@@ -56,11 +56,11 @@ public static class IntroCutscenePatches
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(nameof(IntroCutscene.OnDestroy))]
|
||||
public static void GameBeginPatch()
|
||||
public static void GameBeginPatch(IntroCutscene __instance)
|
||||
{
|
||||
CustomGameModeManager.ActiveMode?.Initialize();
|
||||
}*/
|
||||
MiraEventManager.InvokeEvent(new IntroEndEvent(__instance));
|
||||
MiraEventManager.InvokeEvent(new RoundStartEvent(true));
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
using AmongUs.Data;
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Utilities;
|
||||
using Reactor.Utilities.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace MiraAPI.Patches.Menu;
|
||||
|
||||
[HarmonyPatch(typeof(HatsTab))]
|
||||
public static class HatsTabPatches
|
||||
{
|
||||
private static SortedList<string, List<HatData>> sortedHats = [];
|
||||
|
||||
[HarmonyPatch(nameof(HatsTab.OnEnable))]
|
||||
[HarmonyPrefix]
|
||||
public static bool OnEnablePrefix(HatsTab __instance)
|
||||
{
|
||||
__instance.currentHat = HatManager.Instance.GetHatById(DataManager.Player.Customization.Hat);
|
||||
var allHats = HatManager.Instance.GetUnlockedHats().ToImmutableList();
|
||||
|
||||
if (sortedHats.Count == 0)
|
||||
{
|
||||
var comparer = new ControllableComparer<string>(["vanilla"], [], StringComparer.InvariantCulture);
|
||||
sortedHats = new SortedList<string, List<HatData>>(comparer);
|
||||
foreach (var hat in allHats)
|
||||
{
|
||||
if (!sortedHats.ContainsKey(hat.StoreName)) sortedHats[hat.StoreName] = [];
|
||||
sortedHats[hat.StoreName].Add(hat);
|
||||
}
|
||||
}
|
||||
|
||||
GenerateHats(__instance);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void GenerateHats(HatsTab __instance)
|
||||
{
|
||||
foreach (ColorChip instanceColorChip in __instance.ColorChips) instanceColorChip.gameObject.Destroy();
|
||||
__instance.ColorChips.Clear();
|
||||
__instance.scroller.Inner.GetComponentsInChildren<TextMeshPro>().Do(x => x.gameObject.Destroy());
|
||||
|
||||
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
|
||||
|
||||
int hatIndex = 0;
|
||||
|
||||
foreach ((string groupName, List<HatData> hats) in sortedHats)
|
||||
{
|
||||
hatIndex = (hatIndex + 4) / 5 * 5; // yes it looks redundant, but consider hatindex = 0, symbolically it would be 4, the computer calculates 0.
|
||||
var text = Object.Instantiate(groupNameText, __instance.scroller.Inner);
|
||||
text.enabled = true;
|
||||
text.gameObject.transform.localScale = Vector3.one;
|
||||
text.GetComponent<TextTranslatorTMP>().Destroy();
|
||||
text.EnableStencilMasking();
|
||||
text.text = $"{groupName}";
|
||||
text.alignment = TextAlignmentOptions.Center;
|
||||
text.fontSize = 3f;
|
||||
text.fontSizeMax = 3f;
|
||||
text.fontSizeMin = 0f;
|
||||
float xLerp = __instance.XRange.Lerp(0.5f);
|
||||
float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
|
||||
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
|
||||
|
||||
hatIndex += 5;
|
||||
foreach (var hat in hats.OrderBy(HatManager.Instance.allHats.IndexOf))
|
||||
{
|
||||
float hatXposition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f));
|
||||
float hatYposition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
|
||||
GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), hat);
|
||||
hatIndex += 1;
|
||||
}
|
||||
}
|
||||
|
||||
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIndex + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
|
||||
__instance.currentHatIsEquipped = true;
|
||||
}
|
||||
|
||||
private static void GenerateColorChip(HatsTab __instance, Vector2 position, HatData hat)
|
||||
{
|
||||
var colorChip = Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
|
||||
colorChip.gameObject.name = hat.ProductId;
|
||||
colorChip.Button.OnClick.AddListener((Action)(() => __instance.ClickEquip()));
|
||||
colorChip.Button.OnMouseOver.AddListener((Action)(() => __instance.SelectHat(hat)));
|
||||
colorChip.Button.OnMouseOut.AddListener((Action)(() => __instance.SelectHat(HatManager.Instance.GetHatById(DataManager.Player.Customization.Hat))));
|
||||
colorChip.Inner.SetHat(hat, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color);
|
||||
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
|
||||
colorChip.SelectionHighlight.gameObject.SetActive(false);
|
||||
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, hat);
|
||||
colorChip.Inner.SetMaskType(PlayerMaterial.MaskType.SimpleUI);
|
||||
colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f);
|
||||
colorChip.Inner.transform.localPosition = hat.ChipOffset + new Vector2(0f, -0.3f);
|
||||
colorChip.Tag = hat;
|
||||
__instance.ColorChips.Add(colorChip);
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
|
||||
namespace MiraAPI.Patches.Menu;
|
||||
|
||||
/// <summary>
|
||||
/// General MainMenuManage patches.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(MainMenuManager))]
|
||||
public static class MainMenuManagerPatches
|
||||
{
|
||||
/// <summary>
|
||||
/// A postifix on Awake to load all the addressables registered.
|
||||
/// </summary>
|
||||
[HarmonyPatch(nameof(MainMenuManager.Awake))]
|
||||
[HarmonyPostfix]
|
||||
public static void AwakePostfix()
|
||||
{
|
||||
AddressablesLoader.LoadAll();
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
using AmongUs.Data;
|
||||
using HarmonyLib;
|
||||
using Innersloth.Assets;
|
||||
using MiraAPI.Utilities;
|
||||
using Reactor.Utilities.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace MiraAPI.Patches.Menu;
|
||||
|
||||
[HarmonyPatch(typeof(NameplatesTab))]
|
||||
public static class NameplatesTabPatches
|
||||
{
|
||||
private static readonly SortedList<string, List<NamePlateData>> SortedNameplates = new(new ControllableComparer<string>(["vanilla"], [], StringComparer.InvariantCulture));
|
||||
|
||||
internal static void AddRange(IEnumerable<(string Key, NamePlateData Visor)> data)
|
||||
{
|
||||
foreach (var item in data)
|
||||
{
|
||||
if (!SortedNameplates.ContainsKey(item.Key)) SortedNameplates.Add(item.Key, []);
|
||||
SortedNameplates[item.Key].Add(item.Visor);
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPatch(nameof(NameplatesTab.OnEnable))]
|
||||
[HarmonyPrefix]
|
||||
public static bool OnEnablePrefix(NameplatesTab __instance)
|
||||
{
|
||||
__instance.plateId = HatManager.Instance.GetNamePlateById(DataManager.Player.Customization.namePlate).ProdId;
|
||||
|
||||
if (!SortedNameplates.ContainsKey("Vanilla")) AddRange(DestroyableSingleton<HatManager>.Instance.GetUnlockedNamePlates().Select(x => ("Vanilla", x)));
|
||||
GenerateHats(__instance);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void GenerateHats(NameplatesTab __instance)
|
||||
{
|
||||
foreach (ColorChip instanceColorChip in __instance.ColorChips) instanceColorChip.gameObject.Destroy();
|
||||
__instance.ColorChips.Clear();
|
||||
__instance.scroller.Inner.GetComponentsInChildren<TextMeshPro>().Do(x => x.gameObject.Destroy());
|
||||
|
||||
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
|
||||
|
||||
int hatIndex = 0;
|
||||
|
||||
foreach ((string groupName, List<NamePlateData> visors) in SortedNameplates)
|
||||
{
|
||||
hatIndex = (hatIndex + 1) / 2 * 2; // yes it looks redundant, but consider hatindex = 0, symbolically it would be 4, the computer calculates 0.
|
||||
var text = Object.Instantiate(groupNameText, __instance.scroller.Inner);
|
||||
text.enabled = true;
|
||||
text.gameObject.transform.localScale = Vector3.one;
|
||||
text.GetComponent<TextTranslatorTMP>().Destroy();
|
||||
text.EnableStencilMasking();
|
||||
text.text = $"{groupName}";
|
||||
text.alignment = TextAlignmentOptions.Center;
|
||||
text.fontSize = 3f;
|
||||
text.fontSizeMax = 3f;
|
||||
text.fontSizeMin = 0f;
|
||||
float xLerp = __instance.XRange.Lerp(0.5f);
|
||||
float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
|
||||
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
|
||||
|
||||
hatIndex += 2;
|
||||
foreach (var visor in visors.OrderBy(HatManager.Instance.allNamePlates.IndexOf))
|
||||
{
|
||||
float hatXposition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f));
|
||||
float hatYposition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
|
||||
GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), visor);
|
||||
hatIndex += 1;
|
||||
}
|
||||
}
|
||||
|
||||
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIndex + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
|
||||
__instance.currentNameplateIsEquipped = true;
|
||||
}
|
||||
|
||||
private static void GenerateColorChip(NameplatesTab __instance, Vector2 position, NamePlateData namePlate)
|
||||
{
|
||||
var colorChip = Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
|
||||
colorChip.gameObject.name = namePlate.ProductId;
|
||||
colorChip.Button.OnClick.AddListener((Action)(() => __instance.ClickEquip()));
|
||||
colorChip.Button.OnMouseOver.AddListener((Action)(() => __instance.SelectNameplate(namePlate)));
|
||||
colorChip.Button.OnMouseOut.AddListener((Action)(() => __instance.SelectNameplate(HatManager.Instance.GetNamePlateById(DataManager.Player.Customization.NamePlate))));
|
||||
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
|
||||
colorChip.ProductId = namePlate.ProdId;
|
||||
|
||||
var x = (NamePlateViewData viewdata) =>
|
||||
{
|
||||
colorChip.transform.GetChild(1).GetComponent<SpriteRenderer>().sprite = viewdata?.Image;
|
||||
//(colorChip as NameplateChip).image.sprite = viewdata?.Image;
|
||||
};
|
||||
__instance.StartCoroutine(AddressableAssetExtensions.CoLoadAssetAsync<NamePlateViewData>(__instance, namePlate.GetAssetReference(), x));
|
||||
colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f);
|
||||
colorChip.Tag = namePlate;
|
||||
__instance.ColorChips.Add(colorChip);
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
using AmongUs.Data;
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Utilities;
|
||||
using Reactor.Utilities.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace MiraAPI.Patches.Menu;
|
||||
|
||||
[HarmonyPatch(typeof(SkinsTab))]
|
||||
public static class SkinsTabPatches
|
||||
{
|
||||
private static SortedList<string, List<SkinData>> sortedSkins = [];
|
||||
|
||||
[HarmonyPatch(nameof(SkinsTab.OnEnable))]
|
||||
[HarmonyPrefix]
|
||||
public static bool OnEnablePrefix(SkinsTab __instance)
|
||||
{
|
||||
__instance.skinId = HatManager.Instance.GetSkinById(DataManager.Player.Customization.Skin).ProdId;
|
||||
var allSkins = HatManager.Instance.GetUnlockedSkins().ToImmutableList();
|
||||
|
||||
if (sortedSkins.Count == 0)
|
||||
{
|
||||
var comparer = new ControllableComparer<string>(["vanilla"], [], StringComparer.InvariantCulture);
|
||||
sortedSkins = new SortedList<string, List<SkinData>>(comparer);
|
||||
foreach (var skin in allSkins)
|
||||
{
|
||||
if (!sortedSkins.ContainsKey(skin.StoreName)) sortedSkins[skin.StoreName] = [];
|
||||
sortedSkins[skin.StoreName].Add(skin);
|
||||
}
|
||||
}
|
||||
|
||||
GenerateHats(__instance);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void GenerateHats(SkinsTab __instance)
|
||||
{
|
||||
foreach (ColorChip instanceColorChip in __instance.ColorChips) instanceColorChip.gameObject.Destroy();
|
||||
__instance.ColorChips.Clear();
|
||||
__instance.scroller.Inner.GetComponentsInChildren<TextMeshPro>().Do(x => x.gameObject.Destroy());
|
||||
|
||||
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
|
||||
|
||||
int hatIndex = 0;
|
||||
|
||||
foreach ((string groupName, List<SkinData> skins) in sortedSkins)
|
||||
{
|
||||
hatIndex = (hatIndex + 4) / 5 * 5; // yes it looks redundant, but consider hatindex = 0, symbolically it would be 4, the computer calculates 0.
|
||||
var text = Object.Instantiate(groupNameText, __instance.scroller.Inner);
|
||||
text.enabled = true;
|
||||
text.gameObject.transform.localScale = Vector3.one;
|
||||
text.GetComponent<TextTranslatorTMP>().Destroy();
|
||||
text.EnableStencilMasking();
|
||||
text.text = $"{groupName}";
|
||||
text.alignment = TextAlignmentOptions.Center;
|
||||
text.fontSize = 3f;
|
||||
text.fontSizeMax = 3f;
|
||||
text.fontSizeMin = 0f;
|
||||
float xLerp = __instance.XRange.Lerp(0.5f);
|
||||
float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
|
||||
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
|
||||
|
||||
hatIndex += 5;
|
||||
foreach (var skin in skins.OrderBy(HatManager.Instance.allSkins.IndexOf))
|
||||
{
|
||||
float hatXposition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f));
|
||||
float hatYposition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
|
||||
GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), skin);
|
||||
hatIndex += 1;
|
||||
}
|
||||
}
|
||||
|
||||
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIndex + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
|
||||
__instance.currentSkinIsEquipped = true;
|
||||
}
|
||||
|
||||
private static void GenerateColorChip(SkinsTab __instance, Vector2 position, SkinData skin)
|
||||
{
|
||||
var colorChip = Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
|
||||
colorChip.gameObject.name = skin.ProductId;
|
||||
colorChip.Button.OnClick.AddListener((Action)(() => __instance.ClickEquip()));
|
||||
colorChip.Button.OnMouseOver.AddListener((Action)(() => __instance.SelectSkin(skin)));
|
||||
colorChip.Button.OnMouseOut.AddListener((Action)(() => __instance.SelectSkin(HatManager.Instance.GetSkinById(DataManager.Player.Customization.Skin))));
|
||||
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
|
||||
colorChip.ProductId = skin.ProductId;
|
||||
colorChip.SelectionHighlight.gameObject.SetActive(false);
|
||||
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, skin);
|
||||
skin.SetPreview(colorChip.Inner.FrontLayer, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color);
|
||||
colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f);
|
||||
colorChip.Inner.transform.localPosition = skin.ChipOffset + new Vector2(0f, -0.3f);
|
||||
colorChip.Tag = skin;
|
||||
__instance.ColorChips.Add(colorChip);
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
using AmongUs.Data;
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Utilities;
|
||||
using Reactor.Utilities.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace MiraAPI.Patches.Menu;
|
||||
|
||||
[HarmonyPatch(typeof(VisorsTab))]
|
||||
public static class VisorsTabPatches
|
||||
{
|
||||
private static readonly SortedList<string, List<VisorData>> SortedVisors = new(new ControllableComparer<string>(["vanilla"], [], StringComparer.InvariantCulture));
|
||||
|
||||
internal static void AddRange(IEnumerable<(string Key, VisorData Visor)> data)
|
||||
{
|
||||
foreach (var item in data)
|
||||
{
|
||||
if (!SortedVisors.ContainsKey(item.Key)) SortedVisors.Add(item.Key, []);
|
||||
SortedVisors[item.Key].Add(item.Visor);
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPatch(nameof(VisorsTab.OnEnable))]
|
||||
[HarmonyPrefix]
|
||||
public static bool OnEnablePrefix(VisorsTab __instance)
|
||||
{
|
||||
__instance.visorId = HatManager.Instance.GetVisorById(DataManager.Player.Customization.Visor).ProdId;
|
||||
|
||||
if (!SortedVisors.ContainsKey("Vanilla")) AddRange(DestroyableSingleton<HatManager>.Instance.GetUnlockedVisors().Select(x => ("Vanilla", x)));
|
||||
GenerateHats(__instance);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void GenerateHats(VisorsTab __instance)
|
||||
{
|
||||
foreach (ColorChip instanceColorChip in __instance.ColorChips) instanceColorChip.gameObject.Destroy();
|
||||
__instance.ColorChips.Clear();
|
||||
__instance.scroller.Inner.GetComponentsInChildren<TextMeshPro>().Do(x => x.gameObject.Destroy());
|
||||
|
||||
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
|
||||
|
||||
int hatIndex = 0;
|
||||
|
||||
foreach ((string groupName, List<VisorData> visors) in SortedVisors)
|
||||
{
|
||||
hatIndex = (hatIndex + 4) / 5 * 5; // yes it looks redundant, but consider hatindex = 0, symbolically it would be 4, the computer calculates 0.
|
||||
var text = Object.Instantiate(groupNameText, __instance.scroller.Inner);
|
||||
text.enabled = true;
|
||||
text.gameObject.transform.localScale = Vector3.one;
|
||||
text.GetComponent<TextTranslatorTMP>().Destroy();
|
||||
text.EnableStencilMasking();
|
||||
text.text = $"{groupName}";
|
||||
text.alignment = TextAlignmentOptions.Center;
|
||||
text.fontSize = 3f;
|
||||
text.fontSizeMax = 3f;
|
||||
text.fontSizeMin = 0f;
|
||||
float xLerp = __instance.XRange.Lerp(0.5f);
|
||||
float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
|
||||
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
|
||||
|
||||
hatIndex += 5;
|
||||
foreach (var visor in visors.OrderBy(HatManager.Instance.allVisors.IndexOf))
|
||||
{
|
||||
float hatXposition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f));
|
||||
float hatYposition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
|
||||
GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), visor);
|
||||
hatIndex += 1;
|
||||
}
|
||||
}
|
||||
|
||||
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIndex + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
|
||||
__instance.currentVisorIsEquipped = true;
|
||||
}
|
||||
|
||||
private static void GenerateColorChip(VisorsTab __instance, Vector2 position, VisorData visor)
|
||||
{
|
||||
var colorChip = Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
|
||||
colorChip.gameObject.name = visor.ProductId;
|
||||
colorChip.Button.OnClick.AddListener((Action)(() => __instance.ClickEquip()));
|
||||
colorChip.Button.OnMouseOver.AddListener((Action)(() => __instance.SelectVisor(visor)));
|
||||
colorChip.Button.OnMouseOut.AddListener((Action)(() => __instance.SelectVisor(HatManager.Instance.GetVisorById(DataManager.Player.Customization.Visor))));
|
||||
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
|
||||
colorChip.ProductId = visor.ProductId;
|
||||
colorChip.SelectionHighlight.gameObject.SetActive(false);
|
||||
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, visor);
|
||||
visor.SetPreview(colorChip.Inner.FrontLayer, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color);
|
||||
colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f);
|
||||
colorChip.Inner.transform.localPosition = visor.ChipOffset + new Vector2(0f, -0.3f);
|
||||
colorChip.Tag = visor;
|
||||
__instance.ColorChips.Add(colorChip);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using HarmonyLib;
|
||||
|
||||
namespace MiraAPI.Patches;
|
||||
|
||||
[HarmonyPatch(typeof(Minigame), nameof(Minigame.Begin))]
|
||||
internal static class MinigameBeginErrorPatch
|
||||
{
|
||||
public static void Prefix(Minigame __instance)
|
||||
{
|
||||
__instance.logger ??= new Logger(Logger.Category.Gameplay, "Minigame");
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using HarmonyLib;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Gameplay;
|
||||
using MiraAPI.Events.Vanilla.Meeting;
|
||||
using MiraAPI.Roles;
|
||||
|
||||
@@ -9,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))]
|
||||
@@ -31,4 +34,14 @@ public static class EjectionPatches
|
||||
|
||||
__instance.completeString = role.GetCustomEjectionMessage(__instance.initData.networkedPlayer);
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(ExileController), nameof(ExileController.WrapUp))]
|
||||
public static class WrapUpPatch
|
||||
{
|
||||
public static void Postfix()
|
||||
{
|
||||
var @event = new RoundStartEvent(false);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,19 +12,19 @@ namespace MiraAPI.Patches.Roles;
|
||||
[HarmonyPatch(typeof(RoleManager))]
|
||||
public static class RoleManagerPatches
|
||||
{
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(nameof(RoleManager.SetRole))]
|
||||
public static void SetRolePatch(RoleManager __instance, PlayerControl targetPlayer, RoleTypes roleType)
|
||||
public static bool SetRolePatch(RoleManager __instance, PlayerControl targetPlayer, RoleTypes roleType)
|
||||
{
|
||||
if (!targetPlayer)
|
||||
{
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
var data = targetPlayer.Data;
|
||||
if (data == null)
|
||||
{
|
||||
Debug.LogError("It shouldn't be possible, but " + targetPlayer.name + " still doesn't have PlayerData during role selection.");
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
if (data.Role)
|
||||
{
|
||||
@@ -47,7 +47,7 @@ public static class RoleManagerPatches
|
||||
{
|
||||
case true when !targetPlayer.Data.IsDead:
|
||||
targetPlayer.Die(DeathReason.Kill, false);
|
||||
return;
|
||||
return false;
|
||||
case false when targetPlayer.Data.IsDead:
|
||||
targetPlayer.Revive();
|
||||
break;
|
||||
@@ -55,6 +55,8 @@ public static class RoleManagerPatches
|
||||
|
||||
var @event = new SetRoleEvent(targetPlayer, roleType);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace MiraAPI.Patches.Roles;
|
||||
/// <summary>
|
||||
/// Patches to return the correct role counts.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(RoleOptionsCollectionV08))]
|
||||
[HarmonyPatch(typeof(RoleOptionsCollectionV09))]
|
||||
public static class RoleOptionsCollectionPatch
|
||||
{
|
||||
/// <summary>
|
||||
@@ -16,7 +16,7 @@ public static class RoleOptionsCollectionPatch
|
||||
/// </summary>
|
||||
/// <returns>Return false to skip original method, true to not.</returns>
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(nameof(RoleOptionsCollectionV08.GetChancePerGame))]
|
||||
[HarmonyPatch(nameof(RoleOptionsCollectionV09.GetChancePerGame))]
|
||||
public static bool GetChancePrefix(RoleTypes role, ref int __result)
|
||||
{
|
||||
if (!CustomRoleManager.GetCustomRoleBehaviour(role, out var customRole) || customRole == null)
|
||||
@@ -46,7 +46,7 @@ public static class RoleOptionsCollectionPatch
|
||||
/// </summary>
|
||||
/// <returns>Return false to skip original method, true to not.</returns>
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(nameof(RoleOptionsCollectionV08.GetNumPerGame))]
|
||||
[HarmonyPatch(nameof(RoleOptionsCollectionV09.GetNumPerGame))]
|
||||
public static bool GetNumPrefix(RoleTypes role, ref int __result)
|
||||
{
|
||||
if (!CustomRoleManager.GetCustomRoleBehaviour(role, out var customRole) || customRole == null)
|
||||
|
||||
@@ -33,15 +33,4 @@ public static class MinigameStubs
|
||||
{
|
||||
// nothing needed
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fixes the error when creating custom minigames. Credit to Submerged for discovering this fix.
|
||||
/// </summary>
|
||||
/// <param name="__instance">The Minigame instance.</param>
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(Minigame), nameof(Minigame.Begin))]
|
||||
public static void MinigameErrorFixPatch(Minigame __instance)
|
||||
{
|
||||
__instance.logger ??= new Logger("Minigame", Logger.Level.Info, Logger.Category.Gameplay);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
using System.Linq;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using HarmonyLib;
|
||||
using Il2CppInterop.Runtime.InteropTypes.Arrays;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Meeting;
|
||||
using MiraAPI.Events.Vanilla.Meeting.Voting;
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.Utilities;
|
||||
using MiraAPI.Voting;
|
||||
|
||||
namespace MiraAPI.Patches.Voting;
|
||||
|
||||
[HarmonyPatch(typeof(MeetingHud))]
|
||||
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony Convention")]
|
||||
internal static class MeetingHudPatches
|
||||
{
|
||||
[HarmonyPostfix]
|
||||
@@ -26,11 +29,62 @@ internal static class MeetingHudPatches
|
||||
{
|
||||
voteData.SetRemainingVotes(0);
|
||||
}
|
||||
|
||||
foreach (var modifier in plr.GetModifierComponent().ActiveModifiers)
|
||||
{
|
||||
modifier.OnMeetingStart();
|
||||
}
|
||||
}
|
||||
|
||||
var @event = new StartMeetingEvent(__instance);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(nameof(MeetingHud.OnDestroy))]
|
||||
public static void OnDestroyPatch(MeetingHud __instance)
|
||||
{
|
||||
MiraEventManager.InvokeEvent(new EndMeetingEvent(__instance));
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(nameof(MeetingHud.VotingComplete))]
|
||||
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)
|
||||
|
||||
@@ -43,6 +43,9 @@ public sealed class MiraPluginManager
|
||||
var info = new MiraPluginInfo(miraPlugin, pluginInfo);
|
||||
var roles = new List<Type>();
|
||||
|
||||
var oldConfigSetting = info.PluginConfig.SaveOnConfigSet;
|
||||
info.PluginConfig.SaveOnConfigSet = false;
|
||||
|
||||
foreach (var type in assembly.GetTypes())
|
||||
{
|
||||
if (type.GetCustomAttribute<MiraIgnoreAttribute>() != null)
|
||||
@@ -96,6 +99,9 @@ public sealed class MiraPluginManager
|
||||
RegisterColorClasses(type);
|
||||
}
|
||||
|
||||
info.PluginConfig.Save();
|
||||
info.PluginConfig.SaveOnConfigSet = oldConfigSetting;
|
||||
|
||||
info.OptionGroups.Sort((x, y) => x.GroupPriority.CompareTo(y.GroupPriority));
|
||||
QueuedRoleRegistrations.Add(info, roles);
|
||||
|
||||
@@ -103,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);
|
||||
|
||||
@@ -59,6 +59,9 @@ public static class CustomRoleManager
|
||||
{
|
||||
roles.ForEach(x => RoleIds.Add(x, GetNextRoleId()));
|
||||
|
||||
var oldConfigSetting = pluginInfo.PluginConfig.SaveOnConfigSet;
|
||||
pluginInfo.PluginConfig.SaveOnConfigSet = false;
|
||||
|
||||
foreach (var roleType in roles)
|
||||
{
|
||||
ClassInjector.RegisterTypeInIl2Cpp(roleType);
|
||||
@@ -71,6 +74,9 @@ public static class CustomRoleManager
|
||||
|
||||
pluginInfo.CustomRoles.Add((ushort)role.Role, role);
|
||||
}
|
||||
|
||||
pluginInfo.PluginConfig.Save();
|
||||
pluginInfo.PluginConfig.SaveOnConfigSet = oldConfigSetting;
|
||||
}
|
||||
|
||||
private static RoleBehaviour? RegisterRole(Type roleType, MiraPluginInfo parentMod)
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
using Il2CppInterop.Runtime.Attributes;
|
||||
using MiraAPI.Patches.Menu;
|
||||
using Reactor.Utilities;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine.AddressableAssets;
|
||||
using UnityEngine.ResourceManagement.AsyncOperations;
|
||||
|
||||
namespace MiraAPI.Utilities.Assets;
|
||||
|
||||
/// <summary>
|
||||
/// The component for loading Addressables, and cosmetics.
|
||||
/// </summary>
|
||||
public static class AddressablesLoader
|
||||
{
|
||||
private static bool _isInitialized;
|
||||
|
||||
private static readonly List<(string Location, string ProviderSuffix)> CatalogLocations = [];
|
||||
private static readonly List<string> LoadedLocations = [];
|
||||
|
||||
private static readonly List<string> RegisteredHatKeys = [];
|
||||
private static readonly List<(string, string)> RegisteredVisorKeys = [];
|
||||
private static readonly List<(string, string)> RegisteredNameplateKeys = [];
|
||||
private static readonly List<string> RegisteredSkinKeys = [];
|
||||
|
||||
/// <summary>
|
||||
/// Registers a specific addressables package to load asynchronously at the start of the game, when possible.
|
||||
/// </summary>
|
||||
/// <param name="location">The location, remote or otherwise, of the addressables.</param>
|
||||
/// <param name="providerSuffix">The suffix of the provider for an addressables package.</param>
|
||||
public static void RegisterCatalog(string location, string providerSuffix = "")
|
||||
{
|
||||
if (_isInitialized)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("AddressablesLoader has already been initialized, cannot register more catalogs.");
|
||||
return;
|
||||
}
|
||||
|
||||
CatalogLocations.Add((location, providerSuffix));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a specific addressables key as only containing <see cref="HatData"/>'s to load.
|
||||
/// </summary>
|
||||
/// <param name="addressablesKey">The key/label/group for a List <see cref="HatData"/>.</param>
|
||||
public static void RegisterHats(string addressablesKey)
|
||||
{
|
||||
if (_isInitialized)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("AddressablesLoader has already been initialized, cannot register more keys for hats.");
|
||||
return;
|
||||
}
|
||||
|
||||
RegisteredHatKeys.Add(addressablesKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a specific addressables key as only containing <see cref="SkinData"/>'s to load.
|
||||
/// </summary>
|
||||
/// <param name="addressablesKey">The key/label/group for a List <see cref="SkinData"/>.</param>
|
||||
public static void RegisterSkins(string addressablesKey)
|
||||
{
|
||||
if (_isInitialized)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("AddressablesLoader has already been initialized, cannot register more keys for skins.");
|
||||
return;
|
||||
}
|
||||
|
||||
RegisteredSkinKeys.Add(addressablesKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a specific addressables key as only containing <see cref="NamePlateData"/>'s to load.
|
||||
/// </summary>
|
||||
/// <param name="addressablesKey">The key/label/group for a List <see cref="NamePlateData"/>.</param>
|
||||
/// /// <param name="groupTitle">The title of the group for visors.</param>
|
||||
public static void RegisterNameplates(string addressablesKey, string groupTitle)
|
||||
{
|
||||
if (_isInitialized)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("AddressablesLoader has already been initialized, cannot register more keys for nameplates.");
|
||||
return;
|
||||
}
|
||||
|
||||
RegisteredNameplateKeys.Add((addressablesKey, groupTitle));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a specific addressables key as only containing <see cref="VisorData"/>'s to load.
|
||||
/// </summary>
|
||||
/// <param name="addressablesKey">The key/label/group for a List <see cref="VisorData"/>.</param>
|
||||
/// <param name="groupTitle">The title of the group for visors.</param>
|
||||
public static void RegisterVisors(string addressablesKey, string groupTitle)
|
||||
{
|
||||
if (_isInitialized)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("AddressablesLoader has already been initialized, cannot register more keys for visors.");
|
||||
return;
|
||||
}
|
||||
|
||||
RegisteredVisorKeys.Add((addressablesKey, groupTitle));
|
||||
}
|
||||
|
||||
internal static void LoadAll()
|
||||
{
|
||||
if (_isInitialized)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("AddressablesLoader has already been initialized.");
|
||||
return;
|
||||
}
|
||||
|
||||
_isInitialized = true;
|
||||
foreach (var (location, providerSuffix) in CatalogLocations)
|
||||
{
|
||||
Coroutines.Start(CoLoadAddressables(location, providerSuffix));
|
||||
}
|
||||
|
||||
Coroutines.Start(LoadCosmetics());
|
||||
}
|
||||
|
||||
internal static IEnumerator CoLoadAddressables(string location, string suffix = "")
|
||||
{
|
||||
while (!AmongUsClient.Instance) yield return null;
|
||||
// Load the local/remote content catalog
|
||||
var catalogOperation = Addressables.LoadContentCatalog(location, suffix);
|
||||
yield return catalogOperation;
|
||||
|
||||
// Check for errors
|
||||
if (catalogOperation.Status != AsyncOperationStatus.Succeeded)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Failed to load catalog {location}.");
|
||||
}
|
||||
|
||||
Logger<MiraApiPlugin>.Info($"Loaded addressables {location}.");
|
||||
LoadedLocations.Add(location);
|
||||
}
|
||||
|
||||
[HideFromIl2Cpp]
|
||||
internal static IEnumerator LoadCosmetics()
|
||||
{
|
||||
while (!AmongUsClient.Instance || CatalogLocations.Select(x=>x.Location).Any(x=>!LoadedLocations.Contains(x))) yield return null;
|
||||
|
||||
var hatBehaviours = DiscoverData<HatData>(RegisteredHatKeys);
|
||||
var skinBehaviours = DiscoverData<SkinData>(RegisteredSkinKeys);
|
||||
var namePlateBehaviours = DiscoverAndReportData<NamePlateData>(RegisteredNameplateKeys);
|
||||
var visorBehaviours = DiscoverAndReportData<VisorData>(RegisteredVisorKeys);
|
||||
|
||||
var hatData = new List<HatData>();
|
||||
hatData.AddRange(DestroyableSingleton<HatManager>.Instance.allHats);
|
||||
hatData.ForEach(x => x.StoreName = "Vanilla");
|
||||
DestroyableSingleton<HatManager>.Instance.allHats = PrepareArray(hatData, hatBehaviours);
|
||||
|
||||
var skinData = new List<SkinData>();
|
||||
skinData.AddRange(DestroyableSingleton<HatManager>.Instance.allSkins);
|
||||
skinData.ForEach(x => x.StoreName = "Vanilla");
|
||||
DestroyableSingleton<HatManager>.Instance.allSkins = PrepareArray(skinData, skinBehaviours);
|
||||
|
||||
var visorData = new List<VisorData>();
|
||||
visorData.AddRange(DestroyableSingleton<HatManager>.Instance.allVisors);
|
||||
VisorsTabPatches.AddRange(visorBehaviours);
|
||||
DestroyableSingleton<HatManager>.Instance.allVisors = PrepareArray(visorData, visorBehaviours.Select(x=>x.Data).ToList());
|
||||
|
||||
var namePlateData = new List<NamePlateData>();
|
||||
namePlateData.AddRange(DestroyableSingleton<HatManager>.Instance.allNamePlates);
|
||||
NameplatesTabPatches.AddRange(namePlateBehaviours);
|
||||
DestroyableSingleton<HatManager>.Instance.allNamePlates = PrepareArray(namePlateData, namePlateBehaviours.Select(x => x.Data).ToList());
|
||||
}
|
||||
|
||||
private static T[] PrepareArray<T>(List<T> data, List<T> behaviours) where T : CosmeticData
|
||||
{
|
||||
var count = data.Count;
|
||||
for (int i = 0; i < behaviours.Count; i++)
|
||||
{
|
||||
behaviours[i].displayOrder = count + i;
|
||||
data.Add(behaviours[i]);
|
||||
}
|
||||
return data.ToArray();
|
||||
}
|
||||
|
||||
private static List<T> DiscoverData<T>(List<string> tags)
|
||||
{
|
||||
var behaviours = new List<T>();
|
||||
|
||||
foreach (var tag in tags)
|
||||
{
|
||||
try
|
||||
{
|
||||
var allLocations = Addressables.LoadResourceLocationsAsync(tag).WaitForCompletion();
|
||||
var assets = Addressables.LoadAssetsAsync<T>(allLocations, null, false).WaitForCompletion();
|
||||
var array = new Il2CppSystem.Collections.Generic.List<T>(assets.Pointer);
|
||||
behaviours.AddRange(array.ToArray());
|
||||
}
|
||||
catch
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Failed to find tag {tag}");
|
||||
}
|
||||
}
|
||||
return behaviours;
|
||||
}
|
||||
|
||||
private static List<(string Category, T Data)> DiscoverAndReportData<T>(List<(string Tag, string Category)> tags)
|
||||
{
|
||||
var behaviours = new List<(string, T)>();
|
||||
|
||||
foreach (var tag in tags)
|
||||
{
|
||||
try
|
||||
{
|
||||
var allLocations = Addressables.LoadResourceLocationsAsync(tag.Tag).WaitForCompletion();
|
||||
var assets = Addressables.LoadAssetsAsync<T>(allLocations, null, false).WaitForCompletion();
|
||||
var array = new Il2CppSystem.Collections.Generic.List<T>(assets.Pointer);
|
||||
behaviours.AddRange(array.ToArray().Select(x => (tag.Category, x)));
|
||||
}
|
||||
catch
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Failed to find tag {tag}");
|
||||
}
|
||||
}
|
||||
return behaviours;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
using System;
|
||||
using Reactor.Utilities;
|
||||
using UnityEngine.AddressableAssets;
|
||||
|
||||
namespace MiraAPI.Utilities.Assets;
|
||||
|
||||
/// <summary>
|
||||
/// A utility class for loading an asset from ALL addressable locations.
|
||||
/// </summary>
|
||||
/// <param name="uid">The guid of the asset.</param>
|
||||
/// <typeparam name="T">The type of the asset to be loaded.</typeparam>
|
||||
public class LoadableAddressableAsset<T>(string uid) : LoadableAsset<T> where T : UnityEngine.Object
|
||||
{
|
||||
private readonly Action<LoadableAddressableAsset<T>>? _gcAction;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoadableAddressableAsset{T}"/> class, with added garbageCollector logic,
|
||||
/// to help with https://github.com/BepInEx/Il2CppInterop/issues/40.
|
||||
/// </summary>
|
||||
/// <param name="uid">The guid of the asset.</param>
|
||||
/// <param name="garbageCollection">A lambda that allows GCHandle.Alloc calls without garbage collection interferences.</param>
|
||||
public LoadableAddressableAsset(string uid, Action<LoadableAddressableAsset<T>> garbageCollection) : this(uid)
|
||||
{
|
||||
_gcAction = garbageCollection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the asset from addressables.
|
||||
/// </summary>
|
||||
/// <returns>The asset.</returns>
|
||||
/// <exception cref="Exception">The asset did not load properly.</exception>
|
||||
public override T LoadAsset()
|
||||
{
|
||||
if (LoadedAsset != null)
|
||||
{
|
||||
return LoadedAsset;
|
||||
}
|
||||
|
||||
var remoteReference = new AssetReference(uid);
|
||||
|
||||
if (!GC.TryStartNoGCRegion(4096, true)) Logger<MiraApiPlugin>.Error("Could not start NoGCRegion of size 4kb, there is the possibility of injected unmanaged classes being garbage collected as per BepInEx/Il2CppInterop/issues/40");
|
||||
|
||||
LoadedAsset = remoteReference.LoadAssetAsync<T>().WaitForCompletion();
|
||||
if (LoadedAsset == null)
|
||||
{
|
||||
GC.EndNoGCRegion();
|
||||
throw new InvalidOperationException($"INVALID ASSET: {uid}");
|
||||
}
|
||||
|
||||
_gcAction?.Invoke(this);
|
||||
GC.EndNoGCRegion();
|
||||
|
||||
return LoadedAsset;
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using Reactor.Utilities;
|
||||
using UnityEngine.AddressableAssets;
|
||||
|
||||
namespace MiraAPI.Utilities.Assets;
|
||||
|
||||
/// <summary>
|
||||
/// A utility class for loading groups of assets from ALL addressable locations.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the asset to be loaded.</typeparam>
|
||||
public class LoadableAddressableAssets<T>(string key) where T : UnityEngine.Object
|
||||
{
|
||||
private readonly Action<LoadableAddressableAssets<T>>? _gcAction;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets reference to the loaded asset. Intended to be used for caching purposes.
|
||||
/// </summary>
|
||||
protected List<T>? LoadedAssets { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoadableAddressableAssets{T}"/> class, with added garbageCollector logic,
|
||||
/// to help with https://github.com/BepInEx/Il2CppInterop/issues/40.
|
||||
/// </summary>
|
||||
/// <param name="key">The key of the assets.</param>
|
||||
/// <param name="garbageCollection">A lambda that allows GCHandle.Alloc calls without garbage collection interferences.</param>
|
||||
public LoadableAddressableAssets(string key, Action<LoadableAddressableAssets<T>> garbageCollection) : this(key)
|
||||
{
|
||||
_gcAction = garbageCollection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the asset from addressables.
|
||||
/// </summary>
|
||||
/// <returns>The asset.</returns>
|
||||
/// <exception cref="Exception">The asset did not load properly.</exception>
|
||||
public ReadOnlyCollection<T> LoadAssets()
|
||||
{
|
||||
if (LoadedAssets != null)
|
||||
{
|
||||
return LoadedAssets.AsReadOnly();
|
||||
}
|
||||
|
||||
var locations = Addressables.LoadResourceLocationsAsync(key).WaitForCompletion();
|
||||
|
||||
if (!GC.TryStartNoGCRegion(4096, true)) Logger<MiraApiPlugin>.Error("Could not start NoGCRegion of size 4kb, there is the possibility of injected unmanaged classes being garbage collected as per BepInEx/Il2CppInterop/issues/40");
|
||||
|
||||
var assetsIList = Addressables.LoadAssetsAsync<T>(locations, null, false).WaitForCompletion();
|
||||
if (assetsIList == null)
|
||||
{
|
||||
GC.EndNoGCRegion();
|
||||
throw new InvalidOperationException($"INVALID ASSET/s: {key}");
|
||||
}
|
||||
|
||||
var assetsList = new Il2CppSystem.Collections.Generic.List<T>(assetsIList.Pointer);
|
||||
LoadedAssets = assetsList.ToArray().ToList();
|
||||
|
||||
_gcAction?.Invoke(this);
|
||||
GC.EndNoGCRegion();
|
||||
|
||||
return LoadedAssets.AsReadOnly();
|
||||
}
|
||||
}
|
||||
@@ -3,17 +3,17 @@
|
||||
namespace MiraAPI.Utilities.Assets;
|
||||
|
||||
/// <summary>
|
||||
/// An implementation for creating loadable assets from existing assets.
|
||||
/// An implementation for creating loadable assets from preloaded assets.
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="LoadableAsset{T}"/>
|
||||
/// <inheritdoc />
|
||||
public class PreloadedAsset<T>(T asset) : LoadableAsset<T> where T : UnityEngine.Object
|
||||
{
|
||||
private readonly T _loadedAsset = asset ?? throw new ArgumentNullException(nameof(asset));
|
||||
private readonly T loadedAsset = asset ?? throw new ArgumentNullException(nameof(asset));
|
||||
|
||||
/// <inheritdoc />
|
||||
public override T LoadAsset()
|
||||
{
|
||||
return _loadedAsset;
|
||||
return loadedAsset;
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace MiraAPI.Utilities;
|
||||
|
||||
internal sealed class ControllableComparer<T> : IComparer<T> where T : IComparable
|
||||
{
|
||||
private readonly T[] _forcedToBottom;
|
||||
private readonly T[] _forcedToTop;
|
||||
private readonly IComparer<T> _fallbackComparer;
|
||||
public ControllableComparer(T[] forcedToBottom, T[] forcedToTop, IComparer<T> fallbackComparer)
|
||||
{
|
||||
_forcedToBottom = forcedToBottom;
|
||||
_forcedToTop = forcedToTop;
|
||||
_fallbackComparer = fallbackComparer;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public int Compare(T? x, T? y)
|
||||
{
|
||||
if ((_forcedToBottom.Contains(x) && _forcedToBottom.Contains(y)) || (_forcedToTop.Contains(x) && _forcedToTop.Contains(y)))
|
||||
return _fallbackComparer.Compare(x, y);
|
||||
|
||||
if (_forcedToBottom.Contains(x))
|
||||
return 1;
|
||||
if (_forcedToBottom.Contains(y))
|
||||
return -1;
|
||||
|
||||
if (_forcedToTop.Contains(x))
|
||||
return -1;
|
||||
if (_forcedToTop.Contains(y))
|
||||
return 1;
|
||||
|
||||
return _fallbackComparer.Compare(x, y);
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Il2CppInterop.Runtime.Attributes;
|
||||
using Reactor.Utilities.Attributes;
|
||||
using UnityEngine;
|
||||
|
||||
@@ -19,6 +20,7 @@ public class PlayerVoteData(nint cppPtr) : MonoBehaviour(cppPtr)
|
||||
/// <summary>
|
||||
/// Gets the list of votes the owner has.
|
||||
/// </summary>
|
||||
[HideFromIl2Cpp]
|
||||
public List<CustomVote> Votes { get; private set; } = [];
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user