Compare commits

..
218 Commits
Author SHA1 Message Date
Atony ef19f5f7de Merge pull request #103 from All-Of-Us-Mods/dev
0.5.0
2026-09-03 20:34:33 -05:00
Atony e619acbc2a Merge branch 'master' into dev 2026-09-03 20:30:53 -05:00
Atony 9e21726ced Fix MultiTargetButton being renamed? 2026-09-03 20:29:05 -05:00
Atony 7d7d6469ce Bump version 2026-09-03 02:29:00 -05:00
Atony 087ea2a4bd Clear up il2cpp warnings 2026-09-03 02:28:27 -05:00
Atony 81c6bac979 Add UiButtonResetEvent for better ui button grid 2026-09-02 15:16:32 -05:00
Atony 85fb507a43 Adjust gamemode role checks for info guide 2026-09-02 02:34:01 -05:00
Atony 3e2c6df829 Fix skip button vote area order 2026-08-30 19:00:57 -05:00
Atony 6c7b362f95 Add toggles to disable abilities upon use / vote 2026-08-30 18:24:35 -05:00
Atony 027d4763f3 Expose vote methods for other mods 2026-08-30 17:49:20 -05:00
Atony d2f6ba9718 Fix god-awful spacing in the roles guide 2026-08-29 22:55:44 -05:00
Atony 28871d0a01 Refresh role info on the info guide immediately 2026-08-29 22:35:47 -05:00
Atony b62b8ae216 Add more helpers for getting role strings 2026-08-29 22:35:10 -05:00
Atony 4bdddc6f8a Fix IdPart shenanigans 2026-08-29 19:39:21 -05:00
Atony fa47d1dec4 Merge branch 'xml-translations' of https://github.com/All-Of-Us-Mods/MiraAPI into xml-translations 2026-08-29 18:15:43 -05:00
Atony 004f62eb77 Tweak system for registering changes 2026-08-29 18:15:30 -05:00
Turret 3f7e30a5c3 Translated using Weblate (Polish)
Currently translated at 71.0% (27 of 38 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/pl/
2026-08-29 21:20:07 +00:00
Faulo Fault 1d18a2ac7b Translated using Weblate (Spanish (Latin America))
Currently translated at 100.0% (38 of 38 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/es_419/
2026-08-29 21:20:07 +00:00
Shade the Minior Fan 663480c77f Translated using Weblate (Portuguese (Portugal))
Currently translated at 97.3% (37 of 38 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/pt_PT/
2026-08-29 18:38:23 +00:00
Turret e95b52dbe8 Translated using Weblate (Polish)
Currently translated at 68.4% (26 of 38 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/pl/
2026-08-29 18:38:23 +00:00
Faulo Fault 76105b3116 Translated using Weblate (Spanish (Latin America))
Currently translated at 76.3% (29 of 38 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/es_419/
2026-08-29 18:38:23 +00:00
Anthony c82cc0e173 Translated using Weblate (Spanish)
Currently translated at 31.5% (12 of 38 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/es/
2026-08-29 17:11:26 +00:00
Atony 2a432dd928 Add more localized strings 2026-08-28 00:37:14 -05:00
Atony 648e9ec185 Wrap up locale system 2026-08-27 23:51:25 -05:00
Atony 709b59300b Revert "Set role amount to 0 if chance is 0"
This reverts commit 794c762949.
2026-08-27 22:37:01 -05:00
Atony f064952aa6 Merge pull request #91 from HayashiUme/dev
Add XML Translation Api
2026-08-27 19:50:48 -05:00
Atony e532e558b6 Fix local tabs not being localized without hovering 2026-08-27 19:49:10 -05:00
Atony a3ed901a18 Translate local setting buttons 2026-08-27 19:36:33 -05:00
Atony 48aff163f9 Fix issues with local settings tab localization 2026-08-27 19:29:12 -05:00
Atony 28a77f96cb Fix capitalization of all xml strings 2026-08-27 18:21:14 -05:00
Atony 4206b74d12 Fix localization being applied 2026-08-26 00:24:02 -05:00
Atony 276ab0ac79 Fix overall localization 2026-08-25 19:02:55 -05:00
Atony 34148499b7 Fix up system registration for the most part 2026-08-25 18:26:54 -05:00
Atony 5b006ab7d3 Fix xml loading 2026-08-25 01:04:11 -05:00
Atony 47582897a8 Fix loading errors 2026-08-25 00:47:54 -05:00
Atony 80e1e6e454 Clear some warnings 2026-08-25 00:20:52 -05:00
Atony c449669cf2 Fix example plugin error 2026-08-25 00:15:39 -05:00
Atony 6da1048d09 Adjust system for Crowdin / Weblate support 2026-08-25 00:04:09 -05:00
Atony 6a7f58effa Add localization for gamemodes 2026-08-24 22:23:57 -05:00
Atony 39da0e7d08 Merge branch 'dev' into pr/91 2026-08-24 22:16:53 -05:00
Atony 5a23c38fba Merge pull request #102 from WanderingPix/meeting-abilities
Meeting abilities
2026-08-24 21:56:01 -05:00
Atony 0b1b223a6e Merge branch 'dev' into meeting-abilities 2026-08-24 21:48:54 -05:00
Atony a4a363b015 Merge branch 'dev-update' into meeting-abilities 2026-08-24 21:46:00 -05:00
Atony 794c762949 Set role amount to 0 if chance is 0 2026-08-24 16:18:39 -05:00
Atony e901abfc60 Merge branch 'dev' into dev-update 2026-08-24 15:49:12 -05:00
Atony 853a94681a Merge pull request #17 from All-Of-Us-Mods/game-modes
Game modes
2026-08-24 15:41:24 -05:00
wanderingpix d37222010d Document CenteredGridArrange 2026-08-22 13:37:02 +01:00
wanderingpix 1254de742a Fix text labels visible for disabled meeting abilties 2026-08-22 13:33:55 +01:00
wanderingpix 7bbbd7597d Refactor + untargeted meeting abilities 2026-08-22 13:32:14 +01:00
wanderingpix 4b7f17fa30 Fix skip button being broken 2026-08-21 19:30:24 +01:00
wanderingpix 06d62da24d Multi target meeting abilities 2026-08-21 17:00:24 +01:00
wanderingpix 0050c34225 Add singleton for accessing meeting buttons 2026-08-21 14:00:24 +01:00
wanderingpix 605c792e8f More documentation + Button outline color 2026-08-21 12:32:43 +01:00
wanderingpix 54d7c84e91 Edit example meeting ability 2026-08-21 11:52:48 +01:00
wanderingpix eb4bff1834 Document meeting abilities 2026-08-21 11:44:30 +01:00
wanderingpix e381de033e WIP Targeted meeting abilities API 2026-08-20 22:41:26 +01:00
Atony f230cff5e5 Add RoleMedDescription for the role guide 2026-08-19 23:28:00 -05:00
Atony 7c7d184d1f Wip faction display for roles
These need to be their own text object later.
2026-08-19 17:24:54 -05:00
Atony 6b923cfe01 Show nameplate on player list menu 2026-08-19 17:10:41 -05:00
Atony 247c765176 Fix bad ui because sloth sucx 2026-08-19 15:56:13 -05:00
Atony a3668b3150 Add proper support for modded roles in wiki 2026-08-19 13:52:33 -05:00
Atony aa4dd24ac3 Change options to V11 2026-08-19 13:31:36 -05:00
Atony cb0afe3095 Add ui resizing + wiki in the lobby 2026-08-19 13:29:03 -05:00
Atony 883222be82 Merge branch 'dev-update' into game-modes 2026-08-19 00:18:25 -05:00
Atony 6b774500dd Fix reimplemented Judge for good 2026-08-18 23:07:39 -05:00
Atony f96f75cea1 Fix issues with Judge and new meeting changes 2026-08-18 15:10:11 -05:00
linmeideli acfe345133 enhanced 2026-08-18 21:25:22 +08:00
Atony 75662a6c25 Improve vent checks 2026-08-17 17:47:33 -05:00
Atony 73e4506016 Fix role tab issue 2026-08-17 17:41:24 -05:00
Atony a491592669 Allow gamemodes to be hidden when registered 2026-08-16 23:01:58 -05:00
Atony 01fef0f747 Fix vanilla advanced role settings tab breaking 2026-08-16 22:36:57 -05:00
Atony e22f4daf3e Fix the first role option being duped in the menu 2026-08-16 22:00:24 -05:00
Atony b83cb5cc29 Force role menu to be refreshed on gamemode change 2026-08-16 21:56:48 -05:00
Atony fb164a54e3 Fix broken game options tab for mods 2026-08-16 20:05:30 -05:00
Atony b6475161f1 Merge branch 'dev' into game-modes 2026-08-16 17:03:11 -05:00
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 411340d9e9 Fix role screenshots for combined spritesheets 2026-08-15 16:27:49 -05:00
Atony 57d2a6a9b5 Expose button event types 2026-08-15 16:00:05 -05:00
Atony 6f61a75bb7 Add BundleSubAssetHolder for packed spritesheets 2026-08-15 13:18:05 -05: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
AzandHayashiUmi 182a53442e Update README_zh.md
Co-Authored-By: HayashiUmi <2558527373@qq.com>
2026-08-14 06:57:19 -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
Az 35e4c7cc9d move chinese readme to translated folder 2026-08-14 02:18:15 -04:00
AS b2a5b236c0 Merge pull request #79 from TAIKgroup/master
Translate the README.md of MiraAPI into Simplified Chinese
2026-08-14 02:14:46 -04:00
linmeideli 525f987926 this check does not work for Unity's fake null 2026-08-14 13:38:28 +08:00
linmeideli 0b81a8808a Add Translation API 2026-08-14 13:05:30 +08: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
wangzeyu b100f92525 Update README_zh.md 2026-01-24 06:34:59 +08:00
wangzeyu 202b098857 Create README_zh.md 2026-01-24 06:33:49 +08:00
wangzeyu fedba71889 Update README.md 2026-01-23 05:22:50 +08: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
188 changed files with 8155 additions and 798 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.8.18" 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>
+1 -1
View File
@@ -8,7 +8,7 @@
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<VersionPrefix>0.4.3</VersionPrefix>
<VersionPrefix>0.5.0</VersionPrefix>
<VersionSuffix>dev</VersionSuffix>
<Authors>All Of Us, XtraCube, Angxl</Authors>
@@ -13,7 +13,7 @@ namespace MiraAPI.Example.Buttons.Freezer;
public class FreezeButton : CustomActionButton<PlayerControl>
{
public override string Name => "Freeze";
public override string Name => "button.freeze";
public override float Cooldown => OptionGroupSingleton<FreezerRoleSettings>.Instance.FreezeDuration;
public override bool PauseTimerInVent => true;
+1 -1
View File
@@ -9,7 +9,7 @@ namespace MiraAPI.Example.Buttons;
public class MeetingButton : CustomActionButton
{
public override string Name => "Call Meeting";
public override string Name => "button.callMeeting";
public override float Cooldown => 15;
@@ -10,7 +10,7 @@ namespace MiraAPI.Example.Buttons;
public class NeutralKillerButton : CustomActionButton
{
public override string Name => "Win Game";
public override string Name => "button.winGame";
public override float Cooldown => 0f;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
public override MiraKeybind Keybind => ExampleKeybinds.NeutralWinKeybind;
@@ -12,7 +12,7 @@ namespace MiraAPI.Example.Buttons.Teleporter;
public class TeleportButton : CustomActionButton
{
public override string Name => "Teleport";
public override string Name => "button.teleport";
public override float Cooldown => OptionGroupSingleton<TeleporterOptions>.Instance.TeleportCooldown.Value;
+4 -4
View File
@@ -1,4 +1,5 @@
using MiraAPI.Hud;
using MiraAPI.Translation;
using MiraAPI.Utilities.Assets;
using UnityEngine;
@@ -6,7 +7,7 @@ namespace MiraAPI.Example.Buttons;
public class ThinkButton : CustomActionButton
{
public override string Name => "Think";
public override string Name => "button.think";
public override float Cooldown => 15f;
public override float EffectDuration => 10f;
public override int MaxUses => 1;
@@ -14,13 +15,12 @@ public class ThinkButton : CustomActionButton
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
protected override void OnClick()
{
// This button does absolutely nothing besides changing its text
Button!.OverrideText("Thinking...");
Button!.OverrideText("button.think.thinking".Translate());
}
public override void OnEffectEnd()
{
Button!.OverrideText("Think");
Button!.OverrideText("button.think".Translate());
}
public override bool IsEffectCancellable()
+1
View File
@@ -9,5 +9,6 @@ public static class ExampleAssets
// Credit to EpicHorrors for the teleport button asset.
public static LoadableResourceAsset TeleportButton { get; } = new("MiraAPI.Example.Resources.TeleportButton.png");
public static LoadableResourceAsset SharpshootButton { get; } = new("MiraAPI.Example.Resources.SharpshootButton.png");
public static LoadableResourceAsset Banner { get; } = new("MiraAPI.Example.Resources.FortniteBanner.jpeg");
}
+3 -3
View File
@@ -6,12 +6,12 @@ namespace MiraAPI.Example;
[RegisterCustomColors]
public static class ExampleColors
{
public static CustomColor Cerulean { get; } = new("Cerulean", new Color(0.0f, 0.48f, 0.65f))
public static CustomColor Cerulean { get; } = new("color.cerulean", new Color(0.0f, 0.48f, 0.65f))
{
ColorBrightness = CustomColorBrightness.Lighter,
};
public static CustomColor Rose { get; } = new("Rose", new Color(0.98f, 0.26f, 0.62f));
public static CustomColor Rose { get; } = new("color.rose", new Color(0.98f, 0.26f, 0.62f));
public static CustomColor Gold { get; } = new("Gold", new Color(1.0f, 0.84f, 0.0f));
public static CustomColor Gold { get; } = new("color.gold", new Color(1.0f, 0.84f, 0.0f));
}
+2 -2
View File
@@ -8,7 +8,7 @@ namespace MiraAPI.Example;
public class ExampleLocalSettings(ConfigFile config) : LocalSettingsTab(config)
{
public override string TabName => "Mira Example";
public override string TabName => "settings.miraExample";
protected override bool ShouldCreateLabels => false;
public override LocalSettingTabAppearance TabAppearance => new()
@@ -18,7 +18,7 @@ public class ExampleLocalSettings(ConfigFile config) : LocalSettingsTab(config)
};
[LocalSettingsButton]
public LocalSettingsButton ExampleButton { get; private set; } = new("Example Button", OnExampleButtonClick);
public LocalSettingsButton ExampleButton { get; private set; } = new("settings.miraExample.button.exampleButton", OnExampleButtonClick);
[LocalToggleSetting]
public ConfigEntry<bool> ExampleToggle { get; private set; } = config.Bind("General", "Example Bool", true);
+6
View File
@@ -3,6 +3,7 @@ using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MiraAPI.Translation;
using Reactor;
using Reactor.Networking;
using Reactor.Networking.Attributes;
@@ -16,8 +17,13 @@ namespace MiraAPI.Example;
[ReactorModFlags(ModFlags.RequireOnAllClients)]
public partial class ExamplePlugin : BasePlugin, IMiraPlugin
{
public ExamplePlugin()
{
MiraLocaleManager.Register("mira.example");
}
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;
}
@@ -1,5 +1,6 @@
using MiraAPI.Example.Roles;
using MiraAPI.GameEnd;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
@@ -14,7 +15,7 @@ public class NeutralKillerGameOver : CustomGameOver
public override void AfterEndGameSetup(EndGameManager endGameManager)
{
endGameManager.WinText.text = "Outcast Killer Wins!";
endGameManager.WinText.text = "gameover.outcastKiller.win".Translate();
endGameManager.WinText.color = Color.magenta;
endGameManager.BackgroundBar.material.SetColor(ShaderID.Color, Color.magenta);
}
@@ -0,0 +1,29 @@
using MiraAPI.Example.Roles;
using MiraAPI.MeetingAbilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.MeetingAbilities;
public class EndMeetingButton : MeetingActionButton
{
public override string Name => "End Meeting";
public override float Cooldown => 15;
public override float InitialCooldown => 30;
public override int MaxUses => 3;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
public override bool Enabled(RoleBehaviour? role)
{
return PlayerControl.LocalPlayer != null && role is MayorRole;
}
protected override void OnClick()
{
MeetingHud.Instance.RpcClose();
}
}
@@ -0,0 +1,37 @@
using MiraAPI.MeetingAbilities;
using MiraAPI.Networking;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.MeetingAbilities;
public class ShootButton : TargetedMeetingButton
{
public override string Name => "Shoot";
public override int MaxUses => 3;
public override float InitialCooldown => 5;
public override float Cooldown => 3;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.SharpshootButton;
public override Color OutlineColor => Color.red;
public override bool Enabled(RoleBehaviour r)
{
return r.IsImpostor;
}
protected override void OnClick(PlayerVoteArea playerVoteArea)
{
playerVoteArea.SetDisabled();
var player = playerVoteArea.GetPlayer();
if (player != null)
{
PlayerControl.LocalPlayer.RpcCustomMurder(player);
}
}
}
@@ -0,0 +1,54 @@
using MiraAPI.MeetingAbilities;
using MiraAPI.Networking;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.MeetingAbilities;
public class ShotgunButton : MultiTargetMeetingButton
{
public override string Name => "Shotgun";
public override int MaxUses => 3;
public override float InitialCooldown => 5;
public override float Cooldown => 3;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.SharpshootButton;
public override Color OutlineColor => Color.red;
public override bool Enabled(RoleBehaviour r)
{
return r.IsImpostor;
}
protected override void OnClick(PlayerVoteArea playerVoteArea)
{
// Emptu because it only triggers the actual kills once all meeting abilities have been used.
}
public override LoadableAsset<Sprite> SpriteActive => ExampleAssets.CallMeetingButton;
public override int TargetsCount => 4;
protected override void OnSelect(PlayerVoteArea playerVoteArea, bool toggle)
{
HudManager.Instance.PlayerCam.ShakeScreen(0.5f, 2);
}
public override void OnFinish()
{
foreach (var playerVoteArea in Targets.Keys)
{
playerVoteArea.SetDisabled();
var player = playerVoteArea.GetPlayer();
if (player != null)
{
PlayerControl.LocalPlayer.RpcCustomMurder(player);
}
}
}
}
+1
View File
@@ -3,6 +3,7 @@
<Version>1.0.0</Version>
<Description>Example mod for Mira API</Description>
<Authors>Angxl, XtraCube</Authors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
+3 -2
View File
@@ -2,6 +2,7 @@
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.Modifiers.Types;
using MiraAPI.Translation;
using MiraAPI.Utilities.Assets;
using UnityEngine;
@@ -9,7 +10,7 @@ namespace MiraAPI.Example.Modifiers;
public class CaptainModifier : GameModifier
{
public override string ModifierName => "Captain";
public override string ModifierName => MiraLocaleManager.Get("modifier.captain");
public override LoadableAsset<Sprite>? ModifierIcon => ExampleAssets.CallMeetingButton;
public override void OnDeath(DeathReason reason)
@@ -19,7 +20,7 @@ public class CaptainModifier : GameModifier
public override string GetDescription()
{
return $"You can call a meeting from anywhere on the map.";
return MiraLocaleManager.Get("modifier.captain.TabDescription");
}
public override int GetAssignmentChance()
@@ -1,13 +1,14 @@
using Il2CppSystem;
using MiraAPI.Example.Roles;
using MiraAPI.Modifiers.Types;
using MiraAPI.Translation;
using UnityEngine;
namespace MiraAPI.Example.Modifiers.Freezer;
public class FreezeModifier : TimedModifier
{
public override string ModifierName => "Freezed";
public override string ModifierName => MiraLocaleManager.Get("modifier.freezed");
public override bool HideOnUi => false;
public override float Duration => 15f;
public override bool AutoStart => true;
@@ -1,14 +1,15 @@
using MiraAPI.Modifiers.Types;
using MiraAPI.Translation;
namespace MiraAPI.Example.Modifiers;
public class HighPriorityModifier : GameModifier
{
public override string ModifierName => "High Priority";
public override string ModifierName => MiraLocaleManager.Get("modifier.highPriority");
public override string GetDescription()
{
return "You are high priority! Idrk what this means either tbh...";
return MiraLocaleManager.Get("modifier.highPriority.TabDescription");
}
public override int GetAssignmentChance()
+5 -5
View File
@@ -7,19 +7,19 @@ namespace MiraAPI.Example.Options;
public class ExampleOptions : AbstractOptionGroup
{
public override string GroupName => "Example Options 1";
public override string GroupName => "options.exampleOptions1";
public override Color GroupColor => Color.green;
[ModdedToggleOption("Toggle Opt 1")]
[ModdedToggleOption("options.exampleOptions1.toggleOpt1")]
public bool ToggleOpt { get; set; } = false;
[ModdedToggleOption("Toggle Opt 2")]
[ModdedToggleOption("options.exampleOptions1.toggleOpt1")]
public bool ToggleOpt2 { get; set; } = true;
[ModdedNumberOption("Number Opt", min: 0, max: 10, increment: .25f, formatString: "0.00", suffixType: MiraNumberSuffixes.Percent)]
[ModdedNumberOption("options.exampleOptions1.numberOpt", min: 0, max: 10, increment: .25f, formatString: "0.00", suffixType: MiraNumberSuffixes.Percent)]
public float NumberOpt { get; set; } = 4f;
[ModdedEnumOption("Best API", typeof(BestApi), ["Mira API", "Mitochondria", "Reactor"])]
[ModdedEnumOption("options.exampleOptions1.bestApi", typeof(BestApi), ["Mira API", "Mitochondria", "Reactor"])]
public BestApi Opt { get; set; } = BestApi.MiraAPI;
}
+6 -6
View File
@@ -6,22 +6,22 @@ namespace MiraAPI.Example.Options;
public class ExampleOptions2 : AbstractOptionGroup
{
public override string GroupName => "Example Options 2";
public override string GroupName => "options.exampleOptions2";
public override uint GroupPriority => 0; // This group will be displayed first. The default value is uint.MaxValue.
public override MenuCategory ParentMenu => MenuCategory.CustomTwo;
public ModdedPlayerOption PlayerOption2 { get; } = new("YOU MUST CHOSE A PLAYER", false);
public ModdedPlayerOption PlayerOption { get; } = new("Eh whatever");
public ModdedToggleOption ToggleOpt1 { get; } = new("Toggle Option 1", false);
public ModdedPlayerOption PlayerOption2 { get; } = new("options.exampleOptions2.youMustChoseAPlayer", false);
public ModdedPlayerOption PlayerOption { get; } = new("options.exampleOptions2.ehWhatever");
public ModdedToggleOption ToggleOpt1 { get; } = new("options.exampleOptions2.toggleOption1", false);
public ModdedToggleOption ToggleOpt2 { get; } = new("Toggle Option 2", false)
public ModdedToggleOption ToggleOpt2 { get; } = new("options.exampleOptions2.toggleOption2", false)
{
Visible = () => OptionGroupSingleton<ExampleOptions2>.Instance.ToggleOpt1, // implicit cast from ModdedToggleOption to bool
};
public ModdedEnumOption<TestingData> EnumOpt { get; } = new("Enum Opt", 0)
public ModdedEnumOption<TestingData> EnumOpt { get; } = new("options.exampleOptions2.enumOpt", 0)
{
ChangedEvent = x => Logger<ExamplePlugin>.Info($"changed Enum Opt to {x}"),
};
@@ -6,14 +6,14 @@ namespace MiraAPI.Example.Options.Modifiers;
public class CaptainModifierSettings : AbstractOptionGroup<CaptainModifier>
{
public override string GroupName => "Captain Settings";
public override string GroupName => "options.captainSettings";
[ModdedNumberOption("Amount", 0, 5)]
[ModdedNumberOption("options.captainSettings.amount", 0, 5)]
public float Amount { get; set; } = 1;
[ModdedNumberOption("Chance", 0, 100, 10)]
[ModdedNumberOption("options.captainSettings.chance", 0, 100, 10)]
public float Chance { get; set; } = 50;
[ModdedNumberOption("Uses", 1, 5)]
[ModdedNumberOption("options.captainSettings.uses", 1, 5)]
public float NumUses { get; set; } = 3;
}
@@ -6,8 +6,8 @@ namespace MiraAPI.Example.Options.Modifiers;
public class FreezeModifierSettings : AbstractOptionGroup<FreezeModifier>
{
public override string GroupName => "Freeze";
public override string GroupName => "options.freezeModifierSettings";
[ModdedToggleOption("Use Color")]
[ModdedToggleOption("options.freezeModifierSettings.useColor")]
public bool UseColor { get; set; } = true;
}
@@ -5,15 +5,15 @@ namespace MiraAPI.Example.Options.Modifiers;
public class GeneralModifierOptions : AbstractOptionGroup
{
public override string GroupName => "General";
public override string GroupName => "options.generalModifier";
public override uint GroupPriority => 0;
public override MenuCategory ParentMenu => MenuCategory.Modifiers;
[ModdedToggleOption("Some Boolean Option")]
[ModdedToggleOption("options.generalModifier.someBooleanOption")]
public bool SomeBooleanOption { get; set; } = true;
[ModdedNumberOption("Number Option", 0, 10, 1)]
[ModdedNumberOption("options.generalModifier.numberOption", 0, 10, 1)]
public float NumberOption { get; set; } = 5;
}
@@ -13,11 +13,11 @@ public class FreezerRoleSettings : AbstractOptionGroup<FreezerRole>
TmpSpriteUtils.CreateSpriteAsset(
MiraAssets.ImpostorFile.LoadAsset(),
"ApiExample.Role.Impostor.FreezerRole"));
public override string GroupName => "Custom Role";
public override string GroupName => "ApiExample.Role.Freezer";
[ModdedNumberOption("Freeze Duration", 1, 15, 1, MiraNumberSuffixes.Seconds)]
[ModdedNumberOption("ApiExample.Role.Freezer.Settings.FreezeDuration", 1, 15, 1, MiraNumberSuffixes.Seconds)]
public float FreezeDuration { get; set; } = 5;
[ModdedNumberOption("Freeze Uses", 1, 5)]
[ModdedNumberOption("ApiExample.Role.Freezer.Settings.FreezeUses", 1, 5)]
public float FreezeUses { get; set; } = 1;
}
@@ -8,13 +8,13 @@ namespace MiraAPI.Example.Options.Roles;
public class TeleporterOptions : AbstractRoleOptionGroup<TeleporterRole>
{
public override string GroupName => "Teleporter";
public override string GroupName => "ApiExample.Role.Teleporter";
public ModdedNumberOption TeleportCooldown { get; set; } = new("Teleport Cooldown", 10, 5, 60, 2.5f, MiraNumberSuffixes.Seconds);
public ModdedNumberOption TeleportCooldown { get; set; } = new("ApiExample.Role.Teleporter.Settings.TeleportCooldown", 10, 5, 60, 2.5f, MiraNumberSuffixes.Seconds);
[ModdedNumberOption("Teleport Duration", 5, 25, 1, MiraNumberSuffixes.Seconds)]
[ModdedNumberOption("ApiExample.Role.Teleporter.Settings.TeleportDuration", 5, 25, 1, MiraNumberSuffixes.Seconds)]
public float TeleportDuration { get; set; } = 10;
[ModdedNumberOption("Zoom Distance", 4, 15)]
[ModdedNumberOption("ApiExample.Role.Teleporter.Settings.ZoomDistance", 4, 15)]
public float ZoomDistance { get; set; } = 6;
}
@@ -0,0 +1,83 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="ApiExample.Role.Crewmate.Teleporter">Teleporter</string>
<string name="ApiExample.Role.Crewmate.Teleporter.IntroBlurb">Zoom out and teleport across the map!</string>
<string name="ApiExample.Role.Crewmate.Teleporter.MedDescription">Zoom out and teleport across the map!</string>
<string name="ApiExample.Role.Crewmate.Teleporter.TabDescription">Zoom out and teleport across the map!</string>
<string name="ApiExample.Role.Crewmate.Teleporter.WikiDescription">The Teleporter is a Crewmate role that can move around the map using their dope-ass ability.</string>
<string name="ApiExample.Role.Impostor.Freezer">Freezer</string>
<string name="ApiExample.Role.Impostor.Freezer.IntroBlurb">Get iced, nerd.</string>
<string name="ApiExample.Role.Impostor.Freezer.MedDescription">Freeze others for a duration of time.</string>
<string name="ApiExample.Role.Impostor.Freezer.TabDescription">Freeze another player for a duration of time.</string>
<string name="ApiExample.Role.Impostor.Freezer.WikiDescription">The Freezer is an Impostor role that can freeze players. Or something along those lines.</string>
<string name="ApiExample.Role.Crewmate.Mayor">Mayor</string>
<string name="ApiExample.Role.Crewmate.Mayor.IntroBlurb">Democracy is the best policy.</string>
<string name="ApiExample.Role.Crewmate.Mayor.MedDescription">Vote out the Impostors with more votes.
Your votes have double the power.</string>
<string name="ApiExample.Role.Crewmate.Mayor.TabDescription">You get one extra vote in the meeting!</string>
<string name="ApiExample.Role.Crewmate.Mayor.WikiDescription">The Mayor is a Crewmate role that gets two votes in the meeting, instead of the singular vote other Crewmates get.</string>
<string name="ApiExample.Role.Crewmate.Chamelon">Chamelon</string>
<string name="ApiExample.Role.Crewmate.Chamelon.IntroBlurb">Become one with the environment.</string>
<string name="ApiExample.Role.Crewmate.Chamelon.MedDescription">Fade out of everyone's vision by not moving.</string>
<string name="ApiExample.Role.Crewmate.Chamelon.TabDescription">Stay invisible while not moving.</string>
<string name="ApiExample.Role.Crewmate.Chamelon.WikiDescription">The Chamelon is a Crewmate role that slowly becomes invisible while standing still.</string>
<string name="ApiExample.Role.Outcast.OutcastKiller">Outcast Killer</string>
<string name="ApiExample.Role.Outcast.OutcastKiller.IntroBlurb">Kill everyone else.</string>
<string name="ApiExample.Role.Outcast.OutcastKiller.MedDescription">Be the last outcast standing.
Eliminate every other faction.</string>
<string name="ApiExample.Role.Outcast.OutcastKiller.TabDescription">Outcast who can kill.</string>
<string name="ApiExample.Role.Outcast.OutcastKiller.WikiDescription">The Outcast Killer is an Outcast role that can kill, like some sort of neutral killer...</string>
<string name="outcast">Outcast</string>
<string name="outcast.group">Outcast Roles</string>
<string name="outcast.roleTitle">OUTCAST</string>
<string name="outcast.teamIntroDescription">You are an Outcast. You do not have a team.</string>
<string name="button.think">Think</string>
<string name="button.think.thinking">Thinking...</string>
<string name="button.freeze">Freeze</string>
<string name="button.teleport">Teleport</string>
<string name="button.callMeeting">Call Meeting</string>
<string name="button.winGame">Win Game</string>
<string name="modifier.captain">Captain</string>
<string name="modifier.captain.TabDescription">You can call a meeting from anywhere on the map.</string>
<string name="modifier.freezed">Freezed</string>
<string name="modifier.highPriority">High Priority</string>
<string name="modifier.highPriority.TabDescription">You are high priority! Idrk what this means either tbh...</string>
<string name="options.exampleOptions1">Example Options 1</string>
<string name="options.exampleOptions1.toggleOpt1">Toggle Opt 1</string>
<string name="options.exampleOptions1.toggleOpt2">Toggle Opt 2</string>
<string name="options.exampleOptions1.numberOpt">Number Opt</string>
<string name="options.exampleOptions1.bestApi">Best API</string>
<string name="options.exampleOptions2">Example Options 2</string>
<string name="options.exampleOptions2.youMustChoseAPlayer">YOU MUST CHOSE A PLAYER</string>
<string name="options.exampleOptions2.ehWhatever">Eh whatever</string>
<string name="options.exampleOptions2.toggleOption1">Toggle Option 1</string>
<string name="options.exampleOptions2.toggleOption2">Toggle Option 2</string>
<string name="options.exampleOptions2.enumOpt">Enum Opt</string>
<string name="options.captainSettings">Captain Settings</string>
<string name="options.captainSettings.amount">Amount</string>
<string name="options.captainSettings.chance">Chance</string>
<string name="options.captainSettings.uses">Uses</string>
<string name="options.freezeModifierSettings">Freeze</string>
<string name="options.freezeModifierSettings.useColor">Use Color</string>
<string name="options.generalModifier">General</string>
<string name="options.generalModifier.someBooleanOption">Some Boolean Option</string>
<string name="options.generalModifier.numberOption">Number Option</string>
<string name="options.freezerRoleSettings">Custom Role</string>
<string name="ApiExample.Role.Freezer.Settings.FreezeDuration">Freeze Duration</string>
<string name="ApiExample.Role.Freezer.Settings.FreezeUses">Freeze Uses</string>
<string name="ApiExample.Role.Teleporter.Settings.TeleportCooldown">Teleport Cooldown</string>
<string name="ApiExample.Role.Teleporter.Settings.TeleportDuration">Teleport Duration</string>
<string name="ApiExample.Role.Teleporter.Settings.ZoomDistance">Zoom Distance</string>
<string name="settings.miraExample">Mira Example</string>
<string name="settings.miraExample.exampleBool">Example Bool</string>
<string name="settings.miraExample.exampleBool2">Example Bool 2</string>
<string name="settings.miraExample.slider">Slider</string>
<string name="settings.miraExample.exampleNumber">Example Number</string>
<string name="settings.miraExample.exampleMultiplier">Example Multplier</string>
<string name="settings.miraExample.exampleEnum">Example Enum</string>
<string name="settings.miraExample.button.exampleButton">Example Button</string>
<string name="gameover.outcastKiller.win">Outcast Killer Wins!</string>
<string name="color.cerulean">Cerulean</string>
<string name="color.rose">Rose</string>
<string name="color.gold">Gold</string>
</resources>
@@ -0,0 +1,66 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="ApiExample.Role.Teleporter">传送者</string>
<string name="ApiExample.Role.Teleporter.IntroBlurb">缩小视野并在地图上传送!</string>
<string name="ApiExample.Role.Teleporter.MedDescription">缩小视野并在地图上传送!</string>
<string name="ApiExample.Role.Teleporter.TabDescription">缩小视野并在地图上传送!</string>
<string name="ApiExample.Role.Freezer">冰冻者</string>
<string name="ApiExample.Role.Freezer.TabDescription">将其他玩家冰冻一段时间。</string>
<string name="ApiExample.Role.Crewmate.Mayor">市长</string>
<string name="ApiExample.Role.Crewmate.Mayor.TabDescription">你拥有额外投票权!</string>
<string name="ApiExample.Role.Crewmate.Chamelon">变色龙</string>
<string name="ApiExample.Role.Crewmate.Chamelon.TabDescription">静止不动时保持隐身。</string>
<string name="ApiExample.Role.Outcast.OutcastKiller">流放杀手</string>
<string name="ApiExample.Role.Outcast.OutcastKiller.TabDescription">可以击杀的流放者。</string>
<string name="outcast">流放者</string>
<string name="outcast.roleTitle">流放者</string>
<string name="outcast.teamIntroDescription">你是流放者,你没有队伍。</string>
<string name="button.think">思考</string>
<string name="button.think.thinking">思考中...</string>
<string name="button.freeze">冰冻</string>
<string name="button.teleport">传送</string>
<string name="button.callMeeting">召集会议</string>
<string name="button.winGame">赢得游戏</string>
<string name="modifier.captain">队长</string>
<string name="modifier.captain.TabDescription">你可以在地图上任意位置召集会议。</string>
<string name="modifier.freezed">已被冰冻</string>
<string name="modifier.highPriority">高优先级</string>
<string name="modifier.highPriority.TabDescription">你是高优先级!老实说我也不太清楚这是什么意思……</string>
<string name="options.exampleOptions1">示例选项组 1</string>
<string name="options.exampleOptions1.toggleOpt1">开关选项 1</string>
<string name="options.exampleOptions1.toggleOpt2">开关选项 2</string>
<string name="options.exampleOptions1.numberOpt">数字选项</string>
<string name="options.exampleOptions1.bestApi">谁是最好的API</string>
<string name="options.exampleOptions2">示例选项组 2</string>
<string name="options.exampleOptions2.youMustChoseAPlayer">你必须选择一个玩家</string>
<string name="options.exampleOptions2.ehWhatever">咕咕嘎嘎</string>
<string name="options.exampleOptions2.toggleOption1">开关选项 1</string>
<string name="options.exampleOptions2.toggleOption2">开关选项 2</string>
<string name="options.exampleOptions2.enumOpt">枚举选项</string>
<string name="options.captainSettings">队长设置</string>
<string name="options.captainSettings.amount">数量</string>
<string name="options.captainSettings.chance">概率</string>
<string name="options.captainSettings.uses">使用次数</string>
<string name="options.freezeModifierSettings">冰冻</string>
<string name="options.freezeModifierSettings.useColor">使用颜色</string>
<string name="options.generalModifier">通用</string>
<string name="options.generalModifier.someBooleanOption">某个布尔选项</string>
<string name="options.generalModifier.numberOption">数字选项</string>
<string name="ApiExample.Role.Freezer.Settings.FreezeDuration">冰冻时长</string>
<string name="ApiExample.Role.Freezer.Settings.FreezeUses">冰冻次数</string>
<string name="ApiExample.Role.Teleporter.Settings.TeleportCooldown">传送冷却</string>
<string name="ApiExample.Role.Teleporter.Settings.TeleportDuration">传送持续时间</string>
<string name="ApiExample.Role.Teleporter.Settings.ZoomDistance">缩放距离</string>
<string name="settings.miraExample">Mira 示例插件</string>
<string name="settings.miraExample.exampleBool">示例布尔</string>
<string name="settings.miraExample.exampleBool2">示例布尔 2</string>
<string name="settings.miraExample.slider">滑块</string>
<string name="settings.miraExample.exampleNumber">示例数字</string>
<string name="settings.miraExample.exampleMultiplier">示例倍数</string>
<string name="settings.miraExample.exampleEnum">示例枚举</string>
<string name="settings.miraExample.button.exampleButton">示例按钮</string>
<string name="gameover.outcastKiller.win">流放杀手获胜!</string>
<string name="color.cerulean">天蓝</string>
<string name="color.rose">玫瑰红</string>
<string name="color.gold">金色</string>
</resources>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

+14 -6
View File
@@ -10,9 +10,8 @@ namespace MiraAPI.Example.Roles;
public class ChameloenRole : CrewmateRole, ICustomRole
{
public string RoleName => "Chamelon";
public string RoleLongDescription => "Stay invisible while not moving.";
public string RoleDescription => RoleLongDescription;
public string IdPart => "Chamelon";
public string IdPrefix => "ApiExample.Role.Crewmate";
public Color RoleColor => Palette.AcceptedGreen;
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
@@ -22,7 +21,9 @@ public class ChameloenRole : CrewmateRole, ICustomRole
{
OptionsScreenshot = ExampleAssets.Banner,
Icon = MiraAssets.CrewmateFile,
IconTmp = TmpSpriteUtils.CreateSpriteAsset(MiraAssets.CrewmateFile.LoadAsset(), "ApiExample.Role.Impostor.ChameleonRole"),
IconTmp = TmpSpriteUtils.CreateSpriteAsset(
MiraAssets.CrewmateFile.LoadAsset(),
"ApiExample.Role.Impostor.ChameleonRole"),
IntroSound = CustomRoleUtils.GetIntroSound(RoleTypes.Shapeshifter),
};
@@ -56,12 +57,18 @@ public class ChameloenRole : CrewmateRole, ICustomRole
{
SpriteRenderer rend = Player.cosmetics.currentBodySprite.BodySprite;
TextMeshPro tmp = Player.cosmetics.nameText;
tmp.color = Color.Lerp(tmp.color, new Color(tmp.color.r, tmp.color.g, tmp.color.b, Player.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
tmp.color = Color.Lerp(
tmp.color,
new Color(tmp.color.r, tmp.color.g, tmp.color.b, Player.AmOwner ? 0.3f : 0),
Time.deltaTime * 4f);
rend.color = Color.Lerp(rend.color, new Color(1, 1, 1, Player.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
foreach (var cosmetic in Player.cosmetics.transform.GetComponentsInChildren<SpriteRenderer>())
{
cosmetic.color = Color.Lerp(cosmetic.color, new Color(1, 1, 1, Player.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
cosmetic.color = Color.Lerp(
cosmetic.color,
new Color(1, 1, 1, Player.AmOwner ? 0.3f : 0),
Time.deltaTime * 4f);
}
}
}
@@ -75,6 +82,7 @@ public class ChameloenRole : CrewmateRole, ICustomRole
{
cosmetic.color = Color.white;
}
Player.cosmetics.currentBodySprite.BodySprite.color = Color.white;
Player.cosmetics.nameText.color = Color.white;
}
+3 -4
View File
@@ -6,16 +6,15 @@ namespace MiraAPI.Example.Roles;
public class FreezerRole : ImpostorRole, ICustomRole
{
public string RoleName => "Freezer";
public string RoleLongDescription => "Freeze another player for a duration of time.";
public string RoleDescription => RoleLongDescription;
public string IdPart => "Freezer";
public string IdPrefix => "ApiExample.Role.Impostor";
public Color RoleColor => Palette.Blue;
public ModdedRoleTeams Team => ModdedRoleTeams.Impostor;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
{
Icon = MiraAssets.ImpostorFile,
IconTmp = TmpSpriteUtils.CreateSpriteAsset(MiraAssets.ImpostorFile.LoadAsset(), "ApiExample.Role.Impostor.FreezerRole"),
IconTmp = TmpSpriteUtils.CreateSpriteAsset(MiraAssets.ImpostorFile.LoadAsset(), "ApiExample.Role.Impostor.Freezer"),
OptionsScreenshot = ExampleAssets.Banner,
MaxRoleCount = 2,
};
+2 -3
View File
@@ -5,9 +5,8 @@ namespace MiraAPI.Example.Roles;
public class MayorRole : CrewmateRole, ICustomRole
{
public string RoleName => "Mayor";
public string RoleLongDescription => "You get extra votes!";
public string RoleDescription => RoleLongDescription;
public string IdPart => "Mayor";
public string IdPrefix => "ApiExample.Role.Crewmate";
public Color RoleColor => new Color32(221, 176, 152, 255);
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
public CustomRoleConfiguration Configuration => new(this);
+5 -6
View File
@@ -8,9 +8,8 @@ namespace MiraAPI.Example.Roles;
public class NeutralKillerRole : ImpostorRole, ICustomRole
{
public string RoleName => "Outcast Killer";
public string RoleDescription => "Outcast who can kill.";
public string RoleLongDescription => RoleDescription;
public string IdPart => "OutcastKiller";
public string IdPrefix => "ApiExample.Role.Outcast";
public Color RoleColor => Color.magenta;
public ModdedRoleTeams Team => ModdedRoleTeams.Custom;
@@ -21,13 +20,13 @@ public class NeutralKillerRole : ImpostorRole, ICustomRole
CanUseVent = true,
};
public RoleOptionsGroup RoleOptionsGroup { get; } = new("Outcast", Color.gray);
public RoleOptionsGroup RoleOptionsGroup { get; } = new("outcast.group", Color.gray);
[HideFromIl2Cpp]
public TeamIntroConfiguration? IntroConfiguration { get; } = new(
Color.gray,
"OUTCAST",
"You are an Outcast. You do not have a team.");
"outcast.roleTitle",
"outcast.teamIntroDescription");
public override void SpawnTaskHeader(PlayerControl playerControl)
{
+2 -3
View File
@@ -5,9 +5,8 @@ namespace MiraAPI.Example.Roles;
public class TeleporterRole : CrewmateRole, ICustomRole
{
public string RoleName => "Teleporter";
public string RoleLongDescription => "Zoom out and teleport across the map!";
public string RoleDescription => RoleLongDescription;
public string IdPart => "Teleporter";
public string IdPrefix => "ApiExample.Role.Crewmate";
public Color RoleColor => new Color32(221, 176, 152, 255);
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
+3 -3
View File
@@ -1,5 +1,5 @@
using MiraAPI.Utilities;
using Reactor.Localization.Utilities;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Colors;
@@ -43,7 +43,7 @@ public sealed class CustomColor(StringNames name, Color32 mainColor, Color32 sha
}
/// <inheritdoc />
public CustomColor(string name, Color32 mainColor, Color32 shadowColor) : this(CustomStringName.CreateAndRegister(name), mainColor, shadowColor)
public CustomColor(string name, Color32 mainColor, Color32 shadowColor) : this(MiraLocaleManager.GetOrCreateLocaleString(name), mainColor, shadowColor)
{
}
}
+2 -1
View File
@@ -20,7 +20,8 @@ public static class PaletteManager
{
var colors = CustomColors.Select(x => x.MainColor).ToArray();
var shadowColors = CustomColors.Select(x => x.ShadowColor).ToArray();
var stringNames = CustomColors.Select(x => x.Name).ToArray();
var stringNames = CustomColors.Select(x =>
x.Name).ToArray();
Palette.PlayerColors = Palette.PlayerColors.ToArray().AddRangeToArray(colors);
Palette.ShadowColors = Palette.ShadowColors.ToArray().AddRangeToArray(shadowColors);
+2 -2
View File
@@ -6,7 +6,7 @@ namespace MiraAPI.Events.Mira;
/// Button click event for <see cref="CustomActionButton"/>s only. Do not use for vanilla <see cref="AbilityButton"/>s.
/// </summary>
/// <typeparam name="T">The <see cref="CustomActionButton"/> type.</typeparam>
public sealed class MiraButtonClickEvent<T> : MiraCancelableEvent where T : CustomActionButton
public class MiraButtonClickEvent<T> : MiraCancelableEvent where T : CustomActionButton
{
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
@@ -33,7 +33,7 @@ public sealed class MiraButtonClickEvent<T> : MiraCancelableEvent where T : Cust
/// <summary>
/// Button click event for <see cref="CustomActionButton"/>s only. Do not use for vanilla <see cref="AbilityButton"/>s.
/// </summary>
public sealed class MiraButtonClickEvent : MiraCancelableEvent
public class MiraButtonClickEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
@@ -0,0 +1,30 @@
using UnityEngine;
namespace MiraAPI.Events.Mira;
/// <summary>
/// Event fired by Mira API to adjust the UI buttons at the top right of the screen.
/// </summary>
public class UiButtonPostResetEvent : MiraEvent
{
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the very top UI row.
/// </summary>
public GameObject MainTopUiRow { get; }
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the second top UI row.
/// </summary>
public GameObject SecondTopUiRow { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UiButtonPostResetEvent"/> class.
/// </summary>
/// <param name="topUiRow">The <see cref="GameObject"/> for the top UI row.</param>
/// <param name="secondUiRow">The <see cref="GameObject"/> for the second UI row.</param>
public UiButtonPostResetEvent(GameObject topUiRow, GameObject secondUiRow)
{
MainTopUiRow = topUiRow;
SecondTopUiRow = secondUiRow;
}
}
+15
View File
@@ -0,0 +1,15 @@
namespace MiraAPI.Events.Mira;
/// <summary>
/// Event fired by Mira API prior to adjusting the UI buttons at the top right of the screen.
/// </summary>
public class UiButtonResetEvent : MiraEvent
{
/// <summary>
/// Initializes a new instance of the <see cref="UiButtonResetEvent"/> class.
/// </summary>
public UiButtonResetEvent()
{
// nothing!
}
}
+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,15 +25,20 @@ 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.
/// </summary>
public NetworkedPlayerInfo TargetPlayerInfo { get; }
/// <summary>
/// Gets or sets a value indicating whether the vote event is an Overrule caused by a Judge.
/// </summary>
public bool IsOverruling { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="HandleVoteEvent"/> class.
/// </summary>
@@ -47,4 +52,20 @@ public class HandleVoteEvent : MiraCancelableEvent
PreventVote = false;
TargetPlayerInfo = GameData.Instance.GetPlayerById(targetId);
}
/// <summary>
/// Initializes a new instance of the <see cref="HandleVoteEvent"/> class.
/// </summary>
/// <param name="playerVoteData">The voter's <see cref="PlayerVoteData"/>.</param>
/// <param name="targetId">The target's playerId.</param>
/// <param name="isOverruling">Whether the vote is actually for a Judge.</param>
public HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool isOverruling)
{
VoteData = playerVoteData;
Player = playerVoteData.Owner;
TargetId = targetId;
PreventVote = false;
IsOverruling = isOverruling;
TargetPlayerInfo = GameData.Instance.GetPlayerById(targetId);
}
}
@@ -33,6 +33,16 @@ public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exil
/// </summary>
public List<CustomVote> Votes { get; } = votes;
/// <summary>
/// Gets or sets a value indicating whether an overruling was done. Normally set by judge but can be overwritten.
/// </summary>
public bool OverruledVote { get; set; }
/// <summary>
/// Gets or sets a value specifically to determine which Judge (if any) caused the overruling. Normally set by judge but can be overwritten.
/// </summary>
public ushort OverruledNonce { get; set; }
/// <summary>
/// Gets or sets the player to be exiled. Will be <see langword="null"/> if no player is to be exiled.
/// </summary>
+297
View File
@@ -0,0 +1,297 @@
using System.Collections;
using System.Collections.Generic;
using AmongUs.GameOptions;
using MiraAPI.GameOptions;
using MiraAPI.PluginLoading;
using MiraAPI.Translation;
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 a value indicating whether the mode is visible in the menu. Only checked at startup.
/// </summary>
public virtual bool HideMode => false;
/// <summary>
/// Gets the game mode description.
/// </summary>
public abstract string Description { get; }
/// <summary>
/// Gets the game mode color to display on the lobby pane.
/// </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 or sets 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=#{Color.ToHtmlStringRGBA()}>{MiraLocaleManager.Get(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 => "MiraApi.Gamemode.Classic";
/// <inheritdoc/>
public override string Description => "MiraApi.Gamemode.Classic.Description";
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;
}
+97 -43
View File
@@ -1,70 +1,124 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Translation;
using MiraAPI.PluginLoading;
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))
if (!mode.HideMode)
{
Error($"ID for gamemode {gameMode.Name} already exists!");
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 n 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;
var hnsMode = new HideAndSeekMode();
if (!hnsMode.HideMode)
{
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;
}
+161
View File
@@ -0,0 +1,161 @@
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.Translation;
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 = MiraLocaleManager.GetOrCreateLocaleString("Gamemode");
internal static readonly StringNames CustomName = MiraLocaleManager.GetOrCreateLocaleString("Custom");
internal static readonly Dictionary<uint, StringNames> Values = new()
{
[0] = MiraLocaleManager.GetOrCreateLocaleString("MiraApi.Gamemode.Classic"),
};
internal static void AddOption(AbstractGameMode mode)
{
if (!Values.ContainsKey(mode.ID))
Values.Add(mode.ID, MiraLocaleManager.GetOrCreateLocaleString(mode.Name));
}
/*[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;
var previousMode = CustomGameModeManager.ActiveMode;
CustomGameModeManager.GetAndSetGameMode();
HudPatches.SetGameModeText(CustomGameModeManager.GetMode(Values.ElementAt(_lastValue).Key).ColoredName);
var gm = CustomGameModeManager.ActiveMode!;
if (gm != previousMode)
{
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
GamemodeName,
gm.ColoredName,
new Color(0.7333f, 0.7333f, 0.7333f, 1),
gm.TmpIcon,
true);
if (MenuState.Instance)
{
// should force reset roles for gamemodes properly
foreach (var roleMenu in MenuState.Instance.QueuedRoleMenuRefresh)
{
MenuState.Instance.QueuedRoleMenuRefresh[roleMenu.Key] = 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);
}
}
+534
View File
@@ -0,0 +1,534 @@
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 => "MiraApi.Gamemode.HideAndSeek";
/// <inheritdoc/>
public override string Description => "MiraApi.Gamemode.HideAndSeek.Description";
// TODO: Once the Hide n Seek port is ready for release, we will remove this.
public override bool HideMode => !MiraApiPlugin.IsDevBuild;
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);
}
}
@@ -1,6 +1,7 @@
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
@@ -13,7 +14,7 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
var opt = new ModdedEnumOption(Title, (int)(value ?? 0), enumType, values);
var opt = new ModdedEnumOption(Title.Translate(), (int)(value ?? 0), enumType, values);
return opt;
}
@@ -1,6 +1,7 @@
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.Attributes;
@@ -22,7 +23,7 @@ public class ModdedNumberOptionAttribute(
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
return new ModdedNumberOption(
Title,
Title.Translate(),
(float)(value ?? min + increment),
min,
max,
@@ -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>
@@ -1,6 +1,7 @@
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
@@ -13,7 +14,7 @@ public class ModdedToggleOptionAttribute(string title) : ModdedOptionAttribute(t
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
var toggleOpt = new ModdedToggleOption(Title, (bool)(value ?? false));
var toggleOpt = new ModdedToggleOption(Title.Translate(), (bool)(value ?? false));
return toggleOpt;
}
+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
{
@@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Networking;
using MiraAPI.Translation;
using Reactor.Localization.Utilities;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -37,8 +38,8 @@ public class ModdedEnumOption : ModdedOption<int>
data.Title = StringName;
data.Type = global::OptionTypes.String;
data.Values = values is null ?
Enum.GetNames(enumType).Select(CustomStringName.CreateAndRegister).ToArray()
: [.. values.Select(CustomStringName.CreateAndRegister)];
Enum.GetNames(enumType).Select(MiraLocaleManager.GetOrCreateLocaleString).ToArray()
: [.. values.Select(MiraLocaleManager.GetOrCreateLocaleString)];
data.Index = Value;
}
@@ -136,8 +137,8 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
data.Title = StringName;
data.Type = global::OptionTypes.String;
data.Values = values is null ?
Enum.GetNames(typeof(T)).Select(CustomStringName.CreateAndRegister).ToArray()
: [.. values.Select(CustomStringName.CreateAndRegister)];
Enum.GetNames(typeof(T)).Select(MiraLocaleManager.GetOrCreateLocaleString).ToArray()
: [.. values.Select(MiraLocaleManager.GetOrCreateLocaleString)];
data.Index = Convert.ToInt32(Value, NumberFormatInfo.InvariantInfo);
}
@@ -1,7 +1,8 @@
using System;
using System;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
using MiraAPI.Translation;
using Reactor.Localization.Utilities;
using Reactor.Networking.Rpc;
using UnityEngine;
@@ -78,10 +79,10 @@ public abstract class ModdedOption<T> : IModdedOption
protected ModdedOption(string title, T defaultValue, bool includeInPreset = true)
{
Id = ModdedOptionsManager.NextId;
Title = title;
Title = title.Translate();
DefaultValue = defaultValue;
Value = defaultValue;
StringName = CustomStringName.CreateAndRegister(Title);
StringName = MiraLocaleManager.GetOrCreateLocaleString(Title);
Visible = () => true;
IncludeInPreset = includeInPreset;
}
@@ -2,6 +2,7 @@
using System.Linq;
using Il2CppSystem.Collections.Generic;
using MiraAPI.Networking;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -65,7 +66,7 @@ public class ModdedPlayerOption : ModdedOption<int>
playerOption.OnValueChanged = (Il2CppSystem.Action<OptionBehaviour>)ValueChanged;
playerOption.Title = StringName;
playerOption.TitleText.text = TranslationController.Instance.GetString(StringName);
playerOption.TitleText.text = Title.Translate();
playerOption.Values = Values;
playerOption.Value = Value;
playerOption.playerIndex = filteredList.FindIndex(p => p.PlayerId == Value);
@@ -0,0 +1,177 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Networking;
using MiraAPI.Translation;
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, MiraLocaleManager.GetOrCreateLocaleString(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(MiraLocaleManager.GetOrCreateLocaleString).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);
}
}
}
@@ -1,5 +1,6 @@
using System;
using MiraAPI.Networking;
using MiraAPI.Translation;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -35,7 +36,7 @@ public class ModdedToggleOption : ModdedOption<bool>
toggleOption.SetUpFromData(Data, 20);
toggleOption.Title = StringName;
toggleOption.TitleText.text = Title;
toggleOption.TitleText.text = Title.Translate();
toggleOption.CheckMark.enabled = Value;
toggleOption.OnValueChanged = (Il2CppSystem.Action<OptionBehaviour>)ValueChanged;
@@ -0,0 +1,287 @@
using System.Collections;
using System.Linq;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using Il2CppInterop.Runtime.Attributes;
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;
}
}
[HideFromIl2Cpp]
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);
}
+2 -1
View File
@@ -5,6 +5,7 @@ using MiraAPI.Events.Mira;
using MiraAPI.Keybinds;
using MiraAPI.LocalSettings;
using MiraAPI.Patches;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Rewired;
@@ -150,7 +151,7 @@ public abstract class CustomActionButton
Button = Object.Instantiate(HudManager.Instance.AbilityButton, parent);
Button.name = Name + "Button";
Button.OverrideText(Name.ToUpperInvariant());
Button.OverrideText(Name.Translate().ToUpperInvariant());
Button.graphic.sprite = Sprite.LoadAsset();
+14
View File
@@ -17,6 +17,20 @@ public static class CustomButtonManager
/// </summary>
public static ReadOnlyCollection<CustomActionButton> Buttons { get; internal set; } = new([]);
/// <summary>
/// Gets a list of all registered button-specific <see cref="MiraButtonClickEvent"/>s.
/// </summary>
public static ReadOnlyDictionary<Type, Type> EventTypes { get; internal set; } = new(
new Dictionary<Type, Type>
{ });
/// <summary>
/// Gets a list of all registered button-specific <see cref="MiraButtonCancelledEvent"/>s.
/// </summary>
public static ReadOnlyDictionary<Type, Type> CancelledEventTypes { get; internal set; } = new(
new Dictionary<Type, Type>
{ });
internal static readonly List<CustomActionButton> CustomButtons = [];
internal static readonly Dictionary<Type, Type> ButtonEventTypes = [];
internal static readonly Dictionary<Type, Type> ButtonCancelledEventTypes = [];
+203
View File
@@ -0,0 +1,203 @@
using BepInEx.Unity.IL2CPP.Utils.Collections;
using InnerNet;
using MiraAPI.LocalSettings;
using MiraAPI.Modifiers.ModifierDisplay;
using Reactor.Utilities.Attributes;
using Reactor.Utilities.Extensions;
using UnityEngine;
namespace MiraAPI.Hud;
[RegisterInIl2Cpp]
public sealed class MiraHudHelper(nint cppPtr) : MonoBehaviour(cppPtr)
{
public static MiraHudHelper Instance { get; private set; }
public static GameObject ModifierDisplayObject;
public static GameObject VanillaMatchInfoButton;
public static bool ModifierDisplayOnRight;
public static GameObject ClonedChatButton;
public static GameObject ExtraUiTopRight;
public static GridArrange ExtraUiGrid;
public static AspectPosition ExtraUiAspectPos;
public static GameObject UiTopRight;
public static GridArrange UiGrid;
public static AspectPosition UiAspectPos;
public static GameObject SubmergedFloorButton;
public static SpriteRenderer SubmergedFloorButtonRenderer;
public static SpriteRenderer SubmergedFloorButtonRendererHover;
public void Awake()
{
Instance = this;
}
public void Start()
{
MiraApiSettings.OldButtonScaleFactor =
LocalSettingsTabSingleton<MiraApiSettings>.Instance.TopRightButtonsFactorSlider.Value;
StartCoroutine(MiraApiSettings.CoResizeSettingsUI().WrapToIl2Cpp());
}
#pragma warning disable S2325
#pragma warning disable CA1822
public void FixedUpdate()
{
if (!HudManager.InstanceExists || !PlayerControl.LocalPlayer || !PlayerControl.LocalPlayer.Data)
{
return;
}
var instance = HudManager.Instance;
CreateUiRow(instance);
CreateNewUiRow(instance);
AdjustModifierTab();
if (!PlayerControl.LocalPlayer || !PlayerControl.LocalPlayer.Data || !PlayerControl.LocalPlayer.Data.Role ||
!ShipStatus.Instance ||
(AmongUsClient.Instance.GameState != InnerNetClient.GameStates.Started &&
!TutorialManager.InstanceExists))
{
return;
}
UpdateSubmergedButtons(instance);
}
#pragma warning restore CA1822
#pragma warning restore S2325
public static Vector3 BelowOptionPos = new(0.435f, 1.25f, 0f);
public static Vector3 FullTopPos = new(0.435f, 0.475f, 0f);
public static void CreateUiRow(HudManager instance)
{
if (!UiTopRight)
{
UiTopRight = instance.MapButton.transform.parent.gameObject;
UiGrid = UiTopRight.AddComponent<GridArrange>();
UiAspectPos = UiTopRight.AddComponent<AspectPosition>();
UiGrid.Alignment = GridArrange.StartAlign.Left;
UiGrid.CellSize = new Vector2(0.85f, 0.85f);
UiGrid.MaxColumns = 6;
UiAspectPos.Alignment = AspectPosition.EdgeAlignments.RightTop;
UiGrid.Start();
UiAspectPos.DistanceFromEdge = FullTopPos;
var mapButton = instance.MapButton.gameObject;
mapButton.GetComponent<AspectPosition>().Destroy();
var settingsButton = instance.SettingsButton;
settingsButton.GetComponent<AspectPosition>().Destroy();
VanillaMatchInfoButton = instance.MatchInfoButton.gameObject;
VanillaMatchInfoButton.GetComponent<AspectPosition>().Destroy();
var oldPos = settingsButton.transform.localPosition;
settingsButton.transform.localPosition = new Vector3(oldPos.x, oldPos.y, -100);
var chatButton = instance.Chat.chatButton.gameObject;
ClonedChatButton = Object.Instantiate(chatButton, chatButton.transform.parent);
ClonedChatButton.SetActive(false);
instance.Chat.chatButtonAspectPosition = ClonedChatButton.GetComponent<AspectPosition>();
chatButton.GetComponent<AspectPosition>().Destroy();
var inactivePos = settingsButton.transform.GetChild(1).transform.localPosition;
var bg = settingsButton.transform.GetChild(2).gameObject;
var bgPos = bg.transform.localPosition;
var bgSprite = bg.GetComponent<SpriteRenderer>().sprite;
var activePos = settingsButton.transform.GetChild(3).transform.localPosition;
var selectedPos = settingsButton.transform.GetChild(4).transform.localPosition;
chatButton.transform.GetChild(2).transform.localPosition = inactivePos;
var chatBg = chatButton.transform.GetChild(3);
chatBg.transform.localPosition = bgPos;
chatBg.GetComponent<SpriteRenderer>().sprite = bgSprite;
chatButton.transform.GetChild(4).transform.localPosition = activePos;
chatButton.transform.GetChild(5).transform.localPosition = selectedPos;
var collider = chatButton.GetComponent<BoxCollider2D>();
collider.size = new Vector2(0.4354f, 0.4003f);
collider.offset = new Vector2(0.0025f, 0.0254f);
if (FriendsListManager.InstanceExists && !TutorialManager.InstanceExists)
{
var listButton = FriendsListManager.Instance.FriendsListButton.transform.GetChild(0);
listButton.transform.SetParent(UiTopRight.transform, false);
FriendsListManager.Instance.FriendsListButton = listButton.GetComponent<FriendsListButton>();
listButton.GetComponent<AspectPosition>().Destroy();
listButton.localPosition = new Vector3(0, 0, 0);
}
settingsButton.transform.SetAsLastSibling();
chatButton.transform.SetParent(UiTopRight.transform, false);
instance.Chat.chatButton = chatButton.GetComponent<PassiveButton>();
var iconContainer = new GameObject("iconContainer")
{
layer = LayerMask.NameToLayer("UI"),
};
iconContainer.transform.SetParent(chatButton.transform, false);
iconContainer.transform.localPosition = new Vector3(0.1f, -0.1f, 0);
instance.Chat.chatNotifyDot.transform.SetParent(iconContainer.transform, false);
instance.Chat.chatNotifyDot = iconContainer.transform.GetChild(0).GetComponent<SpriteRenderer>();
}
if (UiTopRight && UiGrid)
{
var isChatButtonVisible = HudManager.Instance.Chat.isActiveAndEnabled;
instance.Chat.chatButton.gameObject.SetActive(isChatButtonVisible);
if (VanillaMatchInfoButton)
{
VanillaMatchInfoButton.SetActive(!GameSettingMenu.Instance && !Minigame.Instance);
}
}
}
public static void UpdateSubmergedButtons(HudManager instance)
{
if (ModCompatibility.IsSubmerged() && !SubmergedFloorButton && ExtraUiTopRight)
{
if (!SubmergedFloorButton && ExtraUiTopRight)
{
var transform = instance.MapButton.transform.parent.Find(instance.MapButton.name + "(Clone)");
if (transform != null)
{
SubmergedFloorButton = transform.gameObject;
SubmergedFloorButton.transform.SetParent(ExtraUiTopRight.transform, false);
SubmergedFloorButtonRenderer =
SubmergedFloorButton.transform.Find("Inactive").GetComponent<SpriteRenderer>();
SubmergedFloorButtonRendererHover =
SubmergedFloorButton.transform.Find("Active").GetComponent<SpriteRenderer>();
MiraApiSettings.SetUpButtonPositions();
}
}
}
}
public static void AdjustModifierTab()
{
if (!ModifierDisplayObject && UiTopRight && ExtraUiTopRight && ModifierDisplayComponent.Instance)
{
ModifierDisplayObject = ModifierDisplayComponent.Instance?.gameObject ?? null!;
ModifierDisplayOnRight = !LocalSettingsTabSingleton<MiraApiSettings>.Instance.ModifiersHudLeftSide.Value;
if (ModifierDisplayOnRight)
{
ModifierDisplayObject.transform.SetParent(ExtraUiTopRight.transform, false);
ModifierDisplayObject.GetComponent<AspectPosition>().Destroy();
var oldPos = ModifierDisplayObject.transform.GetChild(0).localPosition;
ModifierDisplayObject.transform.GetChild(0).localPosition = new Vector3(-1.1757f, -2.1633f, oldPos.z);
oldPos = ModifierDisplayObject.transform.GetChild(1).localPosition;
ModifierDisplayObject.transform.GetChild(1).localPosition = new Vector3(-0.45f, 0.3f, oldPos.z);
}
MiraApiSettings.SetUpButtonPositions();
}
}
public static void CreateNewUiRow(HudManager instance)
{
if (!ExtraUiTopRight && UiTopRight)
{
ExtraUiTopRight = new GameObject("ExtraUiTopRight")
{
layer = UiTopRight.layer,
};
ExtraUiTopRight.transform.SetParent(instance.MapButton.transform.parent.parent, false);
ExtraUiGrid = ExtraUiTopRight.AddComponent<GridArrange>();
ExtraUiAspectPos = ExtraUiTopRight.AddComponent<AspectPosition>();
ExtraUiGrid.Alignment = GridArrange.StartAlign.Left;
ExtraUiGrid.CellSize = new Vector2(0.85f, 0.85f);
ExtraUiAspectPos.Alignment = AspectPosition.EdgeAlignments.RightTop;
ExtraUiAspectPos.DistanceFromEdge = BelowOptionPos;
ExtraUiGrid.Start();
}
}
}
+5
View File
@@ -39,4 +39,9 @@ public interface ILocalSetting
/// <param name="last">Whether it's the last on the row.</param>
/// <returns>The created setting's <see cref="GameObject"/>.</returns>
GameObject? CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last);
/// <summary>
/// Used to refresh the setting's information, usually for localization.
/// </summary>
void RefreshOption();
}
+10 -1
View File
@@ -1,4 +1,5 @@
using System;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
@@ -28,6 +29,8 @@ public class LocalSettingsButton(string text, Action onClick)
/// </summary>
public LocalSettingsTab? Tab { get; internal set; }
private TextMeshPro _btnText { get; set; }
internal GameObject CreateButton(ToggleButtonBehaviour toggle, Transform parent, ref float offset, ref int order, bool last)
{
var button = Object.Instantiate(toggle, parent).GetComponent<PassiveButton>();
@@ -51,7 +54,8 @@ public class LocalSettingsButton(string text, Action onClick)
button.transform.localPosition = new Vector3(order == 1 ? -1.185f : 1.185f, 1.85f - offset, -7);
}
tmp.text = Text;
tmp.text = Text.Translate();
_btnText = tmp;
button.name = Text;
button.OnClick = new UnityEngine.UI.Button.ButtonClickedEvent();
rollover.OutColor = Tab!.TabAppearance.ButtonColor;
@@ -74,4 +78,9 @@ public class LocalSettingsButton(string text, Action onClick)
return button.gameObject;
}
public void RefreshButton()
{
_btnText.text = Text.Translate();
}
}
+35 -8
View File
@@ -2,7 +2,9 @@
using System.Collections.Generic;
using BepInEx.Configuration;
using HarmonyLib;
using MiraAPI.LocalSettings.SettingTypes;
using MiraAPI.Patches.LocalSettings;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
@@ -47,11 +49,21 @@ public abstract class LocalSettingsTab(ConfigFile config)
/// </summary>
public TabGroup? TabButton { get; internal set; }
/// <summary>
/// Gets a collection of <see cref="TextMeshPro"/>s alongside the locale keys for them.
/// </summary>
public static Dictionary<TextMeshPro, string> TabGroups { get; } = [];
/// <summary>
/// Gets the list of <see cref="ILocalSetting"/>s.
/// </summary>
public List<ILocalSetting> Settings { get; } = [];
/// <summary>
/// Gets a collection of <see cref="TextMeshPro"/>s alongside the locale keys for them.
/// </summary>
public Dictionary<TextMeshPro, string> Labels { get; } = [];
/// <summary>
/// Gets the list of <see cref="LocalSettingsButton"/>s.
/// </summary>
@@ -73,12 +85,25 @@ public abstract class LocalSettingsTab(ConfigFile config)
}
/// <summary>
/// Attempts to open the tab.
/// Refreshes setting names upon opening the tab.
/// Override for custom behavior.
/// </summary>
public virtual void Open()
{
OptionsMenuPatches.Instance?.OpenTabGroup(TabIndex);
foreach (var setting in Settings)
{
setting.RefreshOption();
}
foreach (var button in Buttons)
{
button.RefreshButton();
}
foreach (var label in Labels)
{
label.Key.text =
$"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\"><b>{label.Value.Translate()}</b></font>";
}
}
/// <summary>
@@ -216,7 +241,8 @@ public abstract class LocalSettingsTab(ConfigFile config)
tabButtonText.transform.localPosition = new Vector3(0.078f, 0, 0);
tabButtonText.transform.localScale = new Vector3(0.9f, 0.9f);
tabButtonText.alignment = TextAlignmentOptions.Right;
tabButtonText.text = $"<b>{GetShortName(TabName)}</b>";
tabButtonText.text = $"<b>{GetShortName(TabName.Translate())}</b>";
TabGroups.Add(tabButtonText, TabName);
var tabButton = tabButtonObject.GetComponent<PassiveButton>();
var rollover = tabButtonObject.Rollover;
@@ -244,7 +270,7 @@ public abstract class LocalSettingsTab(ConfigFile config)
tabButtonText.gameObject.SetActive(true);
tabButtonText.transform.localPosition = new Vector3(-0.024f, 0, 0);
tabButtonText.maxVisibleCharacters = int.MaxValue;
tabButtonText.text = TabName;
tabButtonText.text = TabName.Translate();
tabButtonText.alignment = TextAlignmentOptions.Left;
tabButtonRend?.gameObject.SetActive(!TabAppearance.HideIconOnHover);
}));
@@ -266,13 +292,13 @@ public abstract class LocalSettingsTab(ConfigFile config)
tabButtonText.transform.localPosition = new Vector3(0.1f, 0, 0);
tabButtonText.maxVisibleCharacters = 4;
tabButtonText.text = $"<b>{GetShortName(TabName)}</b>";
tabButtonText.text = $"<b>{GetShortName(TabName.Translate())}</b>";
}));
return tabButtonObject.gameObject;
}
private static void CreateLabel(GameObject template, Transform parent, string text, ref float offset)
private void CreateLabel(GameObject template, Transform parent, string text, ref float offset)
{
var label = Object.Instantiate(template, parent);
label.transform.localPosition = new Vector3(0, 1.85f - offset);
@@ -280,7 +306,8 @@ public abstract class LocalSettingsTab(ConfigFile config)
label.name = text;
var tmp = label.GetComponent<TextMeshPro>();
tmp.text = $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\"><b>{text}</b></font>";
Labels.Add(tmp, text);
tmp.text = $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\"><b>{text.Translate()}</b></font>";
tmp.alignment = TextAlignmentOptions.Center;
var meshRend = label.GetComponent<MeshRenderer>();
@@ -290,7 +317,7 @@ public abstract class LocalSettingsTab(ConfigFile config)
offset += 0.5f;
}
private static string GetShortName(string name)
internal static string GetShortName(string name)
{
var shortName = string.Empty;
name.Split(' ').Do(x => shortName += x[0]);
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using BepInEx.Configuration;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
@@ -25,6 +26,10 @@ public class LocalEnumSetting : LocalSettingBase<int>
/// </summary>
public string[] Values { get; }
private SpriteRenderer _highlight { get; set; }
private TextMeshPro _btnText { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="LocalEnumSetting"/> class.
/// </summary>
@@ -53,6 +58,7 @@ public class LocalEnumSetting : LocalSettingBase<int>
{
var button = Object.Instantiate(toggle, parent).GetComponent<PassiveButton>();
var tmp = button.transform.FindChild("Text_TMP").GetComponent<TextMeshPro>();
_btnText = tmp;
var rollover = button.GetComponent<ButtonRolloverHandler>();
tmp.GetComponent<TextTranslatorTMP>().Destroy();
button.gameObject.SetActive(true);
@@ -62,6 +68,7 @@ public class LocalEnumSetting : LocalSettingBase<int>
var highlight = button.transform.FindChild("ButtonHighlight")?.GetComponent<SpriteRenderer>();
if (highlight != null)
{
_highlight = highlight;
highlight.color = Tab!.TabAppearance.EnumHoverColor;
highlight.gameObject.SetActive(false);
}
@@ -124,9 +131,19 @@ public class LocalEnumSetting : LocalSettingBase<int>
return button.gameObject;
}
/// <inheritdoc/>
public override void RefreshOption()
{
_btnText.text = GetValueText();
if (_highlight)
{
_highlight.gameObject.SetActive(false);
}
}
/// <inheritdoc/>
protected override string GetValueText()
{
return $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\">{Name}: <b>{Values[GetValue()]}</font></b>";
return $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\">{Name.Translate()}: <b>{Values[GetValue()].Translate()}</font></b>";
}
}
@@ -1,5 +1,6 @@
using System;
using BepInEx.Configuration;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
@@ -34,6 +35,10 @@ public class LocalNumberSetting : LocalSettingBase<float>
/// </summary>
public MiraNumberSuffixes SuffixType { get; }
private SpriteRenderer _highlight { get; set; }
private TextMeshPro _btnText { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="LocalNumberSetting"/> class.
/// </summary>
@@ -64,6 +69,7 @@ public class LocalNumberSetting : LocalSettingBase<float>
{
var button = Object.Instantiate(toggle, parent).GetComponent<PassiveButton>();
var tmp = button.transform.FindChild("Text_TMP").GetComponent<TextMeshPro>();
_btnText = tmp;
var rollover = button.GetComponent<ButtonRolloverHandler>();
tmp.GetComponent<TextTranslatorTMP>().Destroy();
button.gameObject.SetActive(true);
@@ -73,6 +79,7 @@ public class LocalNumberSetting : LocalSettingBase<float>
var highlight = button.transform.FindChild("ButtonHighlight")?.GetComponent<SpriteRenderer>();
if (highlight != null)
{
_highlight = highlight;
highlight.color = Tab!.TabAppearance.NumberHoverColor;
highlight.gameObject.SetActive(false);
}
@@ -135,11 +142,21 @@ public class LocalNumberSetting : LocalSettingBase<float>
return button.gameObject;
}
/// <inheritdoc/>
public override void RefreshOption()
{
_btnText.text = GetValueText();
if (_highlight)
{
_highlight.gameObject.SetActive(false);
}
}
/// <inheritdoc/>
protected override string GetValueText()
{
var value = GetValue();
var formated = Helpers.FormatValue(value, SuffixType, FormatString);
return $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\">{Name}: <b>{formated}</font></b>";
return $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\">{Name.Translate()}: <b>{formated}</font></b>";
}
}
@@ -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 />
@@ -52,6 +54,9 @@ public abstract class LocalSettingBase<T> : ILocalSetting
/// <returns>The created setting.</returns>
public abstract GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last);
/// <inheritdoc/>
public abstract void RefreshOption();
/// <summary>
/// Returns the formated string to use in the text of the setting.
/// </summary>
@@ -1,5 +1,6 @@
using System;
using BepInEx.Configuration;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
@@ -39,6 +40,8 @@ public class LocalSliderSetting : LocalSettingBase<float>
/// </summary>
public MiraNumberSuffixes SuffixType { get; }
private SlideBar _slider { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="LocalSliderSetting"/> class.
/// </summary>
@@ -70,6 +73,7 @@ public class LocalSliderSetting : LocalSettingBase<float>
public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last)
{
var newSlider = Object.Instantiate(slider, parent).GetComponent<SlideBar>();
_slider = newSlider;
var rollover = newSlider.GetComponent<ButtonRolloverHandler>();
newSlider.Title = newSlider.transform.FindChild("Text_TMP").GetComponent<TextMeshPro>(); // Why the hell slider has a title property that is not even assigned???
newSlider.Title.GetComponent<TextTranslatorTMP>().Destroy();
@@ -104,6 +108,12 @@ public class LocalSliderSetting : LocalSettingBase<float>
return newSlider.gameObject;
}
/// <inheritdoc/>
public override void RefreshOption()
{
_slider.Title.text = GetValueText();
}
/// <inheritdoc/>
protected override string GetValueText()
{
@@ -112,9 +122,9 @@ public class LocalSliderSetting : LocalSettingBase<float>
var value = GetValue();
var formated = Helpers.FormatValue(value, SuffixType, FormatString);
var maxFormated = Helpers.FormatValue(SliderRange.max, SuffixType, FormatString);
return $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\">{Name}: <b>{formated} / {maxFormated}</font></b>";
return $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\">{Name.Translate()}: <b>{formated} / {maxFormated}</font></b>";
}
return $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\">{Name}</font></b>";
return $"<font=\"LiberationSans SDF\" material=\"LiberationSans SDF - Chat Message Masked\">{Name.Translate()}</font></b>";
}
}
@@ -1,5 +1,6 @@
using System;
using BepInEx.Configuration;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using Reactor.Localization.Utilities;
using TMPro;
@@ -14,6 +15,8 @@ namespace MiraAPI.LocalSettings.SettingTypes;
/// </summary>
public class LocalToggleSetting : LocalSettingBase<bool>
{
private ToggleButtonBehaviour _toggle { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="LocalToggleSetting"/> class.
/// </summary>
@@ -31,6 +34,7 @@ public class LocalToggleSetting : LocalSettingBase<bool>
public override GameObject CreateOption(ToggleButtonBehaviour toggle, SlideBar slider, Transform parent, ref float offset, ref int order, bool last)
{
var toggleObject = Object.Instantiate(toggle, parent).GetComponent<ToggleButtonBehaviour>();
_toggle = toggleObject;
var tmp = toggleObject.transform.FindChild("Text_TMP").GetComponent<TextMeshPro>();
var passiveButton = toggleObject.GetComponent<PassiveButton>();
var rollover = toggleObject.GetComponent<ButtonRolloverHandler>();
@@ -46,9 +50,9 @@ public class LocalToggleSetting : LocalSettingBase<bool>
toggleObject.transform.localPosition = new Vector3(order == 1 ? -1.185f : 1.185f, 1.85f - offset, -7);
}
toggleObject.BaseText = CustomStringName.CreateAndRegister(Name);
toggleObject.BaseText = MiraLocaleManager.GetOrCreateLocaleString(Name);
toggleObject.UpdateText(GetValue());
toggleObject.name = Name;
toggleObject.name = Name.Translate();
toggleObject.Background.color = GetValue() ? Tab!.TabAppearance.ToggleActiveColor : Tab!.TabAppearance.ToggleInactiveColor;
passiveButton.OnClick = new UnityEngine.UI.Button.ButtonClickedEvent();
rollover.OverColor = Tab!.TabAppearance.ToggleHoverColor;
@@ -85,4 +89,11 @@ public class LocalToggleSetting : LocalSettingBase<bool>
return toggleObject.gameObject;
}
/// <inheritdoc/>
public override void RefreshOption()
{
_toggle.UpdateText(GetValue());
_toggle.Background.color = GetValue() ? Tab!.TabAppearance.ToggleActiveColor : Tab!.TabAppearance.ToggleInactiveColor;
}
}
@@ -0,0 +1,122 @@
using System;
using System.Globalization;
using Il2CppInterop.Runtime.Attributes;
using Reactor.Utilities.Attributes;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
namespace MiraAPI.MeetingAbilities;
/// <summary>
/// A component for handling targeted meeting buttons.
/// </summary>
[RegisterInIl2Cpp]
public class MeetingAbilityBehaviour : MonoBehaviour
{
/// <summary>
/// Gets or sets whether the component has been initialized.
/// </summary>
private bool _init;
/// <summary>
/// The <see cref="TargetedMeetingButton"/> attached to this component.
/// </summary>
private TargetedMeetingButton _button = null!;
/// <summary>
/// The <see cref="PassiveButton"/> of this component.
/// </summary>
public PassiveButton Button;
/// <summary>
/// The parent <see cref="PlayerVoteArea"/>.
/// </summary>
public PlayerVoteArea VoteArea;
/// <summary>
/// The button's <see cref="SpriteRenderer"/> component.
/// </summary>
public SpriteRenderer Renderer;
/// <summary>
/// The <see cref="TextMeshPro"/> label used for showing the ability's cooldown.
/// </summary>
public TextMeshPro CooldownText;
/// <summary>
/// The <see cref="TextMeshPro"/> label used for showing the ability's remaining uses.
/// </summary>
public TextMeshPro UsesText;
/// <summary>
/// Initializes the various properties of this component.
/// </summary>
/// <param name="button">The <see cref="TargetedMeetingButton"/> to initialize this component for.</param>
/// <param name="voteArea">The parent <see cref="PlayerVoteArea"/>.</param>
[HideFromIl2Cpp]
public void Initialize(TargetedMeetingButton button, PlayerVoteArea voteArea)
{
if (_init) return;
VoteArea = voteArea;
_button = button;
Renderer = GetComponent<SpriteRenderer>();
SetFillUp(1, 1);
if (!TryGetComponent(out Button))
{
Error($"Could not initialize MeetingButtonBehaviour for {Button.GetType().Name}, Destroying...");
Destroy(this);
}
_init = true;
CooldownText = Instantiate(HudManager.Instance.KillButton.cooldownTimerText, transform);
CooldownText.GetComponent<TextTranslatorTMP>().Destroy();
CooldownText.transform.localPosition = new Vector3(0, 0, -10);
CooldownText.m_maxFontSize = 3f;
CooldownText.color = new Color(1, 1, 1, 0.7f);
UsesText = Instantiate(CooldownText, transform);
UsesText.transform.localPosition = new Vector3(0.25f, 0.25f, -10);
UsesText.transform.localScale = Vector3.one * 0.7f;
CooldownText.gameObject.SetActive(true);
UsesText.gameObject.SetActive(true);
}
private void OnEnable()
{
if (!_init) return;
Button.enabled = true;
Renderer.enabled = true;
UsesText.enabled = true;
CooldownText.enabled = true;
if (_button.Enabled(PlayerControl.LocalPlayer.Data.Role) && _button.IsTargetValid(VoteArea)) return;
Button.enabled = false;
Renderer.enabled = false;
UsesText.enabled = false;
CooldownText.enabled = false;
}
private void Update()
{
if (!_init) return;
if (_button.Timer < 0.01f)
{
Renderer.material.SetFloat("_Desat", 0.0f);
CooldownText.text = string.Empty;
UsesText.text = _button.LimitedUses ? _button.UsesLeft.ToString(CultureInfo.InvariantCulture) : string.Empty;
}
else
{
Renderer.material.SetFloat("_Desat", 0.5f);
CooldownText.text = _button.Timer.ToString(_button.CooldownTimerFormatString, NumberFormatInfo.InvariantInfo);
UsesText.text = string.Empty;
}
SetFillUp(_button.Timer, _button.InitialCooldown);
}
public void SetFillUp(float timer, float maxTimer)
{
float percentCool = Mathf.Clamp(timer / maxTimer, 0.001f, 1f);
if (percentCool <= 0) percentCool = 1f;
Renderer.material.SetFloat("_Percent", percentCool);
}
}
@@ -0,0 +1,349 @@
using System;
using MiraAPI.Events;
using MiraAPI.Events.Mira;
using MiraAPI.Hud;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Object = UnityEngine.Object;
namespace MiraAPI.MeetingAbilities;
/// <summary>
/// Class for making custom meeting action buttons.
/// </summary>
public abstract class MeetingActionButton
{
/// <summary>
/// Gets the name and text of the button.
/// </summary>
public abstract string Name { get; }
/// <summary>
/// Gets the initial cooldown duration in seconds.
/// </summary>
public virtual float InitialCooldown => Cooldown;
/// <summary>
/// Gets the button's cooldown duration in seconds.
/// </summary>
public abstract float Cooldown { get; }
/// <summary>
/// Gets the sprite of the button. Use <see cref="LoadableResourceAsset"/> to load a sprite from a resource path. Use <see cref="LoadableBundleAsset{T}"/> to load a sprite from an asset bundle.
/// </summary>
public abstract LoadableAsset<Sprite> Sprite { get; }
/// <summary>
/// Gets the format string for the cooldown timer.
/// </summary>
public virtual string CooldownTimerFormatString => "0";
/// <summary>
/// Gets a value indicating whether the button has limited uses.
/// </summary>
public bool LimitedUses => ZeroIsInfinite ? MaxUses > 0 : MaxUses >= 0;
/// <summary>
/// Gets the maximum number of uses the button has. If the button has infinite uses, set to 0 or -1 based on what value that ZeroIsInfinite is set to.
/// </summary>
public virtual int MaxUses => ZeroIsInfinite ? 0 : -1;
/// <summary>
/// Gets the value indicating uses mode.
/// </summary>
public virtual MeetingButtonUsesMode UsesMode => MeetingButtonUsesMode.PerGame;
/// <summary>
/// Gets the button's text outline <see cref="Color"/>.
/// </summary>
public virtual Color TextOutlineColor => Color.clear;
/// <summary>
/// Gets or sets a value indicating whether limited uses are determined via zero or a negative number of uses.
/// </summary>
public virtual bool ZeroIsInfinite { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether the timer is currently active.
/// </summary>
public bool TimerPaused { get; set; }
/// <summary>
/// Gets or sets a value indicating how many times the ability was used in the current meeting.
/// </summary>
public int UsesSoFar { get; set; }
/// <summary>
/// Gets a value determining if the abiity is disabled upon being used.
/// </summary>
public virtual bool DisableUponUse => false;
/// <summary>
/// Gets a value determining if the abiity is disabled upon voting.
/// </summary>
public virtual bool DisableUponVoting => false;
/// <summary>
/// Gets a value determining if the abiity is hidden when votes wrapping up.
/// </summary>
public virtual bool HideUponWrapUp => false;
/// <summary>
/// Gets or sets the amount of uses left.
/// </summary>
public int UsesLeft { get; set; }
/// <summary>
/// Gets or sets the timer variable to measure cooldowns and effects.
/// </summary>
public float Timer { get; set; }
/// <summary>
/// Gets or sets the <see cref="ActionButton"/> object in game. This is created by Mira API automatically.
/// </summary>
public ActionButton? Button { get; set; }
/// <summary>
/// The method used to create the button.
/// </summary>
/// <param name="parent">The parent of the button.</param>
public virtual void CreateButton(Transform parent)
{
if (Button)
{
return;
}
Timer = AmongUsClient.Instance?.NetworkMode == NetworkModes.FreePlay ? 0 : InitialCooldown;
TimerPaused = false;
Button = Object.Instantiate(MeetingHud.Instance.MeetingAbilityButton, parent);
Button.name = Name + "Button";
Button.OverrideText(Name.ToUpperInvariant());
Button.graphic.sprite = Sprite.LoadAsset();
Button.SetUsesRemaining(UsesLeft);
UsesSoFar = 0;
if (MaxUses <= 0)
{
Button.SetInfiniteUses();
}
if (TextOutlineColor != Color.clear)
{
SetTextOutline(TextOutlineColor);
}
var pb = Button.GetComponent<PassiveButton>();
pb.OnClick = new Button.ButtonClickedEvent();
pb.OnClick.AddListener((UnityAction)(() =>
{
ClickHandler();
}));
Button.gameObject.SetActive(Enabled(PlayerControl.LocalPlayer.Data.Role));
}
/// <summary>
/// A utility function to change the outline <see cref="Color"/> of the button's text.
/// </summary>
/// <param name="color">The new <see cref="Color"/>.</param>
public virtual void SetTextOutline(Color color)
{
Button?.buttonLabelText.SetOutlineColor(color);
}
/// <summary>
/// A utility function to override the <see cref="UnityEngine.Sprite"/> of the button.
/// </summary>
/// <param name="sprite">The new <see cref="UnityEngine.Sprite"/> to override with.</param>
public virtual void OverrideSprite(Sprite sprite)
{
if (Button != null)
{
Button.graphic.sprite = sprite;
}
}
/// <summary>
/// A utility function to override the name of the button.
/// </summary>
/// <param name="name">The new name to override with.</param>
public virtual void OverrideName(string name)
{
Button?.OverrideText(name);
}
/// <summary>
/// Set the button's timer.
/// </summary>
/// <param name="time">The time you want to set to.</param>
public virtual void SetTimer(float time)
{
Timer = Mathf.Clamp(time, -1, float.MaxValue);
}
/// <summary>
/// Increase the button's timer.
/// </summary>
/// <param name="amount">The amount you want to increase by.</param>
public virtual void IncreaseTimer(float amount)
{
SetTimer(Timer + amount);
}
/// <summary>
/// Decrease the button's timer.
/// </summary>
/// <param name="amount">The amount you want to decrease by.</param>
public virtual void DecreaseTimer(float amount)
{
SetTimer(Timer - amount);
}
/// <summary>
/// Sets whether the timer is paused or not.
/// </summary>
/// <param name="val">Whether you want to pause/resume the timer.</param>
public virtual void SetTimerPaused(bool val)
{
TimerPaused = val;
}
/// <summary>
/// Set the amount of uses this button has left.
/// </summary>
/// <param name="amount">The amount you want to set to.</param>
public virtual void SetUses(int amount)
{
UsesLeft = Mathf.Clamp(amount, 0, int.MaxValue);
Button?.SetUsesRemaining(UsesLeft);
if (Button != null)
{
Button.usesRemainingSprite.color = UsesLeft == 0 ? Color.red : Color.white;
}
}
/// <summary>
/// Increase the amount of uses this button has left.
/// </summary>
/// <param name="amount">The amount you want to increase by. Default: 1.</param>
public virtual void IncreaseUses(int amount = 1)
{
SetUses(UsesLeft + amount);
}
/// <summary>
/// Decrease the amount of uses this button has left.
/// </summary>
/// <param name="amount">The amount you want to decrease by. Default: 1.</param>
public virtual void DecreaseUses(int amount = 1)
{
SetUses(UsesLeft - amount);
}
/// <summary>
/// A utility function that runs with the local player's <see cref="MeetingHud.Update"/> if the button is enabled.
/// </summary>
/// <param name="hud">the <see cref="MeetingHud"/> instance.</param>
protected virtual void FixedUpdate(MeetingHud hud)
{
}
/// <summary>
/// Callback method for the button click event.
/// </summary>
protected abstract void OnClick();
/// <summary>
/// This method determines if the button should be active or not.
/// <see langword="true"/> means the button is active, <see langword="false"/> means the button is disabled.
/// </summary>
/// <param name="role">The <see cref="RoleBehaviour"/> of the local player.</param>
/// <returns><see langword="true"/> if the button is enabled, <see langword="false"/> otherwise.</returns>
public abstract bool Enabled(RoleBehaviour? role);
/// <summary>
/// When the button is usable, this method is called to determine if the button can be clicked.
/// By default, it takes into account the timer, effect, and uses.
/// You can override it to change the behavior.
/// </summary>
/// <returns>A value that represents whether the button can be clicked or not.</returns>
public virtual bool CanClick()
{
return Timer <= 0 && CanUse();
}
/// <summary>
/// Whether the button should light up or not. This is also the base for CanClick.
/// You can override it to change the behaviour. Do not include timer in here, that is for CanClick.
/// </summary>
/// <returns>A value that represents whether the button should light up or not.</returns>
public virtual bool CanUse()
{
return (!DisableUponUse || UsesSoFar < 1) &&
(!DisableUponVoting || MeetingHud.Instance.CurrentState is not MeetingHud.MeetingStates.Voted) &&
(!LimitedUses || UsesLeft > 0);
}
/// <summary>
/// This method handles the button click event. It is a wrapper for the <see cref="OnClick"/> method.
/// This method takes into account cooldowns, effects, and uses, before calling the <see cref="OnClick"/> method.
/// It can be overridden for custom behavior.
/// </summary>
public virtual void ClickHandler()
{
if (!CanClick())
{
return;
}
if (LimitedUses)
{
UsesLeft--;
Button?.SetUsesRemaining(UsesLeft);
}
Timer = Cooldown;
OnClick();
UsesSoFar++;
if (DisableUponUse && Button)
{
Button!.SetDisabled();
}
}
/// <summary>
/// This method is called on the <see cref="MeetingHud.Update"/> method. It is a wrapper for the <see cref="FixedUpdate"/> method.
/// By default, it handles the cooldown and effect timers, and sets the button to enabled or disabled.
/// It can be overridden for custom behavior.
/// </summary>
/// <param name="hud">The <see cref="MeetingHud"/> instance.</param>
public virtual void UpdateHandler(MeetingHud hud)
{
if (Timer >= 0 && !TimerPaused)
{
Timer -= Time.deltaTime;
}
if (Button)
{
if (CanUse())
{
Button!.SetEnabled();
}
else
{
Button!.SetDisabled();
}
Button.SetCooldownFormat(Timer, Cooldown, CooldownTimerFormatString);
Button.SetCoolDown(Timer, Cooldown);
}
FixedUpdate(hud);
}
}
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Modifiers;
using MiraAPI.Modifiers.Types;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities.Assets;
using MiraAPI.Utilities.Components;
using UnityEngine;
namespace MiraAPI.MeetingAbilities;
/// <summary>
/// Class for managing all registered meeting abilities.
/// </summary>
public static class MeetingButtonManager
{
/// <summary>
/// Gets a list if==of all registered <see cref="TargetedMeetingButton"/>.
/// </summary>
public static List<TargetedMeetingButton> TargetedButtons { get; internal set; } = new();
/// <summary>
/// Gets a list if==of all registered <see cref="MeetingActionButton"/>.
/// </summary>
public static List<MeetingActionButton> UntargetedButtons { get; internal set; } = new();
internal static bool RegisterTargetedMeetingButton(Type type, MiraPluginInfo info)
{
if (!typeof(TargetedMeetingButton).IsAssignableFrom(type))
{
return false;
}
var button = Activator.CreateInstance(type) as TargetedMeetingButton;
info.InternalTargetedMeetingButtons.Add(button);
TargetedButtons.Add(button);
return true;
}
internal static bool RegisterMeetingButton(Type type, MiraPluginInfo info)
{
if (!typeof(MeetingActionButton).IsAssignableFrom(type))
{
return false;
}
var button = Activator.CreateInstance(type) as MeetingActionButton;
info.InternalMeetingButtons.Add(button);
UntargetedButtons.Add(button);
return true;
}
private static CenteredGridArrange? actionButtonsParent = null!;
public static void OnGameStart()
{
foreach (var ability in TargetedButtons.Where(x => x.UsesMode == MeetingButtonUsesMode.PerGame))
{
ability.UsesLeft = ability.MaxUses;
}
foreach (var ability in UntargetedButtons.Where(x => x.UsesMode == MeetingButtonUsesMode.PerGame))
{
ability.UsesLeft = ability.MaxUses;
}
}
/// <summary>
/// Called on <see cref="MeetingHud.Start"/>. Handles button creation, and ability uses.
/// </summary>
/// <param name="meetingHud">The <see cref="MeetingHud"/> instance.</param>
public static void OnMeetingStart(MeetingHud meetingHud)
{
// Untargeted buttons parent.
actionButtonsParent = new GameObject("ActionsButtonParent").AddComponent<CenteredGridArrange>();
actionButtonsParent.transform.SetParent(meetingHud.MeetingAbilityButton.transform.parent, meetingHud.MeetingAbilityButton.transform.parent);
actionButtonsParent.CellSize = new Vector2(0.7f, 0.7f);
actionButtonsParent.transform.localPosition = new Vector3(0, -2.1f, -10);
meetingHud.MeetingAbilityButton.transform.SetParent(actionButtonsParent.transform);
// Untargeted buttons creation.
foreach (var ability in UntargetedButtons)
{
try
{
ability.CreateButton(actionButtonsParent.transform);
if (ability.UsesMode == MeetingButtonUsesMode.PerMeeting) ability.UsesLeft = ability.MaxUses;
ability.Timer = ability.InitialCooldown;
}
catch (Exception e)
{
Error($"Failed to create meeting button {ability.Name}: {e.Message}");
}
}
// Targeted buttons creation.
foreach (var ability in TargetedButtons)
{
try
{
foreach (var playerVoteArea in meetingHud.playerStates)
{
var btn = ability.CreateButton(playerVoteArea);
btn.transform.SetParent(playerVoteArea.Buttons.transform);
}
var btn2 = ability.CreateButton(meetingHud.SkipVoteButton);
btn2.transform.SetParent(meetingHud.SkipVoteButton.Buttons.transform);
if (ability.UsesMode == MeetingButtonUsesMode.PerMeeting) ability.UsesLeft = ability.MaxUses;
if (ability is MultiTargetMeetingButton multiAbility) multiAbility.Targets = new();
}
catch (Exception e)
{
Error($"Failed to create targeted meeting button {ability.Name}: {e.Message}");
}
}
foreach (var playerVoteArea in meetingHud.playerStates)
{
playerVoteArea.CancelButton.transform.SetAsFirstSibling();
}
meetingHud.SkipVoteButton.CancelButton.transform.SetAsFirstSibling();
}
}
@@ -0,0 +1,7 @@
namespace MiraAPI.MeetingAbilities;
public enum MeetingButtonUsesMode
{
PerGame,
PerMeeting
}
@@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Utilities.Assets;
using UnityEngine;
using UnityEngine.UI;
namespace MiraAPI.MeetingAbilities;
/// <summary>
/// Abstract class for creating multi target meeting abilities
/// </summary>
public abstract class MultiTargetMeetingButton : TargetedMeetingButton
{
/// <summary>
/// The <see cref="LoadableAsset{Sprite}"/> used for when the button is on.
/// </summary>
public abstract LoadableAsset<Sprite> SpriteActive { get; }
/// <summary>
/// Gets the required targets count.
/// </summary>
public abstract int TargetsCount { get; }
/// <summary>
/// Gets or sets all selected targets.
/// </summary>
public Dictionary<PlayerVoteArea, MeetingAbilityBehaviour> Targets { get; set; } = new();
/// <inheritdoc />
public override void ClickHandler(MeetingAbilityBehaviour button, PlayerVoteArea playerVoteArea)
{
if (UsesLeft <= 0 && LimitedUses) return;
if (Timer > 0) return;
var toggle = !Targets.Remove(playerVoteArea);
if (toggle) Targets.Add(playerVoteArea, button);
button.Renderer.sprite = toggle ? SpriteActive.LoadAsset() : Sprite.LoadAsset();
if (Targets.Count >= TargetsCount)
{
playerVoteArea.Cancel();
HandleFinish();
return;
}
OnSelect(playerVoteArea, toggle);
}
/// <summary>
/// Handles the finish logic, increasing timer, and decreasing uses.
/// </summary>
public virtual void HandleFinish()
{
Targets = Targets.Take(TargetsCount).ToDictionary(pair => pair.Key, pair => pair.Value);
foreach (var button in Targets.Values)
{
button.Renderer.sprite = Sprite.LoadAsset();
}
Timer = Cooldown;
UsesLeft -= 1;
OnFinish();
Targets = new();
}
/// <summary>
/// Callback method for when a player is selected.
/// </summary>
/// <param name="playerVoteArea">The target <see cref="PlayerVoteArea"/>.</param>
/// <param name="toggle">Whether the button was toggled on/off.</param>
protected abstract void OnSelect(PlayerVoteArea playerVoteArea, bool toggle);
/// <summary>
/// Callback method for the button click.
/// USE <see cref="OnSelect"/> INSTEAD!!!.
/// </summary>
/// <param name="playerVoteArea">The target <see cref="PlayerVoteArea"/>.</param>
protected override void OnClick(PlayerVoteArea playerVoteArea)
{
}
/// <summary>
/// Callback method for when enough targets are chosen.
/// </summary>
public abstract void OnFinish();
/// <inheritdoc />
public override MeetingAbilityBehaviour CreateButton(PlayerVoteArea playerVoteArea)
{
Targets = new();
var button = base.CreateButton(playerVoteArea);
button.Button.OnClick = new Button.ButtonClickedEvent();
button.Button.OnClick.AddListener(new System.Action(() => { ClickHandler(button, playerVoteArea); }));
return button;
}
}
@@ -0,0 +1,155 @@
using System.Collections.Generic;
using MiraAPI.Utilities.Assets;
using UnityEngine;
using UnityEngine.UI;
namespace MiraAPI.MeetingAbilities;
/// <summary>
/// Abstract class for creating targeted meeting abilities.
/// </summary>
public abstract class TargetedMeetingButton
{
/// <summary>
/// Gets the name of the <see cref="TargetedMeetingButton"/>.
/// </summary>
public abstract string Name { get; }
/// <summary>
/// Gets the Max Uses of the button.
/// Set it to 0 for Infinite uses.
/// </summary>
public abstract int MaxUses { get; }
/// <summary>
/// Gets or sets the amount of uses left for this button.
/// </summary>
public int UsesLeft { get; set; }
/// <summary>
/// Gets a value indicating whether the <see cref="TargetedMeetingButton"/> has limited uses.
/// </summary>
public bool LimitedUses => MaxUses != 0;
/// <summary>
/// Gets the cooldown time for this button upon meeting start.
/// Defaults to <see cref="Cooldown"/> unless overridden.
/// </summary>
public virtual float InitialCooldown => Cooldown;
/// <summary>
/// Gets the cooldown time for this button after being used.
/// </summary>
public abstract float Cooldown { get; }
/// <summary>
/// Gets or sets the current cooldown timer for this button.
/// </summary>
public float Timer { get; set; }
/// <summary>
/// Gets the cooldown time for this button.
/// </summary>
public virtual string CooldownTimerFormatString => "0";
/// <summary>
/// Gets the sprite used for this button.
/// </summary>
public abstract LoadableAsset<Sprite> Sprite { get; }
/// <summary>
/// Gets the button's outline color.
/// </summary>
public abstract Color OutlineColor { get; }
/// <summary>
/// Gets the <see cref="MeetingButtonUsesMode"/> for this button.
/// </summary>
public virtual MeetingButtonUsesMode UsesMode { get; } = MeetingButtonUsesMode.PerGame;
/// <summary>
/// Determines if the button is enabled.
/// </summary>
/// <param name="r">The local player's <see cref="RoleBehaviour"/>.</param>
/// <returns>Whether the button is enabled or not.</returns>
public abstract bool Enabled(RoleBehaviour r);
/// <summary>
/// Callback method for when the button is clicked.
/// </summary>
/// <param name="playerVoteArea">The target <see cref="PlayerVoteArea"/>.</param>
protected abstract void OnClick(PlayerVoteArea playerVoteArea);
/// <summary>
/// Handles the button creation.
/// </summary>
/// <param name="playerVoteArea">The target <see cref="PlayerVoteArea"/>.</param>
/// <returns>The <see cref="MeetingAbilityBehaviour"/> instance.</returns>
public virtual MeetingAbilityBehaviour CreateButton(PlayerVoteArea playerVoteArea)
{
if (MeetingHud.Instance == null) return null!;
var btn = Object.Instantiate(MeetingHud.Instance.PlayerButtonPrefab.ConfirmButton).GetComponent<PassiveButton>();
btn.gameObject.name = Name + "Button";
var spriteRenderer = btn.GetComponent<SpriteRenderer>();
spriteRenderer.sprite = Sprite.LoadAsset();
spriteRenderer.material = new Material(HudManager.Instance.KillButton.graphic.material);
spriteRenderer.SetCooldownNormalizedUvs();
btn.gameObject.SetActive(true);
btn.transform.GetChild(0).GetComponent<SpriteRenderer>().color = OutlineColor;
btn.OnClick = new Button.ButtonClickedEvent();
var abilityBehaviour = btn.gameObject.AddComponent<MeetingAbilityBehaviour>();
abilityBehaviour.Initialize(this, playerVoteArea);
btn.OnClick.AddListener(new System.Action(() => ClickHandler(abilityBehaviour, playerVoteArea)));
Timer = InitialCooldown;
return abilityBehaviour;
}
/// <summary>
/// Called every <see cref="MeetingHud.Update"/>.
/// Handles the timer logic.
/// </summary>
public virtual void UpdateHandler()
{
Timer -= Time.deltaTime;
Timer = Mathf.Clamp(Timer, 0, int.MaxValue);
FixedUpdate();
}
/// <summary>
/// Callback method for handling logic every frame.
/// </summary>
public virtual void FixedUpdate()
{
}
/// <summary>
/// Called when the button is clicked
/// Handles increasing cooldown and decreasing uses remaining.
/// </summary>
/// <param name="button">The <see cref="MeetingAbilityBehaviour"/> instance.</param>
/// <param name="playerVoteArea">The target <see cref="PlayerVoteArea"/>.</param>
public virtual void ClickHandler(MeetingAbilityBehaviour button, PlayerVoteArea playerVoteArea)
{
if (UsesLeft <= 0 && LimitedUses) return;
if (Timer > 0) return;
Timer = Cooldown;
UsesLeft--;
playerVoteArea.Cancel();
OnClick(playerVoteArea);
}
/// <summary>
/// Determines whether the target is valid.
/// </summary>
/// <param name="playerVoteArea">The target <see cref="PlayerVoteArea"/>.</param>
/// <returns>Whether the target is valid or not.</returns>
public virtual bool IsTargetValid(PlayerVoteArea playerVoteArea)
{
return playerVoteArea != null && playerVoteArea.PlayerId.Value != PlayerControl.LocalPlayer.Data.PlayerId && playerVoteArea.PlayerId.Value != PlayerVoteArea.SkippedVote;
}
}
@@ -0,0 +1,19 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace MiraAPI.MeetingAbilities;
/// <summary>
/// A utility class to get the instance of a <see cref="TargetedMeetingButton"/>.
/// </summary>
/// <typeparam name="T">The type of the button you are trying to access.</typeparam>
public static class TargetedMeetingButtonSingleton<T> where T : TargetedMeetingButton
{
private static T? _instance;
/// <summary>
/// Gets the instance of the <typeparamref name="T"/> button.
/// </summary>
[SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "This is a utility class to get the instance of a targeted meeting button.")]
public static T Instance => _instance ??= MeetingButtonManager.TargetedButtons.OfType<T>().Single();
}
+33 -3
View File
@@ -1,10 +1,15 @@
global using static Reactor.Utilities.Logger<MiraAPI.MiraApiPlugin>;
using System;
using System.Globalization;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MiraAPI.Translation;
using MiraAPI.VanillaEvents;
using Reactor;
using Reactor.Localization;
using Reactor.Networking;
using Reactor.Networking.Attributes;
using Reactor.Utilities;
@@ -18,10 +23,26 @@ namespace MiraAPI;
[BepInAutoPlugin("mira.api", "MiraAPI")]
[BepInProcess("Among Us.exe")]
[BepInDependency(ReactorPlugin.Id)]
[BepInDependency(ModCompatibility.SubmergedId, BepInDependency.DependencyFlags.SoftDependency)]
[ReactorModFlags(ModFlags.RequireOnAllClients)]
public partial class MiraApiPlugin : BasePlugin
public partial class MiraApiPlugin : BasePlugin, IMiraPlugin
{
/// <inheritdoc />
public ConfigFile GetConfigFile()
{
return Config;
}
/// <summary>
/// Gets the specified Culture for string manipulations.
/// </summary>
public static CultureInfo Culture { get; internal set; } = new("en-US");
/// <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>
@@ -49,10 +70,19 @@ public partial class MiraApiPlugin : BasePlugin
public override void Load()
{
Harmony.PatchAll();
UiResetEvents.Initialize();
JudgeEvents.Initialize();
ReactorCredits.Register("Mira API", Version, IsDevBuild, ReactorCredits.AlwaysShow);
PluginManager = new MiraPluginManager();
PluginManager.Initialize();
PluginManager.Initialize(this, this);
MiraLocaleManager.Register("mira.api");
LocalizationManager.Register(new MiraLocalizationProvider());
IL2CPPChainloader.Instance.Finished +=
ModCompatibility
.Initialize; // Initialise AFTER the mods are loaded to ensure maximum parity (no need for the soft dependency either then)
}
}
+142 -21
View File
@@ -1,7 +1,12 @@
using BepInEx.Configuration;
using System.Collections;
using BepInEx.Configuration;
using MiraAPI.Events;
using MiraAPI.Events.Mira;
using MiraAPI.Hud;
using MiraAPI.LocalSettings;
using MiraAPI.LocalSettings.Attributes;
using MiraAPI.Patches;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
@@ -14,7 +19,7 @@ namespace MiraAPI;
public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config)
{
/// <inheritdoc />
public override string TabName => "Mira API";
public override string TabName => "MiraApi";
/// <inheritdoc />
public override LocalSettingTabAppearance TabAppearance => new()
@@ -25,15 +30,21 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config)
};
/// <summary>
/// Gets or sets the value stored for scaling buttons properly.
/// Gets or sets the value stored for scaling ability buttons properly.
/// </summary>
public static float OldButtonScaleFactor { get; set; }
/// <summary>
/// Gets or sets the value stored for scaling UI buttons properly.
/// </summary>
public static float OldUiButtonScaleFactor { get; set; }
/// <inheritdoc />
public override void Open()
{
base.Open();
OldButtonScaleFactor = ButtonUIFactorSlider.Value;
OldUiButtonScaleFactor = TopRightButtonsFactorSlider.Value;
}
/// <inheritdoc />
@@ -49,53 +60,163 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config)
}
OldButtonScaleFactor = ButtonUIFactorSlider.Value;
}
else if (configEntry == TopRightButtonsFactorSlider)
{
if (MiraHudHelper.Instance)
{
ResizeUI(TopRightButtonsFactorSlider.Value);
}
OldUiButtonScaleFactor = TopRightButtonsFactorSlider.Value;
}
else if (configEntry == WikiOnBottomRow)
{
SetUpButtonPositions();
}
else if (configEntry == SetFpsSlider)
{
Application.targetFrameRate = (int)SetFpsSlider.Value;
}
}
/// <summary>
/// Gets whether the modifiers hud should be on the left side of the screen (under roles/task tab). Recommended for streamers.
/// </summary>
[LocalToggleSetting]
public ConfigEntry<bool> ModifiersHudLeftSide { get; private set; } = config.Bind("Visuals/UI", "Show Modifiers HUD on Left Side", false);
public static void SetUpButtonPositions()
{
var topUi = MiraHudHelper.UiTopRight;
var extraTopUi = MiraHudHelper.ExtraUiTopRight;
if (topUi && extraTopUi)
{
var genericEvent = new UiButtonResetEvent();
MiraEventManager.InvokeEvent(genericEvent);
var genericEvent2 = new UiButtonPostResetEvent(topUi, extraTopUi);
MiraEventManager.InvokeEvent(genericEvent2);
MiraHudHelper.UiGrid.ArrangeChilds();
MiraHudHelper.ExtraUiGrid.ArrangeChilds();
}
}
public static IEnumerator CoResizeSettingsUI()
{
while (!HudManager.Instance || !MiraHudHelper.UiGrid || !MiraHudHelper.ExtraUiGrid)
{
yield return null;
}
yield return new WaitForSeconds(0.01f);
ResizeUI(LocalSettingsTabSingleton<MiraApiSettings>.Instance.TopRightButtonsFactorSlider.Value);
}
public static void ResizeUI(float scaleFactor)
{
var alteredScale = scaleFactor * 0.85f;
var actualScaleVal = scaleFactor * 1.176470588235294f;
var actualScale = new Vector3(actualScaleVal, actualScaleVal, 1);
var baseAspect = MiraHudHelper.UiAspectPos;
var baseGrid = MiraHudHelper.UiGrid;
var baseUi = MiraHudHelper.UiTopRight;
if (baseUi && baseAspect && baseGrid)
{
baseAspect.DistanceFromEdge = new Vector2(0.435f * scaleFactor, 0.475f * scaleFactor);
foreach (var button in baseUi.GetComponentsInChildren<PassiveButton>(true))
{
if (button.gameObject == null)
{
continue;
}
if (button.transform.name.Contains("Friends List Button"))
{
button.gameObject.transform.localScale = new Vector3(0.2675f * actualScaleVal, 0.2675f * actualScaleVal, 1);
continue;
}
button.gameObject.transform.localScale = actualScale;
}
baseGrid.CellSize = new Vector2(alteredScale, alteredScale);
if (baseGrid.gameObject.transform.childCount != 0)
{
baseGrid.ArrangeChilds();
}
baseAspect.AdjustPosition();
}
var extraAspect = MiraHudHelper.ExtraUiAspectPos;
var extraGrid = MiraHudHelper.ExtraUiGrid;
var extraUi = MiraHudHelper.ExtraUiTopRight;
if (extraUi && extraAspect && extraGrid)
{
extraAspect.DistanceFromEdge = new Vector3(0.435f * scaleFactor, 1.25f * scaleFactor, 0f);
foreach (var button in extraUi.GetAllChildren())
{
if (button.gameObject == null)
{
continue;
}
if (button.transform.name.Contains("Modifiers"))
{
button.gameObject.transform.localScale = new Vector3(0.65f * scaleFactor, 0.65f * scaleFactor, 1);
continue;
}
button.gameObject.transform.localScale = actualScale;
}
extraGrid.CellSize = new Vector2(alteredScale, alteredScale);
if (extraGrid.gameObject.transform.childCount != 0)
{
extraGrid.ArrangeChilds();
}
extraAspect.AdjustPosition();
}
}
/// <summary>
/// Gets whether to show keybinds on buttons.
/// </summary>
[LocalToggleSetting]
public ConfigEntry<bool> ShowKeybinds { get; private set; } = config.Bind("Visuals/UI", "Show Keybinds on Buttons", true);
/// <summary>
/// Gets the scale of the buttons.
/// Gets the scale of the ability buttons.
/// </summary>
[LocalSliderSetting(min: 0.5f, max: 1.5f, suffixType: MiraNumberSuffixes.Multiplier, formatString: "0.00", displayValue: true)]
public ConfigEntry<float> ButtonUIFactorSlider { get; private set; } =
config.Bind("Visuals/UI", "Button Scale Factor", 0.75f);
config.Bind("MiraApi.VisualsUi", "MiraApi.ButtonScaleFactor", 0.75f);
/// <summary>
/// Gets the scale of the UI buttons.
/// </summary>
[LocalSliderSetting(min: 0.3f, max: 2f, suffixType: MiraNumberSuffixes.Multiplier, formatString: "0.00", displayValue: true)]
public ConfigEntry<float> TopRightButtonsFactorSlider { get; private set; } =
config.Bind("MiraApi.VisualsUi", "MiraApi.TopRightButtonScaleFactor", 1f);
/// <summary>
/// Gets the fps specified by the player.
/// </summary>
[LocalSliderSetting(min: 60f, max: 240f, suffixType: MiraNumberSuffixes.None, formatString: "0", displayValue: true, roundValue: true)]
public ConfigEntry<float> SetFpsSlider { get; private set; } =
config.Bind("Visuals/UI", "Max FPS", 120f);
config.Bind("MiraApi.VisualsUi", "Max FPS", 120f);
/// <summary>
/// Gets whether to apply cosmetic changes to the TaskAdder.
/// Gets whether the modifiers hud should be on the left side of the screen (under roles/task tab). Recommended for streamers.
/// </summary>
[LocalToggleSetting]
public ConfigEntry<bool> PrettyTaskAdder { get; private set; } = config.Bind("Freeplay", "Pretty Task Laptop", true);
public ConfigEntry<bool> ModifiersHudLeftSide { get; private set; } = config.Bind("MiraApi.VisualsUi", "MiraApi.ShowModifiersHudOnLeftSide", false);
/// <summary>
/// Gets whether to show keybinds on buttons.
/// </summary>
[LocalToggleSetting]
public ConfigEntry<bool> ShowKeybinds { get; private set; } = config.Bind("MiraApi.VisualsUi", "MiraApi.ShowKeybindsOnButtons", true);
[LocalToggleSetting]
public ConfigEntry<bool> WikiOnBottomRow { get; private set; } =
config.Bind("MiraApi.VisualsUi", "MiraApi.WikiOnBottomRow", true);
/// <summary>
/// Gets whether to show the red flash from sabotages.
/// </summary>
[LocalToggleSetting]
public ConfigEntry<bool> EnableSabotageFlashes { get; private set; } = config.Bind("Accessibility", "Enable Sabotage Flashes", true);
public ConfigEntry<bool> EnableSabotageFlashes { get; private set; } = config.Bind("MiraApi.Accessibility", "MiraApi.EnableSabotageFlashes", true);
/// <summary>
/// Gets whether to enable the sabotage sound effects or not.
/// </summary>
[LocalToggleSetting]
public ConfigEntry<bool> EnableSabotageBlares { get; private set; } = config.Bind("Accessibility", "Enable Sabotage Blare", true);
public ConfigEntry<bool> EnableSabotageBlares { get; private set; } = config.Bind("MiraApi.Accessibility", "MiraApi.EnableSabotageBlare", true);
}
+32 -11
View File
@@ -1,6 +1,6 @@
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Reflection;
using BepInEx.Unity.IL2CPP;
using SemanticVersioning;
namespace MiraAPI;
@@ -14,15 +14,36 @@ public static class ModCompatibility
/// </summary>
public const string SubmergedId = "Submerged";
/// <summary>
/// Checks if the Submerged mod is loaded.
/// </summary>
/// <param name="submergedAssembly">Submerged mod assembly if loaded, <see langword="null"/> otherwise.</param>
/// <returns><see langword="true"/> if the Submerged mod is loaded, <see langword="false"/> otherwise.</returns>
public static bool SubmergedLoaded([NotNullWhen(true)] out Assembly? submergedAssembly)
public static Version SubVersion { get; private set; }
public static bool SubLoaded { get; private set; }
public static BasePlugin SubPlugin { get; private set; }
public static Assembly SubAssembly { get; private set; }
public const ShipStatus.MapType SubmergedMapType = (ShipStatus.MapType)6;
public static void Initialize()
{
var result = IL2CPPChainloader.Instance.Plugins.TryGetValue(SubmergedId, out var plugin);
submergedAssembly = result ? plugin?.Instance.GetType().Assembly : null;
return result;
InitSubmerged();
}
public static void InitSubmerged()
{
if (!IL2CPPChainloader.Instance.Plugins.TryGetValue(SubmergedId, out var plugin))
{
return;
}
SubPlugin = (plugin!.Instance as BasePlugin)!;
SubVersion = plugin.Metadata.Version;
SubAssembly = SubPlugin.GetType().Assembly;
SubLoaded = true;
Message("Submerged was detected");
}
public static bool IsSubmerged()
{
return SubLoaded && ShipStatus.Instance && ShipStatus.Instance.Type == SubmergedMapType;
}
}
+2
View File
@@ -8,6 +8,8 @@ using MiraAPI.LocalSettings;
using MiraAPI.Modifiers.ModifierDisplay;
using MiraAPI.Modifiers.Types;
using MiraAPI.Patches.Roles;
using MiraAPI.Translation;
using Reactor.Utilities;
using Reactor.Utilities.Attributes;
using UnityEngine;
@@ -4,6 +4,7 @@ using System.Linq;
using HarmonyLib;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.LocalSettings;
using MiraAPI.Translation;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities.Attributes;
using Reactor.Utilities.Extensions;
@@ -153,7 +154,7 @@ public class ModifierDisplayComponent(nint cppPtr) : MonoBehaviour(cppPtr)
private ModifierUiComponent CreateForModifier(BaseModifier modifier)
{
var newMod = Instantiate(_modTemplate, _children.transform);
newMod.transform.name = modifier.ModifierName;
newMod.transform.name = modifier.ModifierName.Translate();
var comp = newMod.AddComponent<ModifierUiComponent>();
comp.Modifier = modifier;
return comp;
@@ -1,4 +1,5 @@
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Translation;
using Reactor.Utilities.Attributes;
using TMPro;
using UnityEngine;
+16 -4
View File
@@ -4,6 +4,7 @@ using System.Linq;
using System.Runtime.Serialization;
using MiraAPI.Modifiers.Types;
using MiraAPI.PluginLoading;
using MiraAPI.Translation;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
@@ -136,7 +137,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.Translate()}");
}
continue;
}
@@ -157,15 +161,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.Translate()} 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.Translate()} 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)
+30
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,14 @@ public enum MiraRpc : uint
/// Custom RPC to replace Among Us CastVote.
/// </summary>
CastVote,
/// <summary>
/// Custom RPC to replace Among Us QueueOverruleVotes.
/// </summary>
QueueOverruleVotes,
/// <summary>
/// Custom RPC to sync the Gamemode option.
/// </summary>
SyncGamemodeOption,
}
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff. Show more