Compare commits

...
164 Commits
Author SHA1 Message Date
XtraCube fb99f02549 i forgor 2025-02-17 11:10:26 -05:00
XtraCube 8382b9adf1 clearer naming 2025-02-17 11:08:12 -05:00
XtraCube cb1a818377 role configuration improvements 2025-02-17 11:03:39 -05:00
XtraCube e950278bf9 seperate some role configs 2025-02-17 10:58:25 -05:00
XtraCube 3de9482233 add missing minigame stubs 2025-02-17 10:32:28 -05:00
XtraCube 4508aaeb55 add role stubs 2025-02-17 10:32:18 -05:00
XtraCube ee15a1acbe fix neutral default role group title 2025-02-17 09:46:09 -05:00
XtraCube 113c716fd3 hide role groups in settings menu 2025-02-17 00:00:37 -05:00
ang-xd f7c34fb5cd Add ShowInFreeplay configuration 2025-02-16 23:13:04 -05:00
XtraCube 37446964c5 change neutral team to Custom and add more customization 2025-02-16 22:33:16 -05:00
ang-xd 0af392d60e Make buttons act more like vanilla 2025-02-16 01:04:15 -05:00
ang-xd e910805e50 Delete log 2025-02-15 23:54:47 -05:00
ang-xd 2b1db0ee24 Whoops 2025-02-15 17:59:40 -05:00
ang-xd 2bb1d41e65 Fix issue #24 2025-02-15 13:49:38 -05:00
Pietrodjaowjao 7bf35fc8ae Fix player skin resetting on no-teleport murder 2025-02-15 15:49:09 -03:00
XtraCube 719ee0400d for MDB fr this time 🙏 2025-02-13 18:21:36 -05:00
ang-xd 4db7605d27 Some changes to role visibility name text 2025-02-13 18:10:42 -05:00
ang-xd c7d16f7fc9 Try fix console spam bug 2025-02-13 17:43:24 -05:00
ang-xd 8ed38c02ce This ones for Xtra 2025-02-13 17:37:44 -05:00
ang-xd 328ee52549 SetRole event 2025-02-13 17:08:21 -05:00
ang-xd e412e5ead5 Some fixes 2025-02-13 16:51:00 -05:00
XtraCube 59ab2736ab further optimization? 2025-02-13 16:19:12 -05:00
XtraCube bb27f83e8b miradisable -> miraignore 2025-02-13 16:18:53 -05:00
XtraCube 7fe2341be0 fix miradisable bug 2025-02-10 16:43:45 -05:00
XtraCube 5bf39593c5 get rid of annoying log 2025-02-10 16:41:00 -05:00
XtraCube 1e56c8860a Merge pull request #18 from All-Of-Us-Mods/optimization
optimize plugin loading (and other optimizations if I find them)
2025-02-09 22:11:31 -05:00
ang-xd 7042c6e646 New events & extensions 2025-02-09 16:42:09 -05:00
XtraCube 4fe301511d remove annoying logs 2025-02-09 14:47:02 -05:00
ang-xd 22718a708c New events and more flexibility 2025-02-06 20:24:53 -05:00
XtraCube e569c27010 replace most attributes and add MiraDisableAttribute.cs 2025-02-03 21:58:57 -05:00
XtraCube 145ae304eb remove extra thingy 2025-02-02 20:59:44 -05:00
XtraCube dcf557ca46 optimize plugin loading 2025-02-02 20:57:10 -05:00
XtraCube a65de5a938 Epic CI Win! 2025-02-02 20:46:56 -05:00
ang-xd 35689487ae Updated events 2025-02-02 16:08:29 -05:00
XtraCube 51fcc2c88f add ModdedEnumOption<T> 2025-01-29 20:57:21 -05:00
XtraCube d5ac231811 initial cooldown zero in freeplay 2025-01-29 18:07:04 -05:00
XtraCube 3538bea933 implicit conversions for explicit option classes 2025-01-29 18:04:01 -05:00
XtraCube 1d34e82503 implement changfe for MDB 2025-01-26 16:41:01 -05:00
XtraCube c32eabcdff add InitialCooldown property to buttons 2025-01-03 19:05:00 -05:00
XtraCube 96f108ab92 use exception for invalid resource name in spritetools 2025-01-02 11:16:31 -05:00
XtraCube 204d1fe123 Merge pull request #16 from All-Of-Us-Mods/modifier-assignment-priority-2
Modifier assignment priority 2
2024-12-31 14:36:49 -05:00
XtraCube 7b51d9b6e6 fix modifier related errors 2024-12-30 13:48:24 -05:00
XtraCube 786450c7c1 fix SetUses bug in buttons and make effect and use limit optional 2024-12-27 18:48:43 -05:00
XtraCube 82050b9d2b bump version cuz i forgor 2024-12-27 14:15:10 -05:00
XtraCube e2b8c0c0a9 remove unnecessary tolist() 2024-12-26 22:34:40 -05:00
XtraCube 69635e02f1 cleanup 2024-12-26 13:41:26 -05:00
XtraCube f39442785f fix button event bug 2024-12-25 10:37:39 -05:00
XtraCube ed7e9949f5 silly bug 2024-12-23 12:55:47 -05:00
XtraCube 0fe6d98c67 remove unnecessary stuff 2024-12-21 16:21:38 -05:00
AlchlcDvl 9fb8a6bda4 make click handler public to allow forced behaviour 2024-12-21 15:16:25 -05:00
AlchlcDvl 3d2f53ce25 not get the count twice 2024-12-21 15:16:24 -05:00
AlchlcDvl ed0c75acf8 move max count down a bit 2024-12-21 15:16:24 -05:00
AlchlcDvl 246e40539c finally works 2024-12-21 15:16:24 -05:00
AlchlcDvl 160d424707 adding some logging to see what's wrong 2024-12-21 15:16:23 -05:00
AlchlcDvl 14276b6c2b why check the players twice 2024-12-21 15:16:23 -05:00
AlchlcDvl b909fb7447 insurance 2024-12-21 15:16:22 -05:00
AlchlcDvl 8b9621dafa fix up assignment + hide from il2cpp was being annoying 2024-12-21 15:16:21 -05:00
AlchlcDvl 9de2ba8e41 i think i got a better solution to this 2024-12-21 15:16:21 -05:00
AlchlcDvl 23e11fef93 reverse mod assignment order 2024-12-21 15:16:20 -05:00
AlchlcDvl 570bb388b6 add loggin for debugging 2024-12-21 15:16:20 -05:00
AlchlcDvl 5d05a07364 add modifier assignment priority 2024-12-21 15:16:19 -05:00
XtraCube d3a815faa9 Merge pull request #15 from All-Of-Us-Mods/events-system
initial event draft
2024-12-21 15:11:50 -05:00
XtraCube a23de7b51c event system fixes 2024-12-21 14:06:52 -05:00
XtraCube 13268ac70a fix issues with vent events 2024-12-08 17:58:37 -05:00
XtraCube 870c913b5d update to handle emergency meeting 2024-12-08 15:36:41 -05:00
XtraCube c1d2455e4d improve example 2024-12-08 15:20:11 -05:00
XtraCube 29c2939871 improved report body event and added vent events 2024-12-08 15:16:12 -05:00
XtraCube 2567722b52 prolly shouldnt be rpc 2024-12-08 14:57:03 -05:00
XtraCube 04ee35d708 basic "sabotage" event 2024-12-08 14:56:13 -05:00
XtraCube 3ea46d5574 more events 2024-12-08 14:44:01 -05:00
XtraCube 707b5629b4 priority system 2024-11-26 16:27:36 -05:00
XtraCube 8884996c06 button events and stuff properly work 2024-11-24 21:25:51 -05:00
XtraCube eac41a7c9e events 2 electric boogaloo 2024-11-24 18:27:14 -05:00
XtraCube 4c113e5fb8 initial event draft 2024-11-24 15:54:03 -05:00
XtraCube bc756d5c1b real fix for vent 2024-09-23 16:17:58 -04:00
XtraCube bbe7cd5a91 adjust 2024-09-23 16:05:25 -04:00
XtraCube 538ad48d18 modifier didwins 2024-09-23 16:05:24 -04:00
XtraCube 53baac167c custom player menu in mira 2024-09-23 16:05:24 -04:00
XtraCube 167566dc9b fix rpc custom murder 2024-09-23 16:05:23 -04:00
XtraCube 2df1eaa7c0 fix role defaults 2024-09-23 16:05:23 -04:00
XtraCube dd7f643153 only use custom murder 2024-09-23 16:05:23 -04:00
XtraCube 13dd0f4874 fix custom buttons 2024-09-23 16:05:22 -04:00
XtraCube 715d235bdc adjustment to role setting menu 2024-09-23 16:05:22 -04:00
XtraCube 25590242bc fix patch error 2024-09-23 16:05:22 -04:00
XtraCube 49489ff0d1 improvements to custom role (added SetChance and SetCount, improved GetChance and GetCount) 2024-09-23 16:05:21 -04:00
XtraCube aa2350bedf potentially fix mira vent bug 2024-09-23 15:59:42 -04:00
ang-xd 52daf69dfe Fix config disappearing issue 2024-09-17 19:40:14 -04:00
XtraCube 95f78addee oops 2024-09-17 12:33:38 -04:00
XtraCube 12d947748c make plugin manager publicly accessible 2024-09-17 12:31:30 -04:00
XtraCube be28948e7e allow access to plugin information externally 2024-09-17 12:26:01 -04:00
XtraCube d0161ba85c bump version 2024-09-16 16:01:20 -04:00
XtraCube 2411ac28a4 Merge branch 'new-role-configs' into dev 2024-09-16 16:00:59 -04:00
XtraCube 1bc0950acc adjust code 2024-09-14 23:22:19 -04:00
XtraCube 3aecd5a91c fix bug with setting uses of button 2024-09-14 23:22:12 -04:00
XtraCube 836823c477 Merge branch 'master' into dev 2024-09-14 22:56:24 -04:00
XtraCube c24404620b fix bug with modifiers and hud 2024-09-14 19:29:24 -04:00
XtraCube 7471a43d39 fix white button flashing issue 2024-09-14 19:29:14 -04:00
ang-xd dd6d57343e Role singleton 2024-09-14 15:47:02 -04:00
ang-xd fd75c99850 New role options 2024-09-14 14:42:20 -04:00
ang-xd 6e3de08043 New role configs system 2024-09-14 12:55:34 -04:00
XtraCube 1fa30485b0 bump version 2024-09-13 22:10:45 -04:00
XtraCube faed84d0f6 fix issue with example mod 2024-09-13 22:00:45 -04:00
XtraCube 2f7b0692f3 fix error in Polus Outside tasks in TaskAdder 2024-09-13 21:57:03 -04:00
XtraCube 8123381e1e add some more utility methods to timed modifier 2024-09-13 20:43:45 -04:00
XtraCube 4d36c13c5b use .Instance instead of DestroyableSingleton<>.Instance 2024-09-13 20:35:35 -04:00
XtraCube 91b7901528 generic type thingy :) 2024-09-13 20:33:50 -04:00
XtraCube 9a27a0c3d8 slight modification to caching modifier componenets 2024-09-13 20:24:38 -04:00
XtraCube cda441ee56 vent patch improvements 2024-09-13 20:03:46 -04:00
XtraCube 6ee83f8c7d better canvent stuff 2024-09-13 19:52:55 -04:00
XtraCube 8712a2b4e7 add predicate for selecting players in GetClosestPlayer extension method 2024-09-13 19:45:57 -04:00
XtraCube 30d2edfd9c Merge branch 'master' into dev 2024-09-10 09:46:44 -04:00
XtraCube 76cb2a6a59 adjustment to vent patches 2024-09-08 21:52:03 -04:00
XtraCube f20e7459a4 fix issue with hiding/showing options 2024-09-08 12:25:19 -04:00
XtraCube f462a116d7 fix contactfilter thingy 2024-09-08 12:06:01 -04:00
XtraCube 6f771821c8 update nearestobjectsoftype to specify layermask/contactfilter 2024-09-08 12:03:00 -04:00
XtraCube 754b8ef684 Merge branch 'refs/heads/master' into dev 2024-09-07 18:49:37 -04:00
XtraCube d8eb671b49 add pixels per unit to LoadableResourceAsset.cs 2024-09-07 18:46:32 -04:00
XtraCube 24ebee2743 make timers run on all players 2024-09-07 17:13:24 -04:00
XtraCube 878cf15a20 fix timed modifier auto removing if AutoStart is false 2024-09-07 16:47:52 -04:00
XtraCube 2f7cf4d664 fix double deactivation of modifiers when using ClearModifiers 2024-09-07 16:12:20 -04:00
XtraCube 4fcfb2a9ee fix LobbyViewPanePatches.cs AGAIN 2024-09-07 10:38:37 -04:00
XtraCube 41bedd3e16 bump version 2024-09-07 10:24:18 -04:00
XtraCube d27bf67f65 fix lobby view pane issues 2024-09-07 10:23:59 -04:00
XtraCube 76ddfa4126 Merge branch 'dev' 2024-09-05 18:10:04 -04:00
XtraCube 400ad535a4 bump version 2024-09-05 18:09:50 -04:00
XtraCube eaf5890f67 Merge pull request #13 from CallOfCreator/dev 2024-09-05 08:08:52 -04:00
XtraCube b2651adcab adjustments 2024-09-05 07:18:20 -04:00
XtraCube c8c6ab1f61 Update README.md 2024-09-04 18:49:24 -04:00
XtraCube 7f65f2d5bb remove warning from example build 2024-09-04 18:34:45 -04:00
XtraCube 17da594207 fix notif popper issue 2024-09-04 18:34:36 -04:00
ang-xd fa8fdfc4f6 Create ChameleonRole.cs 2024-09-04 17:30:08 -04:00
CallOfCreator 75dd5e8a35 Add CanUseSabotage support in ICustomRole 2024-09-04 16:27:57 +00:00
XtraCube a442f54b82 Merge pull request #12 from Rubyboat1207/audio-resource
Added Loadable Audio Resource Asset
2024-09-03 21:29:50 -04:00
Rubyboat 24dca63df1 File name more descriptive 2024-09-03 20:17:50 -05:00
XtraCube 08a4dc75f2 fix period oops 2024-09-03 21:05:55 -04:00
XtraCube 4e474dc5b2 formatting 2024-09-03 21:05:32 -04:00
XtraCube 3deffb701f Merge branch 'refs/heads/dev' into fork/Rubyboat1207/audio-resource 2024-09-03 21:02:00 -04:00
XtraCube f83dce99ef add group priorities for ordering groups 2024-09-03 20:59:26 -04:00
XtraCube 9c14db0321 slight fix to options Click To Close text 2024-09-03 18:39:03 -04:00
Rubyboat f92d08b825 Added Loadable Audio Resource Asset 2024-09-02 15:37:53 -05:00
XtraCube ae10917f2a hidefromil2cpp 2024-09-02 15:22:56 -04:00
XtraCube 51d08bb168 hide mod in TaskAdder if it has no roles 2024-09-02 15:22:50 -04:00
XtraCube 0e56a30c5c fix most non-documentation warnings 2024-09-02 15:19:32 -04:00
XtraCube 74055b8a17 various code alterations to patches to fix warnings 2024-09-02 14:11:10 -04:00
XtraCube 812cef5f2b fix loadable asset code docs and rework logic slightly 2024-09-02 14:10:44 -04:00
XtraCube 9665188a18 various adjustments to code style 2024-09-02 13:46:10 -04:00
XtraCube cb943c2173 CanKill -> UseVanillaKillButton
ICustomRole changes to clear up confusion
Add KillButtonOutlineColor to ICustomRole
2024-09-02 13:37:45 -04:00
XtraCube dc483adc1c more comments + nullable stuff 2024-09-02 13:04:20 -04:00
XtraCube 3d9bbc0833 comments 2024-09-02 13:01:34 -04:00
XtraCube b032e91e08 using statements 2024-09-02 12:57:32 -04:00
XtraCube 3cada4cb3d fix problem with TimedModifier using RPC on every client, despite being replicated 2024-09-02 12:57:25 -04:00
XtraCube 97ded2fc32 some updates to example mod 2024-09-02 12:53:08 -04:00
XtraCube f207849e5e fix neutral killing issues and rename some properties in ICustomRole to clear confusion 2024-09-02 00:12:50 -04:00
XtraCube f8bb63483f fixing possible issues with ghost roles 2024-09-01 20:54:35 -04:00
XtraCube a3dd4acf43 code document custom murder RPCs 2024-09-01 16:29:42 -04:00
XtraCube f17089f435 split HudManager patches 2024-09-01 16:14:30 -04:00
XtraCube d1c469746e fix poor documentation in ICustomRole 2024-09-01 16:08:18 -04:00
XtraCube b053684235 formatting 2024-09-01 16:08:01 -04:00
XtraCube 0f26cadd9a clean up OptionGroupSingleton.cs 2024-09-01 16:07:36 -04:00
XtraCube a07c332dce add DeathReason to modifier OnDeath method 2024-09-01 16:07:22 -04:00
XtraCube 74ab8c5581 oops 2024-09-01 16:06:41 -04:00
XtraCube aa72770bfc change vent color for custom roles 2024-09-01 16:06:35 -04:00
XtraCube 2b71438cd0 fix button reset after meeting 2024-09-01 15:53:33 -04:00
XtraCube e22032e1fb fix neutral naming from outcast 2024-09-01 15:53:09 -04:00
148 changed files with 4463 additions and 1412 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
[*.{cs,vb}]
dotnet_diagnostic.CA1707.severity = none
+6 -6
View File
@@ -6,11 +6,11 @@ jobs:
build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
submodules: true
- uses: actions/cache@v3
- uses: actions/cache@v4
with:
path: |
~/.nuget/packages
@@ -20,7 +20,7 @@ jobs:
${{ runner.os }}-nuget-
- name: Setup .NET
uses: actions/setup-dotnet@v3
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
@@ -29,17 +29,17 @@ jobs:
with:
verbosity: Diagnostic
- uses: actions/upload-artifact@v3
- uses: actions/upload-artifact@v4
with:
name: MiraAPI.dll
path: MiraAPI/bin/Release/net6.0/MiraAPI.dll
- uses: actions/upload-artifact@v3
- uses: actions/upload-artifact@v4
with:
name: AllOfUs.MiraAPI.nupkg
path: MiraAPI/bin/Release/AllOfUs.MiraAPI.*.nupkg
- uses: softprops/action-gh-release@v1
- uses: softprops/action-gh-release@v2
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.8.13" PrivateAssets="all" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2024.10.29" 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" />
+1 -1
View File
@@ -8,7 +8,7 @@
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<VersionPrefix>0.1.4</VersionPrefix>
<VersionPrefix>0.1.9</VersionPrefix>
<VersionSuffix>dev</VersionSuffix>
<Authors>All Of Us, XtraCube, Angxl</Authors>
@@ -1,5 +1,7 @@
using MiraAPI.Example.Modifiers.Freezer;
using MiraAPI.Example.Options.Roles;
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.Hud;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
@@ -7,13 +9,14 @@ using UnityEngine;
namespace MiraAPI.Example.Buttons.Freezer;
[RegisterButton]
public class FreezeButton : CustomActionButton<PlayerControl>
{
public override string Name => "Freeze";
public override float Cooldown => 5f;
public override float EffectDuration => 0f;
public override int MaxUses => 0;
public override float Cooldown => OptionGroupSingleton<FreezerRoleSettings>.Instance.FreezeDuration;
public override int MaxUses => (int)OptionGroupSingleton<FreezerRoleSettings>.Instance.FreezeUses;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
protected override void OnClick()
@@ -23,7 +26,7 @@ public class FreezeButton : CustomActionButton<PlayerControl>
public override PlayerControl? GetTarget()
{
return PlayerControl.LocalPlayer.GetClosestPlayer(true, Distance, false);
return PlayerControl.LocalPlayer.GetClosestPlayer(true, Distance);
}
public override void SetOutline(bool active)
+1 -4
View File
@@ -6,22 +6,19 @@ 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;
public override bool Enabled(RoleBehaviour? role)
{
return PlayerControl.LocalPlayer.HasModifier<CaptainModifier>();
return PlayerControl.LocalPlayer != null && PlayerControl.LocalPlayer.HasModifier<CaptainModifier>();
}
protected override void OnClick()
@@ -8,24 +8,25 @@ using System.Collections;
using UnityEngine;
namespace MiraAPI.Example.Buttons.Teleporter;
[RegisterButton]
public class TeleportButton : CustomActionButton
{
public override string Name => "Teleport";
public override float Cooldown => OptionGroupSingleton<TeleporterOptions>.Instance.TeleportCooldown;
public override float Cooldown => OptionGroupSingleton<TeleporterOptions>.Instance.TeleportCooldown.Value;
public override float EffectDuration => OptionGroupSingleton<TeleporterOptions>.Instance.TeleportDuration;
public override int MaxUses => 0;
public override int MaxUses => 2;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.TeleportButton;
public static bool IsZoom { get; private set; }
public override bool Enabled(RoleBehaviour role)
public override bool Enabled(RoleBehaviour? role)
{
return role is TeleporterRole;
}
protected override void OnClick()
{
Coroutines.Start(ZoomOutCoroutine());
+2 -2
View File
@@ -6,7 +6,7 @@ public static class ExampleAssets
{
public static LoadableResourceAsset ExampleButton { get; } = new("MiraAPI.Example.Resources.ExampleButton.png");
// Credit to EpicHorrors for the teleport button asset.
// Credit to EpicHorrors for the teleport button asset.
public static LoadableResourceAsset TeleportButton { get; } = new("MiraAPI.Example.Resources.TeleportButton.png");
public static LoadableResourceAsset Banner { get; } = new("MiraAPI.Example.Resources.FortniteBanner.jpeg");
}
}
+3 -3
View File
@@ -6,9 +6,9 @@ namespace MiraAPI.Example;
[RegisterCustomColors]
public static class ExampleColors
{
public static CustomColor Cerulean { get; } = new("Cerulean", new Color(0.0f, 0.48f, 0.65f));
public static CustomColor Cerulean { get; } = new("Cerulean", new Color(0.0f, 0.48f, 0.65f));
public static CustomColor Rose { get; } = new("Rose", new Color(0.98f, 0.26f, 0.62f));
public static CustomColor Gold { get; } = new("Gold", new Color(1.0f, 0.84f, 0.0f));
}
}
+59
View File
@@ -0,0 +1,59 @@
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");
}
}
+1
View File
@@ -21,6 +21,7 @@ public partial class ExamplePlugin : BasePlugin, IMiraPlugin
public ConfigFile GetConfigFile() => Config;
public override void Load()
{
ExampleEventHandlers.Initialize();
Harmony.PatchAll();
}
}
+11 -13
View File
@@ -1,23 +1,21 @@
using Reactor.Utilities.Attributes;
using System;
using Il2CppInterop.Runtime.Attributes;
using Reactor.Utilities.Attributes;
using Reactor.Utilities.ImGui;
using System;
using UnityEngine;
namespace MiraAPI.Example;
[RegisterInIl2Cpp]
public class MiraDebugWindow(IntPtr ptr) : MonoBehaviour(ptr)
public class MiraDebugWindow(IntPtr cppPtr) : MonoBehaviour(cppPtr)
{
public readonly DragWindow DebuggingWindow = new(new Rect(10, 10, 0, 0), "MIRA API DEBUGGING", () =>
{
if (GUILayout.Button("Test modifier"))
[HideFromIl2Cpp]
public DragWindow DebuggingWindow { get; } = new(
new Rect(10, 10, 0, 0),
"MIRA API DEBUGGING",
() =>
{
//PlayerControl.LocalPlayer.AddModifier<ModifierTimerExample>();
}
if (GUILayout.Button("Remove modifier"))
{
//PlayerControl.LocalPlayer.RemoveModifier<ModifierTimerExample>();
}
})
})
{
Enabled = true,
};
@@ -3,7 +3,6 @@ using MiraAPI.Modifiers.Types;
namespace MiraAPI.Example.Modifiers;
[RegisterModifier]
public class CaptainModifier : GameModifier
{
public override string ModifierName => "Captain";
@@ -6,7 +6,6 @@ using UnityEngine;
namespace MiraAPI.Example.Modifiers.Freezer;
[RegisterModifier]
public class FreezeModifier : TimedModifier
{
public override string ModifierName => "Freezed";
@@ -0,0 +1,23 @@
using MiraAPI.Modifiers;
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;
}
}
+5 -3
View File
@@ -8,20 +8,22 @@ public class ExampleOptions2 : AbstractOptionGroup
{
public override string GroupName => "Example Options 2";
public override uint GroupPriority => 0; // This group will be displayed first. The default value is uint.MaxValue.
public ModdedToggleOption ToggleOpt1 { get; } = new("Toggle Option 1", false);
public ModdedToggleOption ToggleOpt2 { get; } = new("Toggle Option 2", false)
{
Visible = () => OptionGroupSingleton<ExampleOptions2>.Instance.ToggleOpt1.Value,
Visible = () => OptionGroupSingleton<ExampleOptions2>.Instance.ToggleOpt1, // implicit cast from ModdedToggleOption to bool
};
public ModdedEnumOption EnumOpt { get; } = new("Enum Opt", 0, typeof(TestingData))
public ModdedEnumOption<TestingData> EnumOpt { get; } = new("Enum Opt", 0)
{
ChangedEvent = x => Logger<ExamplePlugin>.Info($"changed Enum Opt to {x}"),
};
}
public enum TestingData
public enum TestingData : ulong
{
Happy,
Sad,
@@ -1,16 +0,0 @@
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using System;
namespace MiraAPI.Example.Options.Roles;
public class CustomRole2Settings : AbstractOptionGroup
{
public override string GroupName => "Custom Role";
public override Type AdvancedRole => typeof(FreezerRole);
[ModdedToggleOption("Teleportation ability")] public bool Teleport { get; set; } = true;
}
@@ -0,0 +1,20 @@
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using System;
using MiraAPI.Utilities;
namespace MiraAPI.Example.Options.Roles;
public class FreezerRoleSettings : AbstractOptionGroup
{
public override string GroupName => "Custom Role";
public override Type AdvancedRole => typeof(FreezerRole);
[ModdedNumberOption("Freeze Duration", 1, 15, 1, MiraNumberSuffixes.Seconds)]
public float FreezeDuration { get; set; } = 5;
[ModdedNumberOption("Freeze Uses", 1, 5)]
public float FreezeUses { get; set; } = 1;
}
@@ -1,8 +1,9 @@
using MiraAPI.Example.Roles;
using System;
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
using System;
namespace MiraAPI.Example.Options.Roles;
@@ -12,8 +13,7 @@ public class TeleporterOptions : AbstractOptionGroup
public override Type AdvancedRole => typeof(TeleporterRole);
[ModdedNumberOption("Teleport Cooldown", 5, 60, 2.5f, MiraNumberSuffixes.Seconds)]
public float TeleportCooldown { get; set; } = 5;
public ModdedNumberOption TeleportCooldown { get; set; } = new("Teleport Cooldown", 10, 5, 60, 2.5f, MiraNumberSuffixes.Seconds);
[ModdedNumberOption("Teleport Duration", 5, 25, 1, MiraNumberSuffixes.Seconds)]
public float TeleportDuration { get; set; } = 10;
+47
View File
@@ -0,0 +1,47 @@
using MiraAPI.Roles;
using TMPro;
using UnityEngine;
namespace MiraAPI.Example.Roles;
public class ChameloenRole : CrewmateRole, ICustomRole
{
public string RoleName => "Chamelon";
public string RoleLongDescription => "Stay invisible while not moving.";
public string RoleDescription => RoleLongDescription;
public Color RoleColor => Palette.AcceptedGreen;
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
{
OptionsScreenshot = ExampleAssets.Banner,
};
public void PlayerControlFixedUpdate(PlayerControl playerControl)
{
if (playerControl.MyPhysics.Velocity.magnitude > 0)
{
SpriteRenderer rend = playerControl.cosmetics.currentBodySprite.BodySprite;
TextMeshPro 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);
foreach (var cosmetic in playerControl.cosmetics.transform.GetComponentsInChildren<SpriteRenderer>())
{
cosmetic.color = Color.Lerp(cosmetic.color, new Color(1, 1, 1, 1), Time.deltaTime * 4f);
}
}
else
{
SpriteRenderer rend = playerControl.cosmetics.currentBodySprite.BodySprite;
TextMeshPro 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);
foreach (var cosmetic in playerControl.cosmetics.transform.GetComponentsInChildren<SpriteRenderer>())
{
cosmetic.color = Color.Lerp(cosmetic.color, new Color(1, 1, 1, playerControl.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
}
}
}
}
+7 -7
View File
@@ -1,11 +1,8 @@
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using MiraAPI.Roles;
using UnityEngine;
namespace MiraAPI.Example.Roles;
[RegisterCustomRole]
public class FreezerRole : ImpostorRole, ICustomRole
{
public string RoleName => "Freezer";
@@ -13,7 +10,10 @@ public class FreezerRole : ImpostorRole, ICustomRole
public string RoleDescription => RoleLongDescription;
public Color RoleColor => Palette.Blue;
public ModdedRoleTeams Team => ModdedRoleTeams.Impostor;
[HideFromIl2Cpp]
public LoadableAsset<Sprite> OptionsScreenshot => ExampleAssets.Banner;
public int MaxPlayers => 2;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
{
OptionsScreenshot = ExampleAssets.Banner,
MaxRoleCount = 2,
};
}
@@ -0,0 +1,37 @@
using MiraAPI.Roles;
using UnityEngine;
namespace MiraAPI.Example.Roles;
public class NeutralKillerRole : ImpostorRole, ICustomRole
{
public string RoleName => "Outcast Killer";
public string RoleDescription => "Outcast who can kill.";
public string RoleLongDescription => RoleDescription;
public Color RoleColor => Color.magenta;
public ModdedRoleTeams Team => ModdedRoleTeams.Custom;
public CustomRoleConfiguration Configuration => new(this)
{
UseVanillaKillButton = true,
CanGetKilled = true,
CanUseVent = true,
};
public RoleOptionsGroup RoleOptionsGroup { get; } = new("Outcast", Color.gray);
public TeamIntroConfiguration? IntroConfiguration { get; } = new(
Color.gray,
"NEUTRAL",
"You are an Outcast. You do not have a team.");
public override void SpawnTaskHeader(PlayerControl playerControl)
{
// remove existing task header.
}
public override bool DidWin(GameOverReason gameOverReason)
{
return GameManager.Instance.DidHumansWin(gameOverReason);
}
}
+14 -6
View File
@@ -1,11 +1,8 @@
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using MiraAPI.Roles;
using UnityEngine;
namespace MiraAPI.Example.Roles;
[RegisterCustomRole]
public class TeleporterRole : CrewmateRole, ICustomRole
{
public string RoleName => "Teleporter";
@@ -13,6 +10,17 @@ public class TeleporterRole : CrewmateRole, ICustomRole
public string RoleDescription => RoleLongDescription;
public Color RoleColor => new Color32(221, 176, 152, 255);
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
[HideFromIl2Cpp]
public LoadableAsset<Sprite> OptionsScreenshot => ExampleAssets.Banner;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
{
OptionsScreenshot = ExampleAssets.Banner,
CanModifyChance = false,
DefaultChance = 73,
DefaultRoleCount = 4,
};
public bool CanLocalPlayerSeeRole(PlayerControl player)
{
return true;
}
}
@@ -0,0 +1,44 @@
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;
}
}
@@ -0,0 +1,51 @@
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
@@ -0,0 +1,28 @@
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
@@ -0,0 +1,6 @@
namespace MiraAPI.Events;
/// <summary>
/// Abstract class for Mira Events.
/// </summary>
public abstract class MiraEvent;
+81
View File
@@ -0,0 +1,81 @@
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
@@ -0,0 +1,30 @@
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;
}
}
@@ -0,0 +1,28 @@
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;
}
}
@@ -0,0 +1,28 @@
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;
}
}
@@ -0,0 +1,21 @@
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;
}
}
@@ -0,0 +1,21 @@
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;
}
}
@@ -0,0 +1,30 @@
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;
}
}
@@ -0,0 +1,21 @@
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;
}
}
@@ -0,0 +1,21 @@
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;
}
}
@@ -0,0 +1,34 @@
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;
}
}
@@ -0,0 +1,21 @@
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;
}
}
@@ -0,0 +1,35 @@
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;
}
}
@@ -0,0 +1,28 @@
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;
}
}
@@ -0,0 +1,28 @@
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;
}
}
@@ -0,0 +1,23 @@
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;
}
}
@@ -0,0 +1,30 @@
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;
}
}
@@ -0,0 +1,28 @@
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;
}
}
@@ -0,0 +1,28 @@
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;
}
}
@@ -0,0 +1,15 @@
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)
{
}
}
@@ -0,0 +1,34 @@
namespace MiraAPI.Events.Vanilla;
/// <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>();
}
}
+9 -9
View File
@@ -6,12 +6,12 @@ using System.Linq;
namespace MiraAPI.GameModes;
/// <summary>
/// Manages custom gamemodes
/// Manages custom gamemodes.
/// </summary>
public static class CustomGameModeManager
{
/// <summary>
/// List of registered gamemodes
/// List of registered gamemodes.
/// </summary>
internal static readonly Dictionary<int, CustomGameMode> GameModes = [];
@@ -21,14 +21,14 @@ public static class CustomGameModeManager
}
/// <summary>
/// Current gamemode
/// Current gamemode.
/// </summary>
public static CustomGameMode? ActiveMode { get; internal set; } = new DefaultMode();
/// <summary>
/// Set current gamemode
/// Set current gamemode.
/// </summary>
/// <param name="id">gamemode ID</param>
/// <param name="id">gamemode ID.</param>
public static void SetGameMode(int id)
{
if (GameModes.TryGetValue(id, out var gameMode))
@@ -41,9 +41,9 @@ public static class CustomGameModeManager
}
/// <summary>
/// Register gamemode from type
/// Register gamemode from type.
/// </summary>
/// <param name="gameModeType">Type of gamemode class, should inherit from <see cref="CustomGameMode"/></param>
/// <param name="gameModeType">Type of gamemode class, should inherit from <see cref="CustomGameMode"/>.</param>
internal static void RegisterGameMode(Type gameModeType)
{
if (!typeof(CustomGameMode).IsAssignableFrom(gameModeType))
@@ -59,7 +59,7 @@ public static class CustomGameModeManager
Logger<MiraApiPlugin>.Error($"Failed to create instance of {gameModeType.Name}");
return;
}
if (GameModes.Any(x => x.Key == gameMode.Id))
{
Logger<MiraApiPlugin>.Error($"ID for gamemode {gameMode.Name} already exists!");
@@ -68,4 +68,4 @@ public static class CustomGameModeManager
GameModes.Add(gameMode.Id, gameMode);
}
}
}
+1 -2
View File
@@ -1,9 +1,8 @@
namespace MiraAPI.GameModes;
[RegisterGameMode]
public class DefaultMode : CustomGameMode
{
public override string Name => "Default";
public override string Description => "Default Among Us GameMode";
public override int Id => 0;
}
}
@@ -1,28 +0,0 @@
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);
}
}
}
}
@@ -26,6 +26,12 @@ public abstract class AbstractOptionGroup
/// </summary>
public virtual Color GroupColor => Color.clear;
/// <summary>
/// Gets the group priority. This is used to determine the order in which groups are displayed in the options menu.
/// Zero is the highest priority, and the default value is the max uint value.
/// </summary>
public virtual uint GroupPriority => uint.MaxValue;
/// <summary>
/// Gets the role the group is associated with. This is used for the advanced role options menu.
/// </summary>
@@ -27,10 +27,8 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va
/// <inheritdoc />
public override object GetValue()
{
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");
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");
}
}
+3 -3
View File
@@ -6,18 +6,18 @@ using UnityEngine;
namespace MiraAPI.GameOptions;
internal interface IModdedOption
public interface IModdedOption
{
uint Id { get; }
string Title { get; }
StringNames StringName { get; }
IMiraPlugin? ParentMod { get; set; }
BaseGameSetting? Data { get; }
BaseGameSetting Data { get; }
Type? AdvancedRole { get; set; }
OptionBehaviour? OptionBehaviour { get; }
Func<bool> Visible { get; set; }
ConfigDefinition? ConfigDefinition { get; set; }
OptionBehaviour? CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, Transform container);
OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, Transform container);
float GetFloatData();
NetData GetNetData();
void HandleNetData(byte[] data);
+7 -4
View File
@@ -18,10 +18,10 @@ namespace MiraAPI.GameOptions;
/// </summary>
public static class ModdedOptionsManager
{
private static readonly Dictionary<PropertyInfo, ModdedOptionAttribute> OptionAttributes = new();
private static readonly Dictionary<Type, AbstractOptionGroup> TypeToGroup = new();
private static readonly Dictionary<PropertyInfo, ModdedOptionAttribute> OptionAttributes = [];
private static readonly Dictionary<Type, AbstractOptionGroup> TypeToGroup = [];
internal static readonly Dictionary<uint, IModdedOption> ModdedOptions = new();
internal static readonly Dictionary<uint, IModdedOption> ModdedOptions = [];
internal static readonly List<AbstractOptionGroup> Groups = [];
internal static uint NextId => _nextId++;
@@ -31,7 +31,6 @@ public static class ModdedOptionsManager
{
if (Activator.CreateInstance(type) is not AbstractOptionGroup group)
{
Logger<MiraApiPlugin>.Error($"Failed to create group from {type.Name}");
return false;
}
@@ -45,6 +44,10 @@ public static class ModdedOptionsManager
TypeToGroup.Add(type, group);
pluginInfo.OptionGroups.Add(group);
typeof(OptionGroupSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
.SetValue(null, group);
return true;
}
+4 -4
View File
@@ -1,5 +1,4 @@
using System;
using System.Linq;
using System.Linq;
namespace MiraAPI.GameOptions;
@@ -7,13 +6,14 @@ namespace MiraAPI.GameOptions;
/// Singleton for option groups.
/// </summary>
/// <typeparam name="T">The option group type.</typeparam>
public class OptionGroupSingleton<T> where T : AbstractOptionGroup
public static class OptionGroupSingleton<T> where T : AbstractOptionGroup
{
private static T? _instance;
/// <summary>
/// Gets the instance of the option group.
/// </summary>
/// <exception cref="InvalidOperationException">Can't</exception>
#pragma warning disable CA1000
public static T Instance => _instance ??= ModdedOptionsManager.Groups.OfType<T>().Single();
#pragma warning restore CA1000
}
@@ -1,8 +1,10 @@
using MiraAPI.Networking;
using Reactor.Localization.Utilities;
using System;
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Networking;
using Reactor.Localization.Utilities;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -86,7 +88,7 @@ public class ModdedEnumOption : ModdedOption<int>
/// <inheritdoc />
protected override void OnValueChanged(int newValue)
{
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(StringName, Data?.GetValueString(newValue), false);
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data?.GetValueString(newValue), false);
if (!OptionBehaviour)
{
return;
@@ -98,3 +100,96 @@ 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);
OptionBehaviour = stringOption;
return stringOption;
}
/// <inheritdoc />
public override float GetFloatData()
{
return Convert.ToSingle(Value);
}
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value)));
}
/// <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());
}
/// <inheritdoc />
protected override void OnValueChanged(T newValue)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data?.GetValueString(Convert.ToInt32(newValue)), false);
if (!OptionBehaviour)
{
return;
}
if (OptionBehaviour is StringOption opt)
{
opt.Value = Convert.ToInt32(newValue);
}
}
}
@@ -134,7 +134,7 @@ public class ModdedNumberOption : ModdedOption<float>
protected override void OnValueChanged(float newValue)
{
Value = Mathf.Clamp(newValue, Min, Max);
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(
HudManager.Instance.Notifier.AddSettingsChangeMessage(
StringName,
Data?.GetValueString(Value),
false);
@@ -144,4 +144,14 @@ public class ModdedNumberOption : ModdedOption<float>
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;
}
}
@@ -35,7 +35,7 @@ public abstract class ModdedOption<T> : IModdedOption
/// <summary>
/// Gets the BaseGameSetting data of the option.
/// </summary>
public BaseGameSetting? Data { get; protected init; }
public BaseGameSetting Data { get; protected init; }
/// <summary>
/// Gets or sets the parent mod of the option.
@@ -194,4 +194,14 @@ 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,7 @@ public class ModdedToggleOption : ModdedOption<bool>
/// <inheritdoc />
protected override void OnValueChanged(bool newValue)
{
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(StringName, newValue ? "On" : "Off", false);
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, newValue ? "On" : "Off", false);
if (!OptionBehaviour)
{
return;
+178 -34
View File
@@ -1,7 +1,12 @@
using MiraAPI.Utilities.Assets;
using MiraAPI.Events;
using MiraAPI.Events.Mira;
using MiraAPI.Patches;
using MiraAPI.Utilities.Assets;
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Object = UnityEngine.Object;
namespace MiraAPI.Hud;
@@ -15,30 +20,35 @@ 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 => ButtonLocation.BottomLeft;
public virtual ButtonLocation Location { get; private set; } = ButtonLocation.BottomLeft;
/// <summary>
/// Gets a value indicating whether the button has an effect ability.
@@ -55,6 +65,11 @@ 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>
@@ -70,7 +85,11 @@ public abstract class CustomActionButton
/// </summary>
protected ActionButton? Button { get; private set; }
internal void CreateButton(Transform parent)
/// <summary>
/// The method used to create the button.
/// </summary>
/// <param name="parent">The parent of the button.</param>
public virtual void CreateButton(Transform parent)
{
if (Button)
{
@@ -78,8 +97,9 @@ public abstract class CustomActionButton
}
UsesLeft = MaxUses;
Timer = Cooldown;
Timer = AmongUsClient.Instance?.NetworkMode == NetworkModes.FreePlay ? 0 : InitialCooldown;
EffectActive = false;
TimerPaused = false;
Button = Object.Instantiate(HudManager.Instance.AbilityButton, parent);
Button.name = Name + "Button";
@@ -95,13 +115,87 @@ public abstract class CustomActionButton
var pb = Button.GetComponent<PassiveButton>();
pb.OnClick = new Button.ButtonClickedEvent();
pb.OnClick.AddListener((UnityAction)ClickHandler);
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;
}
}
/// <summary>
/// A utility function to reset the cooldown and/or effect of the button.
/// </summary>
public void ResetCooldownAndOrEffect()
public virtual void ResetCooldownAndOrEffect()
{
Timer = Cooldown;
if (EffectActive)
@@ -116,7 +210,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 void OverrideSprite(Sprite sprite)
public virtual void OverrideSprite(Sprite sprite)
{
if (Button != null)
{
@@ -128,7 +222,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 void OverrideName(string name)
public virtual void OverrideName(string name)
{
Button?.OverrideText(name);
}
@@ -137,7 +231,7 @@ public abstract class CustomActionButton
/// Set the button's timer.
/// </summary>
/// <param name="time">The time you want to set to.</param>
public void SetTimer(float time)
public virtual void SetTimer(float time)
{
Timer = Mathf.Clamp(time, -1, float.MaxValue);
}
@@ -146,7 +240,7 @@ public abstract class CustomActionButton
/// Increase the button's timer.
/// </summary>
/// <param name="amount">The amount you want to increase by.</param>
public void IncreaseTimer(float amount)
public virtual void IncreaseTimer(float amount)
{
SetTimer(Timer + amount);
}
@@ -155,25 +249,40 @@ public abstract class CustomActionButton
/// Decrease the button's timer.
/// </summary>
/// <param name="amount">The amount you want to decrease by.</param>
public void DecreaseTimer(float amount)
public virtual 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 void SetUses(int amount)
public virtual 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;
}
}
/// <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 void IncreaseUses(int amount = 1)
public virtual void IncreaseUses(int amount = 1)
{
SetUses(UsesLeft + amount);
}
@@ -182,7 +291,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 void DecreaseUses(int amount = 1)
public virtual void DecreaseUses(int amount = 1)
{
SetUses(UsesLeft - amount);
}
@@ -217,14 +326,24 @@ public abstract class CustomActionButton
}
/// <summary>
/// When the button is enabled, this method is called to determine if the button can be used.
/// When the button is usable, this method is called to determine if the button can be clicked.
/// 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 used or not.</returns>
/// <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>
public virtual bool CanUse()
{
return Timer <= 0 && !EffectActive && (!LimitedUses || UsesLeft > 0);
return !LimitedUses || UsesLeft > 0;
}
/// <summary>
@@ -244,9 +363,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>
protected virtual void ClickHandler()
public virtual void ClickHandler()
{
if (!CanUse())
if (!CanClick())
{
return;
}
@@ -258,7 +377,7 @@ public abstract class CustomActionButton
}
OnClick();
Button?.SetDisabled();
if (HasEffect)
{
EffectActive = true;
@@ -278,7 +397,7 @@ public abstract class CustomActionButton
/// <param name="playerControl">The local PlayerControl.</param>
public virtual void FixedUpdateHandler(PlayerControl playerControl)
{
if (Timer >= 0)
if (Timer >= 0 && !TimerPaused)
{
Timer -= Time.deltaTime;
}
@@ -298,7 +417,17 @@ public abstract class CustomActionButton
Button?.SetDisabled();
}
Button?.SetCoolDown(Timer, EffectActive ? EffectDuration : Cooldown);
if (EffectActive)
{
Button?.SetFillUp(Timer, EffectDuration);
Button!.cooldownTimerText.text = Mathf.CeilToInt(Timer).ToString();
Button!.cooldownTimerText.gameObject.SetActive(true);
}
else
{
Button?.SetCoolDown(Timer, Cooldown);
}
FixedUpdate(playerControl);
}
@@ -327,7 +456,7 @@ public abstract class CustomActionButton<T> : CustomActionButton where T : MonoB
/// <returns>True if the target object is valid, false otherwise.</returns>
public virtual bool IsTargetValid(T? target)
{
return target;
return target != null;
}
/// <summary>
@@ -354,6 +483,21 @@ public abstract class CustomActionButton<T> : CustomActionButton where T : MonoB
Target = IsTargetValid(newTarget) ? newTarget : null;
SetOutline(true);
return base.CanUse() && Target;
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);
}
}
+24 -13
View File
@@ -1,31 +1,42 @@
using System;
using MiraAPI.Events.Mira;
using MiraAPI.PluginLoading;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using Reactor.Utilities;
namespace MiraAPI.Hud;
internal static class CustomButtonManager
/// <summary>
/// Custom button manager for handling custom buttons.
/// </summary>
public 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 void RegisterButton(Type buttonType)
internal static bool RegisterButton(Type buttonType, MiraPluginInfo pluginInfo)
{
if (!typeof(CustomActionButton).IsAssignableFrom(buttonType))
if (!buttonType.IsAssignableTo(typeof(CustomActionButton)) || Activator.CreateInstance(buttonType) is not CustomActionButton button)
{
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;
return false;
}
CustomButtons.Add(button);
pluginInfo.Buttons.Add(button);
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;
}
}
+2
View File
@@ -13,5 +13,7 @@ public static class CustomButtonSingleton<T> where T : CustomActionButton
/// <summary>
/// Gets the instance of the button.
/// </summary>
#pragma warning disable CA1000
public static T Instance => _instance ??= CustomButtonManager.CustomButtons.OfType<T>().Single();
#pragma warning restore CA1000
}
+119
View File
@@ -0,0 +1,119 @@
using AmongUs.GameOptions;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Patches.Stubs;
using Reactor.Utilities.Attributes;
using Reactor.Utilities.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
namespace MiraAPI.Hud;
/// <summary>
/// Custom Player Menu using the ShapeshifterPanel as a base.
/// </summary>
/// <param name="il2CppPtr">Used by Il2Cpp. Do not use constructor, this is a MonoBehaviour.</param>
[RegisterInIl2Cpp]
public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr)
{
public ShapeshifterPanel PanelPrefab;
public float XStart = -0.8f;
public float YStart = 2.15f;
public float XOffset = 1.95f;
public float YOffset = -0.65f;
public UiElement BackButton;
public UiElement DefaultButtonSelected;
public List<ShapeshifterPanel> potentialVictims;
/// <summary>
/// Creates a CustomPlayerMenu.
/// </summary>
/// <returns>New CustomPlayerMenu object.</returns>
public static CustomPlayerMenu Create()
{
var shapeShifterRole = RoleManager.Instance.GetRole(RoleTypes.Shapeshifter);
var ogMenu = shapeShifterRole.TryCast<ShapeshifterRole>().ShapeshifterMenu;
var newMenu = Instantiate(ogMenu);
var customMenu = newMenu.gameObject.AddComponent<CustomPlayerMenu>();
customMenu.PanelPrefab = newMenu.PanelPrefab;
customMenu.XStart = newMenu.XStart;
customMenu.YStart = newMenu.YStart;
customMenu.XOffset = newMenu.XOffset;
customMenu.YOffset = newMenu.YOffset;
customMenu.BackButton = newMenu.BackButton;
var back = customMenu.BackButton.GetComponent<PassiveButton>();
back.OnClick.RemoveAllListeners();
back.OnClick.AddListener((UnityAction)(() =>
{
Instance.Close();
}));
customMenu.CloseSound = newMenu.CloseSound;
customMenu.logger = newMenu.logger;
customMenu.OpenSound = newMenu.OpenSound;
newMenu.DestroyImmediate();
customMenu.transform.SetParent(Camera.main.transform, false);
customMenu.transform.localPosition = new Vector3(0f, 0f, -50f);
return customMenu;
}
private void OnDisable()
{
ControllerManager.Instance.CloseOverlayMenu(name);
}
public override void Begin(PlayerTask task)
{
throw new NotImplementedException("Use the other Begin method.");
}
/// <summary>
/// Begins/opens the custom player menu.
/// </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)
{
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 = [];
var list2 = new Il2CppSystem.Collections.Generic.List<UiElement>();
for (var i = 0; i < list.Count; i++)
{
var player = list[i];
var num = i % 3;
var num2 = i / 3;
var flag = PlayerControl.LocalPlayer.Data.Role.NameColor == player.Data.Role.NameColor;
var shapeshifterPanel = Instantiate(PanelPrefab, transform);
shapeshifterPanel.transform.localPosition = new Vector3(XStart + num * XOffset, YStart + num2 * YOffset, -1f);
shapeshifterPanel.SetPlayer(i, player.Data, (Il2CppSystem.Action)(() => { onClick(player); }));
shapeshifterPanel.NameText.color = flag ? player.Data.Role.NameColor : Color.white;
potentialVictims.Add(shapeshifterPanel);
list2.Add(shapeshifterPanel.Button);
}
ControllerManager.Instance.OpenOverlayMenu(name, BackButton, DefaultButtonSelected, list2);
}
}
-9
View File
@@ -1,9 +0,0 @@
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;
+3 -3
View File
@@ -16,10 +16,10 @@ namespace MiraAPI;
[ReactorModFlags(ModFlags.RequireOnAllClients)]
public partial class MiraApiPlugin : BasePlugin
{
public Harmony Harmony { get; } = new(Id);
private static MiraPluginManager PluginManager { get; set; }
private static MiraPluginManager? PluginManager { get; set; }
public static Color MiraColor = new Color32(238, 154, 112, 255);
public Harmony Harmony { get; } = new(Id);
public static Color MiraColor { get; } = new Color32(238, 154, 112, 255);
public override void Load()
{
+9 -3
View File
@@ -10,6 +10,11 @@ public abstract class BaseModifier
/// </summary>
public PlayerControl? Player { get; internal set; }
/// <summary>
/// Gets the modifier component that the modifier is attached to.
/// </summary>
public ModifierComponent? ModifierComponent { get; internal set; }
/// <summary>
/// Gets the modifier id.
/// </summary>
@@ -62,13 +67,14 @@ public abstract class BaseModifier
/// <summary>
/// Called when the player dies.
/// </summary>
public virtual void OnDeath()
/// <param name="reason">The Death Reason.</param>
public virtual void OnDeath(DeathReason reason)
{
}
/// <summary>
/// Determines whether the player can vent.
/// </summary>
/// <returns>True if the player can vent, false otherwise.</returns>
public virtual bool CanVent() => Player?.Data.Role.CanVent == true;
/// <returns>True if the player can vent, false otherwise. Null for no effect.</returns>
public virtual bool? CanVent() => null;
}
+31 -15
View File
@@ -1,14 +1,14 @@
using System;
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 Il2CppInterop.Runtime.Attributes;
using MiraAPI.Modifiers.Types;
using MiraAPI.Utilities;
using Reactor.Utilities;
using Reactor.Utilities.Attributes;
using TMPro;
using UnityEngine;
@@ -18,7 +18,7 @@ namespace MiraAPI.Modifiers;
/// The component for handling modifiers.
/// </summary>
[RegisterInIl2Cpp]
public class ModifierComponent(IntPtr ptr) : MonoBehaviour(ptr)
public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
{
/// <summary>
/// Gets the active modifiers on the player.
@@ -39,11 +39,6 @@ public class ModifierComponent(IntPtr ptr) : MonoBehaviour(ptr)
internal void ClearModifiers()
{
foreach (var modifier in Modifiers)
{
modifier.OnDeactivate();
}
_toRemove.AddRange(Modifiers);
}
@@ -74,7 +69,7 @@ public class ModifierComponent(IntPtr ptr) : MonoBehaviour(ptr)
Modifiers.Add(modifier);
modifier.OnActivate();
if (_player?.AmOwner == true && modifier is TimedModifier { AutoStart: true } timer)
if (modifier is TimedModifier { AutoStart: true } timer)
{
timer.StartTimer();
}
@@ -84,7 +79,7 @@ public class ModifierComponent(IntPtr ptr) : MonoBehaviour(ptr)
{
if (_player?.AmOwner == true)
{
HudManager.Instance?.SetHudActive(true);
HudManager.Instance?.SetHudActive(_player, _player.Data.Role, HudManager.Instance.TaskPanel.isActiveAndEnabled);
}
_toAdd.Clear();
_toRemove.Clear();
@@ -112,7 +107,7 @@ public class ModifierComponent(IntPtr ptr) : MonoBehaviour(ptr)
var baseModifiers = filteredModifiers as BaseModifier[] ?? filteredModifiers.ToArray();
if (baseModifiers.Length != 0)
if (baseModifiers.Length != 0 && !MeetingHud.Instance)
{
var stringBuild = new StringBuilder();
foreach (var mod in baseModifiers)
@@ -213,6 +208,7 @@ public class ModifierComponent(IntPtr ptr) : MonoBehaviour(ptr)
_toAdd.Add(modifier);
modifier.Player = _player;
modifier.ModifierComponent = this;
modifier.ModifierId = modifierId.Value;
return modifier;
}
@@ -259,4 +255,24 @@ public class ModifierComponent(IntPtr ptr) : MonoBehaviour(ptr)
{
return AddModifier(typeof(T)) as T;
}
/// <summary>
/// Checks if a player has an active or queued modifier by its ID.
/// </summary>
/// <param name="id">The Modifier ID.</param>
/// <returns>True if the Modifier is present, false otherwise.</returns>
public bool HasModifier(uint id)
{
return ActiveModifiers.Exists(x => x.ModifierId == id) || _toAdd.Exists(x => x.ModifierId == id);
}
/// <summary>
/// Checks if a player has an active or queued modifier by its type.
/// </summary>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>True if the Modifier is present, false otherwise.</returns>
public bool HasModifier<T>()
{
return ActiveModifiers.Exists(x => x is T) || _toAdd.Exists(x => x is T);
}
}
+66 -49
View File
@@ -19,6 +19,7 @@ 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 _nextId;
@@ -48,84 +49,100 @@ public static class ModifierManager
return TypeToIdModifierMap.GetValueOrDefault(type);
}
internal static void RegisterModifier(Type modifierType)
internal static bool RegisterModifier(Type modifierType)
{
if (!typeof(BaseModifier).IsAssignableFrom(modifierType))
{
return;
return false;
}
IdToTypeModifierMap.Add(GetNextId(), modifierType);
TypeToIdModifierMap.Add(modifierType, _nextId);
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(_nextId);
return true;
}
internal static void AssignModifiers(List<PlayerControl> plrs)
{
var rand = new Random();
List<uint> filteredModifiers = [];
foreach (var modifier in IdToTypeModifierMap.Where(pair => pair.Value.IsAssignableTo(typeof(GameModifier))))
foreach (var priority in PrioritiesToIdsMap.Keys.OrderByDescending(x => x))
{
if (Activator.CreateInstance(modifier.Value) is not GameModifier mod)
var filteredModifiers = new List<uint>();
foreach (var id in PrioritiesToIdsMap[priority])
{
Logger<MiraApiPlugin>.Error($"Failed to create instance of {modifier.Value.Name}");
continue;
}
var mod = Activator.CreateInstance(IdToTypeModifierMap[id]) as GameModifier;
var chance = Math.Clamp(mod!.GetAssignmentChance(), 0, 100);
var count = mod.GetAmountPerGame();
if (!plrs.Exists(x => IsGameModifierValid(x, mod, modifier.Key)))
{
Logger<MiraApiPlugin>.Warning("No players are valid for modifier: " + mod.ModifierName);
continue;
}
var maxCount = plrs.Count(x => IsGameModifierValid(x, mod, modifier.Key));
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))
if (chance == 0 || count == 0)
{
filteredModifiers.Add(TypeToIdModifierMap[modifier.Value]);
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);
}
}
}
}
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)
if (filteredModifiers.Count == 0)
{
Logger<MiraApiPlugin>.Error($"Failed to create instance of {IdToTypeModifierMap[id].Name}");
Logger<MiraApiPlugin>.Warning($"No filtered modifiers for priority {priority}");
continue;
}
if (!plrs.Exists(x => IsGameModifierValid(x, mod, id)))
var shuffledList = filteredModifiers.Randomize();
if (shuffledList.Count > plrs.Count)
{
shuffledModifiers.RemoveAt(0);
continue;
shuffledList = shuffledList.GetRange(0, plrs.Count);
}
var plr = plrs.Random();
if (plr == null || !IsGameModifierValid(plr, mod, id))
foreach (var id in shuffledList)
{
continue;
}
var mod = Activator.CreateInstance(IdToTypeModifierMap[id]) as GameModifier;
var plr = plrs.Where(x => IsGameModifierValid(x, mod!, id)).Random();
shuffledModifiers.RemoveAt(0);
plr.RpcAddModifier(id);
if (plr == null)
{
Logger<MiraApiPlugin>.Warning($"Somehow valid players for modifier {mod!.ModifierName} disappeared");
}
else
{
plr.RpcAddModifier(id);
}
}
}
}
@@ -1,6 +0,0 @@
using System;
namespace MiraAPI.Modifiers;
[AttributeUsage(AttributeTargets.Class)]
public class RegisterModifierAttribute : Attribute;
+13
View File
@@ -17,10 +17,23 @@ 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>
/// <param name="role">The role to be checked.</param>
/// <returns>True if the modifier is valid on the role, otherwise false.</returns>
public virtual bool IsModifierValidOn(RoleBehaviour role) => true;
/// <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;
}
+51 -11
View File
@@ -1,5 +1,4 @@
using System;
using MiraAPI.Utilities;
using Reactor.Utilities;
using UnityEngine;
@@ -40,6 +39,9 @@ public abstract class TimedModifier : BaseModifier
/// </summary>
public float TimeRemaining { get; protected set; }
/// <inheritdoc />
public override bool HideOnUi => !TimerActive;
/// <summary>
/// Gets the HUD information for Timed Modifier, including the time remaining.
/// </summary>
@@ -54,25 +56,18 @@ public abstract class TimedModifier : BaseModifier
/// </summary>
public override void FixedUpdate()
{
if (Player?.AmOwner == false)
if (!TimerActive)
{
return;
}
if (TimeRemaining > 0 && TimerActive)
if (TimeRemaining > 0)
{
TimeRemaining -= Time.fixedDeltaTime;
}
else
{
TimerActive = false;
TimeRemaining = Duration;
OnTimerComplete();
if (RemoveOnComplete)
{
Player?.RpcRemoveModifier(ModifierId);
}
StopTimer();
}
}
@@ -87,7 +82,52 @@ public abstract class TimedModifier : BaseModifier
return;
}
TimeRemaining = Duration;
TimerActive = true;
}
/// <summary>
/// Stops the timer and calls OnTimerComplete().
/// </summary>
public void StopTimer()
{
if (!TimerActive)
{
return;
}
TimerActive = false;
TimeRemaining = Duration;
OnTimerComplete();
if (RemoveOnComplete)
{
ModifierComponent?.RemoveModifier(ModifierId);
}
}
/// <summary>
/// Resets the timer. Does not call OnTimerComplete().
/// </summary>
public void ResetTimer()
{
TimerActive = false;
TimeRemaining = Duration;
}
/// <summary>
/// Pauses the timer.
/// </summary>
public void PauseTimer()
{
TimerActive = false;
}
/// <summary>
/// Pauses the timer.
/// </summary>
public void ResumeTimer()
{
TimerActive = true;
}
}
+282
View File
@@ -0,0 +1,282 @@
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.Extensions;
using System.Collections;
using System.Linq;
using UnityEngine;
namespace MiraAPI.Networking;
/// <summary>
/// Custom murder RPCs to fix issues with default ones.
/// </summary>
public static class CustomMurderRpc
{
/// <summary>
/// Networked Custom Murder method.
/// </summary>
/// <param name="source">The killer.</param>
/// <param name="target">The player to murder.</param>
/// <param name="didSucceed">Whether the murder was successful or not.</param>
/// <param name="resetKillTimer">Should the kill timer be reset.</param>
/// <param name="createDeadBody">Should a dead body be created.</param>
/// <param name="teleportMurderer">Should the killer be snapped to the dead player.</param>
/// <param name="showKillAnim">Should the kill animation be shown.</param>
/// <param name="playKillSound">Should the kill sound be played.</param>
[MethodRpc((uint)MiraRpc.CustomMurder, LocalHandling = RpcLocalHandling.Before, SendImmediately = true)]
public static void RpcCustomMurder(
this PlayerControl source,
PlayerControl target,
bool didSucceed = true,
bool resetKillTimer = true,
bool createDeadBody = true,
bool teleportMurderer = true,
bool showKillAnim = true,
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(
target,
murderResultFlags2,
resetKillTimer,
createDeadBody,
teleportMurderer,
showKillAnim,
playKillSound);
}
/// <summary>
/// Custom Murder method without networking. If you need a networked version, use <see cref="RpcCustomMurder"/>.
/// </summary>
/// <param name="source">The killer.</param>
/// <param name="target">The player to murder.</param>
/// <param name="resultFlags">Murder result flags.</param>
/// <param name="resetKillTimer">Should the kill timer be reset.</param>
/// <param name="createDeadBody">Should a dead body be created.</param>
/// <param name="teleportMurderer">Should the killer be snapped to the dead player.</param>
/// <param name="showKillAnim">Should the kill animation be shown.</param>
/// <param name="playKillSound">Should the kill sound be played.</param>
public static void CustomMurder(
this PlayerControl source,
PlayerControl target,
MurderResultFlags resultFlags,
bool resetKillTimer = true,
bool createDeadBody = true,
bool teleportMurderer = true,
bool showKillAnim = true,
bool playKillSound = true)
{
source.isKilling = false;
var data = target.Data;
if (resultFlags.HasFlag(MurderResultFlags.FailedError))
{
return;
}
if (resultFlags.HasFlag(MurderResultFlags.FailedProtected) ||
(resultFlags.HasFlag(MurderResultFlags.DecisionByHost) && target.protectedByGuardianId > -1))
{
target.protectedByGuardianThisRound = true;
var flag = PlayerControl.LocalPlayer.Data.Role.Role == RoleTypes.GuardianAngel;
if (flag && PlayerControl.LocalPlayer.Data.PlayerId == target.protectedByGuardianId)
{
StatsManager.Instance.IncrementStat(StringNames.StatsGuardianAngelCrewmatesProtected);
AchievementManager.Instance.OnProtectACrewmate();
}
if (source.AmOwner || flag)
{
target.ShowFailedMurder();
if (resetKillTimer)
{
source.SetKillTimer(
GameOptionsManager.Instance.CurrentGameOptions.GetFloat(FloatOptionNames.KillCooldown) / 2f);
}
}
else
{
target.RemoveProtection();
}
return;
}
if (!resultFlags.HasFlag(MurderResultFlags.Succeeded) &&
!resultFlags.HasFlag(MurderResultFlags.DecisionByHost))
{
return;
}
DebugAnalytics.Instance.Analytics.Kill(target.Data, source.Data);
if (source.AmOwner)
{
StatsManager.Instance.IncrementStat(
GameManager.Instance.IsHideAndSeek()
? StringNames.StatsImpostorKills_HideAndSeek
: StringNames.StatsImpostorKills);
if (source.CurrentOutfitType == PlayerOutfitType.Shapeshifted)
{
StatsManager.Instance.IncrementStat(StringNames.StatsShapeshifterShiftedKills);
}
if (Constants.ShouldPlaySfx() && playKillSound)
{
SoundManager.Instance.PlaySound(source.KillSfx, false, 0.8f);
}
if (resetKillTimer)
{
source.SetKillTimer(GameOptionsManager.Instance.CurrentGameOptions.GetFloat(FloatOptionNames.KillCooldown));
}
}
UnityTelemetry.Instance.WriteMurder();
target.gameObject.layer = LayerMask.NameToLayer("Ghost");
if (target.AmOwner)
{
StatsManager.Instance.IncrementStat(StringNames.StatsTimesMurdered);
if (Minigame.Instance)
{
try
{
Minigame.Instance.Close();
Minigame.Instance.Close();
}
catch
{
// ignored
}
}
if (showKillAnim)
{
HudManager.Instance.KillOverlay.ShowKillAnimation(source.Data, data);
}
target.cosmetics.SetNameMask(false);
target.RpcSetScanner(false);
}
AchievementManager.Instance.OnMurder(
source.AmOwner,
target.AmOwner,
source.CurrentOutfitType == PlayerOutfitType.Shapeshifted,
source.shapeshiftTargetPlayerId,
target.PlayerId);
source.MyPhysics.StartCoroutine(source.KillAnimations.Random()?.CoPerformCustomKill(source, target, createDeadBody, teleportMurderer));
}
/// <summary>
/// Perform a custom kill animation.
/// </summary>
/// <param name="anim">The kill animation.</param>
/// <param name="source">The murderer.</param>
/// <param name="target">The murdered player.</param>
/// <param name="createDeadBody">Should a dead body be created.</param>
/// <param name="teleportMurderer">Should the murder be teleported.</param>
/// <returns>Coroutine.</returns>
public static IEnumerator CoPerformCustomKill(
this KillAnimation anim,
PlayerControl source,
PlayerControl target,
bool createDeadBody = true,
bool teleportMurderer = true)
{
var cam = Camera.main?.GetComponent<FollowerCamera>();
var isParticipant = PlayerControl.LocalPlayer == source || PlayerControl.LocalPlayer == target;
var sourcePhys = source.MyPhysics;
if (teleportMurderer)
{
KillAnimation.SetMovement(source, false);
}
KillAnimation.SetMovement(target, false);
if (isParticipant)
{
PlayerControl.LocalPlayer.isKilling = true;
source.isKilling = true;
}
DeadBody? deadBody = null;
if (createDeadBody)
{
deadBody = Object.Instantiate(GameManager.Instance.DeadBodyPrefab);
deadBody.enabled = false;
deadBody.ParentId = target.PlayerId;
deadBody.bodyRenderers.ToList().ForEach(target.SetPlayerMaterialColors);
target.SetPlayerMaterialColors(deadBody.bloodSplatter);
var vector = target.transform.position + anim.BodyOffset;
vector.z = vector.y / 1000f;
deadBody.transform.position = vector;
}
if (isParticipant)
{
if (cam != null)
{
cam.Locked = true;
}
ConsoleJoystick.SetMode_Task();
if (PlayerControl.LocalPlayer.AmOwner)
{
PlayerControl.LocalPlayer.MyPhysics.inputHandler.enabled = true;
}
}
target.Die(DeathReason.Kill, true);
if (teleportMurderer)
{
yield return source.MyPhysics.Animations.CoPlayCustomAnimation(anim.BlurAnim);
sourcePhys.Animations.PlayIdleAnimation();
source.NetTransform.SnapTo(target.transform.position);
KillAnimation.SetMovement(source, true);
}
KillAnimation.SetMovement(target, true);
if (deadBody != null)
{
deadBody.enabled = true;
}
if (!isParticipant)
{
yield break;
}
if (cam != null)
{
cam.Locked = false;
}
PlayerControl.LocalPlayer.isKilling = false;
source.isKilling = false;
var afterMurderEvent = new AfterMurderEvent(source, target);
MiraEventManager.InvokeEvent(afterMurderEvent);
}
}
-186
View File
@@ -1,186 +0,0 @@
using AmongUs.GameOptions;
using Assets.CoreScripts;
using Reactor.Networking.Attributes;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using System.Collections;
using System.Linq;
using UnityEngine;
namespace MiraAPI.Networking;
public static class CustomMurderRpcs
{
[MethodRpc((uint)MiraRpc.CustomMurder)]
public static void RpcCustomMurder(this PlayerControl source, PlayerControl target, bool didSucceed = true,
bool resetKillTimer = true, bool createDeadBody = true, bool teleportMurderer = true, bool showKillAnim = true, bool playKillSound = true)
{
var murderResultFlags = didSucceed ? MurderResultFlags.Succeeded : MurderResultFlags.FailedError;
var murderResultFlags2 = MurderResultFlags.DecisionByHost | murderResultFlags;
source.CustomMurder(target, murderResultFlags2, resetKillTimer, createDeadBody, teleportMurderer, showKillAnim, playKillSound);
}
public static void CustomMurder(this PlayerControl source, PlayerControl target, MurderResultFlags resultFlags,
bool resetKillTimer = true, bool createDeadBody = true, bool teleportMurderer = true, bool showKillAnim = true, bool playKillSound = true)
{
source.isKilling = false;
source.logger.Debug(string.Format("{0} trying to murder {1}", source.PlayerId, target.PlayerId), null);
var data = target.Data;
if (resultFlags.HasFlag(MurderResultFlags.FailedError))
{
return;
}
if (resultFlags.HasFlag(MurderResultFlags.FailedProtected) || (resultFlags.HasFlag(MurderResultFlags.DecisionByHost) && target.protectedByGuardianId > -1))
{
target.protectedByGuardianThisRound = true;
var flag = PlayerControl.LocalPlayer.Data.Role.Role == RoleTypes.GuardianAngel;
if (flag && PlayerControl.LocalPlayer.Data.PlayerId == target.protectedByGuardianId)
{
StatsManager.Instance.IncrementStat(StringNames.StatsGuardianAngelCrewmatesProtected);
DestroyableSingleton<AchievementManager>.Instance.OnProtectACrewmate();
}
if (source.AmOwner || flag)
{
target.ShowFailedMurder();
if (resetKillTimer)
{
source.SetKillTimer(GameOptionsManager.Instance.CurrentGameOptions.GetFloat(FloatOptionNames.KillCooldown) / 2f);
}
}
else
{
target.RemoveProtection();
}
source.logger.Debug(string.Format("{0} failed to murder {1} due to guardian angel protection", source.PlayerId, target.PlayerId), null);
return;
}
if (resultFlags.HasFlag(MurderResultFlags.Succeeded) || resultFlags.HasFlag(MurderResultFlags.DecisionByHost))
{
DestroyableSingleton<DebugAnalytics>.Instance.Analytics.Kill(target.Data, source.Data);
if (source.AmOwner)
{
if (GameManager.Instance.IsHideAndSeek())
{
StatsManager.Instance.IncrementStat(StringNames.StatsImpostorKills_HideAndSeek);
}
else
{
StatsManager.Instance.IncrementStat(StringNames.StatsImpostorKills);
}
if (source.CurrentOutfitType == PlayerOutfitType.Shapeshifted)
{
StatsManager.Instance.IncrementStat(StringNames.StatsShapeshifterShiftedKills);
}
if (Constants.ShouldPlaySfx() && playKillSound)
{
SoundManager.Instance.PlaySound(source.KillSfx, false, 0.8f, null);
}
if (resetKillTimer)
{
source.SetKillTimer(GameOptionsManager.Instance.CurrentGameOptions.GetFloat(FloatOptionNames.KillCooldown));
}
}
DestroyableSingleton<UnityTelemetry>.Instance.WriteMurder();
target.gameObject.layer = LayerMask.NameToLayer("Ghost");
if (target.AmOwner)
{
StatsManager.Instance.IncrementStat(StringNames.StatsTimesMurdered);
if (Minigame.Instance)
{
try
{
Minigame.Instance.Close();
Minigame.Instance.Close();
}
catch
{
}
}
if (showKillAnim)
{
DestroyableSingleton<HudManager>.Instance.KillOverlay.ShowKillAnimation(source.Data, data);
}
target.cosmetics.SetNameMask(false);
target.RpcSetScanner(false);
}
DestroyableSingleton<AchievementManager>.Instance.OnMurder(source.AmOwner, target.AmOwner, source.CurrentOutfitType == PlayerOutfitType.Shapeshifted, source.shapeshiftTargetPlayerId, (int)target.PlayerId);
Coroutines.Start(source.KillAnimations.Random().CoPerformCustomKill(source, target, createDeadBody, teleportMurderer));
source.logger.Debug(string.Format("{0} succeeded in murdering {1}", source.PlayerId, target.PlayerId), null);
}
}
public static IEnumerator CoPerformCustomKill(this KillAnimation anim, PlayerControl source, PlayerControl target,
bool createDeadBody = true, bool teleportMurderer = true)
{
var cam = Camera.main.GetComponent<FollowerCamera>();
var isParticipant = PlayerControl.LocalPlayer == source || PlayerControl.LocalPlayer == target;
var sourcePhys = source.MyPhysics;
if (teleportMurderer)
{
KillAnimation.SetMovement(source, false);
}
KillAnimation.SetMovement(target, false);
if (isParticipant)
{
PlayerControl.LocalPlayer.isKilling = true;
source.isKilling = true;
}
DeadBody deadBody = null;
if (createDeadBody)
{
deadBody = Object.Instantiate(GameManager.Instance.DeadBodyPrefab);
deadBody.enabled = false;
deadBody.ParentId = target.PlayerId;
deadBody.bodyRenderers.ToArray().ToList().ForEach(target.SetPlayerMaterialColors);
target.SetPlayerMaterialColors(deadBody.bloodSplatter);
var vector = target.transform.position + anim.BodyOffset;
vector.z = vector.y / 1000f;
deadBody.transform.position = vector;
}
if (isParticipant)
{
cam.Locked = true;
ConsoleJoystick.SetMode_Task();
if (PlayerControl.LocalPlayer.AmOwner)
{
PlayerControl.LocalPlayer.MyPhysics.inputHandler.enabled = true;
}
}
target.Die(DeathReason.Kill, true);
yield return source.MyPhysics.Animations.CoPlayCustomAnimation(anim.BlurAnim);
sourcePhys.Animations.PlayIdleAnimation();
if (teleportMurderer)
{
source.NetTransform.SnapTo(target.transform.position);
KillAnimation.SetMovement(source, true);
}
KillAnimation.SetMovement(target, true);
if (deadBody)
{
deadBody.enabled = true;
}
if (isParticipant)
{
cam.Locked = false;
PlayerControl.LocalPlayer.isKilling = false;
source.isKilling = false;
}
yield break;
}
}
+27 -1
View File
@@ -1,11 +1,37 @@
namespace MiraAPI.Networking;
/// <summary>
/// Mira RPCs.
/// </summary>
public enum MiraRpc : uint
{
/// <summary>
/// Syncs the game options.
/// </summary>
SyncGameOptions,
/// <summary>
/// Syncs the role options.
/// </summary>
SyncRoleOptions,
/// <summary>
/// Adds a modifier to a player.
/// </summary>
AddModifier,
/// <summary>
/// Removes a modifier from a player.
/// </summary>
RemoveModifier,
/// <summary>
/// Syncs all modifiers at once.
/// </summary>
SyncModifiers,
/// <summary>
/// Custom Murder RPC.
/// </summary>
CustomMurder,
}
}
+18 -1
View File
@@ -1,8 +1,25 @@
namespace MiraAPI.Networking;
/// <summary>
/// Used to network data and mark it with an ID.
/// </summary>
/// <param name="id">The ID of the data.</param>
/// <param name="data">The byte[] data.</param>
public readonly struct NetData(uint id, byte[] data)
{
/// <summary>
/// Gets the ID of the data.
/// </summary>
public uint Id { get; } = id;
/// <summary>
/// Gets the byte[] data.
/// </summary>
public byte[] Data { get; } = data;
/// <summary>
/// Gets the length of the data in bytes.
/// </summary>
/// <returns>An int representing the number of bytes this NetData takes up.</returns>
public int GetLength() => 4 + Data.Length;
}
}
+13 -7
View File
@@ -6,12 +6,18 @@ using Reactor.Networking.Rpc;
namespace MiraAPI.Networking;
[RegisterCustomRpc((uint)MiraRpc.SyncModifiers)]
internal class SyncModifiersRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, NetData[]>(plugin, id)
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)
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)
{
@@ -26,21 +32,21 @@ internal class SyncModifiersRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc
var data = new NetData[length];
for (var i = 0; i < length; i++)
{
var id = reader.ReadPackedUInt32();
var dataId = reader.ReadPackedUInt32();
var bytes = reader.ReadBytesAndSize();
data[i] = new NetData(id, bytes);
data[i] = new NetData(dataId, bytes);
}
return data;
}
public override void Handle(PlayerControl playerControl, NetData[] data)
public override void Handle(PlayerControl playerControl, NetData[]? data)
{
if (AmongUsClient.Instance.HostId != playerControl.OwnerId)
{
return;
}
ModifierManager.HandleSyncModifiers(data);
ModifierManager.HandleSyncModifiers(data ?? []);
}
}
}
+14 -8
View File
@@ -7,12 +7,18 @@ namespace MiraAPI.Networking;
// METHOD RPC DOESNT WORK WITH THE ARRAYS AND STUFF SO THIS IS HOW WE WILL DO IT FOR NOW
[RegisterCustomRpc((uint)MiraRpc.SyncGameOptions)]
internal class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, NetData[]>(plugin, id)
internal sealed class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, NetData[]>(plugin, id)
{
public override RpcLocalHandling LocalHandling => RpcLocalHandling.None;
public override void Write(MessageWriter writer, NetData[] data)
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)
{
@@ -27,21 +33,21 @@ internal class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<M
var data = new NetData[length];
for (var i = 0; i < length; i++)
{
var id = reader.ReadPackedUInt32();
var dataId = reader.ReadPackedUInt32();
var bytes = reader.ReadBytesAndSize();
data[i] = new NetData(id, bytes);
data[i] = new NetData(dataId, bytes);
}
return data;
}
public override void Handle(PlayerControl playerControl, NetData[] data)
public override void Handle(PlayerControl playerControl, NetData[]? data)
{
if (AmongUsClient.Instance.HostId != playerControl.OwnerId)
{
return;
}
ModdedOptionsManager.HandleSyncOptions(data);
ModdedOptionsManager.HandleSyncOptions(data ?? []);
}
}
}
+13 -8
View File
@@ -6,13 +6,18 @@ using Reactor.Networking.Rpc;
namespace MiraAPI.Networking;
[RegisterCustomRpc((uint)MiraRpc.SyncRoleOptions)]
internal class SyncRoleOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, NetData[]>(plugin, id)
internal sealed class SyncRoleOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, NetData[]>(plugin, id)
{
public override RpcLocalHandling LocalHandling => RpcLocalHandling.None;
public override void Write(MessageWriter writer, NetData[] data)
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)
{
@@ -27,21 +32,21 @@ internal class SyncRoleOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomR
var data = new NetData[length];
for (var i = 0; i < length; i++)
{
var id = reader.ReadPackedUInt32();
var dataId = reader.ReadPackedUInt32();
var bytes = reader.ReadBytesAndSize();
data[i] = new NetData(id, bytes);
data[i] = new NetData(dataId, bytes);
}
return data;
}
public override void Handle(PlayerControl playerControl, NetData[] data)
public override void Handle(PlayerControl playerControl, NetData[]? data)
{
if (AmongUsClient.Instance.HostId != playerControl.OwnerId)
{
return;
}
CustomRoleManager.HandleSyncRoleOptions(data);
CustomRoleManager.HandleSyncRoleOptions(data ?? []);
}
}
}
+21 -3
View File
@@ -1,16 +1,26 @@
using HarmonyLib;
using InnerNet;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Player;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
namespace MiraAPI.Patches;
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CreatePlayer))]
/// <summary>
/// Sync all options, role settings, and modifiers to the player when they join the game.
/// </summary>
[HarmonyPatch(typeof(AmongUsClient))]
public static class AmongUsClientSyncPatch
{
public static void Postfix(ClientData clientData)
[HarmonyPostfix]
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CreatePlayer))]
public static void CreatePlayerPatch(ClientData clientData)
{
var joinEvent = new PlayerJoinEvent(clientData);
MiraEventManager.InvokeEvent(joinEvent);
if (!AmongUsClient.Instance.AmHost)
{
return;
@@ -25,4 +35,12 @@ public static class AmongUsClientSyncPatch
CustomRoleManager.SyncAllRoleSettings(clientData.Id);
ModifierManager.SyncAllModifiers(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);
}
}
@@ -7,8 +7,8 @@ namespace MiraAPI.Patches.Colors;
[HarmonyPatch(typeof(PlayerTab))]
public static class ScrollingColorsPatch
{
/// Collider
private static BoxCollider2D _collider;
// Collider
private static BoxCollider2D? _collider;
/// <summary>
/// Add scrolling to the colors tab
@@ -20,7 +20,7 @@ public static class ScrollingColorsPatch
{
return;
}
var tab = PlayerCustomizationMenu.Instance.Tabs[1].Tab;
if (__instance.scroller == null)
@@ -31,7 +31,7 @@ public static class ScrollingColorsPatch
var maskObj = new GameObject
{
layer = 5,
name = "SpriteMask"
name = "SpriteMask",
};
maskObj.transform.SetParent(__instance.transform);
maskObj.transform.localPosition = new Vector3(0, 0, 0);
@@ -55,4 +55,4 @@ public static class ScrollingColorsPatch
__instance.SetScrollerBounds();
}
}
}
+42
View File
@@ -0,0 +1,42 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Usables;
using System.Collections.Generic;
using System.Reflection;
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;
}
}
+20
View File
@@ -0,0 +1,20 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
namespace MiraAPI.Patches.Events;
/// <summary>
/// Patch for trigging the GameEndEvent.
/// </summary>
[HarmonyPatch]
public static class EndGamePatches
{
[HarmonyPostfix]
[HarmonyPatch(typeof(EndGameManager), nameof(EndGameManager.SetEverythingUp))]
public static void SetEverythingUpPatch(EndGameManager __instance)
{
var @event = new GameEndEvent(__instance);
MiraEventManager.InvokeEvent(@event);
}
}
@@ -0,0 +1,25 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
namespace MiraAPI.Patches;
/// <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);
}
}
@@ -0,0 +1,21 @@
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;
}
}
@@ -0,0 +1,30 @@
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;
}
}
@@ -0,0 +1,21 @@
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
@@ -0,0 +1,35 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla;
using System.Collections.Generic;
using System.Reflection;
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;
}
}
@@ -0,0 +1,57 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Usables;
using System.Linq;
namespace MiraAPI.Patches.Events;
/// <summary>
/// Patches to invoke vent related MiraEvents.
/// </summary>
[HarmonyPatch]
public static class VentEventPatches
{
// necessary because Vent.Use is inlined in il2cpp.
private static bool _showButtons;
[HarmonyPostfix]
[HarmonyPatch(typeof(VentButton), nameof(VentButton.DoClick))]
public static void VentUsePostfix(VentButton __instance)
{
__instance.currentTarget?.SetButtons(_showButtons);
}
[HarmonyPrefix]
[HarmonyPatch(typeof(PlayerPhysics), nameof(PlayerPhysics.RpcEnterVent))]
public static bool PlayerPhysicsRpcEnterVentPrefix(PlayerPhysics __instance, int id)
{
var pc = __instance.myPlayer;
var vent = ShipStatus.Instance.AllVents.FirstOrDefault(v => v.Id == id);
var @event = new EnterVentEvent(pc, vent);
MiraEventManager.InvokeEvent(@event);
if (pc.AmOwner)
{
_showButtons = !@event.IsCancelled;
}
return !@event.IsCancelled;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(PlayerPhysics), nameof(PlayerPhysics.RpcExitVent))]
public static bool PlayerPhysicsRpcExitVentPrefix(PlayerPhysics __instance, int id)
{
var pc = __instance.myPlayer;
var vent = ShipStatus.Instance.AllVents.First(v => v.Id == id);
var @event = new ExitVentEvent(pc, vent);
MiraEventManager.InvokeEvent(@event);
if (pc.AmOwner)
{
_showButtons = @event.IsCancelled;
}
return !@event.IsCancelled;
}
}
+2 -3
View File
@@ -1,5 +1,4 @@

