Compare commits

..
132 Commits
Author SHA1 Message Date
XtraCube c7f3f9d5da Merge remote-tracking branch 'origin/game-modes' into game-modes 2026-08-16 11:16:52 -04:00
XtraCube 5d54a0c2d3 cleanup this file 2026-08-16 11:16:37 -04:00
ang-xd cf1a75f5ea Fix gamemode options visibility 2026-08-16 11:16:37 -04:00
XtraCube 721bd20d2b improve lobby view pane gamemode handling 2026-08-16 11:08:08 -04:00
XtraCube 0e3b6be5be show different plugin gamemodes in lobby view pane 2026-08-16 10:46:19 -04:00
Atony 06c746c632 Add most music logic 2026-08-14 23:24:07 -05:00
Atony 95819cf83a Add (unsynced) in-game timebar + adjust ui pos 2026-08-14 22:29:40 -05:00
Atony d1d11e2bec Show gamemode change notification 2026-08-14 20:22:45 -05:00
Atony b4ed14f7f2 Remove Hide n Seek port on release builds for now 2026-08-14 19:52:51 -05:00
ang-xd 951af42358 Move icons to gamemode and add icons for vanilla modes 2026-08-14 16:39:16 -04:00
AS 27e14488af Merge branch 'dev' into game-modes 2026-08-14 07:11:38 -04:00
ang-xd 9ab87955bb i forgor to mask mod icon 2026-08-14 03:19:06 -04:00
ang-xd 0141dfdea4 Update gamemodes info panel to show mod icon 2026-08-14 03:12:04 -04:00
Atony cd97fab3a2 Show gamemode description in options 2026-08-13 23:59:51 -05:00
Atony 3cd8db1f04 Show gamemode settings properly again 2026-08-13 23:00:09 -05:00
AS 535967475d Merge pull request #100 from All-Of-Us-Mods/shader-improvement
Pass shader caching through helper method
2026-08-13 23:43:50 -04:00
Az 6fd5993959 pass shader caching through helper method 2026-08-13 23:27:07 -04:00
Atony b713599c13 Fix option toggling for vanilla options 2026-08-13 20:51:29 -05:00
ang-xd f44ec15804 Patch console use 2026-08-13 16:19:23 -04:00
ang-xd 847a4dd287 Move initialize to begin 2026-08-13 14:37:52 -04:00
Atony 83d55d409b Change indirect and defense flags to get sets 2026-08-13 10:07:40 -05:00
Atony 7a00ea9174 Merge branch 'dev' into game-modes 2026-08-13 09:24:10 -05:00
Atony 22716b29ab Add Framed and Advanced Murder RPCs 2026-08-13 09:20:26 -05:00
ang-xd 43291bda50 Merge branch 'game-modes' of https://github.com/All-Of-Us-Mods/MiraAPI into game-modes 2026-08-13 00:43:23 -04:00
ang-xd d4a675f2a9 Hide roles tab if no roles in mod 2026-08-13 00:43:15 -04:00
Atony 00c5c5c4ff Merge branch 'dev' into game-modes 2026-08-12 23:23:14 -05:00
Atony abb6f3d161 Add better murder event data 2026-08-12 23:22:55 -05:00
Atony eef098317e Add hide and seek end logic and cooldown checks 2026-08-12 23:20:19 -05:00
Atony 1c097b47df Add end game patches for all gamemodes 2026-08-12 23:18:17 -05:00
Atony 6fe2750545 Make kill timer use whatever the gamemode sets 2026-08-12 23:18:00 -05:00
Atony a57f40fa79 Apply role menu toggle 2026-08-12 23:17:29 -05:00
Atony 54bfd3002b Add role settings toggle and imp cooldown for mode 2026-08-12 22:53:30 -05:00
Atony 4c38189444 Fix initialize patch for gamemodes 2026-08-12 22:25:56 -05:00
Atony 14ce020208 Hide modifier spawning on non-dev builds 2026-08-12 21:14:50 -05:00
Atony 877fc15aec Merge branch 'dev' into game-modes 2026-08-09 22:26:50 -05:00
Atony 2160d1d823 Allow HandleVoteEvent's PreventVote to be set 2026-08-09 22:26:31 -05:00
amber 4d187f3f79 more null checks, yay! 2026-08-09 09:49:25 -04:00
amber 4e37f8b3d4 fix scrollbar 2026-08-09 09:31:59 -04:00
amber 015d175aa0 check if header is not null 2026-08-09 09:11:05 -04:00
Amber ca7da0c343 update gamelibs 2026-08-09 08:43:56 -04:00
Atony 72fa908cb0 Move patches to account for gamemodes 2026-08-08 20:34:10 -05:00
Atony 58067d9f21 Merge branch 'dev' into game-modes 2026-08-08 20:26:39 -05:00
Atony b8b85e2bc3 Merge pull request #99 from yanpla/fix/role-assignment
Fix role assignment
2026-08-08 20:13:02 -05:00
Atony 043845ee11 Fix crashing on Epic and MS Store 2026-08-08 19:57:47 -05:00
yanpla df7c182abb use .select() in loop 2026-08-09 01:52:33 +02:00
yanpla 2a4d16e65e simplify and fix role assignment patch 2026-08-09 01:50:29 +02:00
Nix-main 9606871cbe sync gamemode on join 2026-08-07 23:22:49 -04:00
Atony ae45c506cb Temporary fix for scroller being too small 2026-08-07 18:32:55 -05:00
Atony fd01273635 Merge branch 'dev' into game-modes 2026-08-07 15:08:23 -05:00
amber 121baeb178 Remove IsHideAndSeek 2026-08-06 17:37:55 -04:00
Atony 0cf4954eaf Add in Hide and Seek role logic 2026-08-05 22:36:34 -05:00
Atony 8f403f5408 Add modifier classic check 2026-08-05 22:05:27 -05:00
Atony 2f5c382ece Remove hns IsNormal patch 2026-08-05 22:00:20 -05:00
Nix-main 1ab0c3f4a7 Fix IsInstance for associated mode 2026-08-05 22:55:01 -04:00
Nix-main 0230d98642 make IsClassic and IsHideNSeek use assignable 2026-08-05 22:53:17 -04:00
Nix-main 04b7a9905d make gamemode use assignable from / instance 2026-08-05 22:00:09 -04:00
Nix-main 317e0b6ea9 Fix gamemodes not being properly added to the option 2026-08-05 21:26:09 -04:00
Nix-main cbe44a40d0 Fix button issue and emove options reload logic for now 2026-08-06 01:10:21 -04:00
Nix-main d5c3905684 fix reloading not occuring until next opening of the menu 2026-08-06 00:34:30 -04:00
Nix-main 49d16b707c use ValueChanged patch for logic 2026-08-06 00:31:04 -04:00
Nix-main 3eb5bfae01 Merge remote-tracking branch 'origin/game-modes' into game-modes
# Conflicts:
#	MiraAPI/Patches/Options/RoleSettingMenuPatches.cs
2026-08-06 00:23:51 -04:00
Nix-main b1293081fc Merge remote-tracking branch 'origin/dev' into game-modes
# Conflicts:
#	MiraAPI/Patches/Options/GameSettingMenuPatches.cs
#	MiraAPI/Patches/Options/RoleSettingMenuPatches.cs
2026-08-05 22:04:06 -04:00
Atony 83751a25a9 add back some fixes 2026-08-05 18:58:25 -05:00
Atony bd58fca7bd Merge branch 'dev' into game-modes 2026-08-05 18:50:22 -05:00
amber 119d4c5152 use methodrpc 2026-07-30 01:58:04 -04:00
Nix-main c99f468abf sync gamemode option 2026-07-30 00:39:02 -04:00
Nix-main adde6db1d0 Merge remote-tracking branch 'origin/dev' into game-modes
# Conflicts:
#	MiraAPI/GameModes/AbstractGameMode.cs
#	MiraAPI/GameModes/CustomGameModeManager.cs
#	MiraAPI/GameOptions/AbstractOptionGroup.cs
#	MiraAPI/GameOptions/ModdedOptionsManager.cs
#	MiraAPI/Modifiers/Types/TimedModifier.cs
#	MiraAPI/Patches/Menu/NameplatesTabPatches.cs
#	MiraAPI/Patches/Menu/SkinsTabPatches.cs
#	MiraAPI/Patches/Menu/VisorsTabPatches.cs
#	MiraAPI/Patches/Options/GameOptionsMenuPatch.cs
#	MiraAPI/Patches/Options/GameSettingMenuPatches.cs
#	MiraAPI/Patches/Options/LobbyViewPanePatches.cs
#	MiraAPI/Patches/Options/RoleSettingMenuPatches.cs
#	MiraAPI/PluginLoading/IMiraPlugin.cs
#	MiraAPI/PluginLoading/MiraPluginInfo.cs
#	MiraAPI/PluginLoading/MiraPluginManager.cs
#	MiraAPI/Utilities/Extensions.cs
2026-07-29 19:50:41 -04:00
Nix-main 0012fe8cd6 Make ActiveMode setter private 2026-07-29 18:14:27 -04:00
Nix-main 9148a1e8da Sync gamemode option surely 2026-07-29 18:13:14 -04:00
amber 25a55b1b60 ColoredName property rather than a method 2026-05-31 11:33:14 -04:00
amber af2cc9a3c1 Renames DefaultMode to ClassicMode among other util changes. 2026-05-31 11:27:46 -04:00
Atony e9730f018d Check valid gamemode roles to spawn 2026-05-31 10:08:41 -05:00
Atony 1d316bb02f Merge branch 'dev' into game-modes 2026-05-31 09:17:43 -05:00
Atony 2eac3d04f1 Add more configuration for hns tasks 2026-05-31 09:16:48 -05:00
Atony 154b50fd76 Mods can now choose to appear in the settings menu 2026-05-31 08:54:27 -05:00
Atony 390e4c1157 Fix toggle title 2026-05-13 12:26:24 -05:00
Atony 35b444854a Fix showing/hiding groups 2026-05-13 12:23:51 -05:00
Atony 8e5028c236 Fix scroller issues 2026-05-13 12:07:15 -05:00
Atony ad113a47ab Hide and add gamemode options 2026-05-13 10:15:03 -05:00
Atony 59b8e92c48 WIP option toggling 2026-05-13 08:32:26 -05:00
Atony d313089521 Register MiraAPI within itself 2026-05-13 08:32:11 -05:00
Atony 0852f769ae Fix game mode option appearing in mod tabs 2026-05-12 22:18:48 -05:00
Atony ae4b4d872b Add crewmate kill tracker 2026-05-12 22:09:38 -05:00
Atony b33a66cbd9 Fix OnPlayerDeath for HnS 2026-05-12 21:48:14 -05:00
Atony ac87003d0a Fix color not applying on game mode name 2026-05-12 21:46:01 -05:00
Atony f7de7f127d Merge branch 'dev' into game-modes 2026-05-12 21:24:52 -05:00
Atony e095e2da6a Merge branch 'dev' into game-modes 2026-05-03 22:32:51 -05:00
Atony 50cb8ffc3d Add body type patch for Hide n Seek 2026-05-01 20:52:54 -05:00
Atony 4f4b880ad4 Reimplement Hide n Seek intro (no music) 2026-05-01 20:34:45 -05:00
amber b627006ba1 Move gamemode option to the top, fix registration. 2026-05-01 12:44:54 -04:00
Atony b0ceb129a4 Re-add Hns options as modded options
The options don't appear yet though, this needs to be fixed!
2026-04-30 12:37:54 -05:00
Atony bf7c800613 Add basic Hide n Seek gamemode 2026-04-30 11:58:02 -05:00
Atony 990bac4c06 Merge branch 'dev' into game-modes 2026-04-30 10:09:46 -05:00
amber 08c6883a0d Remove more StringNames duplication 2026-04-26 23:19:01 -04:00
Nix-main 3066720e6e Rename Default -> Classic 2026-04-26 23:09:00 -04:00
Nix-main af363000c7 Fix bugs and add HuD 2026-04-26 23:06:38 -04:00
Amber 77c13bebdc fix goofy 'works on my machine' 2026-03-22 03:30:33 -04:00
amber 00eaa2601c Make Gamemode text bigger 2026-03-11 21:55:40 -04:00
amber ba2deb66f1 Remove from HNS, fix spacing. 2026-03-10 20:24:39 -04:00
amber bb5c212e97 Summary tag for the only public part of the option 2026-03-10 19:57:11 -04:00
amber f59e0af7e8 make patch methods private 2026-03-10 19:54:10 -04:00
amber 8f3a137877 Merge remote-tracking branch 'origin/game-modes' into game-modes 2026-03-10 19:49:56 -04:00
amber 44415019cc Full gamemode option in vanilla Game Options menu. 2026-03-10 19:49:44 -04:00
Atony 7125374cda Merge branch 'runtime-options' into game-modes 2026-03-10 18:47:48 -05:00
Atony cff46ebd19 Merge branch 'dev' into runtime-options 2026-03-10 18:47:28 -05:00
amber 8b19271e34 Merge branch 'runtime-options' into game-modes 2026-03-08 17:57:00 -04:00
amber c29e882d7e Fix error from float data in ModdedStringOption.cs 2026-03-08 13:24:24 -04:00
Atony fdfb876b44 Fix plugin loading 2026-03-07 22:36:39 -06:00
Atony 205eee96b2 Merge branch 'dev' into game-modes 2026-03-07 22:21:08 -06:00
amber 8774c9da70 Fix tony's -1 index 2026-03-07 21:48:28 -05:00
Atony 51c7e248f9 Update Directory.Build.props 2026-03-07 15:24:28 -06:00
Atony 02f9c20804 Add wip string option 2026-03-07 15:23:26 -06:00
XtraCube 7890ec9456 WIP update gamemodes 2025-03-04 19:21:57 -05:00
XtraCube 8bb191270f Merge branch 'dev' into game-modes
# Conflicts:
#	MiraAPI.Example/Modifiers/CaptainModifier.cs
#	MiraAPI/GameModes/CustomGameModeManager.cs
#	MiraAPI/GameOptions/AbstractOptionGroup.cs
#	MiraAPI/GameOptions/Attributes/ModdedEnumOptionAttribute.cs
#	MiraAPI/GameOptions/Attributes/ModdedNumberOptionAttribute.cs
#	MiraAPI/GameOptions/Attributes/ModdedToggleOptionAttribute.cs
#	MiraAPI/GameOptions/IModdedOption.cs
#	MiraAPI/GameOptions/ModdedOptionsManager.cs
#	MiraAPI/GameOptions/OptionTypes/ModdedEnumOption.cs
#	MiraAPI/GameOptions/OptionTypes/ModdedNumberOption.cs
#	MiraAPI/GameOptions/OptionTypes/ModdedOption.cs
#	MiraAPI/GameOptions/OptionTypes/ModdedToggleOption.cs
#	MiraAPI/Hud/CustomActionButton.cs
#	MiraAPI/MiraApiPlugin.cs
#	MiraAPI/Modifiers/BaseModifier.cs
#	MiraAPI/Patches/Options/GameOptionsMenuPatch.cs
#	MiraAPI/Patches/Options/LobbyViewPanePatches.cs
#	MiraAPI/Patches/Options/RoleSettingMenuPatches.cs
#	MiraAPI/PluginLoading/MiraPluginManager.cs
#	MiraAPI/Roles/ICustomRole.cs
2025-03-04 19:02:38 -05:00
XtraCube 65cd177551 fix more scrolling issues 2025-02-18 11:15:00 -05:00
XtraCube 7801f81052 Merge branch 'dev' into game-modes
# Conflicts:
#	MiraAPI/Patches/Options/RoleSettingMenuPatches.cs
2025-02-18 11:07:04 -05:00
XtraCube 2d59b29c15 cleanup 2025-02-18 10:19:55 -05:00
XtraCube a62c75a13b that was stupid 2025-02-18 10:19:22 -05:00
XtraCube c85cf7ef2f finish merge 2025-02-18 10:15:39 -05:00
XtraCube ead28339b0 Merge branch 'dev' into game-modes
# Conflicts:
#	MiraAPI/Patches/Options/RoleSettingMenuPatches.cs
#	MiraAPI/Roles/CustomRoleConfiguration.cs
#	MiraAPI/Roles/ICustomRole.cs
2025-02-18 10:11:53 -05:00
XtraCube 9177d5b456 fix merge stuff 2025-02-17 10:14:38 -05:00
XtraCube 284a0f58b1 oops 2025-02-17 10:14:26 -05:00
XtraCube 47dfa63423 improve CustomRoleConfiguration.cs 2025-02-17 10:13:32 -05:00
XtraCube 1b261d7287 Merge remote-tracking branch 'origin/dev' into game-modes
# Conflicts:
#	MiraAPI/Hud/CustomActionButton.cs
#	MiraAPI/Patches/Options/RoleSettingMenuPatches.cs
#	MiraAPI/PluginLoading/MiraPluginManager.cs
#	MiraAPI/Roles/ICustomRole.cs
2025-02-17 09:59:42 -05:00
XtraCube fa8ea9dbab final fix to logic 2025-02-03 22:44:35 -05:00
XtraCube 9c15ca4d06 update to optimization 2025-02-03 22:43:25 -05:00
XtraCube a4b1868690 Merge branch 'optimization' into game-modes
# Conflicts:
#	MiraAPI/GameModes/DefaultMode.cs
#	MiraAPI/GameModes/RegisterGameModeAttribute.cs
#	MiraAPI/PluginLoading/MiraPluginManager.cs
2025-02-03 22:03:48 -05:00
AlchlcDvl 409503a261 read me change to reflect now mode filtering 2024-12-23 20:57:53 -05:00
AlchlcDvl edca42247d finish full implementation of game modes i hope 2024-12-23 20:52:18 -05:00
AlchlcDvl b6ba8f59bd better approach 2024-12-07 11:21:07 -05:00
AlchlcDvl f9f7898277 set option title 2024-12-07 11:18:58 -05:00
AlchlcDvl dbacd044eb game mode stuff, missing implementation of 4 methods coming soon™️ 2024-12-07 10:46:26 -05:00
74 changed files with 4175 additions and 540 deletions

No files matched your search

