Compare commits

..
Author SHA1 Message Date
XtraCube 2a3c8feeab fix erorr 2024-09-24 20:50:03 -04:00
ang-xd 833585f15f Make modifier text disappear meetings 2024-09-24 20:36:41 -04:00
XtraCube 66b4976619 mira host option thingy 2024-09-24 09:52:27 -04:00
XtraCube 9c0b874e34 Merge branch 'dev' into feat-addressables
# Conflicts:
#	MiraAPI/Roles/ICustomRole.cs
2024-09-23 16:22:01 -04:00
XtraCube ce0662f772 adjust 2024-09-23 06:52:23 -04:00
XtraCube c928eae183 modifier didwins 2024-09-22 20:38:41 -04:00
XtraCube 68afe58678 custom player menu in mira 2024-09-22 10:52:48 -04:00
XtraCube e3b2477cb8 fix rpc custom murder 2024-09-21 19:35:05 -04:00
XtraCube 2b568f933b fix role defaults 2024-09-21 16:20:28 -04:00
XtraCube a0701d582f only use custom murder 2024-09-19 23:19:49 -04:00
XtraCube c42782b157 fix custom buttons 2024-09-19 22:38:55 -04:00
XtraCube f932c4f3ff adjustment to role setting menu 2024-09-19 20:56:28 -04:00
XtraCube 2666aa171d fix patch error 2024-09-19 06:42:47 -04:00
XtraCube 9f99f6abb5 improvements to custom role (added SetChance and SetCount, improved GetChance and GetCount) 2024-09-19 06:40:51 -04:00
XtraCube aa53af112b Merge branch 'dev' into feat-addressables 2024-09-17 20:51:21 -04:00
XtraCube ff2f44fd64 code style stuff and merge 2024-09-17 20:49:15 -04:00
XtraCube d64972a574 Merge branch 'dev' into feat-addressables
# Conflicts:
#	MiraAPI.Example/ExamplePlugin.cs
#	MiraAPI/MiraAPI.csproj
#	MiraAPI/PluginLoading/MiraPluginInfo.cs
#	MiraAPI/PluginLoading/MiraPluginManager.cs
2024-09-17 20:00:09 -04:00
MyDragonBreath bb45bab198 Some cleanup 2024-09-14 18:50:34 +10:00
MyDragonBreath 1eb13d0513 Base Addressables 2024-09-12 23:26:57 +10:00
146 changed files with 1922 additions and 4306 deletions

No files matched your search