/*
/*
[HarmonyPatch]
public static class ConsolePatches
{
@@ -69,4 +68,4 @@ public static class ConsolePatches
canUse = couldUse = true;
return true;
}
}*/
}*/
+2 -4
View File
@@ -1,6 +1,4 @@

/*
/*
[HarmonyPatch(typeof(DeadBody))]
public static class DeadBodyPatch
{
@@ -10,4 +8,4 @@ public static class DeadBodyPatch
{
return CustomGameModeManager.ActiveMode == null || CustomGameModeManager.ActiveMode.CanReport(__instance);
}
}*/
}*/
@@ -1,6 +1,4 @@

/*
/*
[HarmonyPatch]
public static class GameLogicPatches
{
@@ -19,4 +17,4 @@ public static class GameLogicPatches
CustomGameModeManager.ActiveMode?.AssignRoles(out runOriginal, __instance);
return runOriginal;
}
}*/
}*/
@@ -1,6 +1,4 @@

/*
/*
/// <summary>
/// Allow Impostors to kill each other if can kill is enabled in gamemode or friendly fire is toggled on
/// </summary>
@@ -16,11 +14,11 @@ public static class ImpostorTargetPatch
{
return true;
}
__result = target is { Disconnected: false, IsDead: false } &&
target.PlayerId != __instance.Player.PlayerId && !(target.Role == null) &&
!(target.Object == null) && !target.Object.inVent && !target.Object.inMovingPlat;
return false;
}
}*/
}*/
@@ -1,6 +1,4 @@