+2 -2
View File
@@ -2,7 +2,7 @@
<ItemGroup>
<PackageReference Include="Reactor" Version="2.5.0-ci.371" />
<PackageReference Include="BepInEx.Unity.IL2CPP" Version="6.0.0-be.735" Private="false" ExcludeAssets="runtime;native" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2026.3.31" PrivateAssets="all" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2026.6.5" PrivateAssets="all" />
<PackageReference Include="BepInEx.AutoPlugin" Version="1.1.0" PrivateAssets="all" />
<PackageReference Include="BepInEx.IL2CPP.MSBuild" Version="2.1.0-rc.1" PrivateAssets="all" ExcludeAssets="runtime" />
@@ -11,4 +11,4 @@
<Target Name="Copy" AfterTargets="Build" Condition="'$(AmongUs)' != ''">
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(AmongUs)/BepInEx/plugins/" UseSymboliclinksIfPossible="true" />
</Target>
</Project>
</Project>
+3
View File
@@ -3,9 +3,11 @@ using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities.Assets;
using Reactor;
using Reactor.Networking;
using Reactor.Networking.Attributes;
using UnityEngine;
namespace MiraAPI.Example;
@@ -18,6 +20,7 @@ public partial class ExamplePlugin : BasePlugin, IMiraPlugin
{
public Harmony Harmony { get; } = new(Id);
public string OptionsTitleText => "Mira API\nExample Mod";
public string CustomOptionMenuNameTwo => "angxl's Options";
public ConfigFile GetConfigFile() => Config;
public override void Load()
{
+13
View File
@@ -0,0 +1,13 @@
using MiraAPI.GameModes;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.GameModes;
public class ExampleMode : AbstractGameMode
{
public override string Name => "Example Mode";
public override string Description => "An example gamemode.";
public override LoadableAsset<Sprite>? Icon => ExampleAssets.ExampleButton;
public override Color Color => Color.red;
}
+4 -1
View File
@@ -1,8 +1,11 @@
namespace MiraAPI.Events;
using MiraAPI.PluginLoading;
namespace MiraAPI.Events;
/// <summary>
/// Abstract class for Mira Events that can be cancelled.
/// </summary>
[MiraIgnore]
public abstract class MiraCancelableEvent : MiraEvent
{
/// <summary>
+4 -1
View File
@@ -1,6 +1,9 @@
namespace MiraAPI.Events;
using MiraAPI.PluginLoading;
namespace MiraAPI.Events;
/// <summary>
/// Abstract class for Mira Events.
/// </summary>
[MiraIgnore]
public abstract class MiraEvent;
@@ -16,20 +16,76 @@ public class AfterMurderEvent : MiraEvent
public PlayerControl Target { get; }
/// <summary>
/// Gets the <see cref="Target"/>'s <see cref="global::DeadBody"/>, if it exists.
/// Gets the <see cref="PlayerControl"/> that was framed, if any.
/// </summary>
public PlayerControl? Framed { get; }
/// <summary>
/// Gets a value indicating whether the murder was done indirectly.
/// This is commonly used to prevent the <see cref="Source"/> <see cref="PlayerControl"/> from being killed.
/// </summary>
public bool IsIndirectAttack { get; }
/// <summary>
/// Gets a value indicating whether the murder was able to bypass protective roles or general defense, such as <see cref="GuardianAngelRole"/>.
/// </summary>
public bool IgnoreDefense { get; }
/// <summary>
/// Gets the <see cref="Target"/>'s <see cref="DeadBody"/>, if it exists.
/// </summary>
public DeadBody? DeadBody { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
/// </summary>
/// <param name="source">The killer.</param>
/// <param name="target">The killed <see cref="PlayerControl"/>.</param>
/// <param name="deadBody">The <paramref name="target"/>'s <see cref="global::DeadBody"/>, if it exists.</param>
/// <param name="source">The <see cref="PlayerControl"/> that killed the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that was killed.</param>
/// <param name="deadBody">The <paramref name="target"/>'s <see cref="DeadBody"/>, if it exists.</param>
/// <param name="isIndirect">Whether the murder was caused indirectly.</param>
/// <param name="ignoreDefense">Whether the murder ignored protection.</param>
public AfterMurderEvent(PlayerControl source, PlayerControl target, DeadBody? deadBody, bool isIndirect, bool ignoreDefense = false)
{
Source = source;
Target = target;
Framed = null;
DeadBody = deadBody;
IsIndirectAttack = isIndirect;
IgnoreDefense = ignoreDefense;
}
/// <summary>
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
/// </summary>
/// <param name="source">The <see cref="PlayerControl"/> that killed the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that was killed.</param>
/// <param name="framed">The <see cref="PlayerControl"/> that was framed.</param>
/// <param name="deadBody">The <paramref name="target"/>'s <see cref="DeadBody"/>, if it exists.</param>
/// <param name="isIndirect">Whether the murder was caused indirectly.</param>
/// <param name="ignoreDefense">Whether the murder ignored protection.</param>
public AfterMurderEvent(PlayerControl source, PlayerControl target, PlayerControl framed, DeadBody? deadBody, bool isIndirect = true, bool ignoreDefense = false)
{
Source = source;
Target = target;
Framed = framed;
DeadBody = deadBody;
IsIndirectAttack = isIndirect;
IgnoreDefense = ignoreDefense;
}
/// <summary>
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
/// </summary>
/// <param name="source">The <see cref="PlayerControl"/> that killed the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that was killed.</param>
/// <param name="deadBody">The <paramref name="target"/>'s <see cref="DeadBody"/>, if it exists.</param>
public AfterMurderEvent(PlayerControl source, PlayerControl target, DeadBody? deadBody)
{
Source = source;
Target = target;
Framed = null;
DeadBody = deadBody;
IsIndirectAttack = false;
IgnoreDefense = false;
}
}
@@ -17,11 +17,64 @@ public sealed class BeforeMurderEvent : MiraCancelableEvent
/// </summary>
public PlayerControl Target { get; }
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being framed, if any.
/// </summary>
public PlayerControl? Framed { get; }
/// <summary>
/// Gets or sets a value indicating whether the murder is done indirectly.
/// This is commonly used to prevent the <see cref="Source"/> <see cref="PlayerControl"/> from being killed.
/// </summary>
public bool IsIndirectAttack { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the murder should bypass protective roles or general defense, such as <see cref="GuardianAngelRole"/>.
/// </summary>
public bool IgnoreDefense { get; set; }
/// <summary>
/// Gets whether the murder was meant to be done in a meeting, via an enum.
/// </summary>
public MeetingCheck InMeeting { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
/// <param name="source">The <see cref="PlayerControl"/> that is killing the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that is being killed.</param>
/// <param name="isIndirect">Whether the murder is caused indirectly.</param>
/// <param name="ignoreDefense">Whether the murder should ignore protection.</param>
/// <param name="inMeeting">Whether the murder is intended to be triggered in a meeting.</param>
public BeforeMurderEvent(PlayerControl source, PlayerControl target, bool isIndirect, bool ignoreDefense = false, MeetingCheck inMeeting = MeetingCheck.Ignore)
{
Source = source;
Target = target;
Framed = null;
IsIndirectAttack = isIndirect;
IgnoreDefense = ignoreDefense;
InMeeting = inMeeting;
}
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
/// <param name="source">The <see cref="PlayerControl"/> that is killing the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that is being killed.</param>
/// <param name="framed">The <see cref="PlayerControl"/> that is being framed.</param>
/// <param name="isIndirect">Whether the murder is caused indirectly.</param>
/// <param name="ignoreDefense">Whether the murder should ignore protection.</param>
/// <param name="inMeeting">Whether the murder is intended to be triggered in a meeting.</param>
public BeforeMurderEvent(PlayerControl source, PlayerControl target, PlayerControl framed, bool isIndirect = true, bool ignoreDefense = false, MeetingCheck inMeeting = MeetingCheck.Ignore)
{
Source = source;
Target = target;
Framed = framed;
IsIndirectAttack = isIndirect;
IgnoreDefense = ignoreDefense;
InMeeting = inMeeting;
}
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
@@ -32,6 +85,9 @@ public sealed class BeforeMurderEvent : MiraCancelableEvent
{
Source = source;
Target = target;
Framed = null;
IsIndirectAttack = false;
IgnoreDefense = false;
InMeeting = inMeeting;
}
@@ -44,6 +100,9 @@ public sealed class BeforeMurderEvent : MiraCancelableEvent
{
Source = source;
Target = target;
Framed = null;
IsIndirectAttack = false;
IgnoreDefense = false;
InMeeting = MeetingCheck.Ignore;
}
}
@@ -25,9 +25,9 @@ public class HandleVoteEvent : MiraCancelableEvent
public byte TargetId { get; }
/// <summary>
/// Gets a value indicating whether to prevent the vote from commencing.
/// Gets or sets a value indicating whether to prevent the vote from commencing.
/// </summary>
public bool PreventVote { get; }
public bool PreventVote { get; set; }
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
+291
View File
@@ -0,0 +1,291 @@
using System.Collections;
using System.Collections.Generic;
using AmongUs.GameOptions;
using MiraAPI.GameOptions;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
namespace MiraAPI.GameModes;
/// <summary>
/// Base class for custom gamemodes.
/// </summary>
[MiraIgnore]
public abstract class AbstractGameMode : IOptionable
{
/// <summary>
/// Gets the game mode name.
/// </summary>
public abstract string Name { get; }
/// <summary>
/// Gets the game mode description.
/// </summary>
public abstract string Description { get; }
/// <summary>
/// Gets the game mode description.
/// </summary>
public virtual Color Color { get; } = Color.white;
/// <summary>
/// Gets the icon of the gamemode. Will be shown in options menu underneath the gamemode option.
/// </summary>
public virtual LoadableAsset<Sprite>? Icon => null;
/// <summary>
/// Gets the icon of the gamemode for use on the options pop-up.
/// </summary>
public TMP_SpriteAsset TmpIcon { get; set; } = null!;
/// <summary>
/// Gets the colored game mode name, using the color and name properties.
/// </summary>
public string ColoredName => $"<color=#{this.Color.ToHtmlStringRGBA()}>{this.Name}</color>";
/// <summary>
/// Gets the game mode id.
/// </summary>
public uint ID { get; internal set; }
/// <summary>
/// Gets a value indicating whether a specific body type is used by the game mode.
/// </summary>
public virtual bool GameModeBodyTypeOverride => false;
/// <summary>
/// Gets a value indicating whether the gamemode removes the normal game settings.
/// </summary>
public virtual bool ShowNormalGameSettings => true;
/// <summary>
/// Gets a value indicating whether the gamemode removes the normal role settings.
/// </summary>
public virtual bool ShowNormalRoleSettings => true;
/// <summary>
/// Gets a value indicating the default kill cooldown for impostors in this mode.
/// </summary>
public virtual float DefaultImpostorKillCooldown => GameOptionsManager.Instance.CurrentGameOptions.GetFloat(FloatOptionNames.KillCooldown);
/// <summary>
/// Called on GameManager.GetBodyType().
/// </summary>
/// <param name="player">Player to get body type from.</param>
/// <returns>Resulting body type.</returns>
public virtual PlayerBodyTypes GetBodyType(PlayerControl player)
{
if (AprilFoolsMode.ShouldHorseAround())
{
return PlayerBodyTypes.Horse;
}
if (AprilFoolsMode.ShouldLongAround())
{
return PlayerBodyTypes.Long;
}
return PlayerBodyTypes.Normal;
}
/// <summary>
/// Gets a value indicating whether a custom intro sequence is implemented by the game mode.
/// </summary>
public virtual bool ShowGameModeIntroCutscene => false;
/// <summary>
/// Called when Intro Cutscene is destroyed.
/// </summary>
public virtual void Initialize()
{
}
/// <summary>
/// Called on HudManager.Start().
/// </summary>
/// <param name="instance">Instance of HudManager.</param>
public virtual void HudStart(HudManager instance)
{
}
/// <summary>
/// Called every frame on HudManager.Update().
/// </summary>
/// <param name="instance">Instance of HudManager.</param>
public virtual void HudUpdate(HudManager instance)
{
}
/// <summary>
/// Called when a player is killed.
/// </summary>
/// <param name="player">PlayerControl that was killed.</param>
/// <param name="assignGhostRole">Determines whether to assign a ghost role on the player.</param>
public virtual void OnPlayerDeath(PlayerControl player, bool assignGhostRole)
{
GameManager.Instance.LogicRoleSelection.OnPlayerDeath(player, assignGhostRole);
}
/// <summary>
/// Calculate Game End logic.
/// </summary>
/// <param name="runOriginal">Should original game end logic be used.</param>
/// <param name="instance">Instance of LogicGameFlowNormal.</param>
public virtual void CheckGameEnd(out bool runOriginal, LogicGameFlowNormal instance)
{
runOriginal = true;
}
/// <summary>
/// Custom role assignment.
/// </summary>
/// <param name="runOriginal">Should original role assignment be used.</param>
/// <param name="instance">Instance of LogicRoleSelection.</param>
public virtual void AssignRoles(out bool runOriginal, LogicRoleSelectionNormal instance)
{
runOriginal = true;
}
/// <summary>
/// Custom role assignment to run after all roles are handed out.
/// </summary>
/// <param name="instance">Instance of LogicRoleSelection.</param>
public virtual void PostAssignRoles(LogicRoleSelectionNormal instance)
{
}
/// <summary>
/// Custom murder logic.
/// </summary>
/// <param name="runOriginal">Should the original murder logic be used.</param>
/// <param name="result">Result of custom murder logic.</param>
/// <param name="target">Target player for murder.</param>
public virtual void CanKill(out bool runOriginal, out bool result, PlayerControl target)
{
result = false;
runOriginal = true;
}
/// <summary>
/// Custom winner selection.
/// </summary>
/// <returns>List of winners or null.</returns>
public virtual List<NetworkedPlayerInfo>? CalculateWinners() => null;
/// <summary>
/// The IEnumerator that plays the intro cutscene for this gamemode.
/// </summary>
/// <param name="__instance">An instance of IntroCutscene.</param>
/// <returns>An IEnumerator to run the intro cutscene instead of the base game one.</returns>
public virtual IEnumerator IntroCutscene(IntroCutscene __instance)
{
yield return new WaitForEndOfFrame();
}
/// <summary>
/// Can Admin be used in this gamemode.
/// </summary>
/// <param name="console">Admin Console.</param>
/// <returns>True if Admin console is enabled.</returns>
public virtual bool CanUseMapConsole(MapConsole console) => true;
/// <summary>
/// Can a body be reported in this gamemode.
/// </summary>
/// <param name="body">Target body for reporting.</param>
/// <returns>True if dead bodies can be reported.</returns>
public virtual bool CanReport(DeadBody body) => true;
/// <summary>
/// Can system consoles be used in this gamemode.
/// </summary>
/// <param name="console">System Console.</param>
/// <returns>True if system consoles are enabled in this mode.</returns>
public virtual bool CanUseSystemConsole(SystemConsole console) => true;
/// <summary>
/// Can tasks be interacted with in this gamemode.
/// </summary>
/// <param name="console">Task console.</param>
/// <returns>True if tasks are enabled in this mode.</returns>
public virtual bool CanUseTasks(Console console) => true;
/// <summary>
/// Should the sabotage map be used when attempting to open sabotage overlay.
/// </summary>
/// <param name="map">MapBehaviour object.</param>
/// <returns>True if the sabotage map should be shown.</returns>
public virtual bool ShouldShowSabotageMap(MapBehaviour map) => true;
/// <summary>
/// Gets the <see cref="MapOptions"/> to display on the map.
/// </summary>
/// <returns>The <see cref="MapOptions"/> for the gamemode.</returns>
public virtual MapOptions GetMapOptions()
{
return new MapOptions
{
Mode = PlayerControl.LocalPlayer.Data.Role.IsImpostor && !MeetingHud.Instance
? MapOptions.Modes.Sabotage
: MapOptions.Modes.Normal,
};
}
/// <summary>
/// Can a player vent in this gamemode.
/// </summary>
/// <param name="vent">Target vent.</param>
/// <param name="playerInfo">Player attempting to vent.</param>
/// <returns>True if venting is enabled in this mode.</returns>
public virtual bool CanVent(Vent vent, NetworkedPlayerInfo playerInfo) => true;
/// <summary>
/// Does the task bar appear in the gamemode.
/// </summary>
/// <returns>True if the task bar is enabled in this mode.</returns>
public virtual bool ShowTaskBar => true;
public virtual void UpdateTaskPanel(TaskPanelBehaviour instance)
{
instance.background.transform.localScale = (instance.taskText.textBounds.size.x > 0f)
? new Vector3(instance.taskText.textBounds.size.x + 0.2f, instance.taskText.textBounds.size.y + 0.2f, 1f)
: Vector3.zero;
Vector3 vector = instance.background.sprite.bounds.extents;
vector.y = -vector.y;
vector = vector.Mul(instance.background.transform.localScale);
instance.background.transform.localPosition = vector;
Vector3 vector2 = instance.tab.sprite.bounds.extents;
vector2 = vector2.Mul(instance.tab.transform.localScale);
vector2.y = -vector2.y;
vector2.x += vector.x * 2f;
instance.tab.transform.localPosition = vector2;
if (GameManager.Instance == null)
{
return;
}
var yPos = 0.6f;
var xPos = -instance.background.sprite.bounds.size.x * instance.background.transform.localScale.x;
instance.closedPosition = new Vector3(xPos, yPos, instance.closedPosition.z);
instance.openPosition = new Vector3(instance.openPosition.x, yPos, instance.openPosition.z);
if (instance.open)
{
instance.timer = Mathf.Min(1f, instance.timer + Time.deltaTime / instance.animationTimeSeconds);
}
else
{
instance.timer = Mathf.Max(0f, instance.timer - Time.deltaTime / instance.animationTimeSeconds);
}
Vector3 relativePos = new(
Mathf.SmoothStep(instance.closedPosition.x, instance.openPosition.x, instance.timer),
yPos,
instance.openPosition.z);
instance.transform.localPosition =
AspectPosition.ComputePosition(AspectPosition.EdgeAlignments.LeftTop, relativePos);
}
/// <inheritdoc/>
public override string ToString() => Name;
}
+20
View File
@@ -0,0 +1,20 @@
using MiraAPI.PluginLoading;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.GameModes;
/// <summary>
/// The classic game mode.
/// </summary>
[MiraIgnore]
public class ClassicMode : AbstractGameMode
{
/// <inheritdoc/>
public override string Name => "Classic";
/// <inheritdoc/>
public override string Description => "The classic Among Us experience!\nFind the Impostors or deceive the Crew.";
public override LoadableAsset<Sprite>? Icon => MiraAssets.ClassicGamemodeIcon;
}
-154
View File
@@ -1,154 +0,0 @@
using System.Collections.Generic;
namespace MiraAPI.GameModes;
/// <summary>
/// Base class for custom gamemodes.
/// </summary>
public abstract class CustomGameMode
{
/// <summary>
/// Gets the game mode name.
/// </summary>
public abstract string Name { get; }
/// <summary>
/// Gets the game mode description.
/// </summary>
public abstract string Description { get; }
/// <summary>
/// Gets the game mode ID.
/// </summary>
public abstract int Id { get; }
/// <summary>
/// Called when <see cref="IntroCutscene"/> is destroyed.
/// </summary>
public virtual void Initialize()
{
}
/// <summary>
/// Called on <see cref="HudManager.Start"/>.
/// </summary>
/// <param name="instance">Instance of <see cref="HudManager"/>.</param>
public virtual void HudStart(HudManager instance)
{
}
/// <summary>
/// Called every frame on <see cref="HudManager.Update"/>.
/// </summary>
/// <param name="instance">Instance of <see cref="HudManager"/>.</param>
public virtual void HudUpdate(HudManager instance)
{
}
/// <summary>
/// Called when a player is killed.
/// </summary>
/// <param name="player"><see cref="PlayerControl"/> that was killed.</param>
public virtual void OnDeath(PlayerControl player)
{
}
/// <summary>
/// Calculate Game End logic.
/// </summary>
/// <param name="runOriginal">Should original game end logic be used.</param>
/// <param name="instance">Instance of <see cref="LogicGameFlowNormal"/>.</param>
public virtual void CheckGameEnd(out bool runOriginal, LogicGameFlowNormal instance)
{
runOriginal = true;
}
/// <summary>
/// Custom role assignment.
/// </summary>
/// <param name="runOriginal">Should original role assignment be used.</param>
/// <param name="instance">Instance of <see cref="LogicRoleSelection"/>.</param>
public virtual void AssignRoles(out bool runOriginal, LogicRoleSelectionNormal instance)
{
runOriginal = true;
}
/// <summary>
/// Custom murder logic.
/// </summary>
/// <param name="runOriginal">Should the original murder logic be used.</param>
/// <param name="result">Result of custom murder logic.</param>
/// <param name="target">Target <see cref="PlayerControl"/> for murder.</param>
public virtual void CanKill(out bool runOriginal, out bool result, PlayerControl target)
{
result = false;
runOriginal = true;
}
/// <summary>
/// Should Roles Settings be available when this gamemode is selected.
/// </summary>
/// <returns><see langword="true"/> if Role Settings are enabled in this game mode.</returns>
public virtual bool AreRoleSettingsEnabled() => true;
/// <summary>
/// Should Game Settings be available when this gamemode is selected.
/// </summary>
/// <returns><see langword="true"/> if Game Settings are enabled in this mode.</returns>
public virtual bool AreGameSettingsEnabled() => true;
/// <summary>
/// Custom winner selection.
/// </summary>
/// <returns>List of winners or <see langword="null"/>.</returns>
public virtual List<NetworkedPlayerInfo>? CalculateWinners() => null;
/// <summary>
/// Show gamemode in <see cref="IntroCutscene"/>.
/// </summary>
/// <returns><see langword="true"/> if the game mode should be shown in the intro cutscene.</returns>
public virtual bool ShowGameModeIntroCutscene() => false;
/// <summary>
/// Can Admin be used in this gamemode.
/// </summary>
/// <param name="console">Admin Console.</param>
/// <returns><see langword="true"/> if Admin console is enabled.</returns>
public virtual bool CanUseMapConsole(MapConsole console) => true;
/// <summary>
/// Can a <see cref="DeadBody"/> be reported in this gamemode.
/// </summary>
/// <param name="body">Target <see cref="DeadBody"/> for reporting.</param>
/// <returns><see langword="true"/> if <see cref="DeadBody"/>s can be reported.</returns>
public virtual bool CanReport(DeadBody body) => true;
/// <summary>
/// Can <see cref="SystemConsole"/>s be used in this gamemode.
/// </summary>
/// <param name="console">System Console.</param>
/// <returns><see langword="true"/> if <see cref="SystemConsole"/>s are enabled in this mode.</returns>
public virtual bool CanUseSystemConsole(SystemConsole console) => true;
/// <summary>
/// Can tasks be interacted with in this gamemode.
/// </summary>
/// <param name="console">Task console.</param>
/// <returns><see langword="true"/> if tasks are enabled in this mode.</returns>
public virtual bool CanUseTasks(Console console) => true;
/// <summary>
/// Should the sabotage map be used when attempting to open sabotage overlay.
/// </summary>
/// <param name="map"><see cref="MapBehaviour"/> object.</param>
/// <returns><see langword="true"/> if the sabotage map should be shown.</returns>
public virtual bool ShouldShowSabotageMap(MapBehaviour map) => true;
/// <summary>
/// Can a player vent in this gamemode.
/// </summary>
/// <param name="vent">Target vent.</param>
/// <param name="playerInfo">Player attempting to vent.</param>
/// <returns><see langword="true"/> if venting is enabled in this mode.</returns>
public virtual bool CanVent(Vent vent, NetworkedPlayerInfo playerInfo) => true;
}
+95 -43
View File
@@ -1,70 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
namespace MiraAPI.GameModes;
/// <summary>
/// Manages <see cref="CustomGameMode"/>s.
/// Manages custom gamemodes.
/// </summary>
public static class CustomGameModeManager
{
/// <summary>
/// List of registered <see cref="CustomGameMode"/>.
/// </summary>
internal static readonly Dictionary<int, CustomGameMode> GameModes = [];
internal static readonly Dictionary<uint, AbstractGameMode> IdToModeMap = [];
public static bool IsDefault()
private static uint GetNextId() => ++LastId;
private static uint LastId { get; set; }
/// <summary>
/// Register gamemode from type.
/// </summary>
/// <param name="gameModeType">Type of gamemode class, should inherit from <see cref="AbstractGameMode"/>.</param>
/// <param name="pluginInfo">The custom plugin info of the mod.</param>
/// <returns>Whether the gamemode was successfully registered.</returns>
internal static bool RegisterGameMode(Type gameModeType, MiraPluginInfo pluginInfo)
{
return ActiveMode?.Id == 0;
}
/// <summary>
/// Gets the current <see cref="CustomGameMode"/>.
/// </summary>
public static CustomGameMode? ActiveMode { get; internal set; } = new DefaultMode();
/// <summary>
/// Set current <see cref="CustomGameMode"/>.
/// </summary>
/// <param name="id"><see cref="CustomGameMode"/> ID.</param>
public static void SetGameMode(int id)
{
if (GameModes.TryGetValue(id, out var gameMode))
{
ActiveMode = gameMode;
return;
}
Error($"No gamemode with id {id} found!");
}
/// <summary>
/// Register <see cref="CustomGameMode"/> from type.
/// </summary>
/// <param name="gameModeType">Type of <see cref="CustomGameMode"/>, should inherit from <see cref="CustomGameMode"/>.</param>
internal static void RegisterGameMode(Type gameModeType)
{
if (!typeof(CustomGameMode).IsAssignableFrom(gameModeType))
if (!typeof(AbstractGameMode).IsAssignableFrom(gameModeType))
{
Warning($"{gameModeType.Name} does not inherit CustomGameMode!");
return;
return false;
}
var modeObj = Activator.CreateInstance(gameModeType);
var instance = Activator.CreateInstance(gameModeType);
if (modeObj is not CustomGameMode gameMode)
if (instance is not AbstractGameMode mode)
{
Error($"Failed to create instance of {gameModeType.Name}");
return;
return false;
}
if (GameModes.Any(x => x.Key == gameMode.Id))
IdToModeMap.Add(GetNextId(), mode);
pluginInfo.GameModes.Add(LastId, mode);
mode.ID = LastId;
GameModeOption.AddOption(mode);
return true;
}
/// <summary>
/// Checks to see if the current game mode is an instance of the classic mode.
/// </summary>
/// <returns>True if the classic mode is the current one.</returns>
public static bool IsClassic() => ActiveMode != null && ActiveMode.GetType().IsAssignableTo(typeof(ClassicMode));
/// <summary>
/// Checks to see if the current game mode is an instance of the HNS mode.
/// </summary>
/// <returns>True if the Hide & Seek mode is the current one.</returns>
public static bool IsHideNSeek() => ActiveMode != null && ActiveMode.GetType().IsAssignableTo(typeof(HideAndSeekMode));
/// <summary>
/// Checks if a provided GameMode is the current active one.
/// </summary>
/// <typeparam name="T">The AbstractGameMode subclass being checked.</typeparam>
/// <returns>Whether the provided mode is the current active one.</returns>
public static bool IsActiveGameMode<T>() where T : AbstractGameMode => ActiveMode is T;
/// <summary>
/// Gets the current gamemode.
/// </summary>
public static AbstractGameMode? ActiveMode { get; private set; }
/// <summary>
/// Gets a gamemode from an ID.
/// </summary>
/// <param name="id">The ID of the gamemode to fetch.</param>
/// <returns>The gamemode matching that ID.</returns>
public static AbstractGameMode GetMode(uint id) => IdToModeMap[id];
/// <summary>
/// Finds the parent mod of a custom gamemode.
/// </summary>
/// <param name="gameMode">The <see cref="AbstractGameMode"/> object.</param>
/// <returns>A <see cref="MiraPluginInfo"/> object representing the parent mod of the gamemode.</returns>
public static MiraPluginInfo? FindParentMod(AbstractGameMode gameMode)
{
return MiraPluginManager.Instance.RegisteredPlugins.FirstOrDefault(plugin => plugin.GameModes.ContainsValue(gameMode));
}
internal static void RegisterDefaultMode()
{
var defaultMode = new ClassicMode();
IdToModeMap.Add(0, defaultMode);
// no need to add to game mode option as it already contains it
// because we cannot have the option be created with no values
defaultMode.ID = 0;
// TODO: Once Hide n Seek port is ready for release, we will remove this case.
if (MiraApiPlugin.IsDevBuild)
{
Error($"ID for gamemode {gameMode.Name} already exists!");
var hnsMode = new HideAndSeekMode();
IdToModeMap.Add(1, hnsMode);
hnsMode.ID = 1;
GameModeOption.AddOption(hnsMode);
LastId++;
}
}
internal static void GetAndSetGameMode()
{
var id = (uint)GameModeOption.Value;
if (IdToModeMap.TryGetValue(id, out var mode))
{
ActiveMode = mode;
return;
}
GameModes.Add(gameMode.Id, gameMode);
ActiveMode = IdToModeMap[0];
Logger<MiraApiPlugin>.Warning($"Unable to find game mode of id {id}!");
}
}
-8
View File
@@ -1,8 +0,0 @@
namespace MiraAPI.GameModes;
public class DefaultMode : CustomGameMode
{
public override string Name => "Default";
public override string Description => "Default Among Us GameMode";
public override int Id => 0;
}
+148
View File
@@ -0,0 +1,148 @@
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.GameOptions;
using MiraAPI.Networking;
using MiraAPI.Patches.GameModes;
using MiraAPI.Patches.Options;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Localization.Utilities;
using Reactor.Networking.Attributes;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.ProBuilder;
using Object = UnityEngine.Object;
namespace MiraAPI.GameModes;
/// <summary>
/// The game mode option.
/// </summary>
[HarmonyPatch]
public static class GameModeOption
{
/// <summary>
/// Gets the current index of the Game Mode Option
/// For the value as an <see cref="AbstractGameMode"/>, see <see cref="CustomGameModeManager.ActiveMode"/>.
/// </summary>
public static int Value
{
get =>
OptionBehaviour != null
? OptionBehaviour.GetInt()
: _lastValue;
private set
{
_lastValue = value;
if (OptionBehaviour == null)
return;
OptionBehaviour.Value = value;
OptionBehaviour.UpdateValue();
_lastValue = value;
}
}
internal static StringOption OptionBehaviour { get; set; } = null!;
internal static int _lastValue;
internal static readonly StringNames GamemodeName = CustomStringName.CreateAndRegister("Gamemode");
internal static readonly StringNames CustomName = CustomStringName.CreateAndRegister("Custom");
internal static readonly Dictionary<uint, StringNames> Values = new()
{
[0] = CustomStringName.CreateAndRegister("Classic"),
};
internal static void AddOption(AbstractGameMode mode)
{
if (!Values.ContainsKey(mode.ID))
Values.Add(mode.ID, CustomStringName.CreateAndRegister(mode.ColoredName));
}
/*[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.CreateSettings))]
[HarmonyPostfix]
private static void CreateSettingsPatch(GameOptionsMenu __instance)
{
if (MenuState.Instance.CurrentModIdx != 0 || GameManager.Instance.IsHideAndSeek() || CustomGameModeManager.ActiveMode == null)
{
return;
}
var num = 0.713f;
foreach (var category in __instance.settingsContainer.GetComponentsInChildren<CategoryHeaderMasked>())
{
if (category)
category.gameObject.transform.localPosition -= new Vector3(0, 1.3f, 0);
}
CategoryHeaderMasked categoryHeaderMasked = Object.Instantiate(__instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer);
categoryHeaderMasked.SetHeader(CustomName, 20);
categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f;
categoryHeaderMasked.transform.localPosition = new Vector3(-0.903f, num, -2f);
OptionBehaviour = Object.Instantiate(
__instance.stringOptionOrigin,
Vector3.zero,
Quaternion.identity,
__instance.settingsContainer);
num -= 0.63f;
OptionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f);
OptionBehaviour.SetClickMask(__instance.ButtonClickMask);
StringGameSetting setting = ScriptableObject.CreateInstance<StringGameSetting>();
setting.Type = OptionTypes.MultipleChoice;
setting.Title = GamemodeName;
setting.Index = _lastValue;
setting.Values = new Il2CppStructArray<StringNames>([Values[0]]);
OptionBehaviour.SetUpFromData(setting, 20);
Set(_lastValue);
OptionBehaviour.TitleText.fontSize = 3;
foreach (var optionBehaviour in __instance.Children.ToArray().Skip(1))
{
optionBehaviour.gameObject.transform.localPosition -= new Vector3(0, 1.3f, 0);
}
__instance.Children.Add(OptionBehaviour);
for (var i = 1; i < Values.Count; i++)
OptionBehaviour.Values = (Il2CppStructArray<StringNames>)OptionBehaviour.Values.Add(Values.ElementAt(i).Value);
__instance.scrollBar.SetYBoundsMax(__instance.scrollBar.GetYBounds().max + 1);
}*/
internal static void Set(int val)
{
Value = val;
CustomGameModeManager.GetAndSetGameMode();
HudPatches.SetGameModeText(CustomGameModeManager.GetMode(Values.ElementAt(_lastValue).Key).ColoredName);
var gm = CustomGameModeManager.ActiveMode!;
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
GamemodeName,
gm.ColoredName,
new Color(0.7333f, 0.7333f, 0.7333f, 1),
gm.TmpIcon,
true);
// could make Values a dict of AbstractGameMode too
}
[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.ValueChanged))]
[HarmonyPrefix]
private static bool ValueChanged(GameOptionsMenu __instance, OptionBehaviour option)
{
if (OptionBehaviour.Equals(option))
{
Info($"Game mode changed to {option.GetInt()}");
RpcSyncGamemode(PlayerControl.LocalPlayer, option.GetInt());
if (GameSettingMenu.Instance && CustomGameModeManager.ActiveMode != null)
{
GameOptionsMenuPatch.ToggleGamemodeOptions(CustomGameModeManager.ActiveMode, __instance);
GameSettingMenu.Instance.RoleSettingsButton.gameObject.SetActive(CustomGameModeManager.ActiveMode.ShowNormalRoleSettings);
}
return false;
}
return true;
}
[MethodRpc((uint) MiraRpc.SyncGamemodeOption)]
internal static void RpcSyncGamemode(PlayerControl host, int data)
{
Set(data);
}
}
+531
View File
@@ -0,0 +1,531 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AmongUs.Data;
using AmongUs.GameOptions;
using HarmonyLib;
using InnerNet;
using MiraAPI.GameOptions;
using MiraAPI.HnsReimplemented;
using MiraAPI.HnsReimplemented.Options;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using PowerTools;
using UnityEngine;
namespace MiraAPI.GameModes;
/// <summary>
/// The vanilla Hide and Seek game mode, ported to Mira.
/// </summary>
[MiraIgnore]
public class HideAndSeekMode : AbstractGameMode
{
/// <inheritdoc/>
public override string Name => "Hide n Seek";
/// <inheritdoc/>
public override string Description => "You can run, but you can't hide!\nOutlive the timer or eliminate the crew.";
public override Color Color { get; } = new Color32(255, 88, 90, 255);
public override LoadableAsset<Sprite>? Icon => MiraAssets.HnSGamemodeIcon;
public override bool CanReport(DeadBody body) => false;
public override bool ShouldShowSabotageMap(MapBehaviour map) => false;
public override bool ShowGameModeIntroCutscene => true;
public override bool GameModeBodyTypeOverride => true;
public override bool ShowNormalGameSettings => false;
public override bool ShowNormalRoleSettings => false;
public override float DefaultImpostorKillCooldown => 1f;
public override bool ShowTaskBar => false;
public static int ImpostorPlayerID()
{
return OptionGroupSingleton<HnsImpostorOptions>.Instance.SelectedSeeker.Value;
}
public static bool HasImpostorPlayerID()
{
return ImpostorPlayerID() > -1;
}
public static bool ValidateImpostorPlayerID(List<NetworkedPlayerInfo> players)
{
return HasImpostorPlayerID() && players.Find((NetworkedPlayerInfo p) => (int)p.PlayerId == ImpostorPlayerID()) != null;
}
public override void AssignRoles(out bool runOriginal, LogicRoleSelectionNormal instance)
{
runOriginal = false;
Il2CppSystem.Collections.Generic.List<ClientData> list = new();
AmongUsClient.Instance.GetAllClients(list);
List<NetworkedPlayerInfo> list2 = list.ToArray()
.Where(c => c.Character != null && c.Character.Data != null && !c.Character.Data.Disconnected &&
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data)
.ToList();
foreach (NetworkedPlayerInfo networkedPlayerInfo in GameData.Instance.AllPlayers)
{
if (networkedPlayerInfo.Object != null && networkedPlayerInfo.Object.isDummy)
{
list2.Add(networkedPlayerInfo);
}
}
IGameOptions currentGameOptions = GameOptionsManager.Instance.CurrentGameOptions;
int adjustedNumImpostors = GameOptionsManager.Instance.CurrentGameOptions.GetAdjustedNumImpostors(list2.Count);
AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Impostor, Math.Max(adjustedNumImpostors, 1), RoleTypes.Impostor);
AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Crewmate, int.MaxValue, RoleTypes.Engineer);
}
public static void AssignRolesForTeam(
List<NetworkedPlayerInfo> players,
IGameOptions opts,
RoleTeamTypes team,
int teamMax,
RoleTypes defaultRole)
{
Error($"Hide And Seek Mode - AssignRolesForTeam: Team: {team}, Max: {teamMax}, Players: {players.Count}, DefaultRole: {defaultRole}");
int num = 0;
IRoleOptionsCollection roleOptions = opts.RoleOptions;
var source = RoleManager.Instance.AllRoles.ToArray()
.Where(role => role.TeamType == team && !RoleManager.IsGhostRole(role.Role) &&
CustomRoleUtils.CanSpawnOnCurrentMode(role));
var assignmentData = source.Where(x => !x.IsDead).Select(role =>
new RoleManager.RoleAssignmentData(
role,
roleOptions.GetNumPerGame(role.Role),
roleOptions.GetChancePerGame(role.Role))).ToList();
var source2 = CustomRoleUtils.GetPossibleRoles(assignmentData, x => x.Chance == 100);
var guaranteedRoles = source.Where(x => source2.Contains(((ushort)x.Role, 100)));
List<RoleTypes> list = new List<RoleTypes>();
if (team == RoleTeamTypes.Crewmate)
{
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment");
foreach (RoleManager.RoleAssignmentData roleAssignmentData in guaranteedRoles.Select((x) =>
new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100)))
{
while (true)
{
RoleManager.RoleAssignmentData roleAssignmentData2 = roleAssignmentData;
int count = roleAssignmentData2.Count;
roleAssignmentData2.Count = count - 1;
if (count <= 0)
{
break;
}
list.Add(roleAssignmentData.Role.Role);
}
}
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment");
AssignRolesFromList(players, teamMax, list, ref num);
var list2 = source.Where(x => !x.IsDead).Select(role =>
new RoleManager.RoleAssignmentData(
role,
roleOptions.GetNumPerGame(role.Role),
roleOptions.GetChancePerGame(role.Role))).ToList();
list.Clear();
foreach (RoleManager.RoleAssignmentData roleAssignmentData3 in list2)
{
for (int i = 0; i < roleAssignmentData3.Count; i++)
{
if (HashRandom.Next(101) < roleAssignmentData3.Chance)
{
list.Add(roleAssignmentData3.Role.Role);
}
}
}
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Potential Assignment");
AssignRolesFromList(players, teamMax, list, ref num);
var basicRole = RoleTypes.Engineer;
while (list.Count < players.Count && list.Count + num < teamMax)
{
list.Add(basicRole);
}
AssignRolesFromList(players, teamMax, list, ref num);
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Fallback Assignment");
}
else if (team == RoleTeamTypes.Impostor)
{
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment");
var newImpostors = new List<NetworkedPlayerInfo>();
// Specified Seeker
if (HasImpostorPlayerID() &&
ValidateImpostorPlayerID(players) &&
!AmongUsClient.Instance.IsGamePublic)
{
NetworkedPlayerInfo networkedPlayerInfo = players.ToArray()
.First(p => p.PlayerId == ImpostorPlayerID());
players.Remove(networkedPlayerInfo);
newImpostors.Add(networkedPlayerInfo);
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}");
}
// Random Seeker
else
{
int num2 = 0;
while (num2 < teamMax && players.Count > 0)
{
PseudoRandomList<NetworkedPlayerInfo> pseudoRandomList = new PseudoRandomList<NetworkedPlayerInfo>(AmongUsClient.Instance.GameId);
players.Do(x => pseudoRandomList.Add(x));
for (int i = 0; i < GameData.RoundsPlayedInSession; i++)
{
pseudoRandomList.PickRandom();
}
NetworkedPlayerInfo networkedPlayerInfo = pseudoRandomList.PickRandom();
players.Remove(networkedPlayerInfo);
newImpostors.Add(networkedPlayerInfo);
num2++;
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}");
}
}
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment");
foreach (RoleManager.RoleAssignmentData roleAssignmentData in guaranteedRoles.Select((x) =>
new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100)))
{
while (true)
{
RoleManager.RoleAssignmentData roleAssignmentData2 = roleAssignmentData;
int count = roleAssignmentData2.Count;
roleAssignmentData2.Count = count - 1;
if (count <= 0)
{
break;
}
list.Add(roleAssignmentData.Role.Role);
}
}
AssignRolesFromList(newImpostors, teamMax, list, ref num);
var list2 = source.Where(x => !x.IsDead).Select(role =>
new RoleManager.RoleAssignmentData(
role,
roleOptions.GetNumPerGame(role.Role),
roleOptions.GetChancePerGame(role.Role))).ToList();
list.Clear();
foreach (RoleManager.RoleAssignmentData roleAssignmentData3 in list2)
{
for (int i = 0; i < roleAssignmentData3.Count; i++)
{
if (HashRandom.Next(101) < roleAssignmentData3.Chance)
{
list.Add(roleAssignmentData3.Role.Role);
}
}
}
AssignRolesFromList(newImpostors, teamMax, list, ref num);
var basicRole = RoleTypes.Impostor;
while (list.Count < newImpostors.Count && list.Count + num < teamMax)
{
list.Add(basicRole);
}
AssignRolesFromList(newImpostors, teamMax, list, ref num);
}
}
public static void AssignRolesFromList(List<NetworkedPlayerInfo> players, int teamMax, List<RoleTypes> roleList, ref int rolesAssigned)
{
while (roleList.Count > 0 && players.Count > 0 && rolesAssigned < teamMax)
{
int index = HashRandom.FastNext(roleList.Count);
RoleTypes roleType = roleList[index];
roleList.RemoveAt(index);
int index2 = HashRandom.FastNext(players.Count);
players[index2].Object.RpcSetRole(roleType, false);
players.RemoveAt(index2);
rolesAssigned++;
}
}
public override IEnumerator IntroCutscene(IntroCutscene __instance)
{
SoundManager.Instance.PlaySound(__instance.IntroStinger, false, 1f, null);
Logger.GlobalInstance.Info("IntroCutscene :: CoBegin() :: Game Mode: Hide and Seek (MiraAPI)", null);
__instance.LogPlayerRoleData();
__instance.HideAndSeekPanels.SetActive(true);
if (PlayerControl.LocalPlayer.Data.Role.IsImpostor)
{
__instance.CrewmateRules.SetActive(false);
__instance.ImpostorRules.SetActive(true);
}
else
{
__instance.CrewmateRules.SetActive(true);
__instance.ImpostorRules.SetActive(false);
}
__instance.ImpostorName.gameObject.SetActive(true);
__instance.ImpostorTitle.gameObject.SetActive(true);
__instance.BackgroundBar.enabled = false;
__instance.TeamTitle.gameObject.SetActive(false);
var impostor = PlayerControl.AllPlayerControls.ToArray().FirstOrDefault(x => x.Data.Role.IsImpostor);
if (impostor == null)
{
Logger.GlobalInstance.Error("IntroCutscene :: CoBegin() :: impostor is NULL", null);
}
GameManager.Instance.SetSpecialCosmetics(impostor);
if (impostor != null)
{
__instance.ImpostorName.text = impostor.Data.PlayerName;
}
else
{
__instance.ImpostorName.text = "???";
}
yield return new WaitForSecondsRealtime(0.1f);
if (impostor != null)
{
__instance.ImpostorTitle.text = impostor.Data.Role.GetRoleName();
}
PoolablePlayer playerSlot = null;
if (impostor != null)
{
playerSlot = __instance.CreatePlayer(1, 1, impostor.Data, false);
playerSlot.SetBodyType(PlayerBodyTypes.Normal);
playerSlot.SetFlipX(false);
playerSlot.transform.localPosition = __instance.impostorPos;
playerSlot.transform.localScale = Vector3.one * __instance.impostorScale;
}
yield return ShipStatus.Instance.CosmeticsCache.PopulateFromPlayers();
yield return new WaitForSecondsRealtime(6f);
if (playerSlot != null)
{
playerSlot.gameObject.SetActive(false);
}
__instance.HideAndSeekPanels.SetActive(false);
__instance.CrewmateRules.SetActive(false);
__instance.ImpostorRules.SetActive(false);
HnsMusicHandler.Instance.StartMusicWithIntro();
var hideTimer = 10f;
if (PlayerControl.LocalPlayer.Data.Role.IsImpostor)
{
__instance.HideAndSeekTimerText.gameObject.SetActive(true);
PoolablePlayer poolablePlayer;
AnimationClip anim;
if (AprilFoolsMode.ShouldHorseAround())
{
poolablePlayer = __instance.HorseWrangleVisualSuit;
poolablePlayer.gameObject.SetActive(true);
poolablePlayer.SetBodyType(PlayerBodyTypes.Seeker);
anim = __instance.HnSSeekerSpawnHorseAnim;
__instance.HorseWrangleVisualPlayer.SetBodyType(PlayerBodyTypes.Normal);
__instance.HorseWrangleVisualPlayer.UpdateFromPlayerData(
PlayerControl.LocalPlayer.Data,
PlayerControl.LocalPlayer.CurrentOutfitType,
PlayerMaterial.MaskType.None,
false,
null,
false);
}
else if (AprilFoolsMode.ShouldLongAround())
{
poolablePlayer = __instance.HideAndSeekPlayerVisual;
poolablePlayer.gameObject.SetActive(true);
poolablePlayer.SetBodyType(PlayerBodyTypes.LongSeeker);
anim = __instance.HnSSeekerSpawnLongAnim;
}
else
{
poolablePlayer = __instance.HideAndSeekPlayerVisual;
poolablePlayer.gameObject.SetActive(true);
poolablePlayer.SetBodyType(PlayerBodyTypes.Seeker);
anim = __instance.HnSSeekerSpawnAnim;
}
poolablePlayer.SetBodyCosmeticsVisible(false);
poolablePlayer.UpdateFromPlayerData(
PlayerControl.LocalPlayer.Data,
PlayerControl.LocalPlayer.CurrentOutfitType,
PlayerMaterial.MaskType.None,
false,
null,
false);
SpriteAnim component = poolablePlayer.GetComponent<SpriteAnim>();
poolablePlayer.gameObject.SetActive(true);
poolablePlayer.ToggleName(false);
component.Play(anim, 1f);
while (hideTimer > 0f)
{
__instance.HideAndSeekTimerText.text = Mathf.RoundToInt(hideTimer).ToString();
hideTimer -= Time.deltaTime;
yield return null;
}
}
else
{
HideAndSeekHudHelper.Instance.HideCountdown = hideTimer;
if (AprilFoolsMode.ShouldHorseAround())
{
if (impostor != null)
{
impostor.AnimateCustom(__instance.HnSSeekerSpawnHorseInGameAnim);
}
}
else if (AprilFoolsMode.ShouldLongAround())
{
if (impostor != null)
{
impostor.AnimateCustom(__instance.HnSSeekerSpawnLongInGameAnim);
}
}
else if (impostor != null)
{
impostor.AnimateCustom(__instance.HnSSeekerSpawnAnim);
impostor.cosmetics.SetBodyCosmeticsVisible(false);
}
}
ShipStatus.Instance.StartSFX();
HnsMusicHandler.Instance.OnGameStart();
HnsDangerMeter.Instance.OnGameStart();
UnityEngine.Object.Destroy(__instance.gameObject);
}
public override void Initialize()
{
deadPlayerCount = 0;
ShipStatus.Instance.BreakEmergencyButton();
PlayerControl.LocalPlayer.SetKillTimer(0.01f);
if (HudManager.InstanceExists)
{
HudManager.Instance.gameObject.AddComponent<HnsMusicHandler>();
HudManager.Instance.gameObject.AddComponent<HideAndSeekHudHelper>();
HudManager.Instance.gameObject.AddComponent<HnsDangerMeter>();
}
}
public override MapOptions GetMapOptions()
{
MapOptions mapOptions = new MapOptions
{
Mode = MapOptions.Modes.Normal,
};
if (PlayerControl.LocalPlayer.Data.Role.IsImpostor && HideAndSeekHudHelper.Instance.SeekerAdminMapEnabled(PlayerControl.LocalPlayer))
{
mapOptions.Mode = MapOptions.Modes.CountOverlay;
mapOptions.AllowMovementWhileMapOpen = true;
mapOptions.IncludeDeadBodies = false;
mapOptions.ShowLivePlayerPosition = false;
}
return mapOptions;
}
public override void CheckGameEnd(out bool runOriginal, LogicGameFlowNormal instance)
{
runOriginal = false;
if (Helpers.GetAlivePlayers().Count(x => x.Data.Role.IsImpostor) == 0)
{
instance.Manager.RpcEndGame(GameOverReason.ImpostorDisconnect, !DataManager.Player.Ads.HasPurchasedAdRemoval);
}
if (Helpers.GetAlivePlayers().Count(x => !x.Data.Role.IsImpostor) != 0)
{
if (HideAndSeekHudHelper.Instance.AllTimersExpired())
{
instance.Manager.RpcEndGame(GameOverReason.HideAndSeek_CrewmatesByTimer, !DataManager.Player.Ads.HasPurchasedAdRemoval);
}
return;
}
instance.Manager.RpcEndGame(GameOverReason.HideAndSeek_ImpostorsByKills, !DataManager.Player.Ads.HasPurchasedAdRemoval);
}
public override PlayerBodyTypes GetBodyType(PlayerControl player)
{
if (player == null || player.Data == null || player.Data.Role == null)
{
if (AprilFoolsMode.ShouldHorseAround())
{
return PlayerBodyTypes.Horse;
}
if (AprilFoolsMode.ShouldLongAround())
{
return PlayerBodyTypes.Long;
}
return PlayerBodyTypes.Normal;
}
else if (AprilFoolsMode.ShouldHorseAround())
{
if (player.Data.Role.IsImpostor)
{
return PlayerBodyTypes.Normal;
}
return PlayerBodyTypes.Horse;
}
else if (AprilFoolsMode.ShouldLongAround())
{
if (player.Data.Role.IsImpostor)
{
return PlayerBodyTypes.LongSeeker;
}
return PlayerBodyTypes.Long;
}
else
{
if (player.Data.Role.IsImpostor)
{
return PlayerBodyTypes.Seeker;
}
return PlayerBodyTypes.Normal;
}
}
public override void UpdateTaskPanel(TaskPanelBehaviour instance)
{
instance.background.transform.localScale = (instance.taskText.textBounds.size.x > 0f)
? new Vector3(instance.taskText.textBounds.size.x + 0.2f, instance.taskText.textBounds.size.y + 0.2f, 1f)
: Vector3.zero;
Vector3 vector = instance.background.sprite.bounds.extents;
vector.y = -vector.y;
vector = vector.Mul(instance.background.transform.localScale);
instance.background.transform.localPosition = vector;
Vector3 vector2 = instance.tab.sprite.bounds.extents;
vector2 = vector2.Mul(instance.tab.transform.localScale);
vector2.y = -vector2.y;
vector2.x += vector.x * 2f;
instance.tab.transform.localPosition = vector2;
if (GameManager.Instance == null)
{
return;
}
var yPos = 1.6f;
var xPos = -instance.background.sprite.bounds.size.x * instance.background.transform.localScale.x;
instance.closedPosition = new Vector3(xPos, yPos, instance.closedPosition.z);
instance.openPosition = new Vector3(instance.openPosition.x, yPos, instance.openPosition.z);
if (instance.open)
{
instance.timer = Mathf.Min(1f, instance.timer + Time.deltaTime / instance.animationTimeSeconds);
}
else
{
instance.timer = Mathf.Max(0f, instance.timer - Time.deltaTime / instance.animationTimeSeconds);
}
Vector3 relativePos = new(
Mathf.SmoothStep(instance.closedPosition.x, instance.openPosition.x, instance.timer),
yPos,
instance.openPosition.z);
instance.transform.localPosition =
AspectPosition.ComputePosition(AspectPosition.EdgeAlignments.LeftTop, relativePos);
}
private int deadPlayerCount;
public override void OnPlayerDeath(PlayerControl player, bool assignGhostRole)
{
base.OnPlayerDeath(player, assignGhostRole);
HudManager.Instance.NotifyOfDeath();
var popup = GameManagerCreator.Instance.HideAndSeekManagerPrefab.DeathPopupPrefab;
deadPlayerCount++;
var item = UnityEngine.Object.Instantiate(popup, HudManager.Instance.transform.parent);
item.Show(player, deadPlayerCount);
}
}
@@ -8,8 +8,9 @@ namespace MiraAPI.GameOptions.Attributes;
/// </summary>
/// <param name="title">The option title.</param>
/// <param name="roleType">Optional parameter to specify a role Type.</param>
/// <param name="modeType">Optional parameter to specify a game mode Type.</param>
[AttributeUsage(AttributeTargets.Property)]
public abstract class ModdedOptionAttribute(string title, Type? roleType = null) : Attribute
public abstract class ModdedOptionAttribute(string title, Type? roleType = null, Type? modeType = null) : Attribute
{
internal IModdedOption? HolderOption { get; set; }
@@ -23,6 +24,11 @@ public abstract class ModdedOptionAttribute(string title, Type? roleType = null)
/// </summary>
protected Type? RoleType { get; private set; } = roleType;
/// <summary>
/// Gets the game mode type of the option.
/// </summary>
protected Type? ModeType { get; private set; } = modeType;
/// <summary>
/// Sets the value of the option.
/// </summary>
+39 -1
View File
@@ -5,6 +5,8 @@ using System.Linq;
using System.Reflection;
using BepInEx.Configuration;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using MiraAPI.GameModes;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Networking;
@@ -26,6 +28,8 @@ public static class ModdedOptionsManager
private static readonly Dictionary<Type, AbstractOptionGroup> TypeToGroup = [];
internal static readonly Dictionary<OptionBehaviour, ModdedPlayerOption> CreatedPlayerOptions = [];
internal static readonly Dictionary<OptionBehaviour, ModdedStringOption> CreatedStringOptions = [];
internal static readonly Dictionary<Type, List<AbstractOptionGroup>> GameModeOptionGroups = [];
internal static readonly Dictionary<uint, IModdedOption> ModdedOptions = [];
internal static readonly List<AbstractOptionGroup> Groups = [];
@@ -34,7 +38,7 @@ public static class ModdedOptionsManager
public static void AddSettingsChangeMessage(NotificationPopper notif, StringNames key, string value, Color textColor, TMP_SpriteAsset? sprite, bool playSound = true)
{
var item = string.Empty;
string item;
var text = textColor.ToTextColor();
if (sprite != null)
{
@@ -62,6 +66,29 @@ public static class ModdedOptionsManager
notif.SettingsChangeMessageLogic(key, item, playSound);
}
internal static bool RegisterGroup(Type type)
{
if (Activator.CreateInstance(type) is not AbstractOptionGroup group)
{
return false;
}
if (TypeToGroup.ContainsKey(type))
{
Logger<MiraApiPlugin>.Error($"Group {type.Name} already exists.");
return false;
}
Groups.Add(group);
TypeToGroup.Add(type, group);
typeof(OptionGroupSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
.SetValue(null, group);
return true;
}
internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo)
{
if (Activator.CreateInstance(type) is not AbstractOptionGroup group)
@@ -77,6 +104,17 @@ public static class ModdedOptionsManager
Groups.Add(group);
TypeToGroup.Add(type, group);
if (group.OptionableType?.IsAssignableTo(typeof(AbstractGameMode)) == true)
{
if (GameModeOptionGroups.TryGetValue(group.OptionableType, out var oldList))
{
oldList.Add(group);
}
else
{
GameModeOptionGroups.Add(group.OptionableType, new List<AbstractOptionGroup>() { group });
}
}
pluginInfo.InternalOptionGroups.Add(group);
typeof(OptionGroupSingleton<>).MakeGenericType(type)
@@ -1,8 +1,10 @@
using System.Linq;
using MiraAPI.PluginLoading;
namespace MiraAPI.GameOptions;
#pragma warning disable CA1852
[MiraIgnore]
internal class ModifierOptionGroup : AbstractOptionGroup
#pragma warning restore CA1852
{
@@ -1,4 +1,4 @@
using System;
using System;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
@@ -0,0 +1,176 @@
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;
namespace MiraAPI.GameOptions.OptionTypes;
/// <summary>
/// An option for selecting an enum value.
/// </summary>
public class ModdedStringOption : ModdedOption<string>
{
/// <summary>
/// Gets or sets the string values of the option.
/// </summary>
public string[] Values { get; set; }
/// <summary>
/// Gets or sets the String Name values of the option.
/// </summary>
public StringNames[] StringNameValues { get; set; }
/// <summary>
/// Gets the string's index.
/// </summary>
/// <param name="value">The option's string value.</param>
/// <returns>The option's value in the index.</returns>
public int GetIndex(string value, int location)
{
if (Values.Contains(value))
{
return Values.ToList().IndexOf(value);
}
Info($"Cannot find a valid index for {value} in {location}. Returning 0 instead. Values: {string.Join(", ", Values)}");
return 0;
}
/// <summary>
/// Adds a value to the option.
/// </summary>
/// <param name="value">The option's string value.</param>
/// <param name="index">The additional value's index on the list.</param>
public void RegisterExtraValue(string value, int index = -1)
{
if (!Values.Contains(value))
{
if (index <= -1)
index = Values.Length;
var newVals = Values.ToList();
newVals.Insert(index, value);
Values = newVals.ToArray();
var newStrVals = StringNameValues.ToList();
newStrVals.Insert(index, CustomStringName.CreateAndRegister(value));
StringNameValues = newStrVals.ToArray();
}
if (Data != null)
{
var data = (StringGameSetting)Data;
data.Values = StringNameValues;
data.Index = GetIndex(Value, 1);
if (OptionBehaviour != null)
{
var strOpt = OptionBehaviour.TryCast<StringOption>();
if (strOpt != null)
{
strOpt.Values = StringNameValues;
strOpt.Value = GetIndex(Value, 2);
Warning("StringOption is valid");
}
else
{
Error("StringOption is null.");
}
Warning("OptionBehaviour is valid");
}
else
{
Error("OptionBehaviour is null.");
}
Warning("Data is valid");
}
else
{
Error("Data is null.");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedStringOption"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as a string.</param>
/// <param name="values">An option list of string values to use.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedStringOption(string title, string defaultValue, string[] values, bool includeInPreset=true) : base(title, defaultValue, includeInPreset)
{
Values = values;
Data = ScriptableObject.CreateInstance<StringGameSetting>();
var data = (StringGameSetting)Data;
data.Title = StringName;
data.Type = global::OptionTypes.String;
StringNameValues = values.Select(CustomStringName.CreateAndRegister).ToArray();
data.Values = StringNameValues;
data.Index = GetIndex(Value, 3);
}
/// <inheritdoc />
public override OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, PlayerOption playerOpt, Transform container)
{
var stringOption = Object.Instantiate(stringOpt, container);
stringOption.name =
$"{ParentMod!.OptionsTitleText}.StringOption.{TranslationController.Instance.GetString(StringName)}";
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 = GetIndex(Value, 4);
OptionBehaviour = stringOption;
ModdedOptionsManager.CreatedStringOptions.TryAdd(stringOption, this);
return stringOption;
}
/// <inheritdoc />
public override float GetFloatData()
{
return Array.IndexOf(Values, Value);
}
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value, NumberFormatInfo.InvariantInfo)));
}
/// <inheritdoc />
public override void HandleNetData(byte[] data)
{
SetValue(Encoding.Unicode.GetString(data));
}
/// <inheritdoc />
public override string GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
return Values[optionBehaviour.GetInt()];
}
/// <inheritdoc />
protected override void OnValueChanged(string newValue)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(GetIndex(newValue, 5)), false);
if (!OptionBehaviour)
{
return;
}
if (OptionBehaviour is StringOption opt)
{
opt.Value = GetIndex(newValue, 5);
}
}
}
@@ -0,0 +1,285 @@
using System.Collections;
using System.Linq;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using MiraAPI.GameOptions;
using MiraAPI.HnsReimplemented.Options;
using MiraAPI.Utilities;
using Reactor.Utilities.Attributes;
using UnityEngine;
namespace MiraAPI.HnsReimplemented;
[RegisterInIl2Cpp]
public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr)
{
public static HideAndSeekHudHelper Instance { get; private set; }
public AudioClip FinalHideAlertSfx;
public AudioClip FinalHideCountdownSfx;
private AudioClip TaskFinishedSound;
private const int SECONDS_TO_BEEP = 10;
private const float SECONDS_TO_SET_DIRTY = 1f;
private HideAndSeekTimerBar timerBar;
private float totalHideTime = float.MaxValue;
private float currentHideTime = float.MaxValue;
private float totalFinalHideTime = float.MaxValue;
private float currentFinalHideTime = float.MaxValue;
private float secondsSinceLastSetDirty;
private Coroutine beepCoroutine;
private void Awake()
{
Instance = this;
}
public bool IsFinalCountdown
{
get { return currentHideTime <= 0f; }
}
public bool SeekerAdminMapEnabled(PlayerControl player)
{
int item = Helpers.GetAlivePlayers().Count(x => !x.Data.Role.IsImpostor);
return !player.inVent && player.Data != null && player.Data.Role != null &&
((!player.inVent && player.Data.Role.IsImpostor && IsFinalCountdown &&
OptionGroupSingleton<HnsFinalHideOptions>.Instance.FinalHideSeekMap.Value) ||
(player.Data.Role.IsImpostor &&
item <=
(GameData.Instance.PlayerCount - 1) / 3));
}
public void OnTaskComplete(float timeDeduction)
{
if (timerBar != null)
{
timerBar.TaskComplete();
}
AdjustEscapeTimer(timeDeduction, true);
}
public float GetTotalRoundTime()
{
float escapeTime = OptionGroupSingleton<HnsCrewmateOptions>.Instance.HidingTime.Value;
float finalCountdownTime = OptionGroupSingleton<HnsFinalHideOptions>.Instance.FinalHideTime.Value;
return escapeTime + finalCountdownTime;
}
public float GetTotalTimeRemaining()
{
return currentHideTime + currentFinalHideTime;
}
public float GetRoundTimeElapsed()
{
return GetTotalRoundTime() - GetTotalTimeRemaining();
}
public void Start()
{
totalHideTime = OptionGroupSingleton<HnsCrewmateOptions>.Instance.HidingTime.Value;
currentHideTime = totalHideTime;
totalFinalHideTime = OptionGroupSingleton<HnsFinalHideOptions>.Instance.FinalHideTime.Value;
currentFinalHideTime = totalFinalHideTime;
if (timerBar != null)
{
Object.Destroy(timerBar);
}
FinalHideAlertSfx = GameManagerCreator.Instance.HideAndSeekManagerPrefab.FinalHideAlertSFX;
FinalHideCountdownSfx = GameManagerCreator.Instance.HideAndSeekManagerPrefab.FinalHideCountdownSFX;
TaskFinishedSound = GameManagerCreator.Instance.HideAndSeekManagerPrefab.TaskFinishedSound;
timerBar = Object.Instantiate<HideAndSeekTimerBar>(
GameManagerCreator.Instance.HideAndSeekManagerPrefab.TimerBarPrefab,
HudManager.Instance.transform.parent);
}
public void OnGameEnd()
{
if (timerBar != null)
{
Object.Destroy(timerBar.gameObject);
}
if (beepCoroutine != null)
{
StopCoroutine(beepCoroutine);
}
beepCoroutine = null!;
}
private float taskDirtyTimer;
public float HideCountdown { get; set; }
public void LateUpdate()
{
if (!HudManager.InstanceExists)
{
return;
}
if (HideCountdown > 0f && taskDirtyTimer > 0.25f)
{
float num = taskDirtyTimer;
taskDirtyTimer = 0f;
if (!PlayerControl.LocalPlayer)
{
HudManager.Instance.TaskPanel.SetTaskText(string.Empty);
return;
}
NetworkedPlayerInfo data = PlayerControl.LocalPlayer.Data;
if (data == null)
{
return;
}
bool flag = data.Role != null && data.Role.IsImpostor;
HudManager.Instance.tasksString.Clear();
if (PlayerControl.LocalPlayer.myTasks == null || PlayerControl.LocalPlayer.myTasks.Count == 0)
{
HudManager.Instance.tasksString.Append("None");
}
else
{
for (int i = 0; i < PlayerControl.LocalPlayer.myTasks.Count; i++)
{
PlayerTask playerTask = PlayerControl.LocalPlayer.myTasks[i];
if (playerTask)
{
if (playerTask.TaskType == TaskTypes.FixComms && !flag)
{
HudManager.Instance.tasksString.Clear();
playerTask.AppendTaskText(HudManager.Instance.tasksString);
break;
}
playerTask.AppendTaskText(HudManager.Instance.tasksString);
}
}
if (data.Role != null)
{
data.Role.AppendTaskHint(HudManager.Instance.tasksString);
}
if (HideCountdown > 0f)
{
HideCountdown -= num;
HudManager.Instance.tasksString.Append("\n\n" + ((int)HideCountdown));
}
HudManager.Instance.tasksString.TrimEnd();
}
HudManager.Instance.TaskPanel.SetTaskText(HudManager.Instance.tasksString.ToString());
}
}
public void FixedUpdate()
{
secondsSinceLastSetDirty += Time.fixedDeltaTime;
if (IsFinalCountdown)
{
AdjustFinalEscapeTimer(Time.fixedDeltaTime);
return;
}
AdjustEscapeTimer(Time.fixedDeltaTime, false);
}
public void OnDestroy()
{
if (timerBar != null)
{
Object.Destroy(timerBar);
}
}
private void OnFinalCountdownTriggered()
{
foreach (PlayerControl playerControl in PlayerControl.AllPlayerControls)
{
if (!playerControl.Data.Role.IsImpostor && !playerControl.Data.IsDead)
{
playerControl.ClearTasks();
PlayerTask.GetOrCreateTask<ImportantTextTask>(playerControl, 0).Text =
DestroyableSingleton<TranslationController>.Instance.GetString(StringNames.HideActionButton);
}
}
if (!PlayerControl.LocalPlayer.Data.IsDead && Minigame.Instance != null)
{
Minigame instance = Minigame.Instance;
if (instance != null)
{
instance.ForceClose();
}
}
timerBar.StartFinalHide();
SoundManager.Instance.PlaySound(FinalHideAlertSfx, false, 1f, null);
DestroyableSingleton<HudManager>.Instance.SetAlertOverlay(true);
}
private void AdjustEscapeTimer(float timeDeduction, bool forceDirty)
{
float num = currentHideTime;
currentHideTime -= timeDeduction;
currentHideTime = Mathf.Max(currentHideTime, 0f);
if (currentHideTime <= 10f && beepCoroutine == null)
{
beepCoroutine = StartCoroutine(BeepAlmostEverySecond().WrapToIl2Cpp());
}
if (num > 0f && currentHideTime <= 0f)
{
OnFinalCountdownTriggered();
}
timerBar.UpdateTimer(currentHideTime, totalHideTime);
if (forceDirty || secondsSinceLastSetDirty > 1f)
{
secondsSinceLastSetDirty = 0f;
}
}
private IEnumerator BeepAlmostEverySecond()
{
while (!IsFinalCountdown)
{
float num = currentHideTime / 10f;
float pitch = 1.5f - num / 2f;
SoundManager.Instance.PlaySoundImmediate(FinalHideCountdownSfx, false, 1f, pitch, null);
yield return new WaitForSeconds(1f);
}
yield return Effects.Wait(currentFinalHideTime - 10f);
while (currentFinalHideTime > 0f)
{
float num2 = currentFinalHideTime / 10f;
float pitch2 = 1.5f - num2 / 2f;
SoundManager.Instance.PlaySoundImmediate(FinalHideCountdownSfx, false, 1f, pitch2, null);
yield return new WaitForSeconds(1f);
}
yield break;
}
private void AdjustFinalEscapeTimer(float timeDeduction)
{
currentFinalHideTime -= timeDeduction;
currentFinalHideTime = Mathf.Max(currentFinalHideTime, 0f);
timerBar.UpdateTimer(currentFinalHideTime, totalFinalHideTime);
if (secondsSinceLastSetDirty > 1f)
{
secondsSinceLastSetDirty = 0f;
}
}
public bool AllTimersExpired()
{
return currentHideTime <= 0f && currentFinalHideTime <= 0f;
}
}
+142
View File
@@ -0,0 +1,142 @@
using System.Collections.Generic;
using System.Linq;
using MiraAPI.GameOptions;
using MiraAPI.HnsReimplemented.Options;
using MiraAPI.Utilities;
using Reactor.Utilities.Attributes;
using UnityEngine;
namespace MiraAPI.HnsReimplemented;
[RegisterInIl2Cpp]
public sealed class HnsDangerMeter(nint cppPtr) : MonoBehaviour(cppPtr)
{
public static HnsDangerMeter Instance;
private void Awake()
{
Instance = this;
}
private DangerMeter dangerMeter;
private List<PlayerControl> impostors = [];
private float scaryMusicDistance;
private float veryScaryMusicDistance;
private float dangerLevel1;
private float dangerLevel2;
private bool firstMusicActivation;
private float firstCrossfadeCountdown;
public void FixedUpdate()
{
PlayerControl localPlayer = PlayerControl.LocalPlayer;
if (impostors == null || localPlayer == null)
{
return;
}
if (impostors.Count <= 0)
{
return;
}
float num = float.MaxValue;
foreach (PlayerControl playerControl in impostors)
{
if (!(playerControl == null))
{
float sqrMagnitude = (playerControl.transform.position - localPlayer.transform.position).sqrMagnitude;
if (sqrMagnitude < scaryMusicDistance && num > sqrMagnitude)
{
num = sqrMagnitude;
}
}
}
if (HideAndSeekHudHelper.Instance.HideCountdown > 0f)
{
dangerLevel1 = 0f;
dangerLevel2 = 0f;
}
else
{
if (firstMusicActivation)
{
firstMusicActivation = false;
firstCrossfadeCountdown = 3f;
HnsMusicHandler.Instance.SetMusicCrossfadeSpeed(0.6f);
}
if (firstCrossfadeCountdown > 0f)
{
firstCrossfadeCountdown -= Time.deltaTime;
if (firstCrossfadeCountdown <= 0f)
{
HnsMusicHandler.Instance.SetMusicCrossfadeSpeed(5f);
}
}
dangerLevel1 = Mathf.Clamp01(
(scaryMusicDistance - num) / (scaryMusicDistance - veryScaryMusicDistance));
dangerLevel2 = Mathf.Clamp01((veryScaryMusicDistance - num) / veryScaryMusicDistance);
}
UpdateDangerMeter();
UpdateDangerMusic();
}
private void UpdateDangerMusic()
{
PlayerControl localPlayer = PlayerControl.LocalPlayer;
if (localPlayer != null && localPlayer.Data != null && localPlayer.Data.IsDead)
{
HnsMusicHandler.Instance.SetTaskState(false);
HnsMusicHandler.Instance.ResetMusic();
return;
}
HnsMusicHandler.Instance.SetMusicValues(dangerLevel1, dangerLevel2);
}
private void UpdateDangerMeter()
{
if (dangerMeter == null)
{
return;
}
dangerMeter.SetDangerValue(dangerLevel1, dangerLevel2);
}
public void OnGameStart()
{
firstMusicActivation = true;
if (!PlayerControl.LocalPlayer.Data.Role.IsImpostor)
{
dangerMeter = HudManager.Instance.DangerMeter;
dangerMeter.gameObject.SetActive(true);
}
impostors = Helpers.GetAlivePlayers().Where(x => x.Data.Role.IsImpostor).ToList();
var baseSpeed = OptionGroupSingleton<HnsCrewmateOptions>.Instance.PlayerSpeed.Value;
scaryMusicDistance = 55f *
baseSpeed;
veryScaryMusicDistance = 15f *
baseSpeed;
if (scaryMusicDistance < veryScaryMusicDistance)
{
float num = veryScaryMusicDistance;
float num2 = scaryMusicDistance;
scaryMusicDistance = num;
veryScaryMusicDistance = num2;
}
}
}
+237
View File
@@ -0,0 +1,237 @@
using System.Collections.Generic;
using Amongus.GameModes.HideAndSeek;
using MiraAPI.GameOptions;
using MiraAPI.HnsReimplemented.Options;
using Reactor.Utilities.Attributes;
using UnityEngine;
namespace MiraAPI.HnsReimplemented;
[RegisterInIl2Cpp]
public sealed class HnsMusicHandler(nint cppPtr) : MonoBehaviour(cppPtr)
{
public static HnsMusicHandler Instance;
private void Awake()
{
Instance = this;
}
private HideAndSeekMusicCollection musicCollection;
private float lastMusicSyncTime;
private bool isDoingTask;
private float normalVolume;
private float taskVolume;
private float dangerLevel1Volume;
private float dangerLevel2Volume;
private AudioSource normalSource;
private AudioSource taskSource;
private AudioSource dangerLevel1Source;
private AudioSource dangerLevel2Source;
private float musicLerpSpeed = 5f;
public void Start()
{
musicCollection = GameManagerCreator.Instance.HideAndSeekManagerPrefab.MusicCollection;
}
public void OnGameStart()
{
InitMusic();
ResetMusic();
}
public void OnDestroy()
{
ResetMusic();
}
private void InitMusic()
{
if (normalSource == null)
{
normalSource =
SoundManager.Instance.GetNamedSfxSource(musicNames[LogicHnSMusic.HideAndSeekMusicTrack.Normal]);
}
normalSource.outputAudioMixerGroup = SoundManager.Instance.MusicChannel;
normalSource.clip = musicCollection.NormalMusic;
normalSource.loop = true;
if (taskSource == null)
{
taskSource =
SoundManager.Instance.GetNamedSfxSource(musicNames[LogicHnSMusic.HideAndSeekMusicTrack.Task]);
}
taskSource.outputAudioMixerGroup = SoundManager.Instance.MusicChannel;
taskSource.volume = 0f;
taskSource.clip = musicCollection.TaskMusic;
taskSource.loop = true;
if (dangerLevel1Source == null)
{
dangerLevel1Source =
SoundManager.Instance.GetNamedSfxSource(
musicNames[LogicHnSMusic.HideAndSeekMusicTrack.DangerLevel1]);
}
dangerLevel1Source.outputAudioMixerGroup = SoundManager.Instance.MusicChannel;
dangerLevel1Source.volume = 0f;
dangerLevel1Source.clip = musicCollection.DangerLevel1Music;
dangerLevel1Source.loop = true;
if (dangerLevel2Source == null)
{
dangerLevel2Source =
SoundManager.Instance.GetNamedSfxSource(
musicNames[LogicHnSMusic.HideAndSeekMusicTrack.DangerLevel2]);
}
dangerLevel2Source.outputAudioMixerGroup = SoundManager.Instance.MusicChannel;
dangerLevel2Source.volume = 0f;
dangerLevel2Source.clip = musicCollection.DangerLevel2Music;
dangerLevel2Source.loop = true;
normalSource.Play();
taskSource.Play();
dangerLevel1Source.Play();
dangerLevel2Source.Play();
SyncMusic();
}
public void StartMusicWithIntro()
{
if (PlayerControl.LocalPlayer.Data.Role.IsImpostor)
{
AudioClip clip = OptionGroupSingleton<HnsCrewmateOptions>.Instance.HidingTime.Value <= 180f
? musicCollection.ImpostorShortMusic
: musicCollection.ImpostorLongMusic;
if (AprilFoolsMode.ShouldHorseAround())
{
clip = musicCollection.ImpostorRanchMusic;
}
SoundManager.Instance.PlaySound(clip, true, 1f, SoundManager.Instance.MusicChannel);
}
}
public void SetTaskState(bool isDoingTask)
{
isDoingTask = isDoingTask;
}
public void FixedUpdate()
{
if (normalSource == null || taskSource == null || dangerLevel1Source == null ||
dangerLevel2Source == null)
{
return;
}
if (Time.unscaledTime > lastMusicSyncTime + 1f)
{
SyncMusic();
}
normalSource.volume = Mathf.Lerp(
normalSource.volume,
normalVolume,
Time.fixedDeltaTime * musicLerpSpeed);
taskSource.volume = Mathf.Lerp(
taskSource.volume,
taskVolume,
Time.fixedDeltaTime * musicLerpSpeed);
dangerLevel1Source.volume = Mathf.Lerp(
dangerLevel1Source.volume,
dangerLevel1Volume,
Time.fixedDeltaTime * musicLerpSpeed);
dangerLevel2Source.volume = Mathf.Lerp(
dangerLevel2Source.volume,
dangerLevel2Volume,
Time.fixedDeltaTime * musicLerpSpeed);
}
private void SyncMusic()
{
taskSource.timeSamples = normalSource.timeSamples;
dangerLevel1Source.timeSamples = normalSource.timeSamples;
dangerLevel2Source.timeSamples = normalSource.timeSamples;
lastMusicSyncTime = Time.unscaledTime;
}
public void ResetMusic()
{
SetMusicValues(0f, 0f);
}
public void SetMusicCrossfadeSpeed(float lerpSpeed)
{
musicLerpSpeed = lerpSpeed;
}
public void SetMusicValues(float dangerLevel1, float dangerLevel2)
{
if (PlayerControl.LocalPlayer != null && PlayerControl.LocalPlayer.Data.Role.IsImpostor)
{
return;
}
if (normalSource == null || taskSource == null || dangerLevel1Source == null ||
dangerLevel2Source == null)
{
return;
}
normalVolume = (isDoingTask ? 0f : 1f);
taskVolume = (isDoingTask ? 1f : 0f);
dangerLevel1Volume = 0f;
dangerLevel2Volume = 0f;
if (dangerLevel1 > 0f)
{
dangerLevel1Volume = dangerLevel1;
if (isDoingTask)
{
taskVolume = 1f - dangerLevel1;
}
else
{
normalVolume = 1f - dangerLevel1;
}
}
if (dangerLevel2 > 0f)
{
dangerLevel2Volume = dangerLevel2;
dangerLevel1Volume = 1f - dangerLevel2;
}
}
private readonly Dictionary<LogicHnSMusic.HideAndSeekMusicTrack, string> musicNames =
new Dictionary<LogicHnSMusic.HideAndSeekMusicTrack, string>
{
{
LogicHnSMusic.HideAndSeekMusicTrack.Normal,
"HnS_Music_Normal"
},
{
LogicHnSMusic.HideAndSeekMusicTrack.Task,
"HnS_Music_Task"
},
{
LogicHnSMusic.HideAndSeekMusicTrack.DangerLevel1,
"HnS_Music_DangerLevel1"
},
{
LogicHnSMusic.HideAndSeekMusicTrack.DangerLevel2,
"HnS_Music_DangerLevel2"
},
};
}
@@ -0,0 +1,89 @@
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
namespace MiraAPI.HnsReimplemented.Options;
/// <inheritdoc />
public class HnsCrewmateOptions : AbstractOptionGroup<HideAndSeekMode>
{
/// <inheritdoc />
public override string GroupName => "Crewmates";
public ModdedNumberOption PlayerSpeed { get; set; } = new(
"Player Speed",
1f,
0.5f,
3f,
0.25f,
"#",
"#",
MiraNumberSuffixes.Multiplier,
"0.00");
public ModdedNumberOption HidingTime { get; set; } = new(
"Hiding Time",
200,
160,
300,
20,
"#",
"#",
MiraNumberSuffixes.Seconds);
public ModdedNumberOption CrewmateVision { get; set; } = new(
"Crewmate Vision",
0.6f,
0.25f,
1,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier,
"0.00");
public ModdedNumberOption MaxVentUses { get; set; } = new(
"Max Vent Uses",
1,
0,
5,
1,
"#",
"#",
MiraNumberSuffixes.None);
public ModdedNumberOption MaxTimeInVent { get; set; } = new(
"Max Time in Vent",
3,
1,
10,
1,
"#",
"#",
MiraNumberSuffixes.Seconds)
{
Visible = () => (int)OptionGroupSingleton<HnsCrewmateOptions>.Instance.MaxVentUses.Value > 0,
};
public ModdedToggleOption FlashlightMode { get; set; } = new(
"Flashlight Mode",
true);
public ModdedNumberOption CrewmateFlashlightSize { get; set; } = new(
"Crewmate Flashlight Size",
0.35f,
0.1f,
0.5f,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier)
{
Visible = () => OptionGroupSingleton<HnsCrewmateOptions>.Instance.FlashlightMode.Value,
};
public ModdedToggleOption ShowNames { get; set; } = new(
"Show Names",
false);
}
@@ -0,0 +1,52 @@
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
namespace MiraAPI.HnsReimplemented.Options;
/// <inheritdoc />
public class HnsFinalHideOptions : AbstractOptionGroup<HideAndSeekMode>
{
/// <inheritdoc />
public override string GroupName => "Final Hide";
public ModdedNumberOption FinalHideTime { get; set; } = new(
"Hiding Time",
50,
30,
120,
5,
"#",
"#",
MiraNumberSuffixes.Seconds);
public ModdedToggleOption FinalHidePings { get; set; } = new(
"Final Hide Pings",
true);
public ModdedNumberOption FinalHideImpostorSpeed { get; set; } = new(
"Final Hide Impostor Speed",
1.2f,
1f,
3,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier,
"0.00");
public ModdedNumberOption PingInterval { get; set; } = new(
"Ping Interval",
6,
3,
10,
5,
"#",
"#",
MiraNumberSuffixes.Seconds);
public ModdedToggleOption FinalHideSeekMap { get; set; } = new(
"Final Hide Seek Map",
true);
}
@@ -0,0 +1,40 @@
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
namespace MiraAPI.HnsReimplemented.Options;
/// <inheritdoc />
public class HnsImpostorOptions : AbstractOptionGroup<HideAndSeekMode>
{
/// <inheritdoc />
public override string GroupName => "Impostors";
public ModdedPlayerOption SelectedSeeker { get; set; } = new(
"Forced Impostor");
public ModdedNumberOption ImpostorVision { get; set; } = new(
"Impostor Vision",
0.6f,
0.25f,
1,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier,
"0.00");
public ModdedNumberOption ImpostorFlashlightSize { get; set; } = new(
"Impostor Flashlight Size",
0.35f,
0.1f,
0.5f,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier)
{
Visible = () => OptionGroupSingleton<HnsCrewmateOptions>.Instance.FlashlightMode.Value,
};
}
@@ -0,0 +1,43 @@
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
namespace MiraAPI.HnsReimplemented.Options;
/// <inheritdoc />
public class HnsTaskOptions : AbstractOptionGroup<HideAndSeekMode>
{
/// <inheritdoc />
public override string GroupName => "Tasks";
public ModdedNumberOption CommonTasks { get; set; } = new(
"# Common Tasks",
1,
0,
4,
1,
"#",
"#",
MiraNumberSuffixes.None);
public ModdedNumberOption LongTasks { get; set; } = new(
"# Long Tasks",
1,
0,
4,
1,
"#",
"#",
MiraNumberSuffixes.None);
public ModdedNumberOption ShortTasks { get; set; } = new(
"# Short Tasks",
2,
0,
8,
1,
"#",
"#",
MiraNumberSuffixes.None);
}
@@ -1,11 +1,13 @@
using System;
using System.Linq;
using BepInEx.Configuration;
using MiraAPI.PluginLoading;
using UnityEngine;
namespace MiraAPI.LocalSettings.SettingTypes;
/// <inheritdoc />
[MiraIgnore]
public abstract class LocalSettingBase<T> : ILocalSetting
{
/// <inheritdoc />
+15 -2
View File
@@ -1,6 +1,7 @@
global using static Reactor.Utilities.Logger<MiraAPI.MiraApiPlugin>;
using System;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using MiraAPI.PluginLoading;
@@ -20,8 +21,20 @@ namespace MiraAPI;
[BepInDependency(ReactorPlugin.Id)]
[BepInDependency(ModCompatibility.SubmergedId, BepInDependency.DependencyFlags.SoftDependency)]
[ReactorModFlags(ModFlags.RequireOnAllClients)]
public partial class MiraApiPlugin : BasePlugin
public partial class MiraApiPlugin : BasePlugin, IMiraPlugin
{
/// <inheritdoc />
public ConfigFile GetConfigFile()
{
return Config;
}
/// <inheritdoc />
public string OptionsTitleText => "MiraAPI";
/// <inheritdoc />
public bool DisplayOnOptionsMenu => false;
/// <summary>
/// Gets a value indicating whether the current device is running Starlight (on mobile).
/// </summary>
@@ -53,6 +66,6 @@ public partial class MiraApiPlugin : BasePlugin
ReactorCredits.Register("Mira API", Version, IsDevBuild, ReactorCredits.AlwaysShow);
PluginManager = new MiraPluginManager();
PluginManager.Initialize();
PluginManager.Initialize(this, this);
}
}
+15 -4
View File
@@ -136,7 +136,10 @@ public static class ModifierManager
var validPlayers = plrs.Where(x => IsGameModifierValid(x, modifier, modifier.TypeId)).ToList();
if (validPlayers.Count == 0)
{
Warning($"No valid players for modifier {modifier.ModifierName}");
if (MiraApiPlugin.IsDevBuild)
{
Warning($"No valid players for modifier {modifier.ModifierName}");
}
continue;
}
@@ -157,15 +160,23 @@ public static class ModifierManager
if (candidates.Count == 0)
{
Warning(
$"No available players for modifier {modifier.ModifierName} at assignment {i + 1}");
if (MiraApiPlugin.IsDevBuild)
{
Warning(
$"No available players for modifier {modifier.ModifierName} at assignment {i + 1}");
}
break;
}
var plr = candidates.Random();
if (plr == null)
{
Warning($"Valid player for modifier {modifier.ModifierName} disappeared");
if (MiraApiPlugin.IsDevBuild)
{
Warning($"Valid player for modifier {modifier.ModifierName} disappeared");
}
continue;
}
+6 -2
View File
@@ -1,8 +1,12 @@
namespace MiraAPI.Modifiers.Types;
using MiraAPI.GameModes;
using MiraAPI.PluginLoading;
namespace MiraAPI.Modifiers.Types;
/// <summary>
/// The base class for a game modifier. Game modifiers are applied at the start of the game on top of the player's role.
/// </summary>
[MiraIgnore]
public abstract class GameModifier : BaseModifier
{
/// <inheritdoc />
@@ -51,5 +55,5 @@ public abstract class GameModifier : BaseModifier
/// Determines whether the modifier can spawn in general, accounting for gamemodes and everything else.
/// </summary>
/// <returns><see langword="true"/> if the modifier is able to spawn, otherwise <see langword="false"/>.</returns>
public virtual bool CanSpawnOnCurrentMode() => !GameManager.Instance.IsHideAndSeek();
public virtual bool CanSpawnOnCurrentMode() => CustomGameModeManager.IsClassic() && !GameManager.Instance.IsHideAndSeek();
}
+3
View File
@@ -1,4 +1,6 @@
using System;
using MiraAPI.PluginLoading;
using Reactor.Utilities;
using UnityEngine;
namespace MiraAPI.Modifiers.Types;
@@ -6,6 +8,7 @@ namespace MiraAPI.Modifiers.Types;
/// <summary>
/// The base class for all timed modifiers. Timed modifiers have a duration and can be started and stopped.
/// </summary>
[MiraIgnore]
public abstract class TimedModifier : BaseModifier
{
/// <summary>
+443 -10
View File
@@ -7,6 +7,7 @@ using Assets.CoreScripts;
using BepInEx.Unity.IL2CPP.Utils;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
using MiraAPI.GameModes;
using MiraAPI.Utilities;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
@@ -84,13 +85,15 @@ public static class CustomMurderRpc
var beforeMurderEvent = new BeforeMurderEvent(source, target, inMeeting);
MiraEventManager.InvokeEvent(beforeMurderEvent);
var defenseFlag = beforeMurderEvent.IgnoreDefense;
var indirectFlag = beforeMurderEvent.IsIndirectAttack;
var isMeetingActive = MeetingHud.Instance != null || ExileController.Instance != null;
if ((inMeeting is MeetingCheck.ForMeeting && !isMeetingActive) || (inMeeting is MeetingCheck.OutsideMeeting && isMeetingActive))
{
beforeMurderEvent.Cancel();
}
if (target.ProtectedByGa())
if (!defenseFlag && target.ProtectedByGa())
{
beforeMurderEvent.Cancel();
murderResultFlags = MurderResultFlags.FailedProtected;
@@ -114,6 +117,8 @@ public static class CustomMurderRpc
PlayerControl.LocalPlayer,
source,
target,
indirectFlag,
defenseFlag,
murderResultFlags,
resetKillTimer,
createDeadBody,
@@ -128,6 +133,8 @@ public static class CustomMurderRpc
/// <param name="host">The game host.</param>
/// <param name="source">The killer.</param>
/// <param name="target">The player to murder.</param>
/// <param name="isIndirect">Should the kill be indirect.</param>
/// <param name="ignoreDefense">Should the kill ignore defense.</param>
/// <param name="murderResultFlags">End result for the murder.</param>
/// <param name="resetKillTimer">Should the kill timer be reset.</param>
/// <param name="createDeadBody">Should a dead body be created.</param>
@@ -139,6 +146,149 @@ public static class CustomMurderRpc
this PlayerControl host,
PlayerControl source,
PlayerControl target,
bool isIndirect,
bool ignoreDefense,
MurderResultFlags murderResultFlags,
bool resetKillTimer = true,
bool createDeadBody = true,
bool teleportMurderer = true,
bool showKillAnim = true,
bool playKillSound = true)
{
if (LobbyBehaviour.Instance || !host.IsHost() || target.Data.IsDead || target.Data.Disconnected)
{
source.isKilling = false;
return;
}
var murderResultFlags2 = MurderResultFlags.DecisionByHost | murderResultFlags;
if (isIndirect || ignoreDefense)
{
source.CustomMurder(
target,
null,
isIndirect,
ignoreDefense,
murderResultFlags2,
resetKillTimer,
createDeadBody,
teleportMurderer,
showKillAnim,
playKillSound);
}
else
{
source.CustomMurder(
target,
murderResultFlags2,
resetKillTimer,
createDeadBody,
teleportMurderer,
showKillAnim,
playKillSound);
}
}
/// <summary>
/// Networked Custom Murder method, which checks for meetings as well, ran by clients for the host to confirm kills.
/// </summary>
/// <param name="source">The killer.</param>
/// <param name="target">The player to murder.</param>
/// <param name="inMeeting">Whether the murder is intended to be triggered in a meeting.</param>
/// <param name="isIndirect">Should the kill be indirect.</param>
/// <param name="ignoreDefense">Should the kill ignore defense.</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.AdvancedCustomMurder, LocalHandling = RpcLocalHandling.Before)]
public static void RpcAdvancedCustomMurder(
this PlayerControl source,
PlayerControl target,
MeetingCheck inMeeting,
bool isIndirect,
bool ignoreDefense = false,
bool didSucceed = true,
bool resetKillTimer = true,
bool createDeadBody = true,
bool teleportMurderer = true,
bool showKillAnim = true,
bool playKillSound = true)
{
if (LobbyBehaviour.Instance)
{
return;
}
var murderResultFlags = didSucceed ? MurderResultFlags.Succeeded : MurderResultFlags.FailedError;
var beforeMurderEvent = new BeforeMurderEvent(source, target, isIndirect, ignoreDefense, inMeeting);
MiraEventManager.InvokeEvent(beforeMurderEvent);
var defenseFlag = beforeMurderEvent.IgnoreDefense;
var indirectFlag = beforeMurderEvent.IsIndirectAttack;
var isMeetingActive = MeetingHud.Instance != null || ExileController.Instance != null;
if ((inMeeting is MeetingCheck.ForMeeting && !isMeetingActive) || (inMeeting is MeetingCheck.OutsideMeeting && isMeetingActive))
{
beforeMurderEvent.Cancel();
}
if (!defenseFlag && target.ProtectedByGa())
{
beforeMurderEvent.Cancel();
murderResultFlags = MurderResultFlags.FailedProtected;
}
else if (beforeMurderEvent.IsCancelled)
{
murderResultFlags = MurderResultFlags.FailedError;
}
if (beforeMurderEvent.IsCancelled && source.AmOwner)
{
source.isKilling = true;
}
if (!PlayerControl.LocalPlayer.IsHost())
{
return;
}
RpcConfirmAdvancedCustomMurder(
PlayerControl.LocalPlayer,
source,
target,
indirectFlag,
defenseFlag,
murderResultFlags,
resetKillTimer,
createDeadBody,
teleportMurderer,
showKillAnim,
playKillSound);
}
/// <summary>
/// Networked Custom Murder method, which checks for meetings as well, ran by clients for the host to confirm kills.
/// </summary>
/// <param name="host">The game host.</param>
/// <param name="source">The killer.</param>
/// <param name="target">The player to murder.</param>
/// <param name="isIndirect">Should the kill be indirect.</param>
/// <param name="ignoreDefense">Should the kill ignore defense.</param>
/// <param name="murderResultFlags">End result for the murder.</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.ConfirmAdvancedCustomMurder, LocalHandling = RpcLocalHandling.After)]
public static void RpcConfirmAdvancedCustomMurder(
this PlayerControl host,
PlayerControl source,
PlayerControl target,
bool isIndirect,
bool ignoreDefense,
MurderResultFlags murderResultFlags,
bool resetKillTimer = true,
bool createDeadBody = true,
@@ -156,6 +306,9 @@ public static class CustomMurderRpc
source.CustomMurder(
target,
null,
isIndirect,
ignoreDefense,
murderResultFlags2,
resetKillTimer,
createDeadBody,
@@ -165,10 +318,145 @@ public static class CustomMurderRpc
}
/// <summary>
/// Custom Murder method without networking. If you need a networked version, use <see cref="RpcCustomMurder(PlayerControl, PlayerControl, bool, bool, bool, bool, bool, bool)"/>.
/// Networked Custom Murder method, which checks for meetings as well, ran by clients for the host to confirm kills.
/// </summary>
/// <param name="source">The killer.</param>
/// <param name="target">The player to murder.</param>
/// <param name="framed">The player to frame.</param>
/// <param name="inMeeting">Whether the murder is intended to be triggered in a meeting.</param>
/// <param name="isIndirect">Should the kill be indirect.</param>
/// <param name="ignoreDefense">Should the kill ignore defense.</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 framed player 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.FramedCustomMurder, LocalHandling = RpcLocalHandling.Before)]
public static void RpcFramedCustomMurder(
this PlayerControl source,
PlayerControl target,
PlayerControl framed,
MeetingCheck inMeeting,
bool isIndirect = true,
bool ignoreDefense = false,
bool didSucceed = true,
bool resetKillTimer = true,
bool createDeadBody = true,
bool teleportMurderer = true,
bool showKillAnim = true,
bool playKillSound = true)
{
if (LobbyBehaviour.Instance)
{
return;
}
var murderResultFlags = didSucceed ? MurderResultFlags.Succeeded : MurderResultFlags.FailedError;
var beforeMurderEvent = new BeforeMurderEvent(source, target, framed, isIndirect, ignoreDefense, inMeeting);
MiraEventManager.InvokeEvent(beforeMurderEvent);
var defenseFlag = beforeMurderEvent.IgnoreDefense;
var indirectFlag = beforeMurderEvent.IsIndirectAttack;
var isMeetingActive = MeetingHud.Instance != null || ExileController.Instance != null;
if ((inMeeting is MeetingCheck.ForMeeting && !isMeetingActive) || (inMeeting is MeetingCheck.OutsideMeeting && isMeetingActive))
{
beforeMurderEvent.Cancel();
}
if (!defenseFlag && target.ProtectedByGa())
{
beforeMurderEvent.Cancel();
murderResultFlags = MurderResultFlags.FailedProtected;
}
else if (beforeMurderEvent.IsCancelled)
{
murderResultFlags = MurderResultFlags.FailedError;
}
if (beforeMurderEvent.IsCancelled && source.AmOwner)
{
source.isKilling = true;
}
if (!PlayerControl.LocalPlayer.IsHost())
{
return;
}
RpcConfirmFramedCustomMurder(
PlayerControl.LocalPlayer,
source,
target,
framed,
indirectFlag,
defenseFlag,
murderResultFlags,
resetKillTimer,
createDeadBody,
teleportMurderer,
showKillAnim,
playKillSound);
}
/// <summary>
/// Networked Custom Murder method, which checks for meetings as well, ran by clients for the host to confirm kills.
/// </summary>
/// <param name="host">The game host.</param>
/// <param name="source">The killer.</param>
/// <param name="target">The player to murder.</param>
/// <param name="framed">The player to frame.</param>
/// <param name="isIndirect">Should the kill be indirect.</param>
/// <param name="ignoreDefense">Should the kill ignore defense.</param>
/// <param name="murderResultFlags">End result for the murder.</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 framed player 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.ConfirmFramedCustomMurder, LocalHandling = RpcLocalHandling.After)]
public static void RpcConfirmFramedCustomMurder(
this PlayerControl host,
PlayerControl source,
PlayerControl target,
PlayerControl framed,
bool isIndirect,
bool ignoreDefense,
MurderResultFlags murderResultFlags,
bool resetKillTimer = true,
bool createDeadBody = true,
bool teleportMurderer = true,
bool showKillAnim = true,
bool playKillSound = true)
{
if (LobbyBehaviour.Instance || !host.IsHost() || target.Data.IsDead || target.Data.Disconnected)
{
source.isKilling = false;
return;
}
var murderResultFlags2 = MurderResultFlags.DecisionByHost | murderResultFlags;
source.CustomMurder(
target,
framed,
isIndirect,
ignoreDefense,
murderResultFlags2,
resetKillTimer,
createDeadBody,
teleportMurderer,
showKillAnim,
playKillSound);
}
/// <summary>
/// Custom Murder method without networking. If you need a networked version, use <see cref="RpcFramedCustomMurder"/> or <see cref="RpcAdvancedCustomMurder"/>.
/// </summary>
/// <param name="source">The killer.</param>
/// <param name="target">The player to murder.</param>
/// <param name="framed">The player to frame, if any.</param>
/// <param name="isIndirect">Should the kill be indirect.</param>
/// <param name="ignoreDefense">Should the kill ignore defense.</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>
@@ -178,6 +466,9 @@ public static class CustomMurderRpc
public static void CustomMurder(
this PlayerControl source,
PlayerControl target,
PlayerControl? framed,
bool isIndirect,
bool ignoreDefense,
MurderResultFlags resultFlags,
bool resetKillTimer = true,
bool createDeadBody = true,
@@ -191,8 +482,9 @@ public static class CustomMurderRpc
return;
}
if (resultFlags.HasFlag(MurderResultFlags.FailedProtected) ||
(resultFlags.HasFlag(MurderResultFlags.DecisionByHost) && target.protectedByGuardianId > -1))
if (!ignoreDefense && (resultFlags.HasFlag(MurderResultFlags.FailedProtected) ||
(resultFlags.HasFlag(MurderResultFlags.DecisionByHost) &&
target.protectedByGuardianId > -1)))
{
target.protectedByGuardianThisRound = true;
var flag = PlayerControl.LocalPlayer.Data.Role.Role == RoleTypes.GuardianAngel;
@@ -290,7 +582,141 @@ public static class CustomMurderRpc
source.CurrentOutfitType == PlayerOutfitType.Shapeshifted,
source.shapeshiftTargetPlayerId,
target.PlayerId);
source.MyPhysics.StartCoroutine(source.KillAnimations.RandomSnapshot().CoPerformCustomKill(source, target, createDeadBody, teleportMurderer));
source.MyPhysics.StartCoroutine(source.KillAnimations.RandomSnapshot().CoPerformCustomKill(source, target, framed, isIndirect, ignoreDefense, createDeadBody, teleportMurderer));
}
/// <summary>
/// Custom Murder method without networking. If you need a networked version, use <see cref="RpcCustomMurder(PlayerControl, PlayerControl, bool, bool, bool, bool, bool, bool)"/>.
/// </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;
if (resultFlags.HasFlag(MurderResultFlags.FailedError) || LobbyBehaviour.Instance)
{
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)
{
DataManager.Player.Stats.IncrementStat(StatID.Role_GuardianAngel_CrewmatesProtected);
AchievementManager.Instance.OnProtectACrewmate();
}
if (source.AmOwner || flag)
{
target.ShowFailedMurder();
if (resetKillTimer)
{
source.SetKillTimer(
CustomGameModeManager.ActiveMode != null
? CustomGameModeManager.ActiveMode.DefaultImpostorKillCooldown / 2f
: 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)
{
DataManager.Player.Stats.IncrementStat(
GameManager.Instance.IsHideAndSeek()
? StatID.HideAndSeek_ImpostorKills
: StatID.ImpostorKills);
if (source.CurrentOutfitType == PlayerOutfitType.Shapeshifted)
{
DataManager.Player.Stats.IncrementStat(StatID.Role_Shapeshifter_ShiftedKills);
}
if (Constants.ShouldPlaySfx() && playKillSound)
{
SoundManager.Instance.PlaySound(source.KillSfx, false, 0.8f);
}
if (resetKillTimer)
{
source.SetKillTimer(CustomGameModeManager.ActiveMode != null
? CustomGameModeManager.ActiveMode.DefaultImpostorKillCooldown
: GameOptionsManager.Instance.CurrentGameOptions.GetFloat(FloatOptionNames.KillCooldown));
}
}
UnityTelemetry.Instance.WriteMurder();
target.gameObject.layer = LayerMask.NameToLayer("Ghost");
if (target.AmOwner)
{
DataManager.Player.Stats.IncrementStat(StatID.TimesMurdered);
if (Minigame.Instance)
{
try
{
Minigame.Instance.Close();
Minigame.Instance.Close();
}
catch
{
// ignored
}
}
if (showKillAnim)
{
try
{
HudManager.Instance.KillOverlay.ShowKillAnimation(source.Data, target.Data);
}
catch (Exception e)
{
Error($"Error with kill animation: {e.ToString()}");
}
}
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.RandomSnapshot().CoPerformCustomKill(source, target, null, false, false, createDeadBody, teleportMurderer));
}
/// <summary>
@@ -299,6 +725,9 @@ public static class CustomMurderRpc
/// <param name="anim">The kill animation.</param>
/// <param name="source">The murderer.</param>
/// <param name="target">The murdered player.</param>
/// <param name="framed">The framed player, if any.</param>
/// <param name="isIndirect">Was the kill indirect.</param>
/// <param name="ignoreDefense">Would the kill ignore defense.</param>
/// <param name="createDeadBody">Should a dead body be created.</param>
/// <param name="teleportMurderer">Should the murder be teleported.</param>
/// <returns>Coroutine.</returns>
@@ -306,6 +735,9 @@ public static class CustomMurderRpc
this KillAnimation anim,
PlayerControl source,
PlayerControl target,
PlayerControl? framed,
bool isIndirect,
bool ignoreDefense,
bool createDeadBody = true,
bool teleportMurderer = true)
{
@@ -314,12 +746,13 @@ public static class CustomMurderRpc
yield break;
}
var cam = Camera.main?.GetComponent<FollowerCamera>();
var isParticipant = source.AmOwner || target.AmOwner;
var sourcePhys = source.MyPhysics;
var playerToLunge = framed ?? source;
var isParticipant = playerToLunge.AmOwner || target.AmOwner;
var sourcePhys = playerToLunge.MyPhysics;
if (teleportMurderer)
{
KillAnimation.SetMovement(source, false);
KillAnimation.SetMovement(playerToLunge, false);
}
KillAnimation.SetMovement(target, false);
@@ -373,7 +806,7 @@ public static class CustomMurderRpc
yield return source.MyPhysics.Animations.CoPlayCustomAnimation(anim.BlurAnim);
sourcePhys.Animations.PlayIdleAnimation();
source.NetTransform.SnapTo(target.transform.position);
KillAnimation.SetMovement(source, true);
KillAnimation.SetMovement(playerToLunge, true);
}
KillAnimation.SetMovement(target, true);
@@ -383,7 +816,7 @@ public static class CustomMurderRpc
deadBody.enabled = true;
}
var afterMurderEvent = new AfterMurderEvent(source, target, deadBody);
var afterMurderEvent = framed != null ? new AfterMurderEvent(source, target, framed, deadBody, isIndirect, ignoreDefense) : new AfterMurderEvent(source, target, deadBody, isIndirect, ignoreDefense);
MiraEventManager.InvokeEvent(afterMurderEvent);
if (!isParticipant)
+25
View File
@@ -40,6 +40,26 @@ public enum MiraRpc : uint
/// </summary>
ConfirmCustomMurder,
/// <summary>
/// Advanced Custom Murder RPC.
/// </summary>
AdvancedCustomMurder,
/// <summary>
/// Advanced Custom Murder RPC Confirmation.
/// </summary>
ConfirmAdvancedCustomMurder,
/// <summary>
/// Framed Custom Murder RPC.
/// </summary>
FramedCustomMurder,
/// <summary>
/// Framed Custom Murder RPC Confirmation.
/// </summary>
ConfirmFramedCustomMurder,
/// <summary>
/// Custom Game Over RPC.
/// </summary>
@@ -54,4 +74,9 @@ public enum MiraRpc : uint
/// Custom RPC to replace Among Us CastVote.
/// </summary>
CastVote,
/// <summary>
/// Custom RPC to sync the Gamemode option.
/// </summary>
SyncGamemodeOption,
}
@@ -2,6 +2,7 @@
using InnerNet;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Player;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.Roles;
@@ -32,6 +33,7 @@ internal static class AmongUsClientSyncPatch
ModdedOptionsManager.SyncAllOptions(clientData.Id);
CustomRoleManager.SyncAllRoleSettings(clientData.Id);
GameModeOption.RpcSyncGamemode(PlayerControl.LocalPlayer, GameModeOption.Value);
}
[HarmonyPostfix]
@@ -0,0 +1,20 @@
using BepInEx.Unity.IL2CPP.Utils.Collections;
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(IntroCutscene), nameof(IntroCutscene.CoBegin))]
internal static class BodyTypePatch
{
public static bool Prefix(IntroCutscene __instance, ref Il2CppSystem.Collections.IEnumerator __result)
{
if (CustomGameModeManager.ActiveMode?.ShowGameModeIntroCutscene == true)
{
__result = CustomGameModeManager.ActiveMode.IntroCutscene(__instance).WrapToIl2Cpp();
return false;
}
return true;
}
}
+48 -10
View File
@@ -1,14 +1,18 @@
/*
using HarmonyLib;
using InnerNet;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch]
public static class ConsolePatches
internal static class ConsolePatches
{
[HarmonyPrefix]
[HarmonyPatch(typeof(Console), nameof(Console.CanUse))]
[HarmonyPrefix, HarmonyPatch(typeof(Console), nameof(Console.CanUse))]
public static bool CanUsePatch(Console __instance, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] out bool canUse, [HarmonyArgument(2)] out bool couldUse)
{
if (AmongUsClient.Instance.GameState == InnerNetClient.GameStates.Started && ShipStatus.Instance)
{
if (CustomGameModeManager.ActiveMode != null && CustomGameModeManager.ActiveMode.CanUseConsole(__instance))
if (CustomGameModeManager.ActiveMode != null && CustomGameModeManager.ActiveMode.CanUseTasks(__instance))
{
var task = __instance.FindTask(pc.Object);
@@ -31,8 +35,7 @@ public static class ConsolePatches
return true;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(SystemConsole), nameof(SystemConsole.CanUse))]
[HarmonyPrefix, HarmonyPatch(typeof(SystemConsole), nameof(SystemConsole.CanUse))]
public static bool SystemCanUsePatch(SystemConsole __instance, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] out bool canUse, [HarmonyArgument(2)] out bool couldUse)
{
if (AmongUsClient.Instance.GameState == InnerNetClient.GameStates.Started && ShipStatus.Instance)
@@ -50,8 +53,7 @@ public static class ConsolePatches
return true;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(MapConsole), nameof(MapConsole.CanUse))]
[HarmonyPrefix, HarmonyPatch(typeof(MapConsole), nameof(MapConsole.CanUse))]
public static bool MapCanUsePatch(MapConsole __instance, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] out bool canUse, [HarmonyArgument(2)] out bool couldUse)
{
if (AmongUsClient.Instance.GameState == InnerNetClient.GameStates.Started && ShipStatus.Instance)
@@ -68,4 +70,40 @@ public static class ConsolePatches
canUse = couldUse = true;
return true;
}
}*/
[HarmonyPrefix, HarmonyPatch(typeof(MapConsole), nameof(MapConsole.Use))]
public static bool MapUsePatch(MapConsole __instance)
{
if (AmongUsClient.Instance.GameState == InnerNetClient.GameStates.Started && ShipStatus.Instance)
{
return CustomGameModeManager.ActiveMode == null ||
CustomGameModeManager.ActiveMode!.CanUseMapConsole(__instance);
}
return true;
}
[HarmonyPrefix, HarmonyPatch(typeof(SystemConsole), nameof(SystemConsole.Use))]
public static bool SystemUsePatch(SystemConsole __instance)
{
if (AmongUsClient.Instance.GameState == InnerNetClient.GameStates.Started && ShipStatus.Instance)
{
return CustomGameModeManager.ActiveMode == null ||
CustomGameModeManager.ActiveMode!.CanUseSystemConsole(__instance);
}
return true;
}
[HarmonyPrefix, HarmonyPatch(typeof(Console), nameof(Console.Use))]
public static bool ConsoleUsePatch(Console __instance)
{
if (AmongUsClient.Instance.GameState == InnerNetClient.GameStates.Started && ShipStatus.Instance)
{
return CustomGameModeManager.ActiveMode == null ||
CustomGameModeManager.ActiveMode!.CanUseTasks(__instance);
}
return true;
}
}
@@ -0,0 +1,18 @@
using HarmonyLib;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(CreateOptionsPicker), nameof(CreateOptionsPicker.SetGameMode))]
internal static class CreateOptionsPatch
{
public static bool Prefix(CreateOptionsPicker __instance, AmongUs.GameOptions.GameModes mode)
{
if (mode <= AmongUs.GameOptions.GameModes.SeekFools)
{
return true;
}
// TODO: finish this
return false;
}
}
+9 -6
View File
@@ -1,11 +1,14 @@
/*
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(DeadBody))]
public static class DeadBodyPatch
internal static class DeadBodyPatch
{
[HarmonyPrefix]
[HarmonyPatch(nameof(DeadBody.OnClick))]
[HarmonyPrefix, HarmonyPatch(nameof(DeadBody.OnClick))]
public static bool OnClickPatch(DeadBody __instance)
{
return CustomGameModeManager.ActiveMode == null || CustomGameModeManager.ActiveMode.CanReport(__instance);
return CustomGameModeManager.ActiveMode?.CanReport(__instance) == true;
}
}*/
}
+71 -13
View File
@@ -1,20 +1,78 @@
/*
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch]
public static class GameLogicPatches
internal static class GameLogicPatches
{
[HarmonyPrefix, HarmonyPatch(typeof(LogicGameFlowNormal), nameof(LogicGameFlowNormal.CheckEndCriteria))]
public static bool EndCritPatch(LogicGameFlowNormal __instance)
[HarmonyPrefix, HarmonyPatch(typeof(GameManager), nameof(GameManager.DidHumansWin))]
public static bool DidHumansWin(GameOverReason reason, ref bool __result)
{
var runOriginal = true;
CustomGameModeManager.ActiveMode?.CheckGameEnd(out runOriginal, __instance);
return runOriginal;
__result = reason == GameOverReason.CrewmatesByTask || reason == GameOverReason.CrewmatesByVote ||
reason == GameOverReason.ImpostorDisconnect || reason == GameOverReason.HideAndSeek_CrewmatesByTimer;
return false;
}
[HarmonyPrefix, HarmonyPatch(typeof(LogicRoleSelectionNormal), nameof(LogicRoleSelectionNormal.AssignRolesFromList))]
public static bool AssignRolesPatch(LogicRoleSelectionNormal __instance)
[HarmonyPrefix, HarmonyPatch(typeof(GameManager), nameof(GameManager.DidImpostorsWin))]
public static bool DidImpostorsWin(GameOverReason reason, ref bool __result)
{
var runOriginal = true;
CustomGameModeManager.ActiveMode?.AssignRoles(out runOriginal, __instance);
return runOriginal;
__result = reason == GameOverReason.ImpostorsByKill || reason == GameOverReason.ImpostorsBySabotage ||
reason == GameOverReason.ImpostorsByVote || reason == GameOverReason.HideAndSeek_ImpostorsByKills ||
reason == GameOverReason.CrewmateDisconnect;
return false;
}
}*/
[HarmonyPrefix, HarmonyPatch(typeof(NormalGameManager), nameof(NormalGameManager.GetBodyType))]
public static bool BodyTypePatch(NormalGameManager __instance, PlayerControl player, ref PlayerBodyTypes __result)
{
if (CustomGameModeManager.ActiveMode == null || !CustomGameModeManager.ActiveMode.GameModeBodyTypeOverride)
{
return true;
}
__result = CustomGameModeManager.ActiveMode.GetBodyType(player);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(LogicGameFlowNormal), nameof(LogicGameFlowNormal.CheckEndCriteria))]
public static bool EndGamePatch(LogicGameFlowNormal __instance)
{
if (TutorialManager.InstanceExists)
{
return true;
}
if (!AmongUsClient.Instance.AmHost)
{
return false;
}
if (!GameData.Instance)
{
return false;
}
if (CustomGameModeManager.ActiveMode != null)
{
CustomGameModeManager.ActiveMode.CheckGameEnd(out var runOriginal, __instance);
if (!runOriginal)
{
return false;
}
}
return true;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(LogicGameFlowNormal), nameof(LogicGameFlowNormal.IsGameOverDueToDeath))]
public static void IsGameOverDueToDeathPatch(LogicGameFlowNormal __instance, ref bool __result)
{
if (CustomGameModeManager.IsActiveGameMode<HideAndSeekMode>())
{
__result = false;
}
}
}
@@ -0,0 +1,56 @@
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(GameManager))]
internal static class GameManagerPatches
{
[HarmonyPrefix, HarmonyPatch(nameof(GameManager.OnPlayerDeath))]
public static bool OnDeathPrefix([HarmonyArgument(0)] PlayerControl player, [HarmonyArgument(1)] bool assignGhostRole)
{
if (CustomGameModeManager.ActiveMode != null)
{
CustomGameModeManager.ActiveMode.OnPlayerDeath(player, assignGhostRole);
return false;
}
return true;
}
[HarmonyPrefix, HarmonyPatch(nameof(GameManager.ShowCrewmatesKilled))]
public static bool ShowCrewmatesKilledPrefix(ref bool __result)
{
if (CustomGameModeManager.ActiveMode != null)
{
__result = CustomGameModeManager.ActiveMode is HideAndSeekMode;
return false;
}
return true;
}
[HarmonyPatch(typeof(NormalGameManager), nameof(NormalGameManager.GetMapOptions))]
[HarmonyPrefix]
public static bool GetMapOptions(ref MapOptions __result)
{
if (CustomGameModeManager.ActiveMode == null)
{
return true;
}
__result = CustomGameModeManager.ActiveMode.GetMapOptions();
return false;
}
}
[HarmonyPatch(typeof(GameStartManager))]
internal static class GameStartManagerPatches
{
[HarmonyPrefix, HarmonyPatch(nameof(GameStartManager.Start))]
public static void StartPatch(GameStartManager __instance)
{
if (MiraApiPlugin.IsDevBuild)
{
__instance.MinPlayers = 1;
}
}
}
+62
View File
@@ -0,0 +1,62 @@
using System.Collections;
using HarmonyLib;
using Il2CppSystem;
using MiraAPI.GameModes;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(HudManager))]
internal static class HudPatches
{
[HarmonyPostfix, HarmonyPatch(nameof(HudManager.Update))]
public static void HudUpdatePatch(HudManager __instance)
{
if (GameManager.Instance != null && GameManager.Instance.GameHasStarted &&
CustomGameModeManager.ActiveMode != null)
{
CustomGameModeManager.ActiveMode.HudUpdate(__instance);
}
}
[HarmonyPatch(typeof(HudManager), nameof(HudManager.Start))]
[HarmonyPostfix]
public static void PostHudStart(HudManager __instance)
{
Coroutines.Start(CoPostHudStart(__instance));
}
private static IEnumerator CoPostHudStart(HudManager instance)
{
yield return new WaitUntil((Func<bool>)(() => GameManager.Instance != null));
if (GameManager.Instance.IsHideAndSeek())
yield return null;
var infoPane = instance.gameObject.transform.FindChild("LobbyInfoPane");
var aspect = infoPane.gameObject.transform.Find("AspectSize");
var modeLabel = aspect!.Find("ModeLabel");
var modeValue = aspect.Find("ModeValue");
var modelText = modeLabel!.Find("Text_TMP").gameObject;
var modelTextClone = Object.Instantiate(modelText, modeLabel);
Object.Destroy(modelTextClone.GetComponent<TextTranslatorTMP>());
modelTextClone.GetComponent<TextMeshPro>().text = "Gamemode";
var gmText = modeValue!.Find("GameModeText").gameObject;
var gmTextClone = Object.Instantiate(gmText, modeValue);
gmText.SetActive(false);
modelText.SetActive(false);
_text = gmTextClone.GetComponent<TextMeshPro>();
_text.text = CustomGameModeManager.ActiveMode != null ? $"<color=#{CustomGameModeManager.ActiveMode.Color.ToHtmlStringRGBA()}>{CustomGameModeManager.ActiveMode.Name}</color>" : "Classic";
CustomGameModeManager.ActiveMode?.HudStart(instance);
}
private static TextMeshPro? _text;
internal static void SetGameModeText(string text)
{
if (_text != null)
_text.text = text;
}
}
@@ -1,9 +1,13 @@
/*
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
/// <summary>
/// Allow Impostors to kill each other if can kill is enabled in gamemode or friendly fire is toggled on
/// Allow Impostors to kill each other if can kill is enabled in gamemode or friendly fire is toggled on.
/// </summary>
[HarmonyPatch(typeof(ImpostorRole), "IsValidTarget")]
public static class ImpostorTargetPatch
internal static class ImpostorTargetPatch
{
public static bool Prefix(ImpostorRole __instance, [HarmonyArgument(0)] NetworkedPlayerInfo target, ref bool __result)
{
@@ -16,9 +20,8 @@ public static class ImpostorTargetPatch
}
__result = target is { Disconnected: false, IsDead: false } &&
target.PlayerId != __instance.Player.PlayerId && !(target.Role == null) &&
!(target.Object == null) && !target.Object.inVent && !target.Object.inMovingPlat;
target.PlayerId != __instance.Player.PlayerId && target.Role != null &&
target.Object != null && !target.Object.inVent && !target.Object.inMovingPlat;
return false;
}
}*/
}
@@ -0,0 +1,20 @@
using BepInEx.Unity.IL2CPP.Utils.Collections;
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(IntroCutscene), nameof(IntroCutscene.CoBegin))]
internal static class IntroCutscenePatch
{
public static bool Prefix(IntroCutscene __instance, ref Il2CppSystem.Collections.IEnumerator __result)
{
if (CustomGameModeManager.ActiveMode?.ShowGameModeIntroCutscene == true)
{
__result = CustomGameModeManager.ActiveMode.IntroCutscene(__instance).WrapToIl2Cpp();
return false;
}
return true;
}
}
@@ -1,9 +1,12 @@
/*
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(MapBehaviour))]
public static class MapBehaviourPatch
internal static class MapBehaviourPatch
{
[HarmonyPrefix]
[HarmonyPatch(nameof(MapBehaviour.ShowSabotageMap))]
[HarmonyPrefix, HarmonyPatch(nameof(MapBehaviour.ShowSabotageMap))]
public static bool ShowSabotagePatch(MapBehaviour __instance)
{
var shouldShow = CustomGameModeManager.ActiveMode?.ShouldShowSabotageMap(__instance);
@@ -15,4 +18,4 @@ public static class MapBehaviourPatch
return true;
}
}*/
}
@@ -0,0 +1,19 @@
/*
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(NormalGameManager))]
internal static class NormalGameManagerPatches
{
[HarmonyPrefix, HarmonyPatch(nameof(NormalGameManager.IsNormal))]
public static void IsNormal(ref bool __result)
{
if (CustomGameModeManager.ActiveMode != null)
{
__result = !CustomGameModeManager.ActiveMode.IsHideAndSeek;
}
}
}
*/
-11
View File
@@ -1,11 +0,0 @@
/*
[HarmonyPatch(typeof(KillAnimation))]
public static class OnDeathPatch
{
[HarmonyPostfix]
[HarmonyPatch(nameof(KillAnimation.CoPerformKill))]
public static void OnDeathPostfix([HarmonyArgument(0)] PlayerControl source, [HarmonyArgument(1)] PlayerControl target)
{
CustomGameModeManager.ActiveMode?.OnDeath(target);
}
}*/
@@ -0,0 +1,17 @@
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(ProgressTracker), nameof(ProgressTracker.Start))]
internal static class ProgressTrackerPatch
{
public static bool Prefix(ProgressTracker __instance)
{
if (CustomGameModeManager.ActiveMode != null && !CustomGameModeManager.ActiveMode.ShowTaskBar)
{
__instance.gameObject.SetActive(false);
return false;
}
return true;
}
}
@@ -0,0 +1,17 @@
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(TaskPanelBehaviour), nameof(TaskPanelBehaviour.Update))]
internal static class TaskPanelPatch
{
public static bool Prefix(TaskPanelBehaviour __instance)
{
if (CustomGameModeManager.ActiveMode != null)
{
CustomGameModeManager.ActiveMode.UpdateTaskPanel(__instance);
return false;
}
return true;
}
}
-47
View File
@@ -1,47 +0,0 @@
/*
[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)
{
if (CustomGameModeManager.ActiveMode?.CanVent(__instance, pc) == false)
{
return couldUse = canUse = false;
}
if (pc.Role is not ICustomRole role)
{
return couldUse = canUse = true;
}
var num = float.MaxValue;
var @object = pc.Object;
var customRoleUsable = role.CanUseVent;
canUse = couldUse = customRoleUsable && !pc.IsDead && (@object.CanMove || @object.inVent);
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;
return false;
}
[HarmonyPrefix]
[HarmonyPatch(nameof(Vent.SetOutline))]
public static bool SetOutlinePatch(Vent __instance, [HarmonyArgument(0)] bool on, [HarmonyArgument(1)] bool mainTarget)
{
var color = PlayerControl.LocalPlayer.Data.Role is ICustomRole role
? role.RoleColor : PlayerControl.LocalPlayer.Data.Role.IsImpostor ? Palette.ImpostorRed : Palette.CrewmateBlue;
__instance.myRend.material.SetFloat(ShaderID.Outline, on ? 1 : 0);
__instance.myRend.material.SetColor(ShaderID.OutlineColor, color);
__instance.myRend.material.SetColor(ShaderID.AddColor, mainTarget ? color : Color.clear);
return false;
}
}*/
+27
View File
@@ -0,0 +1,27 @@
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnGameEnd))]
internal static class WinnersPatch
{
[HarmonyPostfix]
public static void ShowWinningScreen()
{
if (CustomGameModeManager.ActiveMode is null or ClassicMode)
return;
var winners = CustomGameModeManager.ActiveMode.CalculateWinners();
if (winners is null)
return;
EndGameResult.CachedWinners.Clear();
foreach (var data in winners)
{
EndGameResult.CachedWinners.Add(new(data));
}
}
}
-11
View File
@@ -112,17 +112,6 @@ public static class HudManagerPatches
}
}
/*
/// <summary>
/// Trigger hudstart on current custom gamemode
/// </summary>
[HarmonyPostfix]
[HarmonyPatch(nameof(HudManager.OnGameStart))]
public static void GameStartPatch(HudManager __instance)
{
CustomGameModeManager.ActiveMode?.HudStart(__instance);
}*/
/// <summary>
/// Create custom buttons and arrange them on the hud.
/// </summary>
+6 -2
View File
@@ -3,6 +3,7 @@ using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
using MiraAPI.GameModes;
using MiraAPI.Roles;
using MiraAPI.Utilities;
@@ -29,6 +30,11 @@ public static class IntroCutscenePatches
{
var @event = new IntroBeginEvent(__instance);
MiraEventManager.InvokeEvent(@event);
if (CustomGameModeManager.ActiveMode != null)
{
CustomGameModeManager.ActiveMode.Initialize();
}
}
[HarmonyPatch]
@@ -121,8 +127,6 @@ public static class IntroCutscenePatches
introCutscene = __instance.Cast<IntroCutscene>();
}
Info("IntroCutscene ended");
MiraEventManager.InvokeEvent(new IntroEndEvent(introCutscene));
var @event = new BeforeRoundStartEvent(true);
@@ -7,6 +7,8 @@ using Reactor.Utilities.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
+454 -21
View File
@@ -1,8 +1,11 @@
using System;
using System;
using System.Collections;
using System.Linq;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.Presets;
@@ -13,6 +16,7 @@ using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.ProBuilder;
using UnityEngine.UI;
using Object = UnityEngine.Object;
@@ -21,6 +25,15 @@ namespace MiraAPI.Patches.Options;
[HarmonyPatch(typeof(GameOptionsMenu))]
internal static class GameOptionsMenuPatch
{
private static List<CategoryHeaderMasked> _vanillaHeaders = new();
private static List<OptionBehaviour> _vanillaOptions = new();
private static List<OptionBehaviour> _mainOptions = new();
private static System.Collections.Generic.Dictionary<AbstractGameMode, System.Collections.Generic.List<AbstractOptionGroup>> _gameModeGroups = new();
private static System.Collections.Generic.Dictionary<AbstractGameMode, System.Collections.Generic.List<OptionBehaviour>> _gameModeOptions = new();
private static System.Collections.Generic.Dictionary<AbstractGameMode, System.Collections.Generic.List<CategoryHeaderMasked>> _gameModeHeaders = new();
private static TextMeshPro _gamemodeDescription = null!;
private static SpriteRenderer _modIcon = null!;
[HarmonyPrefix]
[HarmonyPatch(nameof(GameOptionsMenu.Initialize))]
// ReSharper disable once InconsistentNaming
@@ -41,15 +54,10 @@ internal static class GameOptionsMenuPatch
var mapNameSetting = GameManager.Instance.GameSettingsList.MapNameSetting;
__instance.MapPicker.SetUpFromData(mapNameSetting, 20);
__instance.Children.Add(__instance.MapPicker);
__instance.CreateSettings();
foreach (var optionBehaviour in __instance.Children)
CreateSettings(__instance, container);
if (CustomGameModeManager.ActiveMode != null)
{
if (AmongUsClient.Instance && !AmongUsClient.Instance.AmHost)
{
optionBehaviour.SetAsPlayer();
}
optionBehaviour.OnValueChanged = new Action<OptionBehaviour>(__instance.ValueChanged);
ToggleGamemodeOptions(CustomGameModeManager.ActiveMode, __instance);
}
}
else
@@ -69,6 +77,314 @@ internal static class GameOptionsMenuPatch
return false;
}
public static float AdditionalVanillaScrollNum;
internal static void ToggleGamemodeOptions(AbstractGameMode gameMode, GameOptionsMenu instance)
{
float num = -1.217f;
instance.Children.Clear();
foreach (var opt in _mainOptions)
{
instance.Children.Add(opt);
}
var icon = gameMode.Icon;
if (icon != null)
{
_modIcon.gameObject.SetActive(true);
_gamemodeDescription.transform.localPosition = new Vector3(0.3f, 0, -0.01f);
_gamemodeDescription.horizontalAlignment = HorizontalAlignmentOptions.Left;
var texture = icon.LoadAsset().texture;
var scale = Mathf.Min(128f / texture.width, 128f / texture.height);
var newSprite = Sprite.Create(
texture,
new Rect(0, 0, texture.width, texture.height),
Vector2.one / 2,
100f / scale
);
_modIcon.sprite = newSprite;
_modIcon.drawMode = SpriteDrawMode.Simple;
}
else
{
_gamemodeDescription.transform.localPosition = new Vector3(0f, 0, -0.01f);
_gamemodeDescription.horizontalAlignment = HorizontalAlignmentOptions.Center;
_modIcon.gameObject.SetActive(false);
}
_gamemodeDescription.text = gameMode.Description;
if (gameMode.ShowNormalGameSettings)
{
foreach (var opt in _vanillaHeaders)
{
num -= 0.63f;
opt.gameObject.SetActive(true);
}
foreach (var opt in _vanillaOptions)
{
opt.gameObject.SetActive(true);
instance.Children.Add(opt);
num -= 0.45f;
}
}
else
{
foreach (var opt in _vanillaHeaders)
{
opt.gameObject.SetActive(false);
}
foreach (var opt in _vanillaOptions)
{
opt.gameObject.SetActive(false);
}
}
foreach (var pair in _gameModeGroups)
{
if (pair.Value.Count != 0)
{
if (gameMode == pair.Key)
{
foreach (var opt in _gameModeHeaders[gameMode])
{
num -= 0.63f;
opt.gameObject.SetActive(true);
}
foreach (var opt in _gameModeOptions[gameMode])
{
opt.gameObject.SetActive(true);
instance.Children.Add(opt);
num -= 0.45f;
}
}
else
{
foreach (var opt in _gameModeHeaders[pair.Key])
{
opt.gameObject.SetActive(false);
}
foreach (var opt in _gameModeOptions[pair.Key])
{
opt.gameObject.SetActive(false);
}
}
}
}
instance.ControllerSelectable.Clear();
foreach (var obj in instance.scrollBar.GetComponentsInChildren<UiElement>())
{
if (obj.gameObject.activeSelf)
{
instance.ControllerSelectable.Add(obj);
}
}
instance.scrollBar.SetYBoundsMax(-num - 1.65f);
}
private static void CreateSettings(GameOptionsMenu instance, Transform container)
{
float num = 0.713f;
_vanillaHeaders.Clear();
_vanillaOptions.Clear();
_mainOptions.Clear();
_gameModeHeaders.Clear();
_gameModeOptions.Clear();
_gameModeGroups.Clear();
CategoryHeaderMasked gmCategory = Object.Instantiate(instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, container);
gmCategory.SetHeader(GameModeOption.CustomName, 20);
gmCategory.transform.localScale = Vector3.one * 0.63f;
gmCategory.transform.localPosition = new Vector3(-0.903f, num, -2f);
GameModeOption.OptionBehaviour = Object.Instantiate(
instance.stringOptionOrigin,
Vector3.zero,
Quaternion.identity,
container);
num -= 0.63f;
GameModeOption.OptionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f);
GameModeOption.OptionBehaviour.SetClickMask(instance.ButtonClickMask);
StringGameSetting setting = ScriptableObject.CreateInstance<StringGameSetting>();
setting.Type = OptionTypes.MultipleChoice;
setting.Title = GameModeOption.GamemodeName;
setting.Index = GameModeOption._lastValue;
setting.Values = new Il2CppStructArray<StringNames>([GameModeOption.Values[0]]);
GameModeOption.OptionBehaviour.SetUpFromData(setting, 20);
GameModeOption.Set(GameModeOption._lastValue);
GameModeOption.OptionBehaviour.TitleText.fontSize = 3;
instance.Children.Add(GameModeOption.OptionBehaviour);
foreach (var optionBehaviour in instance.Children)
{
_mainOptions.Add(optionBehaviour);
}
for (var i = 1; i < GameModeOption.Values.Count; i++)
{
GameModeOption.OptionBehaviour.Values =
(Il2CppStructArray<StringNames>)GameModeOption.OptionBehaviour.Values.Add(
GameModeOption.Values.ElementAt(i).Value);
}
var modeInfoHolder = new GameObject("GamemodeInfo")
{
transform =
{
parent = container,
localPosition = new Vector3(1.2f, -0.675f, 1),
localScale = Vector3.one,
},
layer = container.gameObject.layer,
}.transform;
var gamemodeBg = Object.Instantiate(GameModeOption.OptionBehaviour.transform.GetChild(0).gameObject, Vector3.zero, Quaternion.identity, modeInfoHolder);
gamemodeBg.transform.localPosition = Vector3.zero;
gamemodeBg.transform.localScale = new Vector3(1.35f, 0.85f, 1);
gamemodeBg.name = "Background";
var modIconObj = new GameObject("ModIcon")
{
transform =
{
parent = modeInfoHolder,
localPosition = new Vector3(-1.75f, 0, -0.1f),
localScale = new Vector3(0.45f, 0.45f, 1),
},
layer = gamemodeBg.layer,
};
_modIcon = modIconObj.AddComponent<SpriteRenderer>();
_modIcon.sprite = MiraAssets.BlankSprite.LoadAsset();
_modIcon.material = gamemodeBg.gameObject.GetComponent<SpriteRenderer>().material;
var gamemodeTextObj = Object.Instantiate(GameModeOption.OptionBehaviour.transform.GetChild(1).gameObject, Vector3.zero, Quaternion.identity, modeInfoHolder);
gamemodeTextObj.transform.localPosition = new Vector3(0.3f, 0, -0.01f);
gamemodeTextObj.transform.localScale = new Vector3(2.12f, 2.12f, 1);
_gamemodeDescription = gamemodeTextObj.GetComponentInChildren<TextMeshPro>();
_gamemodeDescription.fontSizeMin = 0.65f;
_gamemodeDescription.fontSizeMax = 0.9f;
_gamemodeDescription.alignment = TextAlignmentOptions.Left;
num -= 1.3f;
AdditionalVanillaScrollNum = 0f;
foreach (RulesCategory rulesCategory in GameManager.Instance.GameSettingsList.AllCategories)
{
CategoryHeaderMasked categoryHeaderMasked = Object.Instantiate<CategoryHeaderMasked>(
instance.categoryHeaderOrigin,
Vector3.zero,
Quaternion.identity,
container);
categoryHeaderMasked.SetHeader(rulesCategory.CategoryName, 20);
categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f;
categoryHeaderMasked.transform.localPosition = new Vector3(-0.903f, num, -2f);
_vanillaHeaders.Add(categoryHeaderMasked);
num -= 0.63f;
AdditionalVanillaScrollNum -= 0.63f;
foreach (BaseGameSetting baseGameSetting in rulesCategory.AllGameSettings)
{
switch (baseGameSetting.Type)
{
case OptionTypes.Checkbox:
{
OptionBehaviour optionBehaviour = Object.Instantiate<ToggleOption>(
instance.checkboxOrigin,
Vector3.zero,
Quaternion.identity,
container);
optionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f);
optionBehaviour.SetClickMask(instance.ButtonClickMask);
optionBehaviour.SetUpFromData(baseGameSetting, 20);
_vanillaOptions.Add(optionBehaviour);
break;
}
case OptionTypes.String:
{
OptionBehaviour optionBehaviour = Object.Instantiate<StringOption>(
instance.stringOptionOrigin,
Vector3.zero,
Quaternion.identity,
container);
optionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f);
optionBehaviour.SetClickMask(instance.ButtonClickMask);
optionBehaviour.SetUpFromData(baseGameSetting, 20);
_vanillaOptions.Add(optionBehaviour);
break;
}
case OptionTypes.Float:
case OptionTypes.Int:
{
OptionBehaviour optionBehaviour = Object.Instantiate<NumberOption>(
instance.numberOptionOrigin,
Vector3.zero,
Quaternion.identity,
container);
optionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f);
optionBehaviour.SetClickMask(instance.ButtonClickMask);
optionBehaviour.SetUpFromData(baseGameSetting, 20);
_vanillaOptions.Add(optionBehaviour);
break;
}
case OptionTypes.Player:
{
OptionBehaviour optionBehaviour = Object.Instantiate<PlayerOption>(
instance.playerOptionOrigin,
Vector3.zero,
Quaternion.identity,
container);
optionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f);
optionBehaviour.SetClickMask(instance.ButtonClickMask);
optionBehaviour.SetUpFromData(baseGameSetting, 20);
_vanillaOptions.Add(optionBehaviour);
break;
}
}
num -= 0.45f;
AdditionalVanillaScrollNum -= 0.45f;
}
}
foreach (var optionBehaviour in _vanillaOptions)
{
if (AmongUsClient.Instance && !AmongUsClient.Instance.AmHost)
{
optionBehaviour.SetAsPlayer();
}
instance.Children.Add(optionBehaviour);
}
foreach (var optionBehaviour in instance.Children)
{
optionBehaviour.OnValueChanged = new Action<OptionBehaviour>(instance.ValueChanged);
}
foreach (var mode in CustomGameModeManager.IdToModeMap.Values)
{
var filteredGroups =
ModdedOptionsManager.GameModeOptionGroups
.Where(x => x.Key == mode.GetType()).Select(y => y.Value).SelectMany(y => y) ?? [];
_gameModeGroups.Add(mode, filteredGroups.ToList());
var optionBehaviours = new System.Collections.Generic.List<OptionBehaviour>();
var categoryHeaders = new System.Collections.Generic.List<CategoryHeaderMasked>();
var newNum = mode.ShowNormalGameSettings ? num : num - AdditionalVanillaScrollNum;
foreach (var group in filteredGroups)
{
CreateGroup(instance, group, container, ref newNum, ref optionBehaviours, ref categoryHeaders);
group.Ready = true;
}
_gameModeHeaders.Add(mode, categoryHeaders);
_gameModeOptions.Add(mode, optionBehaviours);
}
instance.ControllerSelectable.Clear();
foreach (var obj in instance.scrollBar.GetComponentsInChildren<UiElement>())
{
instance.ControllerSelectable.Add(obj);
}
instance.scrollBar.SetYBoundsMax(-num - 1.65f);
}
[HarmonyPostfix]
[HarmonyPatch(nameof(GameOptionsMenu.OnEnable))]
public static void OpenPatch(GameOptionsMenu __instance)
@@ -88,15 +404,14 @@ internal static class GameOptionsMenuPatch
// ReSharper disable once InconsistentNaming
public static void UpdatePatch(GameOptionsMenu __instance)
{
if (MenuState.Instance.CurrentModIdx == 0)
{
return;
}
var num = 2.1f;
if (MenuState.Instance.CurrentModIdx == 0 && _gameModeGroups.Count <= 0) return;
var num = MenuState.Instance.CurrentMenu == MenuCategory.Game ? -1.217f : 2.1f;
switch (MenuState.Instance.CurrentMenu)
{
case MenuCategory.Game:
GamemodeOptionsUpdate(ref num);
break;
case MenuCategory.Modifiers:
ModifiersUpdate(ref num);
break;
@@ -122,8 +437,100 @@ internal static class GameOptionsMenuPatch
__instance.scrollBar.SetYBoundsMax(-num - 1.65f);
}
private static void CreateGroup(GameOptionsMenu menu, AbstractOptionGroup group, Transform container, ref float num, ref System.Collections.Generic.List<OptionBehaviour> optionBehaviours, ref System.Collections.Generic.List<CategoryHeaderMasked> categoryHeaders)
{
var categoryHeaderMasked = Object.Instantiate(
menu.categoryHeaderOrigin,
Vector3.zero,
Quaternion.identity,
container);
categoryHeaderMasked.transform.localPosition = new Vector3(-0.903f, num + 1, -2f);
categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f;
categoryHeaders.Add(categoryHeaderMasked);
private static void UpdateGroup(AbstractOptionGroup? group, ref float num)
num -= 0.58f;
categoryHeaderMasked.SetHeader(CustomStringName.CreateAndRegister(group.GroupName), 20);
categoryHeaderMasked.Background.color = group.GroupColor;
categoryHeaderMasked.Divider.color = group.GroupColor;
categoryHeaderMasked.Title.color = group.GroupColor.Equals(MiraApiPlugin.DefaultHeaderColor)
? Color.white
: group.GroupColor.FindAlternateColor();
categoryHeaderMasked.Background.sprite = MiraAssets.CategoryHeader.LoadAsset();
categoryHeaderMasked.Background.sprite.texture.filterMode = FilterMode.Bilinear;
categoryHeaderMasked.Background.sprite.texture.wrapMode = TextureWrapMode.Clamp;
categoryHeaderMasked.Background.transform.localPosition = new Vector3(0.5f, -0.1833f, 0);
categoryHeaderMasked.Background.size = new Vector2(
categoryHeaderMasked.Background.size.x + 1.5f,
categoryHeaderMasked.Background.size.y);
categoryHeaderMasked.gameObject.SetActive(true);
group.Header = categoryHeaderMasked;
categoryHeaderMasked.transform.localPosition += Vector3.down;
var options = group.Options.Select(opt => opt.CreateOption(
menu.checkboxOrigin,
menu.numberOptionOrigin,
menu.stringOptionOrigin,
menu.playerOptionOrigin,
container));
foreach (var newOpt in options)
{
newOpt.SetClickMask(menu.ButtonClickMask);
SpriteRenderer[] componentsInChildren = newOpt.GetComponentsInChildren<SpriteRenderer>(true);
foreach (var renderer in componentsInChildren)
{
if (group.GroupColor != MiraApiPlugin.DefaultHeaderColor)
{
renderer.color = group.GroupColor.FindAlternateColor();
if (renderer.transform.parent.TryGetComponent<GameOptionButton>(out var btn))
{
btn.interactableColor = group.GroupColor.FindAlternateColor();
btn.interactableHoveredColor = Color.white;
}
}
renderer.material.SetInt(PlayerMaterial.MaskLayer, 20);
}
foreach (var textMeshPro in newOpt.GetComponentsInChildren<TextMeshPro>(true))
{
if (group.GroupColor != MiraApiPlugin.DefaultHeaderColor)
{
textMeshPro.color = group.GroupColor;
}
textMeshPro.fontMaterial.SetFloat(ShaderID.StencilComp, 3f);
textMeshPro.fontMaterial.SetFloat(ShaderID.Stencil, 20);
}
if (newOpt is ToggleOption toggle)
{
toggle.CheckMark.sprite = MiraAssets.Checkmark.LoadAsset();
toggle.CheckMark.color = group.GroupColor != MiraApiPlugin.DefaultHeaderColor
? group.GroupColor
: MiraAssets.AcceptedTeal;
var rend = toggle.CheckMark.transform.parent.FindChild("ActiveSprite")
.GetComponent<SpriteRenderer>();
rend.sprite = MiraAssets.CheckmarkBox.LoadAsset();
rend.color = group.GroupColor != MiraApiPlugin.DefaultHeaderColor
? group.GroupColor
: MiraAssets.AcceptedTeal;
}
optionBehaviours.Add(newOpt);
newOpt.transform.localPosition = new Vector3(0.952f, num, -2f);
num -= 0.45f;
newOpt.Initialize();
newOpt.gameObject.SetActive(true);
}
}
internal static void UpdateGroup(AbstractOptionGroup? group, ref float num)
{
if (group is null || !group.Ready || group.Options.Count == 0 || group.Header is null)
{
@@ -132,18 +539,24 @@ internal static class GameOptionsMenuPatch
if (!group.GroupVisible.Invoke())
{
group.Header.gameObject.SetActive(false);
if (group.Header != null && group.Header.gameObject != null)
group.Header.gameObject.SetActive(false);
foreach (var option in group.Options)
{
option.OptionBehaviour?.gameObject.SetActive(false);
if (option.OptionBehaviour != null && option.OptionBehaviour.gameObject != null)
option.OptionBehaviour?.gameObject.SetActive(false);
}
return;
}
group.Header.gameObject.SetActive(true);
group.Header.transform.localScale = Vector3.one * 0.63f;
group.Header.transform.localPosition = new Vector3(-0.903f, num, -2f);
if (group.Header != null)
{
if (group.Header.gameObject != null)
group.Header.gameObject.SetActive(true);
group.Header.transform.localScale = Vector3.one * 0.63f;
group.Header.transform.localPosition = new Vector3(-0.903f, num, -2f);
}
num -= 0.58f;
@@ -175,6 +588,26 @@ internal static class GameOptionsMenuPatch
}
}
private static void GamemodeOptionsUpdate(ref float num)
{
var mode = CustomGameModeManager.ActiveMode;
if (mode == null) return;
if (mode.ShowNormalGameSettings)
{
num += AdditionalVanillaScrollNum;
}
if (!_gameModeGroups.TryGetValue(mode, out var groups) || groups.Count == 0)
{
return;
}
foreach (var group in groups)
{
UpdateGroup(group, ref num);
}
}
private static void CustomMenuOneUpdate(ref float num)
{
var groups = MenuState.Instance.CurrentMod.InternalOptionGroups
@@ -1,17 +1,4 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.PluginLoading;
using MiraAPI.Presets;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using static UnityEngine.UI.Button;
using Object = UnityEngine.Object;
using HarmonyLib;
namespace MiraAPI.Patches.Options;
@@ -1,8 +1,9 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using AmongUs.GameOptions;
using HarmonyLib;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.PluginLoading;
@@ -23,14 +24,51 @@ public static class LobbyViewPanePatches
{
private static int SelectedModIdx { get; set; }
private static MiraPluginInfo[] Plugins => MiraPluginManager.Instance.RegisteredPluginsWithOptions;
private static MiraPluginInfo? SelectedMod => SelectedModIdx == 0
? null
: MiraPluginManager.Instance.RegisteredPluginsWithOptions[SelectedModIdx - 1];
: Plugins[SelectedModIdx - 1];
private static PassiveButton? ModifiersTabButton { get; set; }
private static StringNames ModifiersTabName { get; } = CustomStringName.CreateAndRegister("ModifiersTab");
private static AbstractGameMode? GetCustomGamemode()
{
if (!CustomGameModeManager.IsClassic() && !CustomGameModeManager.IsHideNSeek())
{
return CustomGameModeManager.ActiveMode;
}
return null;
}
private static IEnumerable<AbstractOptionGroup>? GetCustomGamemodeOptions()
{
if (CustomGameModeManager.ActiveMode == null)
{
return null;
}
if (!CustomGameModeManager.IsClassic() && !CustomGameModeManager.IsHideNSeek())
{
var plugin = CustomGameModeManager.FindParentMod(CustomGameModeManager.ActiveMode);
return plugin?.InternalOptionGroups
.Where(x => x.OptionableType?.IsAssignableTo(typeof(AbstractGameMode)) == true && x.GroupVisible());
}
return null;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(LobbyViewSettingsPane), nameof(LobbyViewSettingsPane.OnEnable))]
public static void OnEnable(LobbyViewSettingsPane __instance)
{
Refresh(__instance);
}
[HarmonyPostfix]
[HarmonyPatch(nameof(LobbyViewSettingsPane.Awake))]
public static void AwakePatch(LobbyViewSettingsPane __instance)
@@ -75,7 +113,7 @@ public static class LobbyViewPanePatches
(UnityAction)(() =>
{
SelectedModIdx += 1;
if (SelectedModIdx > MiraPluginManager.Instance.RegisteredPluginsWithOptions.Length)
if (SelectedModIdx > Plugins.Length)
{
SelectedModIdx = 0;
}
@@ -99,7 +137,7 @@ public static class LobbyViewPanePatches
SelectedModIdx -= 1;
if (SelectedModIdx < 0)
{
SelectedModIdx = MiraPluginManager.Instance.RegisteredPluginsWithOptions.Length;
SelectedModIdx = Plugins.Length;
}
Refresh(__instance);
@@ -108,8 +146,25 @@ public static class LobbyViewPanePatches
private static void Refresh(LobbyViewSettingsPane menu)
{
ModifiersTabButton?.gameObject.SetActive(SelectedModIdx != 0);
menu.gameModeText.text = SelectedMod?.PluginInfo.Metadata.Name ?? "Main";
if (SelectedMod == null)
{
var cgm = GetCustomGamemode();
ModifiersTabButton?.gameObject.SetActive(false);
menu.rolesTabButton.gameObject.SetActive(cgm is null or { ShowNormalRoleSettings: true });
menu.gameModeText.text = cgm is null ? "Main" : cgm.ColoredName;
}
else
{
var showModifierButton = SelectedMod.InternalOptionGroups.Any(m =>
m.ParentMenu is MenuCategory.Modifiers || m.OptionableType?.IsAssignableTo(typeof(BaseModifier)) == true);
var showRolesButton = SelectedMod.InternalOptionGroups.Any(r =>
r.ParentMenu is MenuCategory.Roles || r.OptionableType?.IsAssignableTo(typeof(ICustomRole)) == true);
ModifiersTabButton?.gameObject.SetActive(showModifierButton);
menu.rolesTabButton.gameObject.SetActive(showRolesButton);
menu.gameModeText.text = SelectedMod.PluginInfo.Metadata.Name;
}
menu.RefreshTab();
menu.scrollBar.ScrollToTop();
}
@@ -141,8 +196,15 @@ public static class LobbyViewPanePatches
[HarmonyPatch(nameof(LobbyViewSettingsPane.DrawNormalTab))]
public static bool DrawNormalTabPatch(LobbyViewSettingsPane __instance)
{
if (SelectedModIdx == 0 || SelectedMod == null)
if (SelectedMod == null)
{
var gamemodeOpts = GetCustomGamemodeOptions();
if (gamemodeOpts != null)
{
DrawOptions(__instance, gamemodeOpts);
return false;
}
return true;
}
@@ -349,6 +411,13 @@ public static class LobbyViewPanePatches
else
{
viewSettingsInfoPanel.SetInfo(data.Title, data.GetValueString(option.GetFloatData()), 61);
if (viewSettingsInfoPanel.titleText.text.Contains("Game Mode"))
{
viewSettingsInfoPanel.titleText.text = TranslationController.Instance.GetString(
data.Title, CustomGameModeManager.ActiveMode != null ? $"<color=#{CustomGameModeManager.ActiveMode.Color.ToHtmlStringRGBA()}>{CustomGameModeManager.ActiveMode.Name}</color>" : "Classic"
);
}
}
menu.settingsInfo.Add(viewSettingsInfoPanel.gameObject);
+7 -2
View File
@@ -1,10 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.PluginLoading;
using MiraAPI.Presets;
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities.Attributes;
using Reactor.Utilities.Extensions;
@@ -404,14 +407,16 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr)
if (CurrentModIdx == 0)
{
Gsm.GameSettingsButton.gameObject.SetActive(true);
Gsm.RoleSettingsButton.gameObject.SetActive(true);
Gsm.RoleSettingsButton.gameObject.SetActive(
CustomGameModeManager.ActiveMode != null && CustomGameModeManager.ActiveMode.ShowNormalRoleSettings);
}
else
{
var hasOptions =
CurrentMod.InternalOptionGroups.Exists(g =>
g.OptionableType == null && g.ParentMenu == MenuCategory.Game);
var hasRoles = CurrentMod.InternalRoles.Count > 0;
var customRoles = CurrentMod.InternalRoles.Values.OfType<ICustomRole>();
var hasRoles = customRoles.Any(x => x.VisibleInSettings.Invoke());
var hasModifiers = CurrentMod.InternalOptionGroups.Exists(g =>
g.OptionableType?.IsAssignableTo(typeof(BaseModifier)) == true
|| g.ParentMenu == MenuCategory.Modifiers);
+3 -1
View File
@@ -1,8 +1,10 @@
using HarmonyLib;
using Il2CppSystem;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
using UnityEngine;
using Object = Il2CppSystem.Object;
@@ -199,8 +201,8 @@ public static class OptionsPatches
{
return true;
}
__instance.TitleText.text = TranslationController.Instance.GetString(__instance.Title);
__instance.TitleText.text = TranslationController.Instance.GetString(__instance.Title, Array.Empty<Object>());
return false;
}
@@ -5,6 +5,7 @@ using System.Linq;
using AmongUs.GameOptions;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using HarmonyLib;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.Networking;
using MiraAPI.Roles;
@@ -176,7 +177,7 @@ public static class RoleSettingMenuPatches
foreach (var grouping in sortedRoleGroups)
{
if (!grouping.Any() ||
grouping.All(x => x.Configuration.HideSettings || !x.VisibleInSettings()))
grouping.All(x=> x.Configuration.HideSettings || !x.VisibleInSettings() || !x.Configuration.AssociatedGameMode.IsInstanceOfType(CustomGameModeManager.ActiveMode)))
{
continue;
}
@@ -1,6 +1,8 @@
using HarmonyLib;
using MiraAPI.GameModes;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
namespace MiraAPI.Patches.Roles;
@@ -22,6 +24,13 @@ public static class GameStartupPatch
}
_runOnce = true;
foreach (var mode in CustomGameModeManager.IdToModeMap.Values)
{
if (mode.Icon != null)
{
mode.TmpIcon = TmpSpriteUtils.CreateSpriteAsset(mode.Icon.LoadAsset(), $"MiraApi.Gamemode.{mode.Name.Replace(" ", string.Empty)}.png", 1.35f);
}
}
if (MiraPluginManager.Instance.QueuedRoleRegistrations.Count <= 0)
{
@@ -1,93 +0,0 @@
using AmongUs.GameOptions;
using HarmonyLib;
using Il2CppSystem.Collections.Generic;
using System.Linq;
using MiraAPI.Roles;
namespace MiraAPI.Patches.Roles;
[HarmonyPatch(typeof(LogicRoleSelectionNormal))]
public static class LogicRoleSelectionNormalPatch
{
[HarmonyPrefix]
[HarmonyPatch(nameof(LogicRoleSelectionNormal.AssignRolesForTeam))]
public static bool AssignRolesForTeam(
LogicRoleSelectionNormal __instance,
List<NetworkedPlayerInfo> players,
IGameOptions opts,
RoleTeamTypes team,
int teamMax,
Il2CppSystem.Nullable<RoleTypes> defaultRole)
{
int num = 0;
var source = RoleManager.Instance.AllRoles.ToArray()
.Where(role => role.TeamType == team && !RoleManager.IsGhostRole(role.Role) &&
CustomRoleUtils.CanSpawnOnCurrentMode(role));
List<RoleTypes> list = new List<RoleTypes>();
IRoleOptionsCollection roleOptions = opts.RoleOptions;
var assignmentData = source.Where(x => !x.IsDead).Select(role =>
new RoleManager.RoleAssignmentData(
role,
roleOptions.GetNumPerGame(role.Role),
roleOptions.GetChancePerGame(role.Role))).ToList();
var source2 = CustomRoleUtils.GetPossibleRoles(assignmentData, x => x.Chance == 100);
var guaranteedRoles = source.Where(x => source2.Contains(((ushort)x.Role, 100)));
foreach (RoleManager.RoleAssignmentData roleAssignmentData in guaranteedRoles.Select((x) =>
new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100)))
{
while (true)
{
RoleManager.RoleAssignmentData roleAssignmentData2 = roleAssignmentData;
int count = roleAssignmentData2.Count;
roleAssignmentData2.Count = count - 1;
if (count <= 0)
{
break;
}
list.Add(roleAssignmentData.Role.Role);
}
}
__instance.AssignRolesFromList(players, teamMax, list, ref num);
var list2 = source.Where(x => !x.IsDead).Select(role =>
new RoleManager.RoleAssignmentData(
role,
roleOptions.GetNumPerGame(role.Role),
roleOptions.GetChancePerGame(role.Role))).ToList();
list.Clear();
foreach (RoleManager.RoleAssignmentData roleAssignmentData3 in list2)
{
for (int i = 0; i < roleAssignmentData3.Count; i++)
{
if (HashRandom.Next(101) < roleAssignmentData3.Chance)
{
list.Add(roleAssignmentData3.Role.Role);
}
}
}
__instance.AssignRolesFromList(players, teamMax, list, ref num);
var defaultRole2 = team is RoleTeamTypes.Crewmate ? RoleTypes.Crewmate : RoleTypes.Impostor;
try
{
defaultRole2 = defaultRole.Value;
}
catch
{
// Ignored
}
while (list.Count < players.Count && list.Count + num < teamMax)
{
list.Add(defaultRole2);
}
__instance.AssignRolesFromList(players, teamMax, list, ref num);
return false;
}
}
+11 -4
View File
@@ -3,6 +3,7 @@ using AmongUs.GameOptions;
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
using MiraAPI.GameModes;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
using UnityEngine;
@@ -65,14 +66,20 @@ public static class RoleManagerPatches
[HarmonyPatch(nameof(RoleManager.SelectRoles))]
public static void ModifierSelectionPatches(RoleManager __instance)
{
if (!AmongUsClient.Instance.AmHost || !ModifierManager.MiraAssignsModifiers)
if (AmongUsClient.Instance.AmHost && ModifierManager.MiraAssignsModifiers)
{
ModifierManager.AssignModifiers(
PlayerControl.AllPlayerControls.ToArray().Where(plr => !plr.Data.IsDead && !plr.Data.Disconnected)
.ToList());
}
var roleSelection = GameManager.Instance.LogicRoleSelection.Cast<LogicRoleSelectionNormal>();
if (CustomGameModeManager.ActiveMode == null || roleSelection == null)
{
return;
}
ModifierManager.AssignModifiers(
PlayerControl.AllPlayerControls.ToArray().Where(plr => !plr.Data.IsDead && !plr.Data.Disconnected)
.ToList());
CustomGameModeManager.ActiveMode.PostAssignRoles(roleSelection);
}
[HarmonyPrefix]
+127
View File
@@ -0,0 +1,127 @@
using System.Collections.Generic;
using AmongUs.GameOptions;
using HarmonyLib;
using System.Linq;
using InnerNet;
using MiraAPI.GameModes;
using MiraAPI.Roles;
namespace MiraAPI.Patches.Roles;
[HarmonyPatch(typeof(RoleManager))]
public static class SelectRolesPatch
{
public static bool ApiHandlesRoleSelect = true;
[HarmonyPrefix]
[HarmonyPatch(nameof(RoleManager.SelectRoles))]
public static bool SelectRoles()
{
var roleSelection = GameManager.Instance.LogicRoleSelection.Cast<LogicRoleSelectionNormal>();
if (!AmongUsClient.Instance.AmHost || roleSelection == null)
{
return true;
}
if (CustomGameModeManager.ActiveMode != null)
{
CustomGameModeManager.ActiveMode.AssignRoles(out var runOriginal, roleSelection);
if (!runOriginal)
{
return false;
}
}
if (!ApiHandlesRoleSelect)
{
return true;
}
Il2CppSystem.Collections.Generic.List<ClientData> list = new();
AmongUsClient.Instance.GetAllClients(list);
List<NetworkedPlayerInfo> list2 = list.ToArray()
.Where(c => c.Character != null && c.Character.Data != null && !c.Character.Data.Disconnected &&
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data)
.ToList();
foreach (NetworkedPlayerInfo networkedPlayerInfo in GameData.Instance.AllPlayers)
{
if (networkedPlayerInfo.Object != null && networkedPlayerInfo.Object.isDummy)
{
list2.Add(networkedPlayerInfo);
}
}
IGameOptions currentGameOptions = GameOptionsManager.Instance.CurrentGameOptions;
int adjustedNumImpostors = GameOptionsManager.Instance.CurrentGameOptions.GetAdjustedNumImpostors(list2.Count);
AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Impostor, adjustedNumImpostors, RoleTypes.Impostor);
AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Crewmate, int.MaxValue, RoleTypes.Crewmate);
return false;
}
public static void AssignRolesForTeam(
List<NetworkedPlayerInfo> players,
IGameOptions opts,
RoleTeamTypes team,
int teamMax,
RoleTypes defaultRole)
{
int num = 0;
var source = RoleManager.Instance.AllRoles.ToArray()
.Where(role => role.TeamType == team && !RoleManager.IsGhostRole(role.Role) &&
CustomRoleUtils.CanSpawnOnCurrentMode(role));
List<RoleTypes> list = new List<RoleTypes>();
IRoleOptionsCollection roleOptions = opts.RoleOptions;
// Assign guaranteed roles first, just like the vanilla selector. This is
// important because the list of players is shared by both team passes.
foreach (var role in source.Where(x => roleOptions.GetChancePerGame(x.Role) == 100)
.Select(role => role.Role))
{
for (var i = 0; i < roleOptions.GetNumPerGame(role); i++)
{
list.Add(role);
}
}
AssignRolesFromList(players, teamMax, list, ref num);
// A 100% role was already assigned above. Including it here can consume
// another player and, more importantly, leaves the fallback count wrong.
list.Clear();
foreach (var role in source.Where(x =>
roleOptions.GetChancePerGame(x.Role) > 0 &&
roleOptions.GetChancePerGame(x.Role) < 100)
.Select(role => role.Role))
{
for (var i = 0; i < roleOptions.GetNumPerGame(role); i++)
{
if (HashRandom.Next(101) < roleOptions.GetChancePerGame(role))
{
list.Add(role);
}
}
}
AssignRolesFromList(players, teamMax, list, ref num);
// Assign the remaining players up to the requested team limit. The
// vanilla list has been consumed by AssignRolesFromList at this point,
// so checking list.Count can leave players unassigned.
while (players.Count > 0 && num < teamMax)
{
list.Add(defaultRole);
AssignRolesFromList(players, teamMax, list, ref num);
}
}
private static void AssignRolesFromList(List<NetworkedPlayerInfo> players, int teamMax, List<RoleTypes> roleList, ref int rolesAssigned)
{
while (roleList.Count > 0 && players.Count > 0 && rolesAssigned < teamMax)
{
int index = HashRandom.FastNext(roleList.Count);
RoleTypes roleType = roleList[index];
roleList.RemoveAt(index);
int index2 = HashRandom.FastNext(players.Count);
players[index2].Object.RpcSetRole(roleType, false);
players.RemoveAt(index2);
rolesAssigned++;
}
}
}
+3 -1
View File
@@ -1,5 +1,7 @@
using System.Linq;
using BepInEx.Configuration;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.PluginLoading;
@@ -17,7 +19,7 @@ public interface IMiraPlugin
/// Gets the name to display on the options menu.
/// </summary>
string OptionsTitleText { get; }
/// <summary>
/// Gets the abbreviated name to display for other mods to pick up.
/// </summary>
+10 -2
View File
@@ -44,6 +44,15 @@ public class MiraPluginInfo
/// </summary>
public ReadOnlyDictionary<ushort, RoleBehaviour> Roles { get; private set; } = null!;
/// <summary>
/// Gets a read only dictionary of Game Mode IDs and the AbstractGameMode object they are associated with.
/// </summary>
/// <returns>Read only dictionary of IDs and Game Modes.</returns>
public ReadOnlyDictionary<uint, AbstractGameMode> GetModes()
{
return new ReadOnlyDictionary<uint, AbstractGameMode>(GameModes);
}
/// <summary>
/// Gets a <see cref="IReadOnlyCollection{T}"/> of this <see cref="IMiraPlugin"/>'s <see cref="CustomActionButton"/>.
/// </summary>
@@ -72,10 +81,9 @@ public class MiraPluginInfo
internal List<BaseModifier> InternalModifiers { get; } = [];
internal Dictionary<uint, AbstractGameMode> GameModes { get; } = [];
internal Dictionary<ushort, RoleBehaviour> InternalRoles { get; } = [];
internal Dictionary<int, CustomGameMode> InternalGameModes { get; } = [];
internal List<CustomActionButton> InternalButtons { get; } = [];
/// <summary>
+143 -3
View File
@@ -7,9 +7,11 @@ using System.Reflection;
using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using MiraAPI.Colors;
using MiraAPI.Events;
using MiraAPI.GameEnd;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.Hud;
@@ -21,6 +23,7 @@ using MiraAPI.Patches.Options;
using MiraAPI.Presets;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using Reactor.Localization.Utilities;
using Reactor.Networking;
using Reactor.Utilities;
@@ -33,15 +36,117 @@ public sealed class MiraPluginManager
{
private readonly Dictionary<Assembly, MiraPluginInfo> _registeredPlugins = [];
internal MiraPluginInfo[] RegisteredPlugins { get; private set; } = null!;
internal MiraPluginInfo[] RegisteredPluginsWithOptions { get; private set; } = null!;
internal MiraPluginInfo[] RegisteredPlugins { get; private set; } = [];
internal MiraPluginInfo[] RegisteredPluginsWithOptions { get; private set; } = [];
internal MiraPluginInfo[] PluginsWithOptionsOrGameModes { get; private set; } = [];
internal Dictionary<MiraPluginInfo, List<Type>> QueuedRoleRegistrations { get; } = [];
internal static MiraPluginManager Instance { get; private set; } = new();
public static ConfigFile MiraApiConfig { get; private set; } = null!;
public static MiraPluginInfo MiraApiPluginInfo { get; private set; } = null!;
internal void Initialize()
internal void Initialize(BasePlugin miraApiPlugin, IMiraPlugin apiPlugin)
{
Instance = this;
CustomGameModeManager.RegisterDefaultMode();
CustomGameModeManager.GetAndSetGameMode();
if (IL2CPPChainloader.Instance.Plugins.TryGetValue(MiraApiPlugin.Id, out var newPlugin))
{
var assembly = Assembly.GetCallingAssembly();
var info = new MiraPluginInfo(apiPlugin, newPlugin);
var roles = new List<Type>();
var oldConfigSetting = info.PluginConfig.SaveOnConfigSet;
info.PluginConfig.SaveOnConfigSet = false;
foreach (var type in assembly.GetTypes())
{
if (type.IsAbstract || type.GetCustomAttribute<MiraIgnoreAttribute>() != null)
{
continue;
}
foreach (var method in AccessTools.GetDeclaredMethods(type))
{
var eventAttribute = method.GetCustomAttribute<RegisterEventAttribute>();
if (eventAttribute == null)
{
continue;
}
if (!method.IsStatic)
{
Error($"Event method {method.Name} in {type.Name} must be static.");
continue;
}
var parameters = method.GetParameters();
if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent)))
{
Error($"Invalid event registration method {method.Name} in {type.Name}");
continue;
}
var paramType = parameters[0].ParameterType;
MiraEventManager.RegisterEventHandler(paramType, method, eventAttribute.Priority);
}
if (RegisterModifier(type, info))
{
continue;
}
if (RegisterOptions(type, info))
{
continue;
}
if (RegisterLocalTabs(type, miraApiPlugin))
{
continue;
}
if (RegisterRole(type, info, out var role))
{
roles.Add(role);
continue;
}
if (RegisterButton(type, info))
{
continue;
}
if (RegisterGameOver(type))
{
continue;
}
if (RegisterGameModeAttribute(type, info))
{
continue;
}
RegisterColorClasses(type);
RegisterKeybinds(type, miraApiPlugin);
}
info.PluginConfig.Save();
info.PluginConfig.SaveOnConfigSet = oldConfigSetting;
MiraApiConfig = info.PluginConfig;
info.InternalOptionGroups.Sort((x, y) => x.GroupPriority.CompareTo(y.GroupPriority));
QueuedRoleRegistrations.Add(info, roles);
_registeredPlugins.Add(assembly, info);
MiraApiPluginInfo = info;
info.SavePublicCollections();
PresetManager.CreateDefaultPreset(info);
PresetManager.LoadPresets(info);
Info($"Registering Mira API as mod.");
}
IL2CPPChainloader.Instance.PluginLoad += (pluginInfo, assembly, plugin) =>
{
if (plugin is not IMiraPlugin miraPlugin)
@@ -118,6 +223,11 @@ public sealed class MiraPluginManager
continue;
}
if (RegisterGameModeAttribute(type, info))
{
continue;
}
RegisterColorClasses(type);
RegisterKeybinds(type, plugin);
}
@@ -144,8 +254,24 @@ public sealed class MiraPluginManager
// Cache all the registered plugins into an array for easy access
RegisteredPlugins = [.. _registeredPlugins.Values];
RegisteredPluginsWithOptions = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu)];
PluginsWithOptionsOrGameModes = [..RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu || m.GameModes.Count > 0)];
ModifierManager.Modifiers = new ReadOnlyCollection<BaseModifier>(ModifierManager.InternalModifiers);
var dict = new Dictionary<string, object>();
foreach (var (key, value) in CustomGameModeManager.IdToModeMap)
{
if (value is ClassicMode)
{
continue;
}
dict.Add(value.Name, key);
if (((AmongUs.GameOptions.GameModes) key) == AmongUs.GameOptions.GameModes.Normal)
return;
// 'Default' was still being registered twice and idk why
GameModesHelpers.ModeToName.Add((AmongUs.GameOptions.GameModes)key, CustomStringName.CreateAndRegister(value.Name));
}
EnumInjector.InjectEnumValues<AmongUs.GameOptions.GameModes>(dict);
};
RegisterKeybinds(typeof(MiraGlobalKeybinds), PluginSingleton<MiraApiPlugin>.Instance);
@@ -321,6 +447,20 @@ public sealed class MiraPluginManager
return false;
}
private static bool RegisterGameModeAttribute(Type type, MiraPluginInfo pluginInfo)
{
try
{
if (typeof(AbstractGameMode).IsAssignableFrom(type))
return CustomGameModeManager.RegisterGameMode(type, pluginInfo);
}
catch (Exception e)
{
Error($"Failed to register gamemode {type.Name}: {e}");
}
return false;
}
private static bool RegisterLocalTabs(Type type, BasePlugin pluginInfo)
{
try
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+7 -1
View File
@@ -1,6 +1,7 @@
using AmongUs.GameOptions;
using System;
using AmongUs.GameOptions;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.GameModes;
using MiraAPI.Patches.Freeplay;
using MiraAPI.Utilities.Assets;
using TMPro;
@@ -100,6 +101,11 @@ public record struct CustomRoleConfiguration
[HideFromIl2Cpp]
public LoadableAsset<AudioClip>? IntroSound { get; set; } = null;
/// <summary>
/// Gets or sets the associated game mode for this role. This is used to determine if the role should be available in a specific game mode.
/// </summary>
public Type AssociatedGameMode { get; set; } = typeof(ClassicMode);
/// <summary>
/// Gets or sets a value indicating whether the role is affected by light affectors on Airship.
/// </summary>
+5 -3
View File
@@ -4,6 +4,8 @@ using System.Globalization;
using System.Linq;
using System.Text;
using AmongUs.GameOptions;
using MiraAPI.GameModes;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
@@ -23,14 +25,14 @@ public static class CustomRoleUtils
{
if (role is ICustomRole custom)
{
return custom.CanSpawnOnCurrentMode();
return custom.CanSpawnOnCurrentMode() && custom.Configuration.AssociatedGameMode.IsInstanceOfType(CustomGameModeManager.ActiveMode);
}
if (GameManager.Instance.IsHideAndSeek())
if (CustomGameModeManager.ActiveMode is HideAndSeekMode)
{
return role.Role is RoleTypes.Engineer || role.Role is RoleTypes.Impostor;
}
return true;
return !Helpers.IsRoleBlacklisted(role);
}
public static List<(ushort RoleType, int Chance)> GetPossibleRoles(
+10
View File
@@ -130,6 +130,16 @@ public static class MiraAssets
/// </summary>
public static LoadableResourceAsset ModifierFile { get; } = new("MiraAPI.Resources.ModifierFile.png");
/// <summary>
/// Gets the sprite used for the Classic gamemode.
/// </summary>
public static LoadableResourceAsset ClassicGamemodeIcon { get; } = new("MiraAPI.Resources.ClassicGamemodeIcon.png");
/// <summary>
/// Gets the sprite used for the Hide n Seek gamemode.
/// </summary>
public static LoadableResourceAsset HnSGamemodeIcon { get; } = new("MiraAPI.Resources.HnSGamemodeIcon.png");
/// <summary>
/// Gets the sprite used for timed modifier file in TaskAdderGame.
/// </summary>
+3 -1
View File
@@ -7,6 +7,7 @@ using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using HarmonyLib;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.Networking;
using MiraAPI.Roles;
@@ -611,7 +612,8 @@ public static class Extensions
public static bool IsCustom(this OptionBehaviour optionBehaviour)
{
return ModdedOptionsManager.ModdedOptions.Values.Any(
opt => opt.OptionBehaviour && opt.OptionBehaviour == optionBehaviour);
opt => opt.OptionBehaviour && opt.OptionBehaviour == optionBehaviour)
|| optionBehaviour.Equals(GameModeOption.OptionBehaviour);
}
/// <summary>
+38 -38
View File
@@ -24,80 +24,80 @@ public static class ShaderID
}
// For player shader
public static readonly int BodyColor = Shader.PropertyToID("_BodyColor");
public static readonly int BackColor = Shader.PropertyToID("_BackColor");
public static readonly int VisorColor = Shader.PropertyToID("_VisorColor");
public static readonly int BodyColor = Get("_BodyColor");
public static readonly int BackColor = Get("_BackColor");
public static readonly int VisorColor = Get("_VisorColor");
// Main texture, very obviously used in any shader with a texture
public static readonly int MainTex = Shader.PropertyToID("_MainTex");
public static readonly int MainTex = Get("_MainTex");
// Any masking stuff, like MeetingHud bubbles
public static readonly int Mask = Shader.PropertyToID("_Mask");
public static readonly int MaskComp = Shader.PropertyToID("_MaskComp");
public static readonly int MaskLayer = Shader.PropertyToID("_MaskLayer");
public static readonly int Stencil = Shader.PropertyToID("_Stencil");
public static readonly int StencilComp = Shader.PropertyToID("_StencilComp");
public static readonly int Mask = Get("_Mask");
public static readonly int MaskComp = Get("_MaskComp");
public static readonly int MaskLayer = Get("_MaskLayer");
public static readonly int Stencil = Get("_Stencil");
public static readonly int StencilComp = Get("_StencilComp");
// Used in many tasks
public static readonly int Color = Shader.PropertyToID("_Color");
public static readonly int Color = Get("_Color");
// Has 2 uses in the game, provided for convenience
public static readonly int Opacity = Shader.PropertyToID("_Opacity");
public static readonly int Opacity = Get("_Opacity");
// Used once in CooldownHelpers, once in PowerBarMining
public static readonly int NormalizedUvs = Shader.PropertyToID("_NormalizedUvs");
public static readonly int NormalizedUvs = Get("_NormalizedUvs");
// Used in many consoles
public static readonly int Outline = Shader.PropertyToID("_Outline");
public static readonly int OutlineColor = Shader.PropertyToID("_OutlineColor");
public static readonly int Outline = Get("_Outline");
public static readonly int OutlineColor = Get("_OutlineColor");
// Used in some consoles
public static readonly int AddColor = Shader.PropertyToID("_AddColor");
public static readonly int AddColor = Get("_AddColor");
// Has some uses in various locations
public static readonly int Percent = Shader.PropertyToID("_Percent");
public static readonly int PercentY = Shader.PropertyToID("_PercentY");
public static readonly int Desat = Shader.PropertyToID("_Desat");
public static readonly int Percent = Get("_Percent");
public static readonly int PercentY = Get("_PercentY");
public static readonly int Desat = Get("_Desat");
// Used in LightSource
public static readonly int PlayerRadius = Shader.PropertyToID("_PlayerRadius");
public static readonly int LightRadius = Shader.PropertyToID("_LightRadius");
public static readonly int LightOffset = Shader.PropertyToID("_LightOffset");
public static readonly int FlashlightSize = Shader.PropertyToID("_FlashlightSize");
public static readonly int FlashlightAngle = Shader.PropertyToID("_FlashlightAngle");
public static readonly int PlayerRadius = Get("_PlayerRadius");
public static readonly int LightRadius = Get("_LightRadius");
public static readonly int LightOffset = Get("_LightOffset");
public static readonly int FlashlightSize = Get("_FlashlightSize");
public static readonly int FlashlightAngle = Get("_FlashlightAngle");
// Used once for LightSourceGpuRenderer
public static readonly int DepthCompressionValue = Shader.PropertyToID("_DepthCompressionValue");
public static readonly int DepthCompressionValue = Get("_DepthCompressionValue");
// Used in ProgressTracker
public static readonly int Buckets = Shader.PropertyToID("_Buckets");
public static readonly int FullBuckets = Shader.PropertyToID("_FullBuckets");
public static readonly int Buckets = Get("_Buckets");
public static readonly int FullBuckets = Get("_FullBuckets");
// Used once in IntroCutscene and EndGameManager
public static readonly int Rad = Shader.PropertyToID("_Rad");
public static readonly int Rad = Get("_Rad");
// Used only once for Quick Chat
public static readonly int FaceColor = Shader.PropertyToID("_FaceColor");
public static readonly int FaceColor = Get("_FaceColor");
// Used for NavigationMinigame
public static readonly int CrossHair = Shader.PropertyToID("_CrossHair");
public static readonly int CrossColor = Shader.PropertyToID("_CrossColor");
public static readonly int CrossHair = Get("_CrossHair");
public static readonly int CrossColor = Get("_CrossColor");
// Used for both SurveillanceMinigame (Planet and Normal)
public static readonly int Center = Shader.PropertyToID("_Center");
public static readonly int Color2 = Shader.PropertyToID("_Color2");
public static readonly int Center = Get("_Center");
public static readonly int Color2 = Get("_Color2");
// Used in ReactorShipRoom
public static readonly int Speed = Shader.PropertyToID("_Speed");
public static readonly int Speed = Get("_Speed");
// Used only once in CourseMinigame
public static readonly int AltTex = Shader.PropertyToID("_AltTex");
public static readonly int Perc = Shader.PropertyToID("_Perc");
public static readonly int AltTex = Get("_AltTex");
public static readonly int Perc = Get("_Perc");
// Used once in TextMarquee
public static readonly int VertexOffsetX = Shader.PropertyToID("_VertexOffsetX");
public static readonly int VertexOffsetY = Shader.PropertyToID("_VertexOffsetY");
public static readonly int VertexOffsetX = Get("_VertexOffsetX");
public static readonly int VertexOffsetY = Get("_VertexOffsetY");
// Used in VertLineBehaviour
public static readonly int Fade = Shader.PropertyToID("_Fade");
public static readonly int Fade = Get("_Fade");
}