+6 -6
View File
@@ -6,11 +6,11 @@ jobs:
build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
with:
submodules: true
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~/.nuget/packages
@@ -20,7 +20,7 @@ jobs:
${{ runner.os }}-nuget-
- name: Setup .NET
uses: actions/setup-dotnet@v4
uses: actions/setup-dotnet@v3
with:
dotnet-version: 8.0.x
@@ -29,17 +29,17 @@ jobs:
with:
verbosity: Diagnostic
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v3
with:
name: MiraAPI.dll
path: MiraAPI/bin/Release/net6.0/MiraAPI.dll
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v3
with:
name: AllOfUs.MiraAPI.nupkg
path: MiraAPI/bin/Release/AllOfUs.MiraAPI.*.nupkg
- uses: softprops/action-gh-release@v2
- uses: softprops/action-gh-release@v1
if: github.ref_type == 'tag'
with:
draft: true
+1 -1
View File
@@ -2,7 +2,7 @@
<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="2024.9.4" 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" />
@@ -3,21 +3,19 @@ using MiraAPI.Example.Options.Roles;
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.Hud;
using MiraAPI.Modifiers;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.Buttons.Freezer;
[RegisterButton]
public class FreezeButton : CustomActionButton<PlayerControl>
{
public override string Name => "Freeze";
public override float Cooldown => OptionGroupSingleton<FreezerRoleSettings>.Instance.FreezeDuration;
public override float EffectDuration => 0f;
public override int MaxUses => (int)OptionGroupSingleton<FreezerRoleSettings>.Instance.FreezeUses;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
protected override void OnClick()
+4 -1
View File
@@ -1,17 +1,20 @@
using MiraAPI.Example.Modifiers;
using MiraAPI.Hud;
using MiraAPI.Modifiers;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.Buttons;
[RegisterButton]
public class MeetingButton : CustomActionButton
{
public override string Name => "Call Meeting";
public override float Cooldown => 15;
public override float EffectDuration => 0;
public override int MaxUses => 3;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
@@ -1,24 +0,0 @@
using MiraAPI.Example.GameOver;
using MiraAPI.Example.Roles;
using MiraAPI.GameEnd;
using MiraAPI.Hud;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.Buttons;
public class NeutralKillerButton : CustomActionButton
{
public override string Name => "Win Game";
public override float Cooldown => 0f;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
protected override void OnClick()
{
CustomGameOver.Trigger<NeutralKillerGameOver>([PlayerControl.LocalPlayer.Data]);
}
public override bool Enabled(RoleBehaviour? role)
{
return role is NeutralKillerRole;
}
}
@@ -8,7 +8,7 @@ using Reactor.Utilities;
using UnityEngine;
namespace MiraAPI.Example.Buttons.Teleporter;
[RegisterButton]
public class TeleportButton : CustomActionButton
{
public override string Name => "Teleport";
@@ -16,17 +16,16 @@ public class TeleportButton : CustomActionButton
public override float Cooldown => OptionGroupSingleton<TeleporterOptions>.Instance.TeleportCooldown.Value;
public override float EffectDuration => OptionGroupSingleton<TeleporterOptions>.Instance.TeleportDuration;
public override int MaxUses => 2;
public override int MaxUses => 0;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.TeleportButton;
public static bool IsZoom { get; private set; }
public override bool Enabled(RoleBehaviour? role)
{
return role is TeleporterRole;
}
protected override void OnClick()
{
Coroutines.Start(ZoomOutCoroutine());
@@ -41,7 +40,10 @@ public class TeleportButton : CustomActionButton
{
base.FixedUpdate(playerControl);
if (!EffectActive) return;
if (!EffectActive)
{
return;
}
if (Input.GetKey(KeyCode.Mouse0))
{
@@ -0,0 +1,17 @@
using System.Collections.Generic;
using MiraAPI.Cosmetics;
namespace MiraAPI.Example.Cosmetics;
public class ExampleCosmeticGroup : AbstractCosmeticsGroup
{
public override string GroupName => "Example";
[RegisterCustomCosmetic()]
public List<HatData> hats { get; set; } = new();
[RegisterCustomCosmetic()]
public List<NamePlateData> namePlates { get; set;} = new();
[RegisterCustomCosmetic()]
public List<SkinData> skins { get; set; } = new();
[RegisterCustomCosmetic()]
public List<VisorData> visors { get; set; } = new();
}
-59
View File
@@ -1,59 +0,0 @@
using MiraAPI.Events;
using MiraAPI.Events.Mira;
using MiraAPI.Events.Vanilla.Gameplay;
using MiraAPI.Events.Vanilla.Map;
using MiraAPI.Events.Vanilla.Player;
using MiraAPI.Example.Buttons.Freezer;
using Reactor.Utilities;
namespace MiraAPI.Example;
public static class ExampleEventHandlers
{
public static void Initialize()
{
// Register event handlers here
MiraEventManager.RegisterEventHandler<MiraButtonClickEvent<FreezeButton>>(FreezeButtonClickHandler, 1);
MiraEventManager.RegisterEventHandler<MiraButtonCancelledEvent<FreezeButton>>(FreezeButtonCancelledHandler);
MiraEventManager.RegisterEventHandler<UpdateSystemEvent>(UpdateSystemEventHandler);
MiraEventManager.RegisterEventHandler<BeforeMurderEvent>(@event =>
{
Logger<ExamplePlugin>.Info($"{@event.Source.Data.PlayerName} is about to kill {@event.Target.Data.PlayerName}");
});
MiraEventManager.RegisterEventHandler<AfterMurderEvent>(@event =>
{
Logger<ExamplePlugin>.Info($"{@event.Source.Data.PlayerName} has killed {@event.Target.Data.PlayerName}");
});
MiraEventManager.RegisterEventHandler<CompleteTaskEvent>(@event =>
{
Logger<ExamplePlugin>.Info($"{@event.Player.Data.PlayerName} completed {@event.Task.TaskType.ToString()}");
});
}
public static void UpdateSystemEventHandler(UpdateSystemEvent @event)
{
Logger<ExamplePlugin>.Error(@event.SystemType.ToString());
}
// Example event handler
public static void FreezeButtonClickHandler(MiraButtonClickEvent<FreezeButton> @event)
{
Logger<ExamplePlugin>.Warning("Freeze button clicked!");
if (PlayerControl.LocalPlayer.Data.PlayerName == "stupid")
{
@event.Cancel();
@event.Button.SetTimer(15f);
}
}
// Example event handler
public static void FreezeButtonCancelledHandler(MiraButtonCancelledEvent<FreezeButton> @event)
{
Logger<ExamplePlugin>.Warning("Freeze button cancelled!");
@event.Button.OverrideName("Freeze Canceled");
}
}
+11 -1
View File
@@ -2,7 +2,11 @@
using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MiraAPI.Example.Cosmetics;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities.Assets;
using MiraAPI.Utilities.Assets.Addressable;
using Reactor;
using Reactor.Networking;
using Reactor.Networking.Attributes;
@@ -21,7 +25,13 @@ public partial class ExamplePlugin : BasePlugin, IMiraPlugin
public ConfigFile GetConfigFile() => Config;
public override void Load()
{
ExampleEventHandlers.Initialize();
Harmony.PatchAll();
AddComponent<MiraDebugWindow>();
new Catalog("Output".ToLocalPath()).LoadCatalog();
CosmeticGroupSingleton<ExampleCosmeticGroup>.Instance.hats = new LoadableAddressableGroupAsset<HatData>(CatalogTools.GetResourceLocation("hatdata")).LoadAsset();
CosmeticGroupSingleton<ExampleCosmeticGroup>.Instance.namePlates = new LoadableAddressableGroupAsset<NamePlateData>(CatalogTools.GetResourceLocation("nameplatedata")).LoadAsset();
CosmeticGroupSingleton<ExampleCosmeticGroup>.Instance.skins = new LoadableAddressableGroupAsset<SkinData>(CatalogTools.GetResourceLocation("skindata")).LoadAsset();
CosmeticGroupSingleton<ExampleCosmeticGroup>.Instance.visors = new LoadableAddressableGroupAsset<VisorData>(CatalogTools.GetResourceLocation("visordata")).LoadAsset();
}
}
@@ -1,21 +0,0 @@
using MiraAPI.Example.Roles;
using MiraAPI.GameEnd;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Example.GameOver;
public class NeutralKillerGameOver : CustomGameOver
{
public override bool VerifyCondition(PlayerControl playerControl)
{
return playerControl.Data.Role is NeutralKillerRole;
}
public override void AfterEndGameSetup(EndGameManager endGameManager)
{
endGameManager.WinText.text = "Outcast Killer Wins!";
endGameManager.WinText.color = Color.magenta;
endGameManager.BackgroundBar.material.SetColor(ShaderID.Color, Color.magenta);
}
}
+3 -1
View File
@@ -1,7 +1,9 @@
using MiraAPI.Modifiers.Types;
using MiraAPI.Modifiers;
using MiraAPI.Modifiers.Types;
namespace MiraAPI.Example.Modifiers;
[RegisterModifier]
public class CaptainModifier : GameModifier
{
public override string ModifierName => "Captain";
@@ -1,10 +1,12 @@
using Il2CppSystem;
using MiraAPI.Example.Roles;
using MiraAPI.Modifiers;
using MiraAPI.Modifiers.Types;
using UnityEngine;
namespace MiraAPI.Example.Modifiers.Freezer;
[RegisterModifier]
public class FreezeModifier : TimedModifier
{
public override string ModifierName => "Freezed";
@@ -1,22 +0,0 @@
using MiraAPI.Modifiers.Types;
namespace MiraAPI.Example.Modifiers;
public class HighPriorityModifier : GameModifier
{
public override string ModifierName => "High Priority";
public override int GetAssignmentChance()
{
return 100;
}
public override int GetAmountPerGame()
{
return 1;
}
public override int Priority()
{
return 100;
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ public class ExampleOptions : AbstractOptionGroup
[ModdedToggleOption("Toggle Opt 2")]
public bool ToggleOpt2 { get; set; } = true;
[ModdedNumberOption("Number Opt", min: 0, max: 10, increment: .25f, formatString: "0.00", suffixType: MiraNumberSuffixes.Percent)]
[ModdedNumberOption("Number Opt", min: 0, max: 10, suffixType: MiraNumberSuffixes.Percent)]
public float NumberOpt { get; set; } = 4f;
[ModdedEnumOption("Best API", typeof(BestApi), ["Mira API", "Mitochondria", "Reactor"])]
+3 -3
View File
@@ -14,16 +14,16 @@ public class ExampleOptions2 : AbstractOptionGroup
public ModdedToggleOption ToggleOpt2 { get; } = new("Toggle Option 2", false)
{
Visible = () => OptionGroupSingleton<ExampleOptions2>.Instance.ToggleOpt1, // implicit cast from ModdedToggleOption to bool
Visible = () => OptionGroupSingleton<ExampleOptions2>.Instance.ToggleOpt1.Value,
};
public ModdedEnumOption<TestingData> EnumOpt { get; } = new("Enum Opt", 0)
public ModdedEnumOption EnumOpt { get; } = new("Enum Opt", 0, typeof(TestingData))
{
ChangedEvent = x => Logger<ExamplePlugin>.Info($"changed Enum Opt to {x}"),
};
}
public enum TestingData : ulong
public enum TestingData
{
Happy,
Sad,
+5 -5
View File
@@ -1,9 +1,9 @@
using MiraAPI.Roles;
using TMPro;
using UnityEngine;
namespace MiraAPI.Example.Roles;
[RegisterCustomRole]
public class ChameloenRole : CrewmateRole, ICustomRole
{
public string RoleName => "Chamelon";
@@ -21,8 +21,8 @@ public class ChameloenRole : CrewmateRole, ICustomRole
{
if (playerControl.MyPhysics.Velocity.magnitude > 0)
{
SpriteRenderer rend = playerControl.cosmetics.currentBodySprite.BodySprite;
TextMeshPro tmp = playerControl.cosmetics.nameText;
var rend = playerControl.cosmetics.currentBodySprite.BodySprite;
var tmp = playerControl.cosmetics.nameText;
tmp.color = Color.Lerp(tmp.color, new Color(tmp.color.r, tmp.color.g, tmp.color.b, 1), Time.deltaTime * 4f);
rend.color = Color.Lerp(rend.color, new Color(1, 1, 1, 1), Time.deltaTime * 4f);
@@ -33,8 +33,8 @@ public class ChameloenRole : CrewmateRole, ICustomRole
}
else
{
SpriteRenderer rend = playerControl.cosmetics.currentBodySprite.BodySprite;
TextMeshPro tmp = playerControl.cosmetics.nameText;
var rend = playerControl.cosmetics.currentBodySprite.BodySprite;
var tmp = playerControl.cosmetics.nameText;
tmp.color = Color.Lerp(tmp.color, new Color(tmp.color.r, tmp.color.g, tmp.color.b, playerControl.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
rend.color = Color.Lerp(rend.color, new Color(1, 1, 1, playerControl.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
+1
View File
@@ -3,6 +3,7 @@ using UnityEngine;
namespace MiraAPI.Example.Roles;
[RegisterCustomRole]
public class FreezerRole : ImpostorRole, ICustomRole
{
public string RoleName => "Freezer";
+7 -15
View File
@@ -1,32 +1,24 @@
using MiraAPI.Example.GameOver;
using MiraAPI.GameEnd;
using MiraAPI.Roles;
using MiraAPI.Roles;
using UnityEngine;
namespace MiraAPI.Example.Roles;
[RegisterCustomRole]
public class NeutralKillerRole : ImpostorRole, ICustomRole
{
public string RoleName => "Outcast Killer";
public string RoleDescription => "Outcast who can kill.";
public string RoleName => "Neutral Killer";
public string RoleDescription => "Neutral who can kill.";
public string RoleLongDescription => RoleDescription;
public Color RoleColor => Color.magenta;
public ModdedRoleTeams Team => ModdedRoleTeams.Custom;
public ModdedRoleTeams Team => ModdedRoleTeams.Neutral;
public CustomRoleConfiguration Configuration => new(this)
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
{
UseVanillaKillButton = true,
CanGetKilled = true,
CanUseVent = true,
};
public RoleOptionsGroup RoleOptionsGroup { get; } = new("Outcast", Color.gray);
public TeamIntroConfiguration? IntroConfiguration { get; } = new(
Color.gray,
"OUTCAST",
"You are an Outcast. You do not have a team.");
public override void SpawnTaskHeader(PlayerControl playerControl)
{
// remove existing task header.
@@ -34,6 +26,6 @@ public class NeutralKillerRole : ImpostorRole, ICustomRole
public override bool DidWin(GameOverReason gameOverReason)
{
return gameOverReason == CustomGameOver.GameOverReason<NeutralKillerGameOver>();
return GameManager.Instance.DidHumansWin(gameOverReason);
}
}
+1 -5
View File
@@ -3,6 +3,7 @@ using UnityEngine;
namespace MiraAPI.Example.Roles;
[RegisterCustomRole]
public class TeleporterRole : CrewmateRole, ICustomRole
{
public string RoleName => "Teleporter";
@@ -18,9 +19,4 @@ public class TeleporterRole : CrewmateRole, ICustomRole
DefaultChance = 73,
DefaultRoleCount = 4,
};
public bool CanLocalPlayerSeeRole(PlayerControl player)
{
return true;
}
}
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
namespace MiraAPI.Cosmetics;
public abstract class AbstractCosmeticsGroup
{
public List<HatData> Hats { get; } = [];
public List<SkinData> Skins { get; } = [];
public List<VisorData> Visors { get; } = [];
public List<NamePlateData> Nameplates { get; } = [];
/// <summary>
/// Gets the name of the group. Visible in options menu.
/// </summary>
public abstract string GroupName { get; }
/// <summary>
/// Gets a function that determines whether the group should be visible or not.
/// </summary>
public virtual Func<bool> GroupVisible => () => true;
/// <summary>
/// Gets the sorting mode of individual hats within this group.
/// </summary>
public virtual SortingMode SortingMode => SortingMode.AlphabeticName;
/// <summary>
/// Gets the priority of a group for sorting groups.
/// </summary>
public virtual int SortingPriority { get; }
}
public enum SortingMode
{
Priority,
AlphabeticProductId,
AlphabeticStoreName,
AlphabeticName,
}
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
namespace MiraAPI.Cosmetics;
internal sealed class AbstractCosmeticsGroupComparer : Comparer<AbstractCosmeticsGroup>
{
public override int Compare(AbstractCosmeticsGroup? x, AbstractCosmeticsGroup? y)
{
switch (x)
{
case not null when y is null:
return 1;
case null when y is null:
return 0;
case null:
return -1;
}
var p = x.SortingPriority - y.SortingPriority;
return p == 0 ? StringComparer.InvariantCultureIgnoreCase.Compare(x.GroupName, y.GroupName) : p;
}
}
+38
View File
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace MiraAPI.Cosmetics;
internal sealed class CosmeticComparer(AbstractCosmeticsGroup group) : Comparer<CosmeticData>
{
internal static readonly string[] NoCosmetics = ["hat_NoHat", "skin_None", "nameplate_NoPlate", "visor_EmptyVisor"];
public override int Compare(CosmeticData? x, CosmeticData? y)
{
if (NoCosmetics.Contains(x?.ProdId))
{
return -1;
}
if (NoCosmetics.Contains(y?.ProdId))
{
return 1;
}
return group.SortingMode switch
{
SortingMode.AlphabeticProductId => StringComparer.InvariantCultureIgnoreCase.Compare(x?.ProductId, y?.ProductId),
SortingMode.Priority => CustomCosmeticManager.CosmeticToPriority[x!] - CustomCosmeticManager.CosmeticToPriority[y!],
SortingMode.AlphabeticStoreName => x switch
{
HatData h1 when y is HatData h2 => StringComparer.InvariantCultureIgnoreCase.Compare(
h1.StoreName,
h2.StoreName),
SkinData s1 when y is SkinData s2 => StringComparer.InvariantCultureIgnoreCase.Compare(
s1.StoreName,
s2.StoreName),
_ => StringComparer.InvariantCultureIgnoreCase.Compare(x?.GetItemName(), y?.GetItemName()),
},
_ => StringComparer.InvariantCultureIgnoreCase.Compare(x?.GetItemName(), y?.GetItemName()),
};
}
}
@@ -0,0 +1,19 @@
using System.Linq;
namespace MiraAPI.Cosmetics;
/// <summary>
/// Used to get access to a CosmeticGroup.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
public static class CosmeticGroupSingleton<T> where T : AbstractCosmeticsGroup
{
private static T? _instance;
/// <summary>
/// Gets instance of the cosmetic group.
/// </summary>
#pragma warning disable CA1000
public static T Instance => _instance ??= CustomCosmeticManager.Groups.OfType<T>().Single();
#pragma warning restore CA1000
}
+127
View File
@@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MonoMod.Utils;
using Reactor.Utilities;
namespace MiraAPI.Cosmetics;
public static class CustomCosmeticManager
{
private static readonly Dictionary<PropertyInfo, RegisterCustomCosmeticAttribute> OptionAttributes = [];
private static readonly Dictionary<Type, AbstractCosmeticsGroup> TypeToGroup = [];
internal static readonly Dictionary<CosmeticData, int> CosmeticToPriority = [];
internal static readonly Dictionary<CosmeticData, AbstractCosmeticsGroup> CosmeticToGroup = [];
internal static readonly List<AbstractCosmeticsGroup> Groups = [];
internal static void RegisterVanilla()
{
if (Activator.CreateInstance(typeof(VanillaCosmeticsGroup)) is not AbstractCosmeticsGroup group)
{
Logger<MiraApiPlugin>.Error($"Failed to create group from Vanilla");
return;
}
if (TypeToGroup.ContainsKey(typeof(VanillaCosmeticsGroup)))
{
Logger<MiraApiPlugin>.Error($"Vanilla group already exists.");
return;
}
Groups.Add(group);
TypeToGroup.Add(typeof(VanillaCosmeticsGroup), group);
}
internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo)
{
if (Activator.CreateInstance(type) is not AbstractCosmeticsGroup group)
{
Logger<MiraApiPlugin>.Error($"Failed to create group from {type.Name}");
return false;
}
if (TypeToGroup.ContainsKey(type))
{
Logger<MiraApiPlugin>.Error($"Group {type.Name} already exists.");
return false;
}
Groups.Add(group);
TypeToGroup.Add(type, group);
pluginInfo.CosmeticGroups.Add(group);
return true;
}
internal static void RegisterAttributeOption(Type type, RegisterCustomCosmeticAttribute attribute, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (OptionAttributes.ContainsKey(property))
{
Logger<MiraApiPlugin>.Error($"Property {property.Name} already has an attribute registered.");
return;
}
if (!TypeToGroup.TryGetValue(type, out var group))
{
Logger<MiraApiPlugin>.Error($"Failed to get group for {type.Name}");
return;
}
OptionAttributes.Add(property, attribute);
}
internal static void LoadCosmetic(PropertyInfo property, RegisterCustomCosmeticAttribute attribute)
{
if (!TypeToGroup.TryGetValue(property.DeclaringType, out var group))
{
Logger<MiraApiPlugin>.Error($"Failed to get group for {property.DeclaringType.Name}");
return;
}
if (property.PropertyType.IsAssignableTo(typeof(IEnumerable<HatData>)))
{
group.Hats.AddRange((IEnumerable<HatData>)property.GetValue(group));
}
else if (property.PropertyType.IsAssignableTo(typeof(IEnumerable<SkinData>)))
{
group.Skins.AddRange((IEnumerable<SkinData>)property.GetValue(group));
}
else if (property.PropertyType.IsAssignableTo(typeof(IEnumerable<VisorData>)))
{
group.Visors.AddRange((IEnumerable<VisorData>)property.GetValue(group));
}
else if (property.PropertyType.IsAssignableTo(typeof(IEnumerable<NamePlateData>)))
{
group.Nameplates.AddRange((IEnumerable<NamePlateData>)property.GetValue(group));
}
else
{
Logger<MiraApiPlugin>.Error($"Failed to get enumerable for {property.Name}");
return;
}
CosmeticToPriority.AddRange(((IEnumerable<CosmeticData>)property.GetValue(group)).ToDictionary(y => y, x => attribute.Priority));
CosmeticToGroup.AddRange(((IEnumerable<CosmeticData>)property.GetValue(group)).ToDictionary(y => y, x => group));
}
internal static bool Registered { get; set; }
internal static void LoadAll()
{
CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance.runtimeRegister();
if (Registered || !CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance.registered)
{
return;
}
Registered = true;
CosmeticToPriority.AddRange(CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance.Cosmetics.ToDictionary(y => y, x => 0));
CosmeticToGroup.AddRange(CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance.Cosmetics.ToDictionary(y => y, x => CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance));
OptionAttributes.Do(x => LoadCosmetic(x.Key, x.Value));
DestroyableSingleton<HatManager>.Instance.allHats = CosmeticToGroup.Keys.OfType<HatData>().ToArray();
DestroyableSingleton<HatManager>.Instance.allVisors = CosmeticToGroup.Keys.OfType<VisorData>().ToArray();
DestroyableSingleton<HatManager>.Instance.allSkins = CosmeticToGroup.Keys.OfType<SkinData>().ToArray();
DestroyableSingleton<HatManager>.Instance.allNamePlates = CosmeticToGroup.Keys.OfType<NamePlateData>().ToArray();
}
}
@@ -0,0 +1,9 @@
using System;
namespace MiraAPI.Cosmetics;
[AttributeUsage(AttributeTargets.Property)]
public class RegisterCustomCosmeticAttribute(int priority = 0) : Attribute
{
public int Priority { get; } = priority;
}
@@ -0,0 +1,40 @@
using System.Collections.Generic;
namespace MiraAPI.Cosmetics;
public class VanillaCosmeticsGroup : AbstractCosmeticsGroup
{
public override string GroupName => "Vanilla";
internal static HatData[] VanillaHats => DestroyableSingleton<HatManager>.Instance.allHats;
internal static VisorData[] VanillaVisors => DestroyableSingleton<HatManager>.Instance.allVisors;
internal static SkinData[] VanillaSkins => DestroyableSingleton<HatManager>.Instance.allSkins;
internal static NamePlateData[] VanillaNameplates => DestroyableSingleton<HatManager>.Instance.allNamePlates;
internal List<CosmeticData> Cosmetics { get; } = [];
internal bool registered { get; set; }
internal bool runtimeRegister()
{
if (registered)
{
return true;
}
if (!DestroyableSingleton<HatManager>.InstanceExists || VanillaHats.Length == 0
|| VanillaVisors.Length == 0 || VanillaSkins.Length == 0
|| VanillaNameplates.Length == 0)
{
return false;
}
registered = true;
Hats.AddRange(VanillaHats);
Visors.AddRange(VanillaVisors);
Skins.AddRange(VanillaSkins);
Nameplates.AddRange(VanillaNameplates);
Cosmetics.AddRange(Hats);
Cosmetics.AddRange(Visors);
Cosmetics.AddRange(Skins);
Cosmetics.AddRange(Nameplates);
return true;
}
}
@@ -1,44 +0,0 @@
using MiraAPI.Hud;
namespace MiraAPI.Events.Mira;
/// <summary>
/// Invoked when a Mira Button click is cancelled. Do not use for vanilla buttons.
/// </summary>
/// <typeparam name="T">The Mira Button type.</typeparam>
public sealed class MiraButtonCancelledEvent<T> : MiraEvent where T : CustomActionButton
{
/// <summary>
/// Gets Mira Button whose click was cancelled.
/// </summary>
public T Button { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraButtonCancelledEvent{T}"/> class.
/// </summary>
/// <param name="button">The Mira Button whose click was cancelled.</param>
public MiraButtonCancelledEvent(T button)
{
Button = button;
}
}
/// <summary>
/// Invoked when a Mira Button click is cancelled. Do not use for vanilla buttons.
/// </summary>
public sealed class MiraButtonCancelledEvent : MiraEvent
{
/// <summary>
/// Gets Mira Button whose click was cancelled.
/// </summary>
public CustomActionButton Button { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraButtonCancelledEvent"/> class.
/// </summary>
/// <param name="button">The Mira Button whose click was cancelled.</param>
public MiraButtonCancelledEvent(CustomActionButton button)
{
Button = button;
}
}
@@ -1,51 +0,0 @@
using MiraAPI.Hud;
namespace MiraAPI.Events.Mira;
/// <summary>
/// Button click event for Mira Buttons only. Do not use for vanilla buttons.
/// </summary>
/// <typeparam name="T">The Mira Button type.</typeparam>
public sealed class MiraButtonClickEvent<T> : MiraCancelableEvent where T : CustomActionButton
{
/// <summary>
/// Gets Mira Button that was clicked.
/// </summary>
public T Button { get; }
/// <summary>
/// Gets the generic click event that is invoked before this button-specific event.
/// </summary>
public MiraButtonClickEvent GenericClickEvent { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraButtonClickEvent{T}"/> class.
/// </summary>
/// <param name="button">The Mira Button that was clicked.</param>
/// <param name="genericClickEvent">The generic click event invoked before button-specific events.</param>
public MiraButtonClickEvent(T button, MiraButtonClickEvent genericClickEvent)
{
GenericClickEvent = genericClickEvent;
Button = button;
}
}
/// <summary>
/// Button click event for Mira Buttons only. Do not use for vanilla buttons.
/// </summary>
public sealed class MiraButtonClickEvent : MiraCancelableEvent
{
/// <summary>
/// Gets Mira Button that was clicked.
/// </summary>
public CustomActionButton Button { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraButtonClickEvent"/> class.
/// </summary>
/// <param name="button">The Mira Button that was clicked.</param>
public MiraButtonClickEvent(CustomActionButton button)
{
Button = button;
}
}
-28
View File
@@ -1,28 +0,0 @@
namespace MiraAPI.Events;
/// <summary>
/// Abstract class for Mira Events that can be cancelled.
/// </summary>
public abstract class MiraCancelableEvent : MiraEvent
{
/// <summary>
/// Gets a value indicating whether the event is cancelled.
/// </summary>
public bool IsCancelled { get; private set; }
/// <summary>
/// Cancels the event.
/// </summary>
public void Cancel()
{
IsCancelled = true;
}
/// <summary>
/// Uncancels the event.
/// </summary>
public void UnCancel()
{
IsCancelled = false;
}
}
-6
View File
@@ -1,6 +0,0 @@
namespace MiraAPI.Events;
/// <summary>
/// Abstract class for Mira Events.
/// </summary>
public abstract class MiraEvent;
-81
View File
@@ -1,81 +0,0 @@
using System;
using System.Collections.Generic;
namespace MiraAPI.Events;
/// <summary>
/// Mira Event manager.
/// </summary>
public static class MiraEventManager
{
private static readonly Dictionary<Type, List<MiraEventWrapper>> EventWrappers = [];
/// <summary>
/// Invoke an event.
/// </summary>
/// <param name="eventInstance">The event instance.</param>
/// <typeparam name="T">Type of Event.</typeparam>
/// <returns>If there was an event handler invoked for this event, return true. Otherwise, return false.</returns>
public static bool InvokeEvent<T>(T eventInstance) where T : MiraEvent
{
EventWrappers.TryGetValue(typeof(T), out var handlers);
if (handlers == null)
{
return false;
}
foreach (var handler in handlers)
{
((Action<T>)handler.EventHandler).Invoke(eventInstance);
}
return true;
}
/// <summary>
/// Invoke an event and use a specific type to find the handlers.
/// </summary>
/// <param name="eventInstance">The event instance.</param>
/// <param name="type">The type to use for handler lookup.</param>
/// <returns>If there was an event handler invoked for this event, return true. Otherwise, return false.</returns>
public static bool InvokeEvent(MiraEvent eventInstance, Type type)
{
EventWrappers.TryGetValue(type, out var handlers);
if (handlers == null)
{
return false;
}
foreach (var handler in handlers)
{
handler.EventHandler.DynamicInvoke(eventInstance);
}
return true;
}
/// <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>
/// <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), []);
}
var handlers = EventWrappers[typeof(T)];
handlers.Add(new MiraEventWrapper(handler, priority));
}
internal static void SortAllHandlers()
{
foreach (var handlers in EventWrappers.Values)
{
handlers.Sort((a, b) => a.Priority.CompareTo(b.Priority));
}
}
}
-30
View File
@@ -1,30 +0,0 @@
using System;
namespace MiraAPI.Events;
/// <summary>
/// Wrapper for event handlers.
/// </summary>
public class MiraEventWrapper
{
/// <summary>
/// Gets the event handler delegate.
/// </summary>
public Delegate EventHandler { get; }
/// <summary>
/// Gets the priority of the handler. Higher values are called first.
/// </summary>
public int Priority { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraEventWrapper"/> class.
/// </summary>
/// <param name="eventHandler">The action for the event handler.</param>
/// <param name="priority">The priority of the handler.</param>
public MiraEventWrapper(Delegate eventHandler, int priority)
{
EventHandler = eventHandler;
Priority = priority;
}
}
@@ -1,28 +0,0 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// Event that is invoked after a player is murdered. Only called after a successful murder. This event is not cancelable.
/// </summary>
public class AfterMurderEvent : MiraEvent
{
/// <summary>
/// Gets the player that killed the target.
/// </summary>
public PlayerControl Source { get; }
/// <summary>
/// Gets the player that was killed.
/// </summary>
public PlayerControl Target { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
/// </summary>
/// <param name="source">The killer.</param>
/// <param name="target">The killed player.</param>
public AfterMurderEvent(PlayerControl source, PlayerControl target)
{
Source = source;
Target = target;
}
}
@@ -1,28 +0,0 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// Event that is invoked before a player is murdered. This event is cancelable.
/// </summary>
public sealed class BeforeMurderEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the player that is killing the target.
/// </summary>
public PlayerControl Source { get; }
/// <summary>
/// Gets the player that is being killed.
/// </summary>
public PlayerControl Target { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
/// <param name="source">The player that is killing the target.</param>
/// <param name="target">The player that is being killed.</param>
public BeforeMurderEvent(PlayerControl source, PlayerControl target)
{
Source = source;
Target = target;
}
}
@@ -1,21 +0,0 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// The event that is invoked when the end game screen is shown. Non cancelable.
/// </summary>
public class GameEndEvent : MiraEvent
{
/// <summary>
/// Gets the instance of the EndGameManager.
/// </summary>
public EndGameManager EndGameManager { get; }
/// <summary>
/// Initializes a new instance of the <see cref="GameEndEvent"/> class.
/// </summary>
/// <param name="manager">The instance of the EndGameManager.</param>
public GameEndEvent(EndGameManager manager)
{
EndGameManager = manager;
}
}
@@ -1,21 +0,0 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// The event that is invoked when the intro cutscene is shown. Non cancelable.
/// </summary>
public class IntroBeginEvent : MiraEvent
{
/// <summary>
/// Gets the instance of the IntroCutscene.
/// </summary>
public IntroCutscene IntroCutscene { get; }
/// <summary>
/// Initializes a new instance of the <see cref="IntroBeginEvent"/> class.
/// </summary>
/// <param name="introCutscene">The intro cutscene.</param>
public IntroBeginEvent(IntroCutscene introCutscene)
{
IntroCutscene = introCutscene;
}
}
@@ -1,30 +0,0 @@
using AmongUs.GameOptions;
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// Event that is invoked after a player's role is set. This event is not cancelable.
/// </summary>
public class SetRoleEvent : MiraEvent
{
/// <summary>
/// Gets the player whos role was changed.
/// </summary>
public PlayerControl Player { get; }
/// <summary>
/// Gets the role that the player was set to.
/// </summary>
public RoleTypes Role { get; }
/// <summary>
/// Initializes a new instance of the <see cref="SetRoleEvent"/> class.
/// </summary>
/// <param name="player">The player.</param>
/// <param name="role">The new role.</param>
public SetRoleEvent(PlayerControl player, RoleTypes role)
{
Player = player;
Role = role;
}
}
@@ -1,21 +0,0 @@
namespace MiraAPI.Events.Vanilla.Map;
/// <summary>
/// Event fired when a player closes the doors in a room.
/// </summary>
public class CloseDoorsEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the room that the doors were closed in.
/// </summary>
public SystemTypes Room { get; }
/// <summary>
/// Initializes a new instance of the <see cref="CloseDoorsEvent"/> class.
/// </summary>
/// <param name="room">The room that was closed.</param>
public CloseDoorsEvent(SystemTypes room)
{
Room = room;
}
}
@@ -1,21 +0,0 @@
namespace MiraAPI.Events.Vanilla.Map;
/// <summary>
/// Sabotage from Vanilla Among Us.
/// </summary>
public class PlayerOpenSabotageEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the MapBehaviour.
/// </summary>
public MapBehaviour MapBehaviour { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PlayerOpenSabotageEvent"/> class.
/// </summary>
/// <param name="mapBehaviour">The MapBehaviour.</param>
public PlayerOpenSabotageEvent(MapBehaviour mapBehaviour)
{
MapBehaviour = mapBehaviour;
}
}
@@ -1,34 +0,0 @@
namespace MiraAPI.Events.Vanilla.Map;
/// <summary>
/// Cancelable event that is invoked before a system is updated. Usually used for sabotage events.
/// </summary>
public class UpdateSystemEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the type of system that will be updated.
/// </summary>
public SystemTypes SystemType { get; }
/// <summary>
/// Gets the player that is updating the system.
/// </summary>
public PlayerControl Player { get; }
/// <summary>
/// Gets the byte amount the system is being updated by.
/// </summary>
public byte Amount { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSystemEvent"/> class.
/// </summary>
/// <param name="systemType">The SystemType being updated.</param>
/// <param name="amount">Amount to update System to.</param>
public UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byte amount)
{
SystemType = systemType;
Player = player;
Amount = amount;
}
}
@@ -1,21 +0,0 @@
namespace MiraAPI.Events.Vanilla.Meeting;
/// <summary>
/// The event that is invoked when a player is ejected. Non-cancelable.
/// </summary>
public class EjectionEvent : MiraEvent
{
/// <summary>
/// Gets the instance of the ExileController.
/// </summary>
public ExileController ExileController { get; }
/// <summary>
/// Initializes a new instance of the <see cref="EjectionEvent"/> class.
/// </summary>
/// <param name="controller">The exile controller.</param>
public EjectionEvent(ExileController controller)
{
ExileController = controller;
}
}
@@ -1,35 +0,0 @@
namespace MiraAPI.Events.Vanilla.Meeting;
/// <summary>
/// The event that is invoked when a meeting is called.
/// </summary>
public class StartMeetingEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the player that is calling the meeting.
/// </summary>
public PlayerControl Reporter { get; }
/// <summary>
/// Gets the player that is being reported. Will be null for emergency meeting.
/// </summary>
public NetworkedPlayerInfo? Target { get; }
/// <summary>
/// Gets the body that is being reported. Will be null for emergency meeting.
/// </summary>
public DeadBody? Body { get; }
/// <summary>
/// Initializes a new instance of the <see cref="StartMeetingEvent"/> class.
/// </summary>
/// <param name="reporter">The player who reported the body.</param>
/// <param name="target">The player being reported.</param>
/// <param name="body">The body being reported.</param>
public StartMeetingEvent(PlayerControl reporter, NetworkedPlayerInfo? target, DeadBody? body)
{
Reporter = reporter;
Target = target;
Body = body;
}
}
@@ -1,28 +0,0 @@
namespace MiraAPI.Events.Vanilla.Player;
/// <summary>
/// The event that is invoked when a player completes a task. Non cancelable.
/// </summary>
public class CompleteTaskEvent : MiraEvent
{
/// <summary>
/// Gets the instance of the <see cref="PlayerControl"/>.
/// </summary>
public PlayerControl Player { get; }
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task { get; }
/// <summary>
/// Initializes a new instance of the <see cref="CompleteTaskEvent"/> class.
/// </summary>
/// <param name="player">The player who completed the task.</param>
/// <param name="task">The task that the player completed.</param>
public CompleteTaskEvent(PlayerControl player, PlayerTask task)
{
Player = player;
Task = task;
}
}
@@ -1,28 +0,0 @@
namespace MiraAPI.Events.Vanilla.Player;
/// <summary>
/// Event that is invoked when a player dies. Non cancelable.
/// </summary>
public class PlayerDeathEvent : MiraEvent
{
/// <summary>
/// Gets the player who died.
/// </summary>
public PlayerControl Player { get; }
/// <summary>
/// Gets the reason the player died.
/// </summary>
public DeathReason DeathReason { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PlayerDeathEvent"/> class.
/// </summary>
/// <param name="player">The player who died.</param>
/// <param name="reason">The reason the player died.</param>
public PlayerDeathEvent(PlayerControl player, DeathReason reason)
{
Player = player;
DeathReason = reason;
}
}
@@ -1,23 +0,0 @@
using InnerNet;
namespace MiraAPI.Events.Vanilla.Player;
/// <summary>
/// Event that is invoked when a player joins the lobby. Non cancelable.
/// </summary>
public class PlayerJoinEvent : MiraEvent
{
/// <summary>
/// Gets the player who joined.
/// </summary>
public ClientData ClientData { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PlayerJoinEvent"/> class.
/// </summary>
/// <param name="data">The data of the player who joined.</param>
public PlayerJoinEvent(ClientData data)
{
ClientData = data;
}
}
@@ -1,30 +0,0 @@
using InnerNet;
namespace MiraAPI.Events.Vanilla.Player;
/// <summary>
/// Event that is invoked when a player leaves the game. Non cancelable.
/// </summary>
public class PlayerLeaveEvent : MiraEvent
{
/// <summary>
/// Gets the player who left.
/// </summary>
public ClientData ClientData { get; }
/// <summary>
/// Gets the reason why the player left.
/// </summary>
public DisconnectReasons Reason { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PlayerLeaveEvent"/> class.
/// </summary>
/// <param name="data">The data of the player who left.</param>
/// <param name="reason">The reason why the player left.</param>
public PlayerLeaveEvent(ClientData data, DisconnectReasons reason)
{
ClientData = data;
Reason = reason;
}
}
@@ -1,28 +0,0 @@
namespace MiraAPI.Events.Vanilla.Usables;
/// <summary>
/// Event that is invoked when a player enters a vent. This event is cancelable.
/// </summary>
public class EnterVentEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the player that is entering the vent.
/// </summary>
public PlayerControl Player { get; }
/// <summary>
/// Gets the vent that the player is entering.
/// </summary>
public Vent? Vent { get; }
/// <summary>
/// Initializes a new instance of the <see cref="EnterVentEvent"/> class.
/// </summary>
/// <param name="player">The player that is entering the vent.</param>
/// <param name="vent">The vent being entered.</param>
public EnterVentEvent(PlayerControl player, Vent? vent)
{
Player = player;
Vent = vent;
}
}
@@ -1,28 +0,0 @@
namespace MiraAPI.Events.Vanilla.Usables;
/// <summary>
/// Event that is invoked when a player exits a vent. This event is cancelable.
/// </summary>
public class ExitVentEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the player that is exiting the vent.
/// </summary>
public PlayerControl Player { get; }
/// <summary>
/// Gets the vent that the player is exiting.
/// </summary>
public Vent? Vent { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ExitVentEvent"/> class.
/// </summary>
/// <param name="player">The player who is exiting the vent.</param>
/// <param name="vent">The vent being exited from.</param>
public ExitVentEvent(PlayerControl player, Vent? vent)
{
Player = player;
Vent = vent;
}
}
@@ -1,15 +0,0 @@
namespace MiraAPI.Events.Vanilla.Usables;
/// <summary>
/// Event for if a <see cref="PlayerControl"/> can use an <see cref="IUsable"/> from Vanilla Among Us. Will always be ran locally.
/// </summary>
public class PlayerCanUseEvent : PlayerUseEvent
{
/// <summary>
/// Initializes a new instance of the <see cref="PlayerCanUseEvent"/> class.
/// </summary>
/// <param name="usable">The IUsable.</param>
public PlayerCanUseEvent(IUsable usable) : base(usable)
{
}
}
@@ -1,34 +0,0 @@
namespace MiraAPI.Events.Vanilla.Usables;
/// <summary>
/// Event for <see cref="PlayerControl"/> using a <see cref="IUsable"/> from Vanilla Among Us. Will always be ran locally.
/// </summary>
public class PlayerUseEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the instance of <see cref="IUsable"/> that was used.
/// </summary>
public IUsable Usable { get; }
/// <summary>
/// Gets a value indicating whether the IUsable is a <see cref="Console"/>, <see cref="MapConsole"/>, or <see cref="SystemConsole"/>.
/// </summary>
public bool IsPrimaryConsole { get; }
/// <summary>
/// Gets a value indicating whether the IUsable is a <see cref="Vent"/>.
/// </summary>
public bool IsVent { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PlayerUseEvent"/> class.
/// </summary>
/// <param name="usable">The IUsable.</param>
public PlayerUseEvent(IUsable usable)
{
Usable = usable;
IsPrimaryConsole = usable.TryCast<Console>() || usable.TryCast<SystemConsole>() || usable.TryCast<MapConsole>();
IsVent = usable.TryCast<Vent>();
}
}
-77
View File
@@ -1,77 +0,0 @@
using System.Collections.Generic;
using MiraAPI.Networking;
using Reactor.Networking.Rpc;
namespace MiraAPI.GameEnd;
/// <summary>
/// Custom Game Over.
/// </summary>
public abstract class CustomGameOver
{
/// <summary>
/// Gets the current CustomGameOver.
/// </summary>
public static CustomGameOver? Instance { get; internal set; }
/// <summary>
/// Verifies if the condition for this CustomGameOver is met.
/// </summary>
/// <param name="playerControl">The PlayerControl that requested the Game Over.</param>
/// <returns>True if the condition is met, otherwise false.</returns>
public virtual bool VerifyCondition(PlayerControl playerControl)
{
return true;
}
/// <summary>
/// Runs before the base game calls EndGameManager.SetEverythingUp.
/// </summary>
/// <param name="endGameManager">The EndGameManager instance.</param>
/// <returns>Return True to use the run the original method, return False to skip it.</returns>
public virtual bool BeforeEndGameSetup(EndGameManager endGameManager)
{
return true;
}
/// <summary>
/// Runs after the base game calls EndGameManager.SetEverythingUp.
/// </summary>
/// <param name="endGameManager">The EndGameManager instance.</param>
public virtual void AfterEndGameSetup(EndGameManager endGameManager)
{
}
/// <summary>
/// Get the GameOverReason associated with this CustomGameOver.
/// </summary>
/// <typeparam name="T">Type of the custom game over.</typeparam>
/// <returns>The GameOverReason associated with the custom game over.</returns>
public static GameOverReason GameOverReason<T>() where T : CustomGameOver
{
return (GameOverReason)GameOverManager.GetGameOverId<T>();
}
/// <summary>
/// Send a custom game over.
/// </summary>
/// <param name="winners">A collection of winners.</param>
/// <typeparam name="T">Type of the custom game over.</typeparam>
public static void Trigger<T>(IEnumerable<NetworkedPlayerInfo> winners) where T : CustomGameOver
{
var reason = GameOverManager.GetGameOverId<T>();
var data = new GameOverData(reason, [.. winners]);
Rpc<CustomGameOverRpc>.Instance.Send(PlayerControl.LocalPlayer, data, true);
}
/// <summary>
/// Implicitly convert a CustomGameOver to a GameOverReason.
/// </summary>
/// <param name="gameOver">The CustomGameOver instance.</param>
/// <returns>The GameOverReason associated with the CustomGameOver.</returns>
public static implicit operator GameOverReason(CustomGameOver gameOver)
{
return (GameOverReason)GameOverManager.GetGameOverId(gameOver.GetType());
}
}
-10
View File
@@ -1,10 +0,0 @@
using System.Collections.Generic;
namespace MiraAPI.GameEnd;
/// <summary>
/// Data for a game over.
/// </summary>
/// <param name="Reason">Reason for the game over.</param>
/// <param name="Winners">A collection of winners.</param>
public record struct GameOverData(int Reason, List<NetworkedPlayerInfo> Winners);
-90
View File
@@ -1,90 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Reactor.Utilities;
namespace MiraAPI.GameEnd;
/// <summary>
/// Manage custom game overs.
/// </summary>
public static class GameOverManager
{
private static readonly Dictionary<Type, int> GameOverIds = [];
private static readonly Dictionary<int, Type> GameOverTypes = [];
private static int _nextId = Enum.GetNames<GameOverReason>().Length;
/// <summary>
/// Register a custom game over.
/// </summary>
/// <param name="gameOverType">Type of the custom game over.</param>
/// <exception cref="ArgumentException">Thrown when the type is not a subclass of CustomGameOver, is abstract, or does not have a parameterless constructor.</exception>
/// <returns>>True if the game over was registered successfully, false otherwise.</returns>
public static bool RegisterGameOver(Type gameOverType)
{
if (!typeof(CustomGameOver).IsAssignableFrom(gameOverType))
{
return false;
}
if (gameOverType.IsAbstract)
{
Logger<MiraApiPlugin>.Error("The type must not be abstract.");
return false;
}
if (gameOverType.GetConstructor(Type.EmptyTypes) == null)
{
Logger<MiraApiPlugin>.Error("The type must have a parameterless constructor.");
return false;
}
GameOverIds.Add(gameOverType, _nextId);
GameOverTypes.Add(_nextId, gameOverType);
_nextId++;
return true;
}
/// <summary>
/// Create an instance of a custom game over.
/// </summary>
/// <param name="id">ID of the custom game over.</param>
/// <param name="customGameOver">The created instance of the custom game over.</param>
/// <returns>An instance of the custom game over.</returns>
public static bool TryGetGameOver(int id, [NotNullWhen(true)] out CustomGameOver? customGameOver)
{
if (GameOverTypes.TryGetValue(id, out var gameOverType))
{
customGameOver = Activator.CreateInstance(gameOverType) as CustomGameOver;
return customGameOver != null;
}
customGameOver = null;
return false;
}
/// <summary>
/// Get the ID of a custom game over.
/// </summary>
/// <typeparam name="T">Type of the custom game over.</typeparam>
/// <returns>The ID of the custom game over.</returns>
public static int GetGameOverId<T>() where T : CustomGameOver
{
return GetGameOverId(typeof(T));
}
/// <summary>
/// Get the ID of a custom game over.
/// </summary>
/// <param name="gameOverType">Type of the custom game over.</param>
/// <returns>The ID of the custom game over.</returns>
/// <exception cref="ArgumentException">Thrown when the type is not registered.</exception>
public static int GetGameOverId(Type gameOverType)
{
if (GameOverIds.TryGetValue(gameOverType, out var id))
return id;
throw new ArgumentException($"{gameOverType.FullName} is not a registered custom game over!");
}
}
+2 -2
View File
@@ -21,7 +21,7 @@ public static class CustomGameModeManager
}
/// <summary>
/// Current gamemode.
/// Gets current gamemode.
/// </summary>
public static CustomGameMode? ActiveMode { get; internal set; } = new DefaultMode();
@@ -29,7 +29,7 @@ public static class CustomGameModeManager
/// Set current gamemode.
/// </summary>
/// <param name="id">gamemode ID.</param>
public static void SetGameMode(int id)
internal static void SetGameMode(int id)
{
if (GameModes.TryGetValue(id, out var gameMode))
{
+1
View File
@@ -1,5 +1,6 @@
namespace MiraAPI.GameModes;
[RegisterGameMode]
public class DefaultMode : CustomGameMode
{
public override string Name => "Default";
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Reflection;
namespace MiraAPI.GameModes;
[AttributeUsage(AttributeTargets.Class)]
public class RegisterGameModeAttribute : Attribute
{
private static readonly HashSet<Assembly> RegisteredAssemblies = [];
internal static void Register(Assembly assembly)
{
if (!RegisteredAssemblies.Add(assembly))
{
return;
}
foreach (var type in assembly.GetTypes())
{
var attribute = type.GetCustomAttribute<RegisterGameModeAttribute>();
if (attribute != null)
{
CustomGameModeManager.RegisterGameMode(type);
}
}
}
}
@@ -27,8 +27,10 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va
/// <inheritdoc />
public override object GetValue()
{
return HolderOption is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType ${enumType.FullName} is not a ModdedEnumOption");
if (HolderOption is ModdedEnumOption opt)
{
return Enum.ToObject(enumType, opt.Value);
}
throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType ${enumType.FullName} is not a ModdedEnumOption");
}
}
@@ -15,14 +15,13 @@ public class ModdedNumberOptionAttribute(
float max,
float increment = 1,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool zeroInfinity = false,
Type? roleType = null)
: ModdedOptionAttribute(title, roleType)
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
return new ModdedNumberOption(Title, (float)(value ?? min+increment), min, max, increment, suffixType, formatString, zeroInfinity, RoleType);
return new ModdedNumberOption(Title, (float)(value ?? min+increment), min, max, increment, suffixType, zeroInfinity, RoleType);
}
/// <inheritdoc />
+1
View File
@@ -21,4 +21,5 @@ public interface IModdedOption
float GetFloatData();
NetData GetNetData();
void HandleNetData(byte[] data);
void ResetToConfig();
}
+1 -2
View File
@@ -31,6 +31,7 @@ public static class ModdedOptionsManager
{
if (Activator.CreateInstance(type) is not AbstractOptionGroup group)
{
Logger<MiraApiPlugin>.Error($"Failed to create group from {type.Name}");
return false;
}
@@ -141,7 +142,6 @@ public static class ModdedOptionsManager
{
// necessary to disable then re-enable this setting
// we dont know how other plugins handle their configs
// this way, all the options are saved at once, instead of one by one
var oldConfigSetting = new Dictionary<MiraPluginInfo, bool>();
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins())
{
@@ -161,7 +161,6 @@ public static class ModdedOptionsManager
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins())
{
plugin.PluginConfig.Save();
plugin.PluginConfig.SaveOnConfigSet = oldConfigSetting[plugin];
}
@@ -1,7 +1,5 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Networking;
using Reactor.Localization.Utilities;
@@ -88,7 +86,10 @@ public class ModdedEnumOption : ModdedOption<int>
/// <inheritdoc />
protected override void OnValueChanged(int newValue)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data?.GetValueString(newValue), false);
if (HudManager.InstanceExists)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(newValue), false);
}
if (!OptionBehaviour)
{
return;
@@ -100,96 +101,3 @@ public class ModdedEnumOption : ModdedOption<int>
}
}
}
/// <summary>
/// An option for selecting an enum value.
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
{
/// <summary>
/// Gets the string values of the enum.
/// </summary>
public string[]? Values { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption{T}"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an int.</param>
/// <param name="enumType">The Enum type.</param>
/// <param name="values">An option list of string values to use in place of the enum name.</param>
/// <param name="roleType">An optional role type to specify for a specific role.</param>
public ModdedEnumOption(string title, T defaultValue, string[]? values = null, Type? roleType = null) : base(title, defaultValue, roleType)
{
Values = values ?? Enum.GetNames(typeof(T));
Data = ScriptableObject.CreateInstance<StringGameSetting>();
var data = (StringGameSetting)Data;
data.Title = StringName;
data.Type = global::OptionTypes.String;
data.Values = values is null ?
Enum.GetNames(typeof(T)).Select(CustomStringName.CreateAndRegister).ToArray()
: values.Select(CustomStringName.CreateAndRegister).ToArray();
data.Index = Convert.ToInt32(Value);
}
/// <inheritdoc />
public override OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, Transform container)
{
var stringOption = Object.Instantiate(stringOpt, container);
stringOption.SetUpFromData(Data, 20);
stringOption.OnValueChanged = (Il2CppSystem.Action<OptionBehaviour>)ValueChanged;
// SetUpFromData method doesnt work correctly so we must set the values manually
stringOption.Title = StringName;
stringOption.Values = (Data as StringGameSetting)?.Values ?? new Il2CppStructArray<StringNames>(0);
stringOption.Value = Convert.ToInt32(Value, NumberFormatInfo.InvariantInfo);
OptionBehaviour = stringOption;
return stringOption;
}
/// <inheritdoc />
public override float GetFloatData()
{
return Convert.ToSingle(Value, NumberFormatInfo.InvariantInfo);
}
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value, NumberFormatInfo.InvariantInfo)!));
}
/// <inheritdoc />
public override void HandleNetData(byte[] data)
{
SetValue((T)Enum.Parse(typeof(T), Encoding.Unicode.GetString(data)));
}
/// <inheritdoc />
public override T GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
return (T)Enum.Parse(typeof(T), optionBehaviour.GetInt().ToString(NumberFormatInfo.InvariantInfo));
}
/// <inheritdoc />
protected override void OnValueChanged(T newValue)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo)), false);
if (!OptionBehaviour)
{
return;
}
if (OptionBehaviour is StringOption opt)
{
opt.Value = Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo);
}
}
}
@@ -46,7 +46,6 @@ public class ModdedNumberOption : ModdedOption<float>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="roleType">An optional role type.</param>
public ModdedNumberOption(
@@ -56,7 +55,6 @@ public class ModdedNumberOption : ModdedOption<float>
float max,
float increment,
MiraNumberSuffixes suffixType,
string? formatString = null,
bool zeroInfinity = false,
Type? roleType = null) : base(title, defaultValue, roleType)
{
@@ -76,13 +74,7 @@ public class ModdedNumberOption : ModdedOption<float>
data.Value = Value;
data.Increment = Increment;
data.ValidRange = new FloatRange(Min, Max);
data.FormatString = formatString ??
(!Mathf.Approximately(defaultValue, 0) ||
!Mathf.Approximately(Increment % 1, 0) ||
!Mathf.Approximately(Value % 1, 0) ||
!Mathf.Approximately(Min % 1, 0) ||
!Mathf.Approximately(Max % 1, 0) ? "0.0" : "0");
data.FormatString = Increment % 1 == 0 && Value % 1 == 0 && Min % 1 == 0 && Max % 1 == 0 ? "0" : "0.0"; // not sure if the == checks will work since this is floats but we'll find out
data.ZeroIsInfinity = ZeroInfinity;
data.SuffixType = (NumberSuffixes)SuffixType;
data.OptionName = FloatOptionNames.Invalid;
@@ -142,24 +134,17 @@ public class ModdedNumberOption : ModdedOption<float>
protected override void OnValueChanged(float newValue)
{
Value = Mathf.Clamp(newValue, Min, Max);
HudManager.Instance.Notifier.AddSettingsChangeMessage(
StringName,
Data?.GetValueString(Value),
false);
if (HudManager.InstanceExists)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(
StringName,
Data.GetValueString(Value),
false);
}
if (OptionBehaviour is NumberOption opt)
{
opt.Value = Value;
}
}
/// <summary>
/// Implicitly converts the option to an int.
/// </summary>
/// <param name="option">The option.</param>
/// <returns>Integer value.</returns>
public static implicit operator int(ModdedNumberOption option)
{
return (int)option.Value;
}
}
+14 -22
View File
@@ -45,7 +45,11 @@ public abstract class ModdedOption<T> : IModdedOption
get => _parentMod;
set
{
if (_parentMod != null || value == null) return;
if (_parentMod != null || value == null)
{
return;
}
_parentMod = value;
var entry = _parentMod.GetConfigFile().Bind(ConfigDefinition, DefaultValue);
Value = entry.Value;
@@ -85,17 +89,7 @@ public abstract class ModdedOption<T> : IModdedOption
/// <summary>
/// Gets or sets the config definition of the option.
/// </summary>
public ConfigDefinition? ConfigDefinition
{
get => _configDefinition;
set
{
if (_configDefinition is not null) return;
_configDefinition = value;
}
}
private ConfigDefinition? _configDefinition;
public ConfigDefinition? ConfigDefinition { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ModdedOption{T}"/> class.
@@ -168,6 +162,14 @@ public abstract class ModdedOption<T> : IModdedOption
/// <param name="data">The NetData's byte array.</param>
public abstract void HandleNetData(byte[] data);
public void ResetToConfig()
{
if (ParentMod?.GetConfigFile().TryGetEntry<T>(ConfigDefinition, out var entry) == true)
{
SetValue(entry.Value);
}
}
/// <summary>
/// Handles the value changed event.
/// </summary>
@@ -194,14 +196,4 @@ public abstract class ModdedOption<T> : IModdedOption
NumberOption numberOpt,
StringOption stringOpt,
Transform container);
/// <summary>
/// Implicitly converts the option to type of <typeparamref name="T"/>.
/// </summary>
/// <param name="option">The option.</param>
/// <returns>Value of type <typeparamref name="T"/>.</returns>
public static implicit operator T(ModdedOption<T> option)
{
return option.Value;
}
}
@@ -69,7 +69,10 @@ public class ModdedToggleOption : ModdedOption<bool>
/// <inheritdoc />
protected override void OnValueChanged(bool newValue)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, newValue ? "On" : "Off", false);
if (HudManager.InstanceExists)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, newValue ? "On" : "Off", false);
}
if (!OptionBehaviour)
{
return;
+33 -177
View File
@@ -1,13 +1,7 @@
using System;
using System.Globalization;
using MiraAPI.Events;
using MiraAPI.Events.Mira;
using MiraAPI.Patches;
using MiraAPI.Utilities.Assets;
using MiraAPI.Utilities.Assets;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Object = UnityEngine.Object;
namespace MiraAPI.Hud;
@@ -21,35 +15,30 @@ public abstract class CustomActionButton
/// </summary>
public abstract string Name { get; }
/// <summary>
/// Gets the initial cooldown duration in seconds.
/// </summary>
public virtual float InitialCooldown => Cooldown;
/// <summary>
/// Gets the button's cooldown duration in seconds.
/// </summary>
public abstract float Cooldown { get; }
/// <summary>
/// Gets the button's effect duration in seconds. If the button has no effect, set to 0.
/// </summary>
public abstract float EffectDuration { get; }
/// <summary>
/// Gets the maximum amount of uses the button has. If the button has infinite uses, set to 0.
/// </summary>
public abstract int MaxUses { get; }
/// <summary>
/// Gets the sprite of the button. Use <see cref="LoadableResourceAsset"/> to load a sprite from a resource path. Use <see cref="LoadableBundleAsset{T}"/> to load a sprite from an asset bundle.
/// </summary>
public abstract LoadableAsset<Sprite> Sprite { get; }
/// <summary>
/// Gets the button's effect duration in seconds. If the button has no effect, set to 0.
/// </summary>
public virtual float EffectDuration => 0;
/// <summary>
/// Gets the maximum amount of uses the button has. If the button has infinite uses, set to 0.
/// </summary>
public virtual int MaxUses => 0;
/// <summary>
/// Gets the location of the button on the screen.
/// </summary>
public virtual ButtonLocation Location { get; private set; } = ButtonLocation.BottomLeft;
public virtual ButtonLocation Location => ButtonLocation.BottomLeft;
/// <summary>
/// Gets a value indicating whether the button has an effect ability.
@@ -66,11 +55,6 @@ public abstract class CustomActionButton
/// </summary>
public bool EffectActive { get; protected set; }
/// <summary>
/// Gets or sets a value indicating whether the timer is currently active.
/// </summary>
public bool TimerPaused { get; protected set; }
/// <summary>
/// Gets or sets the amount of uses left.
/// </summary>
@@ -86,11 +70,7 @@ public abstract class CustomActionButton
/// </summary>
protected ActionButton? Button { get; private set; }
/// <summary>
/// The method used to create the button.
/// </summary>
/// <param name="parent">The parent of the button.</param>
public virtual void CreateButton(Transform parent)
internal void CreateButton(Transform parent)
{
if (Button)
{
@@ -98,9 +78,8 @@ public abstract class CustomActionButton
}
UsesLeft = MaxUses;
Timer = AmongUsClient.Instance?.NetworkMode == NetworkModes.FreePlay ? 0 : InitialCooldown;
Timer = Cooldown;
EffectActive = false;
TimerPaused = false;
Button = Object.Instantiate(HudManager.Instance.AbilityButton, parent);
Button.name = Name + "Button";
@@ -116,87 +95,13 @@ public abstract class CustomActionButton
var pb = Button.GetComponent<PassiveButton>();
pb.OnClick = new Button.ButtonClickedEvent();
pb.OnClick.AddListener((UnityAction)(() =>
{
// Invoke the generic button click event.
var genericEvent = new MiraButtonClickEvent(this);
MiraEventManager.InvokeEvent(genericEvent);
if (genericEvent.IsCancelled)
{
MiraEventManager.InvokeEvent(new MiraButtonCancelledEvent(this));
}
// Invoke the button click event for specific button.
var eventType = CustomButtonManager.ButtonEventTypes[GetType()];
var @event = (MiraCancelableEvent)Activator.CreateInstance(eventType, this, genericEvent)!;
var specificInvoked = MiraEventManager.InvokeEvent(@event, eventType);
if (@event.IsCancelled)
{
var cancelEventType = CustomButtonManager.ButtonCancelledEventTypes[GetType()];
var cancelEvent = (MiraEvent)Activator.CreateInstance(cancelEventType, this)!;
MiraEventManager.InvokeEvent(cancelEvent, cancelEventType);
}
if (specificInvoked)
{
if (!@event.IsCancelled)
{
ClickHandler();
}
}
else
{
if (!genericEvent.IsCancelled)
{
ClickHandler();
}
}
}));
}
/// <summary>
/// Allows you to change the button's location.
/// </summary>
/// <param name="location">The new location.</param>
/// <param name="moveButton">Whether the button's position should change ingame.</param>
public virtual void SetButtonLocation(ButtonLocation location, bool moveButton = true)
{
if (!HudManager.InstanceExists || Button == null)
{
return;
}
this.Location = location;
if (!moveButton) return;
if (HudManagerPatches._bottomLeft == null || HudManagerPatches._bottomRight == null)
{
return;
}
switch (location)
{
case ButtonLocation.BottomLeft:
var gridArrange = HudManagerPatches._bottomLeft.GetComponent<GridArrange>();
var aspectPosition = HudManagerPatches._bottomLeft.GetComponent<AspectPosition>();
Button.transform.SetParent(HudManagerPatches._bottomLeft.transform);
gridArrange.Start();
gridArrange.ArrangeChilds();
aspectPosition.AdjustPosition();
break;
case ButtonLocation.BottomRight:
Button.transform.SetParent(HudManagerPatches._bottomRight);
break;
}
pb.OnClick.AddListener((UnityAction)ClickHandler);
}
/// <summary>
/// A utility function to reset the cooldown and/or effect of the button.
/// </summary>
public virtual void ResetCooldownAndOrEffect()
public void ResetCooldownAndOrEffect()
{
Timer = Cooldown;
if (EffectActive)
@@ -211,7 +116,7 @@ public abstract class CustomActionButton
/// A utility function to override the sprite of the button.
/// </summary>
/// <param name="sprite">The new sprite to override with.</param>
public virtual void OverrideSprite(Sprite sprite)
public void OverrideSprite(Sprite sprite)
{
if (Button != null)
{
@@ -223,7 +128,7 @@ public abstract class CustomActionButton
/// A utility function to override the name of the button.
/// </summary>
/// <param name="name">The new name to override with.</param>
public virtual void OverrideName(string name)
public void OverrideName(string name)
{
Button?.OverrideText(name);
}
@@ -232,7 +137,7 @@ public abstract class CustomActionButton
/// Set the button's timer.
/// </summary>
/// <param name="time">The time you want to set to.</param>
public virtual void SetTimer(float time)
public void SetTimer(float time)
{
Timer = Mathf.Clamp(time, -1, float.MaxValue);
}
@@ -241,7 +146,7 @@ public abstract class CustomActionButton
/// Increase the button's timer.
/// </summary>
/// <param name="amount">The amount you want to increase by.</param>
public virtual void IncreaseTimer(float amount)
public void IncreaseTimer(float amount)
{
SetTimer(Timer + amount);
}
@@ -250,40 +155,26 @@ public abstract class CustomActionButton
/// Decrease the button's timer.
/// </summary>
/// <param name="amount">The amount you want to decrease by.</param>
public virtual void DecreaseTimer(float amount)
public void DecreaseTimer(float amount)
{
SetTimer(Timer - amount);
}
/// <summary>
/// Sets whether the timer is paused or not.
/// </summary>
/// <param name="val">Whether you want to pause/resume the timer.</param>
public virtual void SetTimerPaused(bool val)
{
TimerPaused = val;
}
/// <summary>
/// Set the amount of uses this button has left.
/// </summary>
/// <param name="amount">The amount you want to set to.</param>
public virtual void SetUses(int amount)
public void SetUses(int amount)
{
UsesLeft = Mathf.Clamp(amount, 0, int.MaxValue);
Button?.SetUsesRemaining(UsesLeft);
if (Button != null)
{
Button.usesRemainingSprite.color = UsesLeft == 0 ? Color.red : Color.white;
}
Button?.SetUsesRemaining(MaxUses);
}
/// <summary>
/// Increase the amount of uses this button has left.
/// </summary>
/// <param name="amount">The amount you want to increase by. Default: 1.</param>
public virtual void IncreaseUses(int amount = 1)
public void IncreaseUses(int amount = 1)
{
SetUses(UsesLeft + amount);
}
@@ -292,7 +183,7 @@ public abstract class CustomActionButton
/// Decrease the amount of uses this button has left.
/// </summary>
/// <param name="amount">The amount you want to decrease by. Default: 1.</param>
public virtual void DecreaseUses(int amount = 1)
public void DecreaseUses(int amount = 1)
{
SetUses(UsesLeft - amount);
}
@@ -327,24 +218,14 @@ public abstract class CustomActionButton
}
/// <summary>
/// When the button is usable, this method is called to determine if the button can be clicked.
/// When the button is enabled, this method is called to determine if the button can be used.
/// By default, it takes into account the timer, effect, and uses.
/// You can override it to change the behavior.
/// </summary>
/// <returns>A value that represents whether the button can be clicked or not.</returns>
public virtual bool CanClick()
{
return Timer <= 0 && !EffectActive && CanUse();
}
/// <summary>
/// Whether the button should light up or not. This is also the base for CanClick.
/// You can override it to change the behaviour. Do not include timer in here, that is for CanClick.
/// </summary>
/// <returns>A value that represents whether the button should light up or not.</returns>
/// <returns>A value that represents whether the button can be used or not.</returns>
public virtual bool CanUse()
{
return !LimitedUses || UsesLeft > 0;
return Timer <= 0 && !EffectActive && (!LimitedUses || UsesLeft > 0);
}
/// <summary>
@@ -364,9 +245,9 @@ public abstract class CustomActionButton
/// This method takes into account cooldowns, effects, and uses, before calling the <see cref="OnClick"/> method.
/// It can be overridden for custom behavior.
/// </summary>
public virtual void ClickHandler()
protected virtual void ClickHandler()
{
if (!CanClick())
if (!CanUse())
{
return;
}
@@ -378,7 +259,7 @@ public abstract class CustomActionButton
}
OnClick();
Button?.SetDisabled();
if (HasEffect)
{
EffectActive = true;
@@ -398,7 +279,7 @@ 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;
}
@@ -418,17 +299,7 @@ public abstract class CustomActionButton
Button?.SetDisabled();
}
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?.SetCoolDown(Timer, EffectActive ? EffectDuration : Cooldown);
FixedUpdate(playerControl);
}
@@ -486,19 +357,4 @@ public abstract class CustomActionButton<T> : CustomActionButton where T : MonoB
return base.CanUse() && Target != null;
}
/// <inheritdoc />
public override bool CanClick()
{
return base.CanClick() && Target != null;
}
/// <summary>
/// Use this to reset the button's target after used.
/// </summary>
public virtual void ResetTarget()
{
Target = null;
SetOutline(false);
}
}
+12 -21
View File
@@ -1,31 +1,27 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using MiraAPI.Events.Mira;
using MiraAPI.PluginLoading;
using Reactor.Utilities;
namespace MiraAPI.Hud;
/// <summary>
/// Custom button manager for handling custom buttons.
/// </summary>
public static class CustomButtonManager
internal static class CustomButtonManager
{
/// <summary>
/// Gets a list of all registered custom buttons.
/// </summary>
public static ReadOnlyCollection<CustomActionButton> Buttons { get; internal set; } = new([]);
internal static readonly List<CustomActionButton> CustomButtons = [];
internal static readonly Dictionary<Type, Type> ButtonEventTypes = [];
internal static readonly Dictionary<Type, Type> ButtonCancelledEventTypes = [];
internal static bool RegisterButton(Type buttonType, MiraPluginInfo pluginInfo)
internal static void RegisterButton(Type buttonType, MiraPluginInfo pluginInfo)
{
if (!buttonType.IsAssignableTo(typeof(CustomActionButton)) || Activator.CreateInstance(buttonType) is not CustomActionButton button)
if (!typeof(CustomActionButton).IsAssignableFrom(buttonType))
{
return false;
Logger<MiraApiPlugin>.Error($"{buttonType?.Name} does not inherit from CustomActionButton.");
return;
}
if (Activator.CreateInstance(buttonType) is not CustomActionButton button)
{
Logger<MiraApiPlugin>.Error($"Failed to create button from {buttonType.Name}");
return;
}
CustomButtons.Add(button);
@@ -33,10 +29,5 @@ public static class CustomButtonManager
typeof(CustomButtonSingleton<>).MakeGenericType(buttonType)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
.SetValue(null, button);
ButtonEventTypes.Add(buttonType, typeof(MiraButtonClickEvent<>).MakeGenericType(buttonType));
ButtonCancelledEventTypes.Add(buttonType, typeof(MiraButtonCancelledEvent<>).MakeGenericType(buttonType));
return true;
}
}
+1 -9
View File
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Linq;
using AmongUs.GameOptions;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Patches.Stubs;
using Reactor.Utilities.Attributes;
using Reactor.Utilities.Extensions;
@@ -85,17 +84,10 @@ public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr)
/// </summary>
/// <param name="playerMatch">Function to determine if player should show in the custom menu.</param>
/// <param name="onClick">Onclick action for player.</param>
[HideFromIl2Cpp]
public void Begin(Func<PlayerControl, bool> playerMatch, Action<PlayerControl?> onClick)
public void Begin(Func<PlayerControl, bool> playerMatch, Action<PlayerControl> onClick)
{
MinigameStubs.Begin(this, null);
var back = BackButton.GetComponent<PassiveButton>();
back.OnClick.AddListener((UnityAction)(() =>
{
onClick(null);
}));
DestroyableSingleton<DebugAnalytics>.Instance.Analytics.MinigameOpened(PlayerControl.LocalPlayer.Data, TaskType);
var list = PlayerControl.AllPlayerControls.ToArray().Where(playerMatch).ToList();
potentialVictims = [];
+9
View File
@@ -0,0 +1,9 @@
using System;
namespace MiraAPI.Hud;
/// <summary>
/// Attribute to register a button in the HUD. Necessary for the button to be recognized by Mira.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class RegisterButtonAttribute : Attribute;
+2 -3
View File
@@ -10,11 +10,10 @@
<ItemGroup>
<None Include="..\README.md" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\**\*.*" />
</ItemGroup>
<Import Project="../AmongUs.props" />
<Import Project="../AmongUs.props" />
</Project>
+3 -6
View File
@@ -10,20 +10,17 @@ using UnityEngine;
namespace MiraAPI;
/// <summary>
/// The main plugin class for Mira API.
/// </summary>
[BepInAutoPlugin("mira.api", "MiraAPI")]
[BepInProcess("Among Us.exe")]
[BepInDependency(ReactorPlugin.Id)]
[ReactorModFlags(ModFlags.RequireOnAllClients)]
public partial class MiraApiPlugin : BasePlugin
{
public static Color MiraColor { get; } = new Color32(238, 154, 112, 255);
private static MiraPluginManager? PluginManager { get; set; }
internal Harmony Harmony { get; } = new(Id);
/// <inheritdoc />
public Harmony Harmony { get; } = new(Id);
public static Color MiraColor { get; } = new Color32(238, 154, 112, 255);
public override void Load()
{
Harmony.PatchAll();
+3 -25
View File
@@ -1,6 +1,4 @@
using System;
namespace MiraAPI.Modifiers;
namespace MiraAPI.Modifiers;
/// <summary>
/// Base class for all modifiers.
@@ -18,19 +16,9 @@ public abstract class BaseModifier
public ModifierComponent? ModifierComponent { get; internal set; }
/// <summary>
/// Gets a value indicating whether the modifier has been initialized.
/// Gets the modifier id.
/// </summary>
public bool Initialized { get; internal set; }
/// <summary>
/// Gets the unique ID of the modifier.
/// </summary>
public Guid UniqueId { get; internal set; } = Guid.Empty;
/// <summary>
/// Gets the type ID of the modifier.
/// </summary>
public uint TypeId => ModifierManager.GetModifierTypeId(GetType()) ?? throw new InvalidOperationException("Modifier is not registered.");
public uint ModifierId { get; internal set; }
/// <summary>
/// Gets the modifier name.
@@ -42,16 +30,6 @@ public abstract class BaseModifier
/// </summary>
public virtual bool HideOnUi => false;
/// <summary>
/// Gets a value indicating whether the modifier is shown in the freeplay menu.
/// </summary>
public virtual bool ShowInFreeplay => false;
/// <summary>
/// Gets a value indicating whether the modifier is unique. If true, the player can only have one instance of this modifier.
/// </summary>
public virtual bool Unique => true;
/// <summary>
/// Gets the HUD information for this modifier. Defaults to the modifier name. Does nothing if <see cref="HideOnUi"/> is true.
/// </summary>
+63 -290
View File
@@ -1,15 +1,14 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Modifiers.Types;
using MiraAPI.Utilities;
using Reactor.Utilities;
using Reactor.Utilities.Attributes;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Text;
using TMPro;
using UnityEngine;
@@ -68,7 +67,6 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
foreach (var modifier in _toAdd)
{
Modifiers.Add(modifier);
modifier.Initialized = true;
modifier.OnActivate();
if (modifier is TimedModifier { AutoStart: true } timer)
@@ -81,7 +79,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
{
if (_player?.AmOwner == true)
{
HudManager.Instance?.SetHudActive(_player, _player.Data.Role, HudManager.Instance.TaskPanel.isActiveAndEnabled);
HudManager.Instance?.SetHudActive(HudManager.Instance.TaskPanel.isActiveAndEnabled);
}
_toAdd.Clear();
_toRemove.Clear();
@@ -105,12 +103,18 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
return;
}
var filteredModifiers = Modifiers.Where(mod => !mod.HideOnUi).ToArray();
var filteredModifiers = Modifiers.Where(mod => !mod.HideOnUi);
if (filteredModifiers.Length != 0 && !MeetingHud.Instance)
var baseModifiers = filteredModifiers as BaseModifier[] ?? filteredModifiers.ToArray();
var inMeeting = MeetingHud.Instance != null;
_modifierText!.gameObject.SetActive(!inMeeting);
if (baseModifiers.Length != 0)
{
var stringBuild = new StringBuilder();
foreach (var mod in filteredModifiers)
foreach (var mod in baseModifiers)
{
stringBuild.Append(CultureInfo.InvariantCulture, $"\n{mod.GetHudString()}");
}
@@ -123,178 +127,45 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
}
/// <summary>
/// Gets a collection of modifiers by type.
/// </summary>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>A collection of modifiers.</returns>
[HideFromIl2Cpp]
public IEnumerable<T> GetModifiers<T>(Func<T, bool>? predicate=null) where T : BaseModifier
{
return Modifiers.OfType<T>().Where(x => predicate == null || predicate(x));
}
/// <summary>
/// Gets a collection of modifiers by type.
/// Removes a modifier from the player.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>A collection of modifiers.</returns>
[HideFromIl2Cpp]
public IEnumerable<BaseModifier> GetModifiers(Type type, Func<BaseModifier, bool>? predicate=null)
public void RemoveModifier(Type type)
{
return Modifiers.Where(x => x.GetType() == type && (predicate == null || predicate(x)));
}
var modifier = Modifiers.Find(x => x.GetType() == type);
/// <summary>
/// Gets a collection of modifiers by type ID.
/// </summary>
/// <param name="id">The modifier's type ID.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>A collection of modifiers.</returns>
[HideFromIl2Cpp]
public IEnumerable<BaseModifier> GetModifiers(uint id, Func<BaseModifier, bool>? predicate=null)
{
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
$"Cannot get modifier with id {id} because it is not registered.");
if (modifier is null)
{
Logger<MiraApiPlugin>.Error($"Cannot remove modifier {type.Name} because it is not active.");
return;
}
return GetModifiers(type, predicate);
}
/// <summary>
/// Tries to get a modifier by its type.
/// </summary>
/// <param name="modifier">The modifier or null.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>True if the modifier was found, false otherwise.</returns>
[HideFromIl2Cpp]
public bool TryGetModifier<T>([NotNullWhen(true)] out T? modifier, Func<T, bool>? predicate = null) where T : BaseModifier
{
modifier = GetModifier(predicate);
return modifier != null;
}
/// <summary>
/// Tries to get a modifier by its type.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="modifier">The modifier or null.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>True if the modifier was found, false otherwise.</returns>
[HideFromIl2Cpp]
public bool TryGetModifier(Type type, [NotNullWhen(true)] out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
{
modifier = GetModifier(type, predicate);
return modifier != null;
}
/// <summary>
/// Tries to get a modifier by its type ID.
/// </summary>
/// <param name="id">The modifier type ID.</param>
/// <param name="modifier">The modifier or null.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>True if the modifier was found, false otherwise.</returns>
[HideFromIl2Cpp]
public bool TryGetModifier(uint id, [NotNullWhen(true)] out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
{
modifier = GetModifier(id, predicate);
return modifier != null;
}
/// <summary>
/// Tries to get a modifier by its unique ID.
/// </summary>
/// <param name="modifierGuid">The modifier unique ID.</param>
/// <param name="modifier">The modifier or null.</param>
/// <returns>True if the modifier was found, false otherwise.</returns>
[HideFromIl2Cpp]
public bool TryGetModifier(Guid modifierGuid, [NotNullWhen(true)] out BaseModifier? modifier)
{
modifier = GetModifier(modifierGuid);
return modifier != null;
}
/// <summary>
/// Gets a modifier by its type.
/// </summary>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>The Modifier if it is found, null otherwise.</returns>
[HideFromIl2Cpp]
public T? GetModifier<T>(Func<T, bool>? predicate = null) where T : BaseModifier
{
return GetModifiers(predicate).FirstOrDefault();
}
/// <summary>
/// Gets a modifier by its type.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>The Modifier if it is found, null otherwise.</returns>
[HideFromIl2Cpp]
public BaseModifier? GetModifier(Type type, Func<BaseModifier, bool>? predicate = null)
{
return GetModifiers(type).FirstOrDefault(predicate ?? (_ => true));
}
/// <summary>
/// Gets a modifier by its type ID.
/// </summary>
/// <param name="id">The modifier ID.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>The Modifier if it is found, null otherwise.</returns>
[HideFromIl2Cpp]
public BaseModifier? GetModifier(uint id, 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 GetModifier(type, predicate);
}
/// <summary>
/// Gets a modifier by unique ID.
/// </summary>
/// <param name="modifierGuid">The modifier's unique ID.</param>
/// <returns>The modifier if it is found, or null.</returns>
[HideFromIl2Cpp]
public BaseModifier? GetModifier(Guid modifierGuid)
{
return Modifiers.Find(x => x.UniqueId == modifierGuid);
RemoveModifier(modifier);
}
/// <summary>
/// Removes a modifier from the player.
/// </summary>
/// <typeparam name="T">The modifier type.</typeparam>
/// <param name="predicate">The predicate to check the modifier by.</param>
[HideFromIl2Cpp]
public void RemoveModifier<T>(Func<T, bool>? predicate = null) where T : BaseModifier
public void RemoveModifier<T>() where T : BaseModifier
{
RemoveModifier(typeof(T), x => predicate == null || predicate((T)x));
RemoveModifier(typeof(T));
}
/// <summary>
/// Removes a modifier from the player.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <param name="modifierId">The modifier ID.</param>
[HideFromIl2Cpp]
public void RemoveModifier(Type type, Func<BaseModifier, bool>? predicate = null)
public void RemoveModifier(uint modifierId)
{
var modifiers = Modifiers.Where(x => x.GetType() == type && (predicate == null || predicate(x))).ToList();
if (modifiers.Count > 1)
{
throw new InvalidOperationException($"Cannot remove modifier {type.Name} because there are multiple instances of that modifier.");
}
var modifier = Modifiers.Find(x => x.ModifierId == modifierId);
var modifier = modifiers.FirstOrDefault();
if (modifier is null)
{
Logger<MiraApiPlugin>.Error($"Cannot remove modifier {type.Name} because it is not active.");
Logger<MiraApiPlugin>.Error($"Cannot remove modifier with id {modifierId} because it is not active.");
return;
}
@@ -317,48 +188,6 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
_toRemove.Add(modifier);
}
/// <summary>
/// Removes a modifier from the player.
/// </summary>
/// <param name="typeId">The modifier's type ID.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
[HideFromIl2Cpp]
public void RemoveModifier(uint typeId, Func<BaseModifier, bool>? predicate = null)
{
var type = ModifierManager.GetModifierType(typeId) ?? throw new InvalidOperationException(
$"Cannot remove modifier with id {typeId} because it is not registered.");
RemoveModifier(type, predicate);
}
/// <summary>
/// Removes a modifier from the player.
/// </summary>
/// <param name="uniqueId">The modifier's unique ID.</param>
[HideFromIl2Cpp]
public void RemoveModifier(Guid uniqueId)
{
var modifier = GetModifier(uniqueId);
if (modifier == null)
{
Logger<MiraApiPlugin>.Error($"Cannot remove modifier with unique id {uniqueId} because it is not active.");
return;
}
RemoveModifier(modifier);
}
/// <summary>
/// Adds a modifier to the player.
/// </summary>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <typeparam name="T">The Type of the modifier.</typeparam>
/// <returns>The new modifier.</returns>
[HideFromIl2Cpp]
public T? AddModifier<T>(params object[] args) where T : BaseModifier
{
return AddModifier(typeof(T), args) as T;
}
/// <summary>
/// Adds a modifier to the player.
/// </summary>
@@ -367,32 +196,24 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public BaseModifier? AddModifier(BaseModifier modifier)
{
// TODO: Make a proper synchronization system.
if (LobbyBehaviour.Instance)
if (Modifiers.Contains(modifier))
{
Logger<MiraApiPlugin>.Warning($"Modifiers added in the lobby won't sync to new players!");
}
var id = modifier.TypeId;
if (modifier.Unique && Modifiers.Find(x => x.TypeId == id) != null)
{
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {id}!");
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {modifier.ModifierId}!");
return null;
}
if (Modifiers.Contains(modifier))
var modifierId = ModifierManager.GetModifierId(modifier.GetType());
if (modifierId == null)
{
Logger<MiraApiPlugin>.Error($"Player already has this modifier!");
Logger<MiraApiPlugin>.Error($"Cannot add modifier {modifier.GetType().Name} because it has no ID!");
return null;
}
_toAdd.Add(modifier);
modifier.Player = _player;
modifier.ModifierComponent = this;
if (modifier.UniqueId == Guid.Empty)
{
modifier.UniqueId = Guid.NewGuid();
}
modifier.ModifierId = modifierId.Value;
return modifier;
}
@@ -400,90 +221,42 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
/// Adds a modifier to the player.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The modifier that was added.</returns>
[HideFromIl2Cpp]
public BaseModifier? AddModifier(Type type, params object[] args)
public BaseModifier? AddModifier(Type type)
{
BaseModifier? modifier;
if (args.Length > 0)
var modifierId = ModifierManager.GetModifierId(type);
if (modifierId == null)
{
modifier = ModifierFactory.CreateInstance(type, args);
}
else
{
modifier = Activator.CreateInstance(type) as BaseModifier;
if (modifier == null)
{
throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier.");
}
Logger<MiraApiPlugin>.Error($"Cannot add modifier {type.Name} because it is not registered.");
return null;
}
return AddModifier(modifier);
if (Modifiers.Find(x => x.ModifierId == modifierId) != null)
{
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {modifierId}!");
return null;
}
if (Activator.CreateInstance(type) is not BaseModifier modifier)
{
Logger<MiraApiPlugin>.Error($"Cannot add modifier {type.Name} because it is null.");
return null;
}
AddModifier(modifier);
return modifier;
}
/// <summary>
/// Adds a modifier to the player.
/// </summary>
/// <param name="id">The ID of the modifier.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The modifier if it was created, or null if it failed.</returns>
/// <typeparam name="T">The Type of the modifier.</typeparam>
/// <returns>The new modifier.</returns>
[HideFromIl2Cpp]
public BaseModifier? AddModifier(uint id, params object[] args)
public T? AddModifier<T>() where T : BaseModifier
{
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
$"Cannot add modifier with id {id} because it is not registered.");
return AddModifier(type, args);
}
/// <summary>
/// Checks if a player has an active modifier by its type.
/// </summary>
/// <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>(Func<T, bool>? predicate=null) where T : BaseModifier
{
return Modifiers.Exists(x => x 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="predicate">The predicate to check the modifier.</param>
/// <returns>True if the Modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier(Type type, Func<BaseModifier, bool>? predicate=null)
{
return Modifiers.Exists(x => x.GetType() == type && (predicate == null || predicate(x)));
}
/// <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="predicate">The predicate to check the modifier.</param>
/// <returns>True if the modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier(uint id, 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, predicate);
}
/// <summary>
/// Checks if a player has an active modifier by its unique ID.
/// </summary>
/// <param name="id">The modifier's guid.</param>
/// <returns>True if the modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier(Guid id)
{
return Modifiers.Exists(x => x.UniqueId == id);
return AddModifier(typeof(T)) as T;
}
}
-448
View File
@@ -1,448 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.Networking;
using MiraAPI.Networking.Modifiers;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
namespace MiraAPI.Modifiers;
/// <summary>
/// Extensions for modifiers.
/// </summary>
public static class ModifierExtensions
{
/// <summary>
/// Gets the dictionary to cache ModifierComponents.
/// </summary>
public static Dictionary<PlayerControl, ModifierComponent> ModifierComponents { get; } = [];
/// <summary>
/// Remote Procedure Call to add a modifier to a player.
/// </summary>
/// <param name="target">The player to add the modifier to.</param>
/// <param name="typeId">The modifier type ID.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
public static void RpcAddModifier(this PlayerControl target, uint typeId, params object[] args)
{
_ = ModifierManager.GetModifierType(typeId) ?? throw new InvalidOperationException(
$"Modifier with ID {typeId} is not registered.");
Rpc<AddModifierRpc>.Instance.Send(target, new ModifierData(typeId, Guid.NewGuid(), args));
}
/// <summary>
/// Remote Procedure Call to add a modifier to a player.
/// </summary>
/// <param name="player">The player to add the modifier to.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
public static void RpcAddModifier(this PlayerControl player, Type type, params object[] args)
{
var id = ModifierManager.GetModifierTypeId(type) ?? throw new InvalidOperationException(
$"Modifier {type.Name} is not registered.");
player.RpcAddModifier(id, args);
}
/// <summary>
/// Remote Procedure Call to add a modifier to a player.
/// </summary>
/// <param name="player">The player to add the modifier to.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <typeparam name="T">The modifier Type.</typeparam>
public static void RpcAddModifier<T>(this PlayerControl player, params object[] args) where T : BaseModifier
{
player.RpcAddModifier(typeof(T), args);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player.
/// </summary>
/// <param name="target">The player to remove the modifier from.</param>
/// <param name="uniqueId">The unique ID of the modifier.</param>
[MethodRpc((uint)MiraRpc.RemoveModifier)]
public static void RpcRemoveModifier(this PlayerControl target, Guid uniqueId)
{
target.RemoveModifier(uniqueId);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player by type ID.
/// </summary>
/// <param name="target">The player to remove the modifier from.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RpcRemoveModifier(
this PlayerControl target,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
var modifier = target.GetModifier(typeId, predicate);
if (modifier is null)
{
Logger<MiraApiPlugin>.Error($"Player {target.PlayerId} does not have modifier with type ID {typeId}.");
return;
}
target.RpcRemoveModifier(modifier.UniqueId);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player.
/// </summary>
/// <param name="player">The player to remove the modifier from.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RpcRemoveModifier(
this PlayerControl player,
Type type,
Func<BaseModifier, bool>? predicate = null)
{
var id = ModifierManager.GetModifierTypeId(type) ?? throw new InvalidOperationException(
$"Modifier {type.Name} is not registered.");
player.RpcRemoveModifier(id, predicate);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player.
/// </summary>
/// <param name="player">The player to remove the modifier from.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
public static void RpcRemoveModifier<T>(this PlayerControl player, Func<BaseModifier, bool>? predicate = null)
where T : BaseModifier
{
player.RpcRemoveModifier(typeof(T), predicate);
}
/// <summary>
/// Gets the ModifierComponent for a player.
/// </summary>
/// <param name="player">The PlayerControl object.</param>
/// <returns>A ModifierComponent if there is one, null otherwise.</returns>
public static ModifierComponent GetModifierComponent(this PlayerControl player)
{
if (ModifierComponents.TryGetValue(player, out var component))
{
return component;
}
component = player.GetComponent<ModifierComponent>();
if (!component)
{
throw new InvalidOperationException("ModifierComponent is not attached to the player.");
}
ModifierComponents[player] = component;
return component;
}
/// <summary>
/// Checks if the player has a specific modifier.
/// </summary>
/// <typeparam name="T">The type of the modifier.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>True if the player has the modifier, false otherwise.</returns>
public static bool HasModifier<T>(this PlayerControl player, Func<T, bool>? predicate = null) where T : BaseModifier
{
return player.GetModifierComponent().HasModifier(predicate);
}
/// <summary>
/// Checks if the player has a specific modifier by type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>True if the player has the modifier, false otherwise.</returns>
public static bool HasModifier(this PlayerControl player, Type type, Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().HasModifier(type, predicate);
}
/// <summary>
/// Checks if the player has a specific modifier by type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>True if the player has the modifier, false otherwise.</returns>
public static bool HasModifier(
this PlayerControl player,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
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>
/// Tries to get a modifier by its type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="modifier">The modifier or null.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>True if the modifier was found, false otherwise.</returns>
public static bool TryGetModifier<T>(this PlayerControl player, [NotNullWhen(true)] out T? modifier, Func<T, bool>? predicate = null) where T : BaseModifier
{
return player.GetModifierComponent().TryGetModifier(out modifier, predicate);
}
/// <summary>
/// Tries to get a modifier by its type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The modifier type.</param>
/// <param name="modifier">The modifier or null.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>True if the modifier was found, false otherwise.</returns>
public static bool TryGetModifier(this PlayerControl player, Type type, [NotNullWhen(true)] out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().TryGetModifier(type, out modifier, predicate);
}
/// <summary>
/// Tries to get a modifier by its type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="id">The modifier type ID.</param>
/// <param name="modifier">The modifier or null.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>True if the modifier was found, false otherwise.</returns>
public static bool TryGetModifier(this PlayerControl player, uint id, [NotNullWhen(true)] out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().TryGetModifier(id, out modifier, predicate);
}
/// <summary>
/// Tries to get a modifier by its unique ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="modifierGuid">The modifier unique ID.</param>
/// <param name="modifier">The modifier or null.</param>
/// <returns>True if the modifier was found, false otherwise.</returns>
public static bool TryGetModifier(this PlayerControl player, Guid modifierGuid, [NotNullWhen(true)] out BaseModifier? modifier)
{
return player.GetModifierComponent().TryGetModifier(modifierGuid, out modifier);
}
/// <summary>
/// Gets a specific modifier from the player.
/// </summary>
/// <typeparam name="T">The type of the modifier.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>The modifier if found, null otherwise.</returns>
public static T? GetModifier<T>(this PlayerControl player, Func<T, bool>? predicate = null) where T : BaseModifier
{
return player.GetModifierComponent().GetModifier(predicate);
}
/// <summary>
/// Gets a specific modifier from the player by type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>The modifier if found, null otherwise.</returns>
public static BaseModifier? GetModifier(
this PlayerControl player,
Type type,
Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().GetModifier(type, predicate);
}
/// <summary>
/// Gets a specific modifier from the player by its type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>The modifier if found, null otherwise.</returns>
public static BaseModifier? GetModifier(
this PlayerControl player,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().GetModifier(typeId, predicate);
}
/// <summary>
/// Gets a specific modifier from the player by its GUID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="uniqueId">The GUID of the modifier.</param>
/// <returns>The modifier if found, null otherwise.</returns>
public static BaseModifier? GetModifier(
this PlayerControl player,
Guid uniqueId)
{
return player.GetModifierComponent().GetModifier(uniqueId);
}
/// <summary>
/// Gets all modifiers of a specific type from the player.
/// </summary>
/// <typeparam name="T">The type of the modifiers.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>A collection of modifiers.</returns>
public static IEnumerable<T> GetModifiers<T>(this PlayerControl player, Func<T, bool>? predicate = null)
where T : BaseModifier
{
return player.GetModifierComponent().GetModifiers(predicate);
}
/// <summary>
/// Gets all modifiers of a specific type from the player.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifiers.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>A collection of modifiers.</returns>
public static IEnumerable<BaseModifier> GetModifiers(
this PlayerControl player,
Type type,
Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().GetModifiers(type, predicate);
}
/// <summary>
/// Gets all modifiers of a specific type from the player by type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifiers.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>A collection of modifiers.</returns>
public static IEnumerable<BaseModifier> GetModifiers(
this PlayerControl player,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().GetModifiers(typeId, predicate);
}
/// <summary>
/// Removes a specific modifier from the player.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="modifier">The modifier to remove.</param>
public static void RemoveModifier(this PlayerControl player, BaseModifier modifier)
{
player.GetModifierComponent().RemoveModifier(modifier);
}
/// <summary>
/// Removes a specific modifier from the player.
/// </summary>
/// <typeparam name="T">The type of the modifier.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RemoveModifier<T>(this PlayerControl player, Func<T, bool>? predicate = null)
where T : BaseModifier
{
player.GetModifierComponent().RemoveModifier(predicate);
}
/// <summary>
/// Removes a specific modifier from the player by type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RemoveModifier(this PlayerControl player, Type type, Func<BaseModifier, bool>? predicate = null)
{
player.GetModifierComponent().RemoveModifier(type, predicate);
}
/// <summary>
/// Removes a specific modifier from the player by its type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RemoveModifier(
this PlayerControl player,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
player.GetModifierComponent().RemoveModifier(typeId, predicate);
}
/// <summary>
/// Removes a specific modifier from the player by its GUID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="uniqueId">The GUID of the modifier.</param>
public static void RemoveModifier(
this PlayerControl player,
Guid uniqueId)
{
player.GetModifierComponent().RemoveModifier(uniqueId);
}
/// <summary>
/// Adds a specific modifier to the player.
/// </summary>
/// <typeparam name="T">The type of the modifier.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The added modifier.</returns>
public static T? AddModifier<T>(this PlayerControl player, params object[] args) where T : BaseModifier
{
return player.GetModifierComponent().AddModifier<T>(args);
}
/// <summary>
/// Adds a specific modifier to the player.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="modifier">The modifier to add.</param>
/// <returns>The added modifier.</returns>
public static BaseModifier? AddModifier(this PlayerControl player, BaseModifier modifier)
{
return player.GetModifierComponent().AddModifier(modifier);
}
/// <summary>
/// Adds a specific modifier to the player by type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The added modifier.</returns>
public static BaseModifier? AddModifier(this PlayerControl player, Type type, params object[] args)
{
return player.GetModifierComponent().AddModifier(type, args);
}
/// <summary>
/// Adds a specific modifier to the player by type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The added modifier.</returns>
public static BaseModifier? AddModifier(this PlayerControl player, uint typeId, params object[] args)
{
return player.GetModifierComponent().AddModifier(typeId, args);
}
}
-102
View File
@@ -1,102 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MiraAPI.Utilities;
namespace MiraAPI.Modifiers;
/// <summary>
/// Factory for creating instances of a modifier. More efficient than using reflection.
/// </summary>
public static class ModifierFactory
{
private static readonly Dictionary<(Type, Type[]), Func<object[], BaseModifier>> _constructorCache = [];
private static Func<object[], BaseModifier> CreateConstructor(Type type, params object[] args)
{
var constructorInfo = type.GetBestConstructor(args) ?? throw new InvalidOperationException(
$"Could not find a constructor for type {type} with the specified arguments.");
var parameters = constructorInfo.GetParameters();
var argsParam = Expression.Parameter(typeof(object[]), "args");
var constructorParams = new Expression[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
var paramType = parameters[i].ParameterType;
var paramAccess = Expression.ArrayIndex(argsParam, Expression.Constant(i));
var convertedParam = Expression.Convert(paramAccess, paramType);
constructorParams[i] = convertedParam;
}
var newExpr = Expression.New(constructorInfo, constructorParams);
var lambda = Expression.Lambda<Func<object[], BaseModifier>>(newExpr, argsParam);
return lambda.Compile();
}
/// <summary>
/// Creates a modifier with the specified type and arguments.
/// </summary>
/// <param name="type">Modifier type.</param>
/// <param name="args">Arguments.</param>
/// <returns>An instance of the modifier.</returns>
public static BaseModifier CreateInstance(Type type, params object[] args)
{
var argTypes = args.Select(arg => arg?.GetType() ?? typeof(object)).ToArray();
var key = (type, argTypes);
if (!_constructorCache.TryGetValue(key, out var constructor))
{
constructor = CreateConstructor(type, args);
_constructorCache[key] = constructor;
}
return constructor(args);
}
}
/// <summary>
/// Factory for creating instances of a modifier. More efficient than using reflection.
/// </summary>
/// <typeparam name="T">The modifier type.</typeparam>
public static class ModifierFactory<T> where T : BaseModifier
{
private static readonly Func<object[], T> Constructor = CreateConstructor();
private static Func<object[], T> CreateConstructor(params object[] args)
{
var constructorInfo = typeof(T).GetBestConstructor(args) ?? throw new InvalidOperationException(
$"Could not find a constructor for type {typeof(T)} with the specified arguments.");
var parameters = constructorInfo.GetParameters();
var argsParam = Expression.Parameter(typeof(object[]), "args");
var constructorParams = new Expression[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
var paramType = parameters[i].ParameterType;
var paramAccess = Expression.ArrayIndex(argsParam, Expression.Constant(i));
var convertedParam = Expression.Convert(paramAccess, paramType);
constructorParams[i] = convertedParam;
}
var newExpr = Expression.New(constructorInfo, constructorParams);
var lambda = Expression.Lambda<Func<object[], T>>(newExpr, argsParam);
return lambda.Compile();
}
/// <summary>
/// Creates an instance of the modifier.
/// </summary>
/// <param name="args">Parameters for the constructor.</param>
/// <returns>An instance of the modifier.</returns>
public static T CreateInstance(params object[] args)
{
return Constructor(args);
}
}
+130 -89
View File
@@ -1,11 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using MiraAPI.Modifiers.Types;
using MiraAPI.PluginLoading;
using MiraAPI.Networking;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using Random = System.Random;
@@ -19,18 +19,17 @@ public static class ModifierManager
{
private static readonly Dictionary<uint, Type> IdToTypeModifierMap = [];
private static readonly Dictionary<Type, uint> TypeToIdModifierMap = [];
private static readonly Dictionary<int, List<uint>> PrioritiesToIdsMap = [];
private static uint _nextTypeId;
private static uint _nextId;
private static uint GetNextTypeId()
private static uint GetNextId()
{
_nextTypeId++;
return _nextTypeId;
_nextId++;
return _nextId;
}
/// <summary>
/// Gets the modifier type from the type id.
/// Gets the modifier type from the id.
/// </summary>
/// <param name="id">The ID.</param>
/// <returns>The Type of the modifier.</returns>
@@ -44,118 +43,160 @@ public static class ModifierManager
/// </summary>
/// <param name="type">The Type.</param>
/// <returns>The ID of the modifier.</returns>
public static uint? GetModifierTypeId(Type type)
public static uint? GetModifierId(Type type)
{
if (!TypeToIdModifierMap.TryGetValue(type, out var id))
{
return null;
}
return id;
return TypeToIdModifierMap.GetValueOrDefault(type);
}
internal static bool RegisterModifier(Type modifierType, MiraPluginInfo info)
internal static void RegisterModifier(Type modifierType)
{
if (!typeof(BaseModifier).IsAssignableFrom(modifierType))
{
return false;
return;
}
IdToTypeModifierMap.Add(GetNextTypeId(), modifierType);
TypeToIdModifierMap.Add(modifierType, _nextTypeId);
var bm = (BaseModifier)FormatterServices.GetUninitializedObject(modifierType); // this probably isn't a great idea
info.Modifiers.Add(bm);
if (!typeof(GameModifier).IsAssignableFrom(modifierType))
{
return true;
}
var mod = Activator.CreateInstance(modifierType) as GameModifier;
var priority = mod!.Priority();
if (!PrioritiesToIdsMap.TryGetValue(priority, out var list))
{
PrioritiesToIdsMap[priority] = list = [];
}
list.Add(_nextTypeId);
return true;
IdToTypeModifierMap.Add(GetNextId(), modifierType);
TypeToIdModifierMap.Add(modifierType, _nextId);
}
internal static void AssignModifiers(List<PlayerControl> plrs)
{
var rand = new Random();
foreach (var priority in PrioritiesToIdsMap.Keys.OrderByDescending(x => x))
List<uint> filteredModifiers = [];
foreach (var modifier in IdToTypeModifierMap.Where(pair => pair.Value.IsAssignableTo(typeof(GameModifier))))
{
var filteredModifiers = new List<uint>();
foreach (var id in PrioritiesToIdsMap[priority])
if (Activator.CreateInstance(modifier.Value) is not GameModifier mod)
{
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>.Error($"Failed to create instance of {modifier.Value.Name}");
continue;
}
var shuffledList = filteredModifiers.Randomize();
if (shuffledList.Count > plrs.Count)
if (!plrs.Exists(x => IsGameModifierValid(x, mod, modifier.Key)))
{
shuffledList = shuffledList.GetRange(0, plrs.Count);
Logger<MiraApiPlugin>.Warning("No players are valid for modifier: " + mod.ModifierName);
continue;
}
foreach (var id in shuffledList)
{
var mod = Activator.CreateInstance(IdToTypeModifierMap[id]) as GameModifier;
var plr = plrs.Where(x => IsGameModifierValid(x, mod!, id)).Random();
var maxCount = plrs.Count(x => IsGameModifierValid(x, mod, modifier.Key));
if (!plr || plr == null)
var num = Math.Clamp(mod.GetAmountPerGame(), 0, maxCount);
var chance = mod.GetAssignmentChance();
for (var i = 0; i < num; i++)
{
var randomNum = rand.Next(100);
if (randomNum < Math.Clamp(chance, 0, 100))
{
Logger<MiraApiPlugin>.Warning($"Somehow valid players for modifier {mod!.ModifierName} disappeared");
}
else
{
plr.RpcAddModifier(id);
filteredModifiers.Add(TypeToIdModifierMap[modifier.Value]);
}
}
}
var shuffledModifiers = filteredModifiers.Randomize();
if (shuffledModifiers.Count > plrs.Count)
{
shuffledModifiers = shuffledModifiers.GetRange(0, plrs.Count);
}
while (shuffledModifiers.Count > 0)
{
var id = shuffledModifiers[0];
if (Activator.CreateInstance(IdToTypeModifierMap[id]) is not GameModifier mod)
{
Logger<MiraApiPlugin>.Error($"Failed to create instance of {IdToTypeModifierMap[id].Name}");
continue;
}
if (!plrs.Exists(x => IsGameModifierValid(x, mod, id)))
{
shuffledModifiers.RemoveAt(0);
continue;
}
var plr = plrs.Random();
if (plr == null || !IsGameModifierValid(plr, mod, id))
{
continue;
}
shuffledModifiers.RemoveAt(0);
plr.RpcAddModifier(id);
}
}
private static bool IsGameModifierValid(PlayerControl player, GameModifier modifier, uint modifierId)
{
return (player.Data.Role is not ICustomRole role || role.IsModifierApplicable(modifier)) &&
modifier.IsModifierValidOn(player.Data.Role) && !player.HasModifier(modifierId);
modifier.IsModifierValidOn(player.Data.Role) &&
!player.HasModifier(modifierId);
}
internal static void SyncAllModifiers(int targetId = -1)
{
var data = new List<NetData>();
foreach (var player in PlayerControl.AllPlayerControls)
{
data.Add(GetPlayerModifiers(player));
}
Rpc<SyncModifiersRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, [.. data]);
}
internal static void HandleSyncModifiers(NetData[] data)
{
foreach (var netData in data)
{
var ids = new uint[netData.Data.Length / 4];
Buffer.BlockCopy(netData.Data, 0, ids, 0, netData.Data.Length);
var plr = GameData.Instance.GetPlayerById((byte)netData.Id).Object;
var modifierComponent = plr.GetComponent<ModifierComponent>();
if (!modifierComponent)
{
continue;
}
modifierComponent.ClearModifiers();
foreach (var id in ids)
{
if (!IdToTypeModifierMap.TryGetValue(id, out var type))
{
Logger<MiraApiPlugin>.Error($"Cannot add modifier with id {id} because it is not registered.");
continue;
}
modifierComponent.AddModifier(type);
}
}
}
private static NetData GetPlayerModifiers(PlayerControl? player)
{
if (player == null || !player)
{
return new NetData(0, []);
}
List<byte> bytes = [];
var modifierComponent = player.GetComponent<ModifierComponent>();
if (modifierComponent == null || !modifierComponent)
{
return new NetData(player.PlayerId, []);
}
foreach (var modifier in modifierComponent.ActiveModifiers)
{
bytes.AddRange(BitConverter.GetBytes(TypeToIdModifierMap[modifier.GetType()]));
}
return new NetData(player.PlayerId, [.. bytes]);
}
}
@@ -0,0 +1,9 @@
using System;
namespace MiraAPI.Modifiers;
/// <summary>
/// Marks a class as a modifier that can be registered with the <see cref="ModifierManager"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class RegisterModifierAttribute : Attribute;
-10
View File
@@ -5,9 +5,6 @@
/// </summary>
public abstract class GameModifier : BaseModifier
{
/// <inheritdoc />
public override bool ShowInFreeplay => true;
/// <summary>
/// Gets the chance of the modifier being assigned to a player.
/// </summary>
@@ -20,12 +17,6 @@ public abstract class GameModifier : BaseModifier
/// <returns>An int value greater than or equal to zero.</returns>
public abstract int GetAmountPerGame();
/// <summary>
/// Gets the priority at which the modifier will spawn. The higher the value, the higher up on the assignment list.
/// </summary>
/// <returns>An int value greater than or equal to -1.</returns>
public virtual int Priority() => -1;
/// <summary>
/// Determines whether the modifier is valid on a role.
/// </summary>
@@ -36,7 +27,6 @@ public abstract class GameModifier : BaseModifier
/// <summary>
/// Determines whether the player won the game with this modifier.
/// </summary>
/// <param name="reason">The reason why the game ended.</param>
/// <returns>True if the player won, false if they lost. Return null to use the player's default win condition.</returns>
public virtual bool? DidWin(GameOverReason reason) => null;
}
+3 -5
View File
@@ -17,7 +17,7 @@ public abstract class TimedModifier : BaseModifier
/// <summary>
/// Gets a value indicating whether the timer should start automatically when added.
/// </summary>
public virtual bool AutoStart => true;
public virtual bool AutoStart => false;
/// <summary>
/// Gets a value indicating whether the modifier should be removed when the timer completes.
@@ -27,9 +27,7 @@ public abstract class TimedModifier : BaseModifier
/// <summary>
/// Called when the timer completes.
/// </summary>
public virtual void OnTimerComplete()
{
}
public abstract void OnTimerComplete();
/// <summary>
/// Gets or sets a value indicating whether the timer is active.
@@ -104,7 +102,7 @@ public abstract class TimedModifier : BaseModifier
if (RemoveOnComplete)
{
ModifierComponent?.RemoveModifier(this);
ModifierComponent?.RemoveModifier(ModifierId);
}
}
-70
View File
@@ -1,70 +0,0 @@
using System.Collections.Generic;
using Hazel;
using InnerNet;
using MiraAPI.GameEnd;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
namespace MiraAPI.Networking;
/// <summary>
/// Custom Game Over RPC.
/// </summary>
/// <inheritdoc />
[RegisterCustomRpc((uint)MiraRpc.CustomGameOver)]
public class CustomGameOverRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, GameOverData>(plugin, id)
{
/// <inheritdoc />
public override RpcLocalHandling LocalHandling => RpcLocalHandling.After;
/// <inheritdoc />
public override void Write(MessageWriter writer, GameOverData data)
{
writer.WritePacked(data.Reason);
writer.WritePacked(data.Winners.Count);
foreach (var player in data.Winners)
{
writer.WriteNetObject(player);
}
}
/// <inheritdoc />
public override GameOverData Read(MessageReader reader)
{
var reason = reader.ReadPackedInt32();
var count = reader.ReadPackedInt32();
var data = new List<NetworkedPlayerInfo>(count);
for (var i = 0; i < count; i++)
{
data.Add(reader.ReadNetObject<NetworkedPlayerInfo>());
}
return new GameOverData(reason, data);
}
/// <inheritdoc />
public override void Handle(PlayerControl innerNetObject, GameOverData data)
{
if (GameOverManager.TryGetGameOver(data.Reason, out var gameOver))
{
if (!gameOver.VerifyCondition(innerNetObject))
{
Logger<MiraApiPlugin>.Info($"Game over condition not met for {gameOver.GetType().Name}");
return;
}
CustomGameOver.Instance = gameOver;
if (AmongUsClient.Instance.AmHost)
{
GameManager.Instance.RpcEndGame(gameOver, false);
}
}
else
{
CustomGameOver.Instance = null;
Logger<MiraApiPlugin>.Error($"Unknown game over reason: {data.Reason}");
}
}
}
+6 -16
View File
@@ -3,10 +3,9 @@ using System.Linq;
using AmongUs.GameOptions;
using Assets.CoreScripts;
using BepInEx.Unity.IL2CPP.Utils;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using UnityEngine;
@@ -40,15 +39,6 @@ public static class CustomMurderRpc
bool playKillSound = true)
{
var murderResultFlags = didSucceed ? MurderResultFlags.Succeeded : MurderResultFlags.FailedError;
var beforeMurderEvent = new BeforeMurderEvent(source, target);
MiraEventManager.InvokeEvent(beforeMurderEvent);
if (beforeMurderEvent.IsCancelled)
{
murderResultFlags = MurderResultFlags.FailedError;
}
var murderResultFlags2 = MurderResultFlags.DecisionByHost | murderResultFlags;
source.CustomMurder(
@@ -83,6 +73,7 @@ public static class CustomMurderRpc
bool playKillSound = true)
{
source.isKilling = false;
Logger<MiraApiPlugin>.Error($"{source.PlayerId} trying to murder {target.PlayerId}");
var data = target.Data;
if (resultFlags.HasFlag(MurderResultFlags.FailedError))
{
@@ -115,6 +106,7 @@ public static class CustomMurderRpc
target.RemoveProtection();
}
Logger<MiraApiPlugin>.Error($"{source.PlayerId} failed to murder {target.PlayerId} due to guardian angel protection");
return;
}
@@ -182,6 +174,7 @@ public static class CustomMurderRpc
source.shapeshiftTargetPlayerId,
target.PlayerId);
source.MyPhysics.StartCoroutine(source.KillAnimations.Random()?.CoPerformCustomKill(source, target, createDeadBody, teleportMurderer));
Logger<MiraApiPlugin>.Error($"{source.PlayerId} succeeded in murdering {target.PlayerId}");
}
/// <summary>
@@ -247,11 +240,11 @@ public static class CustomMurderRpc
}
target.Die(DeathReason.Kill, true);
yield return source.MyPhysics.Animations.CoPlayCustomAnimation(anim.BlurAnim);
sourcePhys.Animations.PlayIdleAnimation();
if (teleportMurderer)
{
yield return source.MyPhysics.Animations.CoPlayCustomAnimation(anim.BlurAnim);
sourcePhys.Animations.PlayIdleAnimation();
source.NetTransform.SnapTo(target.transform.position);
KillAnimation.SetMovement(source, true);
}
@@ -263,9 +256,6 @@ public static class CustomMurderRpc
deadBody.enabled = true;
}
var afterMurderEvent = new AfterMurderEvent(source, target);
MiraEventManager.InvokeEvent(afterMurderEvent);
if (!isParticipant)
{
yield break;
-32
View File
@@ -1,32 +0,0 @@
using System;
using Hazel;
using Reactor.Networking.Attributes;
using Reactor.Networking.Serialization;
namespace MiraAPI.Networking;
/// <summary>
/// Converter for <see cref="Guid"/>.
/// </summary>
[MessageConverter]
public class GuidConverter : MessageConverter<Guid>
{
/// <summary>
/// Writes a <see cref="Guid"/> to the writer.
/// </summary>
/// <inheritdoc />
public override void Write(MessageWriter writer, Guid value)
{
writer.WriteBytesAndSize(value.ToByteArray());
}
/// <summary>
/// Reads a <see cref="Guid"/> from the reader.
/// </summary>
/// <inheritdoc />
/// <returns>A GUID object.</returns>
public override Guid Read(MessageReader reader, Type objectType)
{
return new Guid(reader.ReadBytesAndSize());
}
}
-5
View File
@@ -34,9 +34,4 @@ public enum MiraRpc : uint
/// Custom Murder RPC.
/// </summary>
CustomMurder,
/// <summary>
/// Custom Game Over RPC.
/// </summary>
CustomGameOver,
}
@@ -1,76 +0,0 @@
using System;
using Hazel;
using MiraAPI.Modifiers;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
using Reactor.Networking.Serialization;
namespace MiraAPI.Networking.Modifiers;
/// <summary>
/// Remote procedure call for adding a modifier.
/// </summary>
/// <param name="plugin">Mira plugin.</param>
/// <param name="id">RPC ID.</param>
[RegisterCustomRpc((uint)MiraRpc.AddModifier)]
public class AddModifierRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, ModifierData>(plugin, id)
{
/// <inheritdoc />
public override RpcLocalHandling LocalHandling => RpcLocalHandling.Before;
/// <inheritdoc />
public override void Write(MessageWriter writer, ModifierData data)
{
writer.WritePacked(data.TypeId);
writer.WriteBytesAndSize(data.UniqueId.ToByteArray());
writer.WritePacked(data.Args.Length);
foreach (var arg in data.Args)
{
writer.Write(arg.GetType().AssemblyQualifiedName);
writer.Serialize(arg);
}
}
/// <inheritdoc />
public override ModifierData Read(MessageReader reader)
{
var modId = reader.ReadPackedUInt32();
var guid = new Guid(reader.ReadBytesAndSize());
var argCount = reader.ReadPackedUInt32();
var objects = new object[argCount];
if (argCount > 0)
{
var types = new Type[argCount];
for (var i = 0; i < argCount; i++)
{
var name = reader.ReadString();
types[i] = Type.GetType(name) ?? throw new InvalidOperationException($"Type not found: {name}");
objects[i] = reader.Deserialize(types[i]);
}
}
return new ModifierData(modId, guid, objects);
}
/// <inheritdoc />
public override void Handle(PlayerControl player, ModifierData data)
{
var type = ModifierManager.GetModifierType(data.TypeId) ?? throw new InvalidOperationException($"Modifier type not found for ID {data.TypeId}.");
BaseModifier? modifier;
if (data.Args.Length > 0)
{
modifier = ModifierFactory.CreateInstance(type, data.Args);
}
else
{
modifier = Activator.CreateInstance(type) as BaseModifier;
if (modifier == null)
{
throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier.");
}
}
modifier.UniqueId = data.UniqueId;
player.AddModifier(modifier);
}
}
@@ -1,40 +0,0 @@
using System;
using Hazel;
using InnerNet;
using MiraAPI.Modifiers;
using Reactor.Networking.Attributes;
using Reactor.Networking.Serialization;
namespace MiraAPI.Networking.Modifiers;
/// <summary>
/// Converter for serializing and deserializing <see cref="BaseModifier"/> objects.
/// </summary>
[MessageConverter]
public class ModifierConverter : MessageConverter<BaseModifier>
{
/// <summary>
/// Writes a <see cref="BaseModifier"/> to the writer.
/// </summary>
/// <param name="writer">The writer to write to.</param>
/// <param name="value">The <see cref="BaseModifier"/> to write.</param>
public override void Write(MessageWriter writer, BaseModifier value)
{
writer.WriteNetObject(value.Player);
writer.WriteBytesAndSize(value.UniqueId.ToByteArray());
}
/// <summary>
/// Reads a <see cref="BaseModifier"/> from the reader.
/// </summary>
/// <param name="reader">The reader to read from.</param>
/// <param name="objectType">The type of the object to read.</param>
/// <returns>The <see cref="BaseModifier"/> that was read.</returns>
/// <exception cref="InvalidOperationException">Thrown if the modifier is not found.</exception>
public override BaseModifier Read(MessageReader reader, Type objectType)
{
var player = reader.ReadNetObject<PlayerControl>();
var guid = new Guid(reader.ReadBytesAndSize());
return player.GetModifier(guid) ?? throw new InvalidOperationException($"Modifier with GUID {guid} not found for player with ID: {player.PlayerId}");
}
}
@@ -1,11 +0,0 @@
using System;
namespace MiraAPI.Networking.Modifiers;
/// <summary>
/// Modifier data for networking.
/// </summary>
/// <param name="TypeId">The ID of the modifier.</param>
/// <param name="UniqueId">The unique ID of the modifier.</param>
/// <param name="Args">Parameters for constructor.</param>
public record struct ModifierData(uint TypeId, Guid UniqueId, object[] Args);
+52
View File
@@ -0,0 +1,52 @@
using Hazel;
using MiraAPI.Modifiers;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
namespace MiraAPI.Networking;
[RegisterCustomRpc((uint)MiraRpc.SyncModifiers)]
internal sealed class SyncModifiersRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, NetData[]>(plugin, id)
{
public override RpcLocalHandling LocalHandling => RpcLocalHandling.None;
public override void Write(MessageWriter writer, NetData[]? data)
{
if (data == null)
{
writer.WritePacked(0U);
return;
}
writer.WritePacked((uint)data.Length);
foreach (var netData in data)
{
writer.WritePacked(netData.Id);
writer.WriteBytesAndSize(netData.Data);
}
}
public override NetData[] Read(MessageReader reader)
{
var length = reader.ReadPackedUInt32();
var data = new NetData[length];
for (var i = 0; i < length; i++)
{
var dataId = reader.ReadPackedUInt32();
var bytes = reader.ReadBytesAndSize();
data[i] = new NetData(dataId, bytes);
}
return data;
}
public override void Handle(PlayerControl playerControl, NetData[]? data)
{
if (AmongUsClient.Instance.HostId != playerControl.OwnerId)
{
return;
}
ModifierManager.HandleSyncModifiers(data ?? []);
}
}
+6 -19
View File
@@ -1,25 +1,19 @@
using HarmonyLib;
using InnerNet;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Player;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
namespace MiraAPI.Patches;
/// <summary>
/// Sync all settings to the player when they join the game.
/// Sync all options, role settings, and modifiers to the player when they join the game.
/// </summary>
[HarmonyPatch(typeof(AmongUsClient))]
internal static class AmongUsClientSyncPatch
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CreatePlayer))]
public static class AmongUsClientSyncPatch
{
[HarmonyPostfix]
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CreatePlayer))]
public static void CreatePlayerPatch(ClientData clientData)
public static void Postfix(ClientData clientData)
{
var joinEvent = new PlayerJoinEvent(clientData);
MiraEventManager.InvokeEvent(joinEvent);
if (!AmongUsClient.Instance.AmHost)
{
return;
@@ -32,13 +26,6 @@ internal static class AmongUsClientSyncPatch
ModdedOptionsManager.SyncAllOptions(clientData.Id);
CustomRoleManager.SyncAllRoleSettings(clientData.Id);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerLeft))]
public static void PlayerLeftPatch(ClientData data, DisconnectReasons reason)
{
var leftEvent = new PlayerLeaveEvent(data, reason);
MiraEventManager.InvokeEvent(leftEvent);
ModifierManager.SyncAllModifiers(clientData.Id);
}
}
@@ -4,10 +4,7 @@ using UnityEngine;
namespace MiraAPI.Patches.Colors;
/// <summary>
/// This patch adds scrolling to the colors tab in the player customization menu.
/// </summary>
[HarmonyPatch(typeof(PlayerTab), nameof(PlayerTab.OnEnable))]
[HarmonyPatch(typeof(PlayerTab))]
public static class ScrollingColorsPatch
{
// Collider
@@ -16,7 +13,8 @@ public static class ScrollingColorsPatch
/// <summary>
/// Add scrolling to the colors tab.
/// </summary>
public static void Postfix(PlayerTab __instance)
[HarmonyPostfix, HarmonyPatch("OnEnable")]
public static void AddScrollingToColorsTabPatch(PlayerTab __instance)
{
if (!PlayerCustomizationMenu.Instance)
{
+76
View File
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MonoMod.Utils;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(HatsTab), nameof(HatsTab.OnEnable))]
public static class HatsTabPatch
{
public static bool Prefix(HatsTab __instance)
{
var hatGroups = new SortedList<AbstractCosmeticsGroup, List<HatData>>(
new AbstractCosmeticsGroupComparer()
);
CustomCosmeticManager.Groups.Do(x => x.Hats.Sort(new CosmeticComparer(x)));
var c = CustomCosmeticManager.Groups.Select(x => new KeyValuePair<AbstractCosmeticsGroup, List<HatData>>(x, x.Hats)).
ToDictionary(x => x.Key, x => x.Value.Where(x=>x.Free || DataManager.Player.Purchases.GetPurchase(x.ProductId, x.BundleId)).ToList());
hatGroups.AddRange<AbstractCosmeticsGroup, List<HatData>>(c);
foreach (var colorchip in __instance.ColorChips) colorchip.gameObject.Destroy();
__instance.ColorChips.Clear();
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
var hatIdx = 0;
__instance.currentHat = DestroyableSingleton<HatManager>.Instance.GetHatById(DataManager.Player.Customization.Hat);
foreach (var (group, hats) in hatGroups.Where(x=>x.Key.GroupVisible() && x.Key.Hats.Count > 0))
{
var text = UnityEngine.Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.text = group.GroupName;
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 3f;
text.fontSizeMax = 3f;
text.fontSizeMin = 0f;
hatIdx = (hatIdx + 4) / 5 * 5;
var xLerp = __instance.XRange.Lerp(0.5f);
var yLerp = __instance.YStart - (hatIdx / __instance.NumPerRow) * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIdx += 5;
foreach (var hat in hats)
{
var num = __instance.XRange.Lerp(hatIdx % __instance.NumPerRow / (__instance.NumPerRow - 1f));
var num2 = __instance.YStart - hatIdx / __instance.NumPerRow * __instance.YOffset;
var colorChip = UnityEngine.Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.transform.localPosition = new Vector3(num, num2, -1f);
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectHat(hat)));
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.Inner.SetMaskType(PlayerMaterial.MaskType.SimpleUI);
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, hat);
colorChip.Inner.SetHat(hat, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color);
colorChip.Inner.transform.localPosition = hat.ChipOffset + new Vector2(0f, -0.3f);
colorChip.Tag = hat;
colorChip.SelectionHighlight.gameObject.SetActive(false);
__instance.ColorChips.Add(colorChip);
hatIdx += 1;
}
}
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIdx + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
__instance.currentHatIsEquipped = true;
return false;
}
}
@@ -0,0 +1,13 @@
using HarmonyLib;
using MiraAPI.Cosmetics;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(InventoryManager), nameof(InventoryManager.CheckUnlockedItems))]
public static class InventoryManagerPatch
{
public static void Prefix()
{
CustomCosmeticManager.LoadAll();
}
}
@@ -0,0 +1,91 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MiraAPI.Utilities.Assets.Addressable;
using MonoMod.Utils;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(NameplatesTab), nameof(NameplatesTab.OnEnable))]
public static class NameplatesTabPatch
{
public static bool Prefix(NameplatesTab __instance)
{
var groups = new SortedList<AbstractCosmeticsGroup, List<NamePlateData>>(
new AbstractCosmeticsGroupComparer()
);
CustomCosmeticManager.Groups.Do(x => x.Nameplates.Sort(new CosmeticComparer(x)));
var c = CustomCosmeticManager.Groups.Select(x => new KeyValuePair<AbstractCosmeticsGroup, List<NamePlateData>>(x, x.Nameplates)).
ToDictionary(x => x.Key, x => x.Value.Where(x => x.Free || DataManager.Player.Purchases.GetPurchase(x.ProductId, x.BundleId)).ToList());
groups.AddRange<AbstractCosmeticsGroup, List<NamePlateData>>(c);
Logger<MiraApiPlugin>.Info($"{c.Count}");
foreach (var colorchip in __instance.ColorChips) colorchip.gameObject.Destroy();
__instance.ColorChips.Clear();
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
var hatIdx = 0;
__instance.PlayerPreview.gameObject.SetActive(false);
__instance.StartCoroutine(__instance.CoLoadNameplatePreview());
foreach (var (group, hats) in groups.Where(x => x.Key.GroupVisible() && x.Key.Nameplates.Count > 0))
{
var text = UnityEngine.Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.text = group.GroupName;
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 3f;
text.fontSizeMax = 3f;
text.fontSizeMin = 0f;
hatIdx = (hatIdx + 1) / 2 * 2;
var xLerp = __instance.XRange.Lerp(0.5f);
var yLerp = __instance.YStart - (hatIdx / __instance.NumPerRow) * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIdx += 2;
foreach (var hat in hats)
{
var num = __instance.XRange.Lerp(hatIdx % __instance.NumPerRow / (__instance.NumPerRow - 1f));
var num2 = __instance.YStart - hatIdx / __instance.NumPerRow * __instance.YOffset;
var colorChip = UnityEngine.Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.transform.localPosition = new Vector3(num, num2, -1f);
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectNameplate(hat)));
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.ProductId = hat.ProductId;
var handle = Addressables.LoadAssetAsync<NamePlateViewData>(hat.ViewDataRef);
Coroutines.Start(SetupColorChip(colorChip.TryCast<NameplateChip>(), handle));
__instance.ColorChips.Add(colorChip);
hatIdx += 1;
}
}
__instance.GetDefaultSelectable().PlayerEquippedForeground.SetActive(true);
__instance.plateId = DataManager.Player.Customization.NamePlate;
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIdx + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
__instance.currentNameplateIsEquipped = true;
return false;
}
private static IEnumerator SetupColorChip(NameplateChip colorChip, AsyncOperationHandle<NamePlateViewData> handle)
{
yield return new WaitForAsyncOperationHandleFinish(handle);
colorChip.image.sprite = handle.Result?.Image;
}
}
@@ -0,0 +1,86 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MiraAPI.Utilities.Assets.Addressable;
using MonoMod.Utils;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(SkinsTab), nameof(SkinsTab.OnEnable))]
public static class SkinsTabPatch
{
public static bool Prefix(SkinsTab __instance)
{
var groups = new SortedList<AbstractCosmeticsGroup, List<SkinData>>(
new AbstractCosmeticsGroupComparer()
);
CustomCosmeticManager.Groups.Do(x => x.Skins.Sort(new CosmeticComparer(x)));
var c = CustomCosmeticManager.Groups.Select(x => new KeyValuePair<AbstractCosmeticsGroup, List<SkinData>>(x, x.Skins)).
ToDictionary(x => x.Key, x => x.Value.Where(x => x.Free || DataManager.Player.Purchases.GetPurchase(x.ProductId, x.BundleId)).ToList());
groups.AddRange<AbstractCosmeticsGroup, List<SkinData>>(c);
foreach (var colorchip in __instance.ColorChips) colorchip.gameObject.Destroy();
__instance.ColorChips.Clear();
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
var hatIdx = 0;
foreach (var (group, skins) in groups.Where(x => x.Key.GroupVisible() && x.Key.Skins.Count > 0))
{
var text = UnityEngine.Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.text = group.GroupName;
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 3f;
text.fontSizeMax = 3f;
text.fontSizeMin = 0f;
hatIdx = (hatIdx + 4) / 5 * 5;
var xLerp = __instance.XRange.Lerp(0.5f);
var yLerp = __instance.YStart - (hatIdx / __instance.NumPerRow) * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIdx += 5;
foreach (var skin in skins)
{
var num = __instance.XRange.Lerp(hatIdx % __instance.NumPerRow / (__instance.NumPerRow - 1f));
var num2 = __instance.YStart - hatIdx / __instance.NumPerRow * __instance.YOffset;
var colorChip = UnityEngine.Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.transform.localPosition = new Vector3(num, num2, -1f);
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectSkin(skin)));
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.ProductId = skin.ProductId;
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, skin);
var handle = Addressables.LoadAssetAsync<SkinViewData>(skin.ViewDataRef);
Coroutines.Start(SetupColorChip(handle, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color, colorChip));
colorChip.SelectionHighlight.gameObject.SetActive(false);
__instance.ColorChips.Add(colorChip);
hatIdx += 1;
}
}
__instance.skinId = DataManager.Player.Customization.Skin;
__instance.currentSkinIsEquipped = true;
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIdx + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
return false;
}
internal static IEnumerator SetupColorChip(AsyncOperationHandle<SkinViewData> handle, int colorId, ColorChip colorChip)
{
yield return new WaitForAsyncOperationHandleFinish(handle);
colorChip.Inner.FrontLayer.sprite = handle.Result?.IdleFrame;
PlayerMaterial.SetColors(colorId, colorChip.Inner.FrontLayer);
}
}
@@ -0,0 +1,86 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MiraAPI.Utilities.Assets.Addressable;
using MonoMod.Utils;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(VisorsTab), nameof(VisorsTab.OnEnable))]
public static class VisorsTabPatch
{
public static bool Prefix(VisorsTab __instance)
{
var groups = new SortedList<AbstractCosmeticsGroup, List<VisorData>>(
new AbstractCosmeticsGroupComparer()
);
CustomCosmeticManager.Groups.Do(x => x.Visors.Sort(new CosmeticComparer(x)));
var c = CustomCosmeticManager.Groups.Select(x => new KeyValuePair<AbstractCosmeticsGroup, List<VisorData>>(x, x.Visors)).
ToDictionary(x => x.Key, x => x.Value.Where(x => x.Free || DataManager.Player.Purchases.GetPurchase(x.ProductId, x.BundleId)).ToList());
groups.AddRange<AbstractCosmeticsGroup, List<VisorData>>(c);
foreach (var colorchip in __instance.ColorChips) colorchip.gameObject.Destroy();
__instance.ColorChips.Clear();
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
var hatIdx = 0;
foreach (var (group, visors) in groups.Where(x => x.Key.GroupVisible() && x.Key.Visors.Count > 0))
{
var text = UnityEngine.Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.text = group.GroupName;
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 3f;
text.fontSizeMax = 3f;
text.fontSizeMin = 0f;
hatIdx = (hatIdx + 4) / 5 * 5;
var xLerp = __instance.XRange.Lerp(0.5f);
var yLerp = __instance.YStart - (hatIdx / __instance.NumPerRow) * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIdx += 5;
foreach (var visor in visors)
{
var num = __instance.XRange.Lerp(hatIdx % __instance.NumPerRow / (__instance.NumPerRow - 1f));
var num2 = __instance.YStart - hatIdx / __instance.NumPerRow * __instance.YOffset;
var colorChip = UnityEngine.Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.transform.localPosition = new Vector3(num, num2, -1f);
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectVisor(visor)));
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.ProductId = visor.ProductId;
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, visor);
var handle = Addressables.LoadAssetAsync<VisorViewData>(visor.ViewDataRef);
Coroutines.Start(SetupColorChip(handle, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color, colorChip));
colorChip.SelectionHighlight.gameObject.SetActive(false);
__instance.ColorChips.Add(colorChip);
hatIdx += 1;
}
}
__instance.visorId = DataManager.Player.Customization.Visor;
__instance.currentVisorIsEquipped = true;
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIdx + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
return false;
}
internal static IEnumerator SetupColorChip(AsyncOperationHandle<VisorViewData> handle, int colorId, ColorChip colorChip)
{
yield return new WaitForAsyncOperationHandleFinish(handle);
colorChip.Inner.FrontLayer.sprite = handle.Result?.IdleFrame;
PlayerMaterial.SetColors(colorId, colorChip.Inner.FrontLayer);
}
}
-42
View File
@@ -1,42 +0,0 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Usables;
namespace MiraAPI.Patches.Events;
[HarmonyPatch]
public static class CanUsePatches
{
public static IEnumerable<MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(Console), nameof(Console.CanUse));
yield return AccessTools.Method(typeof(MapConsole), nameof(MapConsole.CanUse));
yield return AccessTools.Method(typeof(SystemConsole), nameof(SystemConsole.CanUse));
yield return AccessTools.Method(typeof(Ladder), nameof(Ladder.CanUse));
yield return AccessTools.Method(typeof(PlatformConsole), nameof(PlatformConsole.CanUse));
yield return AccessTools.Method(typeof(OpenDoorConsole), nameof(OpenDoorConsole.CanUse));
yield return AccessTools.Method(typeof(DoorConsole), nameof(DoorConsole.CanUse));
yield return AccessTools.Method(typeof(OptionsConsole), nameof(OptionsConsole.CanUse));
yield return AccessTools.Method(typeof(ZiplineConsole), nameof(ZiplineConsole.CanUse));
}
[HarmonyPriority(Priority.Last)]
[HarmonyPrefix]
public static bool CanUsePatch(Il2CppSystem.Object __instance, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] out bool canUse, [HarmonyArgument(2)] out bool couldUse)
{
canUse = couldUse = false;
IUsable usable = __instance.Cast<IUsable>();
if (usable != null)
{
var @event = new PlayerCanUseEvent(__instance.Cast<IUsable>());
MiraEventManager.InvokeEvent(@event);
return !@event.IsCancelled;
}
return true;
}
}
-33
View File
@@ -1,33 +0,0 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
using MiraAPI.GameEnd;
namespace MiraAPI.Patches.Events;
[HarmonyPatch(typeof(EndGameManager), nameof(EndGameManager.SetEverythingUp))]
internal static class EndGamePatches
{
public static bool Prefix(EndGameManager __instance)
{
if (CustomGameOver.Instance is not { } gameOver)
{
return true;
}
var result = gameOver.BeforeEndGameSetup(__instance);
return result;
}
public static void Postfix(EndGameManager __instance)
{
if (CustomGameOver.Instance is { } gameOver)
{
gameOver.AfterEndGameSetup(__instance);
CustomGameOver.Instance = null;
}
var @event = new GameEndEvent(__instance);
MiraEventManager.InvokeEvent(@event);
}
}
@@ -1,25 +0,0 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
namespace MiraAPI.Patches.Events;
/// <summary>
/// General patches for the KillAnimation class.
/// </summary>
[HarmonyPatch]
public static class KillAnimationPatches
{
/// <summary>
/// Used to trigger the <see cref="AfterMurderEvent"/>.
/// </summary>
/// <param name="source">The killer.</param>
/// <param name="target">The target.</param>
[HarmonyPostfix]
[HarmonyPatch(typeof(KillAnimation), nameof(KillAnimation.CoPerformKill))]
public static void KillAnimPostfix(PlayerControl source, PlayerControl target)
{
var afterMurderEvent = new AfterMurderEvent(source, target);
MiraEventManager.InvokeEvent(afterMurderEvent);
}
}
@@ -1,21 +0,0 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Map;
namespace MiraAPI.Patches.Events;
/// <summary>
/// Patch for map related MiraEvents.
/// </summary>
[HarmonyPatch]
public static class MapBehaviourPatches
{
[HarmonyPrefix]
[HarmonyPatch(typeof(MapBehaviour), nameof(MapBehaviour.ShowSabotageMap))]
public static bool MapShowSabotagePatch(MapBehaviour __instance)
{
var @event = new PlayerOpenSabotageEvent(__instance);
MiraEventManager.InvokeEvent(@event);
return !@event.IsCancelled;
}
}
@@ -1,30 +0,0 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Map;
namespace MiraAPI.Patches.Events;
/// <summary>
/// Used for patching sabotage/system related MiraEvents.
/// </summary>
[HarmonyPatch]
public static class SabotageEventPatches
{
[HarmonyPrefix]
[HarmonyPatch(typeof(ShipStatus), nameof(ShipStatus.RpcUpdateSystem), typeof(SystemTypes), typeof(byte))]
public static bool ShipStatusUpdateSystemPrefix(ShipStatus __instance, SystemTypes systemType, byte amount)
{
var @event = new UpdateSystemEvent(systemType, PlayerControl.LocalPlayer, amount);
MiraEventManager.InvokeEvent(@event);
return !@event.IsCancelled;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(ShipStatus), nameof(ShipStatus.RpcCloseDoorsOfType))]
public static bool ShipStatusCloseDoorsOfTypePrefix(ShipStatus __instance, SystemTypes type)
{
var @event = new CloseDoorsEvent(type);
MiraEventManager.InvokeEvent(@event);
return !@event.IsCancelled;
}
}
@@ -1,21 +0,0 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Meeting;
using MiraAPI.Utilities;
namespace MiraAPI.Patches.Events;
[HarmonyPatch]
public static class StartMeetingEventPatch
{
[HarmonyPrefix]
[HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.CmdReportDeadBody))]
public static bool PlayerControlCmdReportDeadBodyPrefix(PlayerControl __instance, NetworkedPlayerInfo? target)
{
var body = target != null ? Helpers.GetBodyById(target.PlayerId) : null;
var @event = new StartMeetingEvent(__instance, target, body);
MiraEventManager.InvokeEvent(@event);
return !@event.IsCancelled;
}
}
-35
View File
@@ -1,35 +0,0 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Usables;
namespace MiraAPI.Patches.Events;
[HarmonyPatch]
public static class UsePatches
{
public static IEnumerable<MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(Console), nameof(Console.Use));
yield return AccessTools.Method(typeof(MapConsole), nameof(MapConsole.Use));
yield return AccessTools.Method(typeof(SystemConsole), nameof(SystemConsole.Use));
yield return AccessTools.Method(typeof(Vent), nameof(Vent.Use));
yield return AccessTools.Method(typeof(Ladder), nameof(Ladder.Use));
yield return AccessTools.Method(typeof(PlatformConsole), nameof(PlatformConsole.Use));
yield return AccessTools.Method(typeof(OpenDoorConsole), nameof(OpenDoorConsole.Use));
yield return AccessTools.Method(typeof(DoorConsole), nameof(DoorConsole.Use));
yield return AccessTools.Method(typeof(OptionsConsole), nameof(OptionsConsole.Use));
yield return AccessTools.Method(typeof(ZiplineConsole), nameof(ZiplineConsole.Use));
}
[HarmonyPriority(Priority.Last)]
[HarmonyPrefix]
public static bool UsePatch(Il2CppSystem.Object __instance)
{
var @event = new PlayerUseEvent(__instance.Cast<IUsable>());
MiraEventManager.InvokeEvent(@event);
return !@event.IsCancelled;
}
}
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff. Show more