/*
/*
[HarmonyPatch(typeof(MapBehaviour))]
public static class MapBehaviourPatch
{
@@ -17,4 +15,4 @@ public static class MapBehaviourPatch
return true;
}
}*/
}*/
+2 -4
View File
@@ -1,6 +1,4 @@

/*
/*
[HarmonyPatch(typeof(KillAnimation))]
public static class OnDeathPatch
{
@@ -10,4 +8,4 @@ public static class OnDeathPatch
{
CustomGameModeManager.ActiveMode?.OnDeath(target);
}
}*/
}*/
+2 -6
View File
@@ -1,10 +1,7 @@

/*
/*
[HarmonyPatch(typeof(Vent))]
public static class VentPatches
{
[HarmonyPrefix]
[HarmonyPatch(nameof(Vent.CanUse))]
public static bool CanUseVentPatch(Vent __instance, ref float __result, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] ref bool canUse, [HarmonyArgument(2)] ref bool couldUse)
@@ -47,5 +44,4 @@ public static class VentPatches
return false;
}
}*/
}*/
@@ -1,20 +1,20 @@
using HarmonyLib;
using MiraAPI.Hud;
namespace MiraAPI.Patches;
namespace MiraAPI.Patches.Hud;
/// <summary>
/// Harmony patches for the MeetingHud class.
/// Reset button patches
/// </summary>
[HarmonyPatch(typeof(MeetingHud))]
public static class MeetingHudPatches
[HarmonyPatch]
public static class ButtonResetPatches
{
/// <summary>
/// Resets the cooldown and effect of all custom buttons when the meeting starts.
/// </summary>
[HarmonyPostfix]
[HarmonyPatch(nameof(MeetingHud.Start))]
public static void StartPostfix()
[HarmonyPatch(typeof(MeetingHud), nameof(MeetingHud.Start))]
public static void MeetingHudStartPostfix()
{
foreach (var customActionButton in CustomButtonManager.CustomButtons)
{
@@ -23,11 +23,11 @@ public static class MeetingHudPatches
}
/// <summary>
/// Resets the cooldown and effect of all custom buttons when the voting is complete.
/// Resets the cooldown and effect of all custom buttons after the exile screen is closed.
/// </summary>
[HarmonyPostfix]
[HarmonyPatch(nameof(MeetingHud.VotingComplete))]
public static void VotingCompletePostfix()
[HarmonyPatch(typeof(ExileController), nameof(ExileController.ReEnableGameplay))]
public static void ExileControllerReEnableGameplayPostfix()
{
foreach (var customActionButton in CustomButtonManager.CustomButtons)
{
+17 -75
View File
@@ -1,7 +1,5 @@
using HarmonyLib;
using InnerNet;
using MiraAPI.Hud;
using MiraAPI.Roles;
using Reactor.Utilities.Extensions;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -15,63 +13,9 @@ namespace MiraAPI.Patches;
public static class HudManagerPatches
{
// Custom buttons parent.
private static GameObject? _bottomLeft;
// Custom role tab.
private static TaskPanelBehaviour? _roleTab;
/// <summary>
/// Update custom role tab and custom role hud elements.
/// </summary>
/// <param name="__instance">The HudManager instance.</param>
[HarmonyPostfix]
[HarmonyPatch(nameof(HudManager.Update))]
public static void UpdatePostfix(HudManager __instance)
{
var local = PlayerControl.LocalPlayer;
if (AmongUsClient.Instance.GameState != InnerNetClient.GameStates.Started && !ShipStatus.Instance)
{
return;
}
// CustomGameModeManager.ActiveMode?.HudUpdate(__instance);
switch (local?.Data?.Role)
{
case null:
return;
case ICustomRole customRole:
{
customRole.HudUpdate(__instance);
if (customRole.RoleHintType != RoleHintType.RoleTab)
{
_roleTab?.gameObject.Destroy();
return;
}
if (_roleTab == null)
{
_roleTab = CustomRoleManager.CreateRoleTab(customRole);
}
else
{
CustomRoleManager.UpdateRoleTab(_roleTab, customRole);
}
break;
}
default:
if (_roleTab != null)
{
_roleTab.gameObject.Destroy();
}
break;
}
}
internal static GameObject? _bottomLeft;
internal static Transform? _bottomRight;
internal static Transform? _buttons;
/*
/// <summary>
@@ -92,12 +36,19 @@ public static class HudManagerPatches
[HarmonyPatch(nameof(HudManager.Start))]
public static void StartPostfix(HudManager __instance)
{
var buttons = __instance.transform.Find("Buttons");
var bottomRight = buttons.Find("BottomRight");
if (_buttons == null)
{
_buttons = __instance.transform.Find("Buttons");
}
if (_bottomRight == null)
{
_bottomRight = _buttons.Find("BottomRight");
}
if (_bottomLeft == null)
{
_bottomLeft = Object.Instantiate(bottomRight.gameObject, buttons);
_bottomLeft = Object.Instantiate(_bottomRight.gameObject, _buttons);
}
foreach (var t in _bottomLeft.GetComponentsInChildren<ActionButton>(true))
@@ -117,7 +68,7 @@ public static class HudManagerPatches
var location = button.Location switch
{
ButtonLocation.BottomLeft => _bottomLeft.transform,
ButtonLocation.BottomRight => bottomRight,
ButtonLocation.BottomRight => _bottomRight,
_ => null,
};
@@ -136,7 +87,7 @@ public static class HudManagerPatches
}
/// <summary>
/// Set the custom role tab and custom buttons active when the hud is active.
/// Set the custom buttons active when the hud is active.
/// </summary>
/// <param name="__instance">HudManager instance.</param>
/// <param name="localPlayer">The local PlayerControl.</param>
@@ -146,24 +97,15 @@ public static class HudManagerPatches
[HarmonyPatch(nameof(HudManager.SetHudActive), typeof(PlayerControl), typeof(RoleBehaviour), typeof(bool))]
public static void SetHudActivePostfix(HudManager __instance, PlayerControl localPlayer, RoleBehaviour role, bool isActive)
{
if (!localPlayer.Data)
__instance.AdminButton.ToggleVisible(isActive && role.IsImpostor && GameOptionsManager.Instance.CurrentGameOptions.GameMode == AmongUs.GameOptions.GameModes.HideNSeek);
if (localPlayer.Data == null)
{
return;
}
if (_roleTab)
{
_roleTab?.gameObject.SetActive(isActive);
}
foreach (var button in CustomButtonManager.CustomButtons)
{
button.SetActive(isActive, role);
}
if (role is ICustomRole customRole)
{
__instance.ImpostorVentButton.gameObject.SetActive(isActive && customRole.CanUseVent);
}
}
}
+59 -22
View File
@@ -1,4 +1,6 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using UnityEngine;
@@ -19,33 +21,68 @@ public static class IntroCutscenePatches
__instance.TeamTitle.text = $"<size=70%>{mode.Name}</size>\n<size=20%>{mode.Description}</size>";
}
}*/
[HarmonyPostfix]
[HarmonyPatch(nameof(IntroCutscene.CoBegin))]
public static void IntroBeginPatch(IntroCutscene __instance)
{
var @event = new IntroBeginEvent(__instance);
MiraEventManager.InvokeEvent(@event);
}
[HarmonyPrefix]
[HarmonyPatch(nameof(IntroCutscene.BeginImpostor))]
public static void BeginImpostorPatch(IntroCutscene __instance)
{
if (PlayerControl.LocalPlayer.Data.Role is not ICustomRole customRole)
{
return;
}
if (customRole.IntroConfiguration is { } introConfig)
{
__instance.BackgroundBar.material.SetColor(ShaderID.Color, introConfig.IntroTeamColor);
__instance.TeamTitle.color = introConfig.IntroTeamColor;
__instance.TeamTitle.text = introConfig.IntroTeamTitle;
__instance.ImpostorText.text = introConfig.IntroTeamDescription;
}
}
[HarmonyPrefix]
[HarmonyPatch(nameof(IntroCutscene.BeginCrewmate))]
public static bool BeginCrewmatePatch(IntroCutscene __instance)
{
if (PlayerControl.LocalPlayer.Data.Role is ICustomRole customRole)
if (PlayerControl.LocalPlayer.Data.Role is not ICustomRole customRole)
{
if (customRole.Team is not ModdedRoleTeams.Neutral)
{
return true;
}
var barTransform = __instance.BackgroundBar.transform;
var position = barTransform.position;
position.y -= 0.25f;
barTransform.position = position;
__instance.BackgroundBar.material.SetColor(ShaderID.Color, Color.gray);
__instance.TeamTitle.text = "OUTCAST";
__instance.impostorScale = 1f;
__instance.ImpostorText.text = "You are an Outcast. You do not have a team.";
__instance.TeamTitle.color = Color.gray;
__instance.ourCrewmate = __instance.CreatePlayer(0, Mathf.CeilToInt(7.5f), PlayerControl.LocalPlayer.Data, false);
return false;
return true;
}
return true;
if (customRole.IntroConfiguration is { } introConfig)
{
__instance.BackgroundBar.material.SetColor(ShaderID.Color, introConfig.IntroTeamColor);
__instance.TeamTitle.color = introConfig.IntroTeamColor;
__instance.TeamTitle.text = introConfig.IntroTeamTitle;
__instance.ImpostorText.text = introConfig.IntroTeamDescription;
}
if (customRole.Team is not ModdedRoleTeams.Custom)
{
return true;
}
var barTransform = __instance.BackgroundBar.transform;
var position = barTransform.position;
position.y -= 0.25f;
barTransform.position = position;
__instance.impostorScale = 1f;
__instance.ourCrewmate = __instance.CreatePlayer(
0,
Mathf.CeilToInt(7.5f),
PlayerControl.LocalPlayer.Data,
false);
return false;
}
/*
@@ -55,4 +92,4 @@ public static class IntroCutscenePatches
{
CustomGameModeManager.ActiveMode?.Initialize();
}*/
}
}
@@ -0,0 +1,40 @@
using System.Linq;
using HarmonyLib;
using MiraAPI.Modifiers.Types;
using MiraAPI.Utilities;
namespace MiraAPI.Patches.Modifiers;
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CoEndGame))]
public static class EndGameDidWinPatch
{
public static void Prefix()
{
var gameOverReason = EndGameResult.CachedGameOverReason;
EndGameResult.CachedWinners.Clear();
var players = GameData.Instance.AllPlayers.ToArray();
for (var i = 0; i < GameData.Instance.PlayerCount; i++)
{
var networkedPlayerInfo = players[i];
if (networkedPlayerInfo == null)
{
continue;
}
var didWin = networkedPlayerInfo.Role.DidWin(gameOverReason);
var modifierWin = networkedPlayerInfo.Object?.GetModifierComponent()?.ActiveModifiers.OfType<GameModifier>()
.FirstOrDefault(x => x.DidWin(gameOverReason) != null)?.DidWin(gameOverReason);
if (modifierWin != null)
{
didWin = modifierWin.Value;
}
if (didWin)
{
EndGameResult.CachedWinners.Add(new CachedPlayerData(networkedPlayerInfo));
}
}
}
}
-46
View File
@@ -1,46 +0,0 @@
using HarmonyLib;
using MiraAPI.Utilities;
using System.Linq;
using UnityEngine;
namespace MiraAPI.Patches.Modifiers;
[HarmonyPatch(typeof(Vent))]
public static class VentPatches
{
[HarmonyPostfix]
[HarmonyPatch(nameof(Vent.CanUse))]
public static void CanUseVentPatch(Vent __instance, ref float __result, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] ref bool canUse, [HarmonyArgument(2)] ref bool couldUse)
{
var @object = pc.Object;
var role = @object.Data.Role;
var modifiers = @object.GetModifierComponent()?.ActiveModifiers;
if (modifiers is null || modifiers.Count <= 0)
{
return;
}
switch (role.CanVent)
{
case true when modifiers.Any(x => !x.CanVent()):
couldUse = canUse = false;
return;
case false when modifiers.Any(x => x.CanVent()):
couldUse = true;
break;
}
var num = float.MaxValue;
canUse = couldUse;
if (canUse)
{
var center = @object.Collider.bounds.center;
var position = __instance.transform.position;
num = Vector2.Distance(center, position);
canUse &= num <= __instance.UsableDistance && !PhysicsHelpers.AnythingBetween(@object.Collider, center, position, Constants.ShipOnlyMask, false);
}
__result = num;
}
}
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more