Compare commits

...
225 Commits
Author SHA1 Message Date
Az c51ad7e0de consolidate patches 2026-11-17 00:25:35 -05:00
Az 13dce32ae3 fix translation value oops 2026-11-17 00:04:46 -05:00
Az 314e108d0e hail mary fix for s showing up uninvited 2026-11-17 00:04:10 -05:00
Az 16c6b53a8c leverage localisations 2026-11-16 20:04:45 -05:00
Az 2b904d8e8c use defined helper
so there's a single possible point of failure
2026-11-16 17:00:09 -05:00
Az dd0499b5fa fix dubious suffixes(?) 2026-11-16 16:46:36 -05:00
Az bab8243f0b cleanup 2026-11-16 02:13:42 -05:00
Az 3fe399c04d safer type loading 2026-11-16 01:26:19 -05:00
Az 49529b09ee Merge branch 'dev' of https://github.com/All-Of-Us-Mods/MiraAPI into dev 2026-11-16 01:18:23 -05:00
Az 16999684eb skip abstract types correctly 2026-11-16 01:17:52 -05:00
Atony a4f9c21023 Add contents permission for workflow 2026-11-15 22:23:07 -06:00
Atony 9cc1a10480 Merge pull request #122 from All-Of-Us-Mods/dev
## Additions:
- Added the ability to map multiple translation IDs to a single shared string using `@ref:[translation id]` to reduce duplication.
- Added a new `ParseXmlFile` overload to accept a `Stream` instead of a `string`.
- Added a consistent way to add a localization prefix to all colors in a class.
- `IModdedOptionList` now allows typed iteration (PR #114)
## Improvements:
- Option property patches are generic in order to make option value handling faster.
- Improved iterations and allocations within the localization system for efficiency.
## Bugfixes:
- Fixed overlapping "Role" and "Game" settings buttons on the main options page (PR #121)
- Fixed match info guide crashing on mobile.
- Fix UI masking when using a CustomPhoneMenu within a meeting.
- Fixed certain `ModdedOption` types not being listed when getting options for the match info guide.
- Fixed local settings scroller being cut too early, hiding options as a result. (PR #115)
- Removed possibility of creating a new RoleManager instance when getting the intro sound of a base game role.
2026-11-15 22:08:45 -06:00
Atony f37e354d32 Bump version 2026-11-15 21:54:12 -06:00
AS cfb9d07d07 Merge pull request #116 from All-Of-Us-Mods/no-boxing
Some more options improvements
2026-11-15 22:48:27 -05:00
Atony fcf99cfb02 Fix roles breaking from VanillaButtonClickEvent<T> 2026-11-15 20:22:20 -06:00
Az e4b98acf68 Merge branch 'dev' into no-boxing 2026-11-15 20:46:53 -05:00
Az e0df1a80b3 fix very goofy problem 2026-11-15 20:45:40 -05:00
Az 6949ad22dc better delegate method search 2026-11-15 13:46:40 -05:00
Az a2d6b0b2ef helpful debug message 2026-11-15 13:31:33 -05:00
Az c10bb1ef87 remove useless setting of option names 2026-11-15 13:16:56 -05:00
Az 6e91781e4c fixed UI bug + make rounding a consistent behaviour
had accidentally deleted some patches somehow
2026-11-15 02:39:27 -05:00
Az 9fbbfde047 some more acceptable value ranges 2026-11-15 01:34:05 -05:00
Az b9ff6e20e3 add config descriptions for options 2026-11-15 01:14:54 -05:00
Az f862e808a7 support generic methods if possible 2026-11-13 21:26:20 -05:00
Az 6b2bdc11f9 fix small issues + remove deprecated code 2026-11-13 02:43:45 -05:00
Az d04c6da283 add prefix placeholder 2026-11-13 01:19:24 -05:00
Az 4272c2e383 Merge branch 'dev' into no-boxing 2026-11-13 00:59:50 -05:00
Az 94fbaac1ea consolidate plugin loading code 2026-11-13 00:55:24 -05:00
Az 2805599d35 new comparer util + minor optimisations 2026-11-12 13:35:21 -05:00
Az ed74458ba7 make it an extension instead 2026-11-12 12:35:21 -05:00
Az 1750451af7 Merge branch 'dev' into no-boxing 2026-11-12 01:50:14 -05:00
Az 5502dbc287 restore old behaviour + minor improvements
inherited invocations should be opt-in, since most mods likely already accounted for the shortcomings of the original system. so the default should be false instead of true

also deprecates the MiraEventWrapper class to maintain ABI compatibility while ensuring people migrate to using MiraEventHandle instead
2026-11-12 01:50:01 -05:00
AS 9ab526ab36 Merge pull request #120 from TheDavSmasher/mira-events-dev
Mira events dev
2026-11-12 01:37:02 -05:00
Az 02ac47eb45 allow multiple summarisations in a group 2026-11-12 00:47:21 -05:00
Az dc06ce5640 Merge branch 'dev' into no-boxing 2026-11-11 23:55:44 -05:00
Atony bc1913e352 Add back role guide preloading 2026-11-11 22:52:00 -06:00
Az 80bf3abe75 bring back the summarised option position 2026-11-11 22:44:53 -05:00
Az b0f0d19268 undo a single getter change 2026-11-11 22:35:20 -05:00
David Higueros 87dd7b5441 Returned MiraEventWrapper 2026-11-11 15:40:12 -07:00
David Higueros 32642fa6b5 Merge branch 'dev' into mira-events-dev 2026-11-11 15:34:29 -07:00
Az 43f5effe50 Merge branch 'dev' into no-boxing 2026-11-11 14:58:56 -05:00
AzandDavid Higueros a75be40e4a small code stuff
Co-Authored-By: David Higueros <111460331+TheDavSmasher@users.noreply.github.com>
2026-11-11 14:57:30 -05:00
Az 45d4793df3 yet another plugin load improvement (sorry dav) 2026-11-11 14:51:36 -05:00
AS 85daa0aded Merge pull request #119 from All-Of-Us-Mods/translation-improvements
Optimised localisation system
2026-11-11 02:46:32 -05:00
Az 881ad4de70 fix typos and key not found 2026-11-11 01:40:49 -05:00
Az 4300ed4576 slight changes 2026-11-11 00:57:08 -05:00
Az 88f1548fa2 Merge branch 'dev' into no-boxing 2026-11-11 00:35:04 -05:00
AS a8f129f0ce Merge pull request #114 from TheDavSmasher/modded-option-list-enumeration-fix
Changed IModdedOptionList structure to actually allow typed iteration
2026-11-11 00:28:36 -05:00
Az 3c8a841866 patch cleanup 2026-11-10 10:28:10 -05:00
David Higueros f9318b6b34 Merge branch 'dev' into modded-option-list-enumeration-fix 2026-11-09 15:27:54 -07:00
David Higueros fc7a1b182e Merge branch 'dev' into mira-events-dev 2026-11-09 15:27:32 -07:00
Az 5b16a45e6c Merge branch 'dev' into translation-improvements 2026-11-09 16:00:00 -05:00
Az 12bc2c9367 Update .editorconfig 2026-11-09 15:59:42 -05:00
Az fe95af1757 Merge branch 'dev' into no-boxing 2026-11-09 15:59:20 -05:00
Az 3a02733a88 making resharper happy 2026-11-09 15:55:08 -05:00
David Higueros edf68ba7a9 Merge branch 'dev' into modded-option-list-enumeration-fix 2026-11-08 22:47:22 -07:00
David Higueros ecb43716ce Merge branch 'dev' into mira-events-dev 2026-11-08 22:41:18 -07:00
Az 7c77df53bb some oversights fixed + remove redundant code 2026-11-08 02:56:35 -05:00
Az 7c6cc32b34 use InstanceExists 2026-11-08 01:20:17 -05:00
Az 9a53897f28 some more deduplication 2026-11-08 01:10:57 -05:00
Az 2e3a3a7285 fix oversight and add overload 2026-11-07 20:54:52 -05:00
Az ae500b53c8 slight expansion 2026-11-07 20:40:05 -05:00
Az 44e6a04c41 Merge branch 'dev' into no-boxing 2026-11-07 20:36:21 -05:00
Az 32caa8fd71 undo a getter + deprecate some constructors 2026-11-07 16:48:13 -05:00
Az 9557892daf use newer event stuff + fix attribute 2026-11-07 16:42:18 -05:00
Az 623cde27ee fix log spam lol 2026-11-07 15:53:09 -05:00
Az 94d68a34e3 improve registration behaviour 2026-11-07 15:47:22 -05:00
Az 6887029657 several optimisations 2026-11-07 04:57:50 -05:00
Az de37e4a3b0 git please stop confusing me 2026-11-07 04:00:56 -05:00
Az 79f54f87ff Merge branch 'dev' into no-boxing 2026-11-07 04:00:37 -05:00
Az 1aaaf050ad reorganise plugin loading code + debug mode stuff
and also some minor project cleanup
2026-11-07 03:56:47 -05:00
Az 8bdcf44a32 deduplicate code + simplify getters 2026-11-07 02:57:36 -05:00
Amber 326776c417 Merge pull request #118 from All-Of-Us-Mods/color-ids 2026-11-06 19:47:55 -05:00
David Higueros b44fac886b Merge branch 'dev' into mira-events-dev 2026-11-06 17:16:56 -07:00
Az 6176105283 leverage inheritdoc 2026-11-06 17:55:23 -05:00
Az ea1d57c407 Merge branch 'dev' into color-ids 2026-11-06 17:51:00 -05:00
Az b3566e4f19 Merge branch 'dev' into translation-improvements 2026-11-06 17:15:13 -05:00
Az b0549e3a9a consolidate code 2026-11-06 17:14:30 -05:00
David Higueros 14cd9eedf4 Added overloads, backwards compatibility stand tall 2026-11-06 15:07:46 -07:00
Az 1ac55197e9 clear some warnings 2026-11-06 17:01:40 -05:00
AS 42d5af5a31 Merge pull request #121 from Sanc-6231/fix/options-role-button-overlap
Fix overlapping original "Role Settings" and "Game Settings" buttons on the main options page
2026-11-06 16:59:04 -05:00
David Higueros eca00dbfcd Moved method to extensions 2026-11-06 14:54:10 -07:00
David Higueros 06b7099ba5 Added InvokeOnSubype to RegisterEventAttribute 2026-11-06 14:10:53 -07:00
David Higueros 777741569e Merged classes 2026-11-06 13:52:15 -07:00
David Higueros 177734e3eb Made class internal as no public-facing side of the API exposes it 2026-11-06 13:37:29 -07:00
David Higueros b94c1315c4 Added signature as overload 2026-11-06 13:28:05 -07:00
David Higueros 6a25793599 Used as extension method 2026-11-06 13:18:16 -07:00
David Higueros 6fce7b20b3 Reverted method signature change 2026-11-06 13:07:04 -07:00
David Higueros 903f6250b6 Merge branch 'dev' into mira-events-dev 2026-11-06 12:58:17 -07:00
David Higueros 795ccb71e4 Merge branch 'dev' into modded-option-list-enumeration-fix 2026-11-06 12:53:50 -07:00
Az 82c8c0e043 fix android crashing on trying to open the wiki 2026-11-06 03:22:38 -05:00
Atony 93e8b9ae4e Merge branch 'dev' of https://github.com/All-Of-Us-Mods/MiraAPI into dev 2026-11-05 23:40:48 -06:00
Az ca285d4af6 removing even more useless calls 2026-11-05 23:48:28 -05:00
Az f06562a281 remove useless .gameObject uses 2026-11-05 23:05:03 -05:00
Az 9874713ec8 experimental settings sync fix + improvements 2026-11-05 22:41:55 -05:00
Atony 115e5fde5d Revert "meet potential fix"
This reverts commit 01925d94e4.
2026-11-05 21:29:55 -06:00
Atony 01925d94e4 meet potential fix 2026-11-05 21:18:14 -06:00
AzandIdkImNeil 6b8ff627a1 quick player menu fix
Co-Authored-By: IdkImNeil <69025896+idkimneil@users.noreply.github.com>
2026-11-05 20:24:28 -05:00
Az d5e43a84d3 abstract away string option code
and also make the behaviour in line with base game handling
2026-11-05 15:26:40 -05:00
Az 3316daaf20 Merge branch 'dev' into translation-improvements 2026-11-05 13:28:32 -05:00
Az 7f37259576 Merge branch 'dev' into no-boxing 2026-11-05 13:28:20 -05:00
Az 0c9ab951c8 Merge branch 'dev' into color-ids 2026-11-05 13:27:20 -05:00
Az 852b464ff8 remove warnings 2026-11-05 13:26:00 -05:00
Atony 063428156a Merge pull request #115 from idkimneil/develop-idk
Scroll Bound Fixes
2026-11-05 08:38:45 -06:00
Az af6a486ce8 remove null check skip 2026-11-05 03:10:50 -05:00
Az b277a86f2b Merge branch 'dev' into pr/115 2026-11-05 03:10:05 -05:00
Az 5dd5f33ae4 lol new warnings 2026-11-05 02:55:40 -05:00
Az e146ace93d Merge branch 'dev' into pr/121 2026-11-05 02:48:01 -05:00
Az fbeb610cb5 some more code cleanup + undoing a todo
it is a miracle the game mod option worked the way it did. i would like to have a word with the one who was using a dictionary like a list. prepare to meet your maker
2026-11-04 21:21:12 -05:00
David Higueros 5b0fee0079 Removed parameter that should be calculated to prevent desyncs or type errors 2026-11-04 14:23:17 -07:00
Az 1bd96041ee complete two todos + minor improvements 2026-11-04 15:00:54 -05:00
David Higueros 1132e86f8f Removed now only-once-used method 2026-11-04 12:44:19 -07:00
David Higueros e9a317c164 Invoke all events with DynamicInvoke due to contravariance 2026-11-04 12:42:51 -07:00
David Higueros 88b2166d09 Used IsAssignableTo instead 2026-11-04 12:36:22 -07:00
David Higueros bbd8e1deef Inverted tracking direction to subtypes for correct EventWrappers contravariance 2026-11-04 12:33:17 -07:00
Az 1c44653a8d slight project cleanup 2026-11-04 14:12:06 -05:00
David Higueros e6994f4e99 Cleared ToLoad dictionary of lists 2026-11-04 11:35:11 -07:00
David Higueros 1eaf633f88 Correctly used EventHandlerAdded 2026-11-04 11:32:30 -07:00
David Higueros 8a48296d45 Moved type to just EventWrapper with EventHandle providing a property access 2026-11-04 11:27:06 -07:00
David Higueros 5f4943f92a Used IsSubclassOf instead 2026-11-04 10:45:37 -07:00
David Higueros 484a78c215 Renamed method and made extension 2026-11-04 10:44:20 -07:00
David Higueros f2381e0fb8 Merge branch 'dev' into mira-events-dev 2026-11-04 09:53:38 -07:00
Sanc-6231 b6df13a2de fix:restore vanilla button layout when returning to the Main page. 2026-11-04 18:10:14 +08:00
Az 7bd7456547 Merge branch 'modded-option-list-enumeration-fix' of https://github.com/TheDavSmasher/MiraAPI into pr/114 2026-11-04 01:55:03 -05:00
Az 5a2894b185 Merge branch 'dev' into pr/114 2026-11-04 01:54:08 -05:00
Az 00a89d13c2 Merge branch 'dev' into pr/115 2026-11-04 01:51:45 -05:00
Az acfb7fb9b8 use new extension 2026-11-04 01:44:01 -05:00
Az 6f6a2977e8 Merge branch 'dev' into color-ids 2026-11-04 01:42:55 -05:00
Az 4f9720d917 Merge branch 'dev' into no-boxing 2026-11-04 01:42:35 -05:00
Az 18c1b8a6fd Merge branch 'dev' into translation-improvements 2026-11-04 01:39:21 -05:00
Az f18e375122 Merge branch 'master' into dev 2026-11-04 01:38:50 -05:00
Az b3900576d6 formatting + squeezing out some more performance
this is very nitpicky, but better be overly conscious about it early iykwim

some changes were whacked from pietro's faster load time branch
2026-11-04 01:38:33 -05:00
David Higueros 76a02618d8 Added to summary about generic registered events being non-concrete generic type definitions 2026-11-03 19:13:05 -07:00
David Higueros 7755274863 Renamed property and used IsSubclassOf to allow generics 2026-11-03 19:05:24 -07:00
David Higueros d83bcde8a9 Added concrete type to wrapper to filter Event handlers when invoked 2026-11-03 18:58:18 -07:00
David Higueros e204f70364 Used helper methods 2026-11-03 18:50:47 -07:00
David Higueros e66252b6ae Made Load finilize EventWrappers correctly 2026-11-03 18:32:52 -07:00
David Higueros bc6debb4c0 Made MiraEventWrapper constructor internal 2026-11-03 18:08:15 -07:00
David Higueros 3fef36e5cd Added helper method to allow getting events from generics 2026-11-03 18:02:57 -07:00
David Higueros 8460f1cdaf Handled adding event handlers pre/post load to allow tracker to account for all events 2026-11-03 17:44:59 -07:00
David Higueros 4f80a35e2d Separated methods for later sync 2026-11-03 17:08:15 -07:00
David Higueros 67c039aeba Used already existing internal list to track stored event types 2026-11-03 16:33:00 -07:00
David Higueros a5a4a6eafd Deduplicated with helper method 2026-11-03 16:10:24 -07:00
David Higueros 36ef09b734 Changed to hash set 2026-11-03 15:51:03 -07:00
David Higueros 1e0b0bb7e5 Combined with helper method 2026-11-03 15:43:51 -07:00
David Higueros 8619fe8675 Allowed correct generic tracking 2026-11-03 15:38:45 -07:00
David Higueros 8410d61ac5 Registered MiraEvent types on plugins to track subclasses for inheritance calls 2026-11-03 15:09:54 -07:00
David Higueros 82b3200f9b Fixed xmldoc type reference 2026-11-03 13:36:39 -07:00
David Higueros af38fade3d Renamed to event handler 2026-11-03 13:23:59 -07:00
David Higueros d622caaf70 Removed redundant Instance property 2026-11-03 13:18:19 -07:00
Az 72a0755ff3 improve system 2026-11-03 10:31:56 -05:00
AS fff7b04040 Merge branch 'dev' into color-ids 2026-11-03 10:31:34 -05:00
AS e1334449ca Merge branch 'dev' into no-boxing 2026-11-03 10:31:16 -05:00
Az 0e5d94400a oops 2026-11-03 10:21:50 -05:00
Az d7abb1dcb8 clear warnings 2026-11-03 09:30:31 -05:00
Az e62d3c4b05 Merge branch 'dev' into color-ids 2026-11-03 09:26:52 -05:00
Az 011bc22e07 Merge branch 'dev' into no-boxing 2026-11-03 09:26:42 -05:00
Az e54a0b0050 add IsDefined for better checking 2026-11-03 09:25:18 -05:00
Az f93fcc16e9 deprecate some constructors 2026-11-03 09:21:38 -05:00
Az 6543bcfb97 Merge branch 'dev' into color-ids 2026-11-03 09:14:25 -05:00
Az 5fffac33ec remove removed translations 2026-11-03 09:13:22 -05:00
Az 8d48403808 Merge branch 'dev' into no-boxing 2026-11-03 09:12:04 -05:00
Az 8eeccafe48 Merge remote-tracking branch 'origin/xml-translations' into dev 2026-11-03 02:15:32 -05:00
Az deb1d65e8a analyser updates and more warning fixes 2026-11-03 02:10:24 -05:00
Az 0750238ba5 optimise modded option arrays 2026-11-03 01:43:43 -05:00
Az 64ccef1b1d behaviour change 2026-11-03 01:11:20 -05:00
Az d2859dcddf missing display values and some constructors 2026-11-03 00:56:55 -05:00
Az 1117d957a3 fix small copy paste error 2026-11-03 00:42:49 -05:00
Az 32dd4edc08 remove translation id boilerplate 2026-11-03 00:34:29 -05:00
David Higueros cb340ce115 Wrapped instance in array to make sure corrent CreateInstance is called 2026-11-02 21:47:53 -07:00
David Higueros 6b3dfb978d Used as extension method 2026-11-02 20:44:59 -07:00
David Higueros 355d6e63f0 Fixed wrong cast type 2026-11-02 20:35:42 -07:00
David Higueros 9bb865bdf1 Used InvokeEvent as extension method 2026-11-02 20:31:35 -07:00
David Higueros 31546ad012 Actually invoked generic vanilla button events 2026-11-02 20:22:59 -07:00
David Higueros 64a8539bc3 Simplified to single ClickHandler call 2026-11-02 19:52:45 -07:00
David Higueros 61351c958b Combined invoke calls into single method 2026-11-02 19:36:11 -07:00
Az 8f6f97bbc0 options translation handling overhaul 2026-11-02 17:32:56 -05:00
Az ac7e9244f2 Merge branch 'dev' into no-boxing 2026-11-02 01:53:22 -05:00
Az e5195f65e0 squeezing out some more performance 2026-11-02 01:25:42 -05:00
Pietrodjaowjao d415d89070 prevent conflict with IAsyncOperation.DebugName (shared pointer) 2026-10-31 21:54:21 -03:00
Atony 6f3fee3859 Expose color id for custom colors 2026-10-30 15:05:52 -05:00
AS 81ffc7c734 Merge branch 'dev' into no-boxing 2026-10-29 04:58:07 -04:00
Pietrodjaowjao 890fa065e7 use InstanceExists instead 2026-10-28 20:49:29 -03:00
Az 344aa046ac Merge branch 'dev' into no-boxing 2026-10-26 16:53:21 -04:00
Az 51397d78a7 color improvements 2026-10-26 16:53:02 -04:00
Az 28770e4cd8 Merge branch 'no-boxing' of https://github.com/All-Of-Us-Mods/MiraAPI into no-boxing 2026-10-26 15:41:52 -04:00
Az e8ea720ca0 always update the backing array 2026-10-26 15:41:47 -04:00
AS 7945173061 Merge branch 'dev' into no-boxing 2026-10-26 05:11:53 -04:00
Az 98a37721aa fix small issue 2026-10-26 04:55:46 -04:00
Az 08fd56754e fix small issue 2026-10-26 04:55:38 -04:00
Az accfd04209 several big changes
- abstract display value behaviour to the option itself
- updated deprecation notices a bit
- enforced some consistency
- moved the notification code up in the call stack into SetValue
- made the number option round floats instead of directly casting, due to casting having a truncation behaviour (0.999 becomes 0, not 1)
- optimised the wiki behaviour
2026-10-26 04:47:07 -04:00
Az 936da28f6a actually cache the HarmonyMethod instance instead 2026-10-26 03:38:29 -04:00
Az 6f94e4ed21 reduce value boxing 2026-10-26 03:35:11 -04:00
Az 181013efec minor code fixes and nitpicks 2026-10-26 00:52:19 -04:00
Atony e0e55e065e Merge branch 'dev' into pr/114 2026-10-25 18:34:35 -05:00
Atony 79a027e5db Merge branch 'dev' into develop-idk 2026-10-25 18:25:51 -05:00
neilmjain 89e8870e35 Account for Voting Time Ending 2026-10-25 14:29:09 -04:00
neilmjain c627c03590 Wire Up match info guide 2026-10-25 14:28:49 -04:00
neilmjain 29e9f9c8b5 Wire up phone menus to hide player nameplates 2026-10-25 14:28:29 -04:00
neilmjain af255c3e64 Hide Nameplates for menus in meetings 2026-10-25 14:27:59 -04:00
Atony a8dfbb616c Use monobehaviour instead of il2 obj for use event 2026-10-24 17:01:44 -05:00
Az b79c14ce50 resolve warnings that i am responsible for 2026-10-22 22:41:49 -04:00
Az 17dafadec8 move away from using GetCallingAssembly and GetExecutingAssembly 2026-10-22 22:35:17 -04:00
Az f9274eda09 consolidate code 2026-10-22 22:02:33 -04:00
Az 10daf01a55 facepalm 2026-10-22 21:32:13 -04:00
Az 1daffd7560 code ordering and cleanup 2026-10-22 21:15:57 -04:00
Az 26541dc07d clear warnings 2026-10-22 20:54:33 -04:00
neilmjain 7c09dbdaaa add corountimes for setting scroller bounds on options menus 2026-10-22 20:24:20 -04:00
neilmjain 0596278b78 move scroller bounds to be set in Open() 2026-10-22 19:26:07 -04:00
neilmjain 13864b8fd9 clean up 2026-10-22 19:15:43 -04:00
neilmjain f8c9045517 adjust options header sizes and spacing 2026-10-22 19:13:27 -04:00
neilmjain 7632e543c8 decrease scroller bounds to be more precise. 2026-10-22 19:08:26 -04:00
neilmjain 6deaae350e increase localsettings scroller bounds 2026-10-22 19:04:39 -04:00
neilmjain 5f6ac17e52 reset scrollbar when switching between optionmenutabs 2026-10-22 18:37:17 -04:00
neilmjain 16e2c25c2d fix match info guide scroller bounds cutting off content and only spawn scroller if needed to 2026-10-22 18:35:59 -04:00
David Higueros 0e02a02156 Changed IModdedOptionList structure to actually allow typed iteration 2026-10-22 15:43:55 -06:00
Faulo Fault fdd0574ddc Translated using Weblate (Spanish (Latin America))
Currently translated at 100.0% (77 of 77 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/es_419/
2026-10-22 20:19:08 +00:00
Atony 2a7570f022 Adjust code that gets roles and modifiers list 2026-10-22 02:01:05 -05:00
Atony 71138c7bbe Display current role and modifiers at top 2026-10-22 01:17:21 -05:00
Atony 2993ee2bbc Resync options upon clicking start
This is necessary to prevent some pretty common option desync that tends to happen. If anyone else can optimize it further or move it somewhere else, go for it.
2026-10-21 23:37:46 -05:00
Atony 79bbebd12a Allow modifiers and roles to override chance text 2026-10-21 17:48:33 -05:00
Turret 08af14a890 Translated using Weblate (Polish)
Currently translated at 100.0% (77 of 77 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/pl/
2026-10-20 14:19:07 +00:00
Sameer Umar 11e894a29a Add NuGet login step and update push command 2026-10-19 17:20:30 +00:00
Anonymous e2a3dc782b Translated using Weblate (Russian)
Currently translated at 12.9% (10 of 77 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/ru/
2026-10-19 06:19:07 +00:00
Anonymous 109dc796c5 Translated using Weblate (French)
Currently translated at 12.9% (10 of 77 strings)

Translation: Mira API/Mira API
Translate-URL: https://weblate.duikbo.at/projects/mira-api/mira-api/fr/
2026-10-19 06:19:07 +00:00
223 changed files with 5636 additions and 3431 deletions

No files matched your search

+18
View File
@@ -104,3 +104,21 @@ dotnet_diagnostic.S1244.severity = none
# S2325: Methods and properties that don't access instance data should be static
dotnet_diagnostic.S2325.severity = none
# CA1710: Identifiers should have correct suffix
dotnet_diagnostic.CA1710.severity = none
# CA1010: Generic interface should also be implemented
dotnet_diagnostic.CA1010.severity = none
# IDE0005: Using directive is unnecessary.
dotnet_diagnostic.IDE0005.severity = warning
# SA1114: Parameter list should follow declaration
dotnet_diagnostic.SA1114.severity = none
# SA1143: Conditional expressions must be formatted consistently
dotnet_diagnostic.SA1143.severity = none
# SA1504: All accessors should be single-line or multi-line
dotnet_diagnostic.SA1504.severity = none
+13 -3
View File
@@ -5,6 +5,9 @@ on: ["workflow_dispatch", "push", "pull_request"]
jobs:
build:
runs-on: ubuntu-22.04
permissions:
id-token: write
contents: write
steps:
- uses: actions/checkout@v4
with:
@@ -38,14 +41,21 @@ jobs:
with:
name: AllOfUs.MiraAPI.nupkg
path: MiraAPI/bin/Release/AllOfUs.MiraAPI.*.nupkg
- uses: softprops/action-gh-release@v2
if: github.ref_type == 'tag'
with:
draft: true
files: MiraAPI/bin/Release/net6.0/MiraAPI.dll
- name: NuGet login
if: github.ref_type == 'tag'
uses: NuGet/login@v1
id: login
with:
user: xtracube
- name: Push NuGet package
if: github.ref_type == 'tag'
run: |
dotnet nuget push MiraAPI/bin/Release/AllOfUs.MiraAPI.*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push MiraAPI/bin/Release/AllOfUs.MiraAPI.*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ steps.login.outputs.NUGET_API_KEY }}
+8 -6
View File
@@ -5,10 +5,12 @@
<DebugType>embedded</DebugType>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GenerateFullPaths>false</GenerateFullPaths>
<PathMap>$(MSBuildProjectDirectory)=.</PathMap>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<VersionPrefix>0.5.0</VersionPrefix>
<VersionPrefix>0.6.1</VersionPrefix>
<VersionSuffix>dev</VersionSuffix>
<Authors>All Of Us, XtraCube, Angxl</Authors>
@@ -32,11 +34,11 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Roslynator.Analyzers" Version="5.0.0" PrivateAssets="all" />
<PackageReference Include="Roslynator.Formatting.Analyzers" Version="5.0.0" PrivateAssets="all" />
<PackageReference Include="Roslynator.CodeAnalysis.Analyzers" Version="5.0.0" PrivateAssets="all" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.32.0.713" PrivateAssets="all" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556" PrivateAssets="all" />
<PackageReference Include="Roslynator.Analyzers" Version="*-*" PrivateAssets="all" />
<PackageReference Include="Roslynator.Formatting.Analyzers" Version="*-*" PrivateAssets="all" />
<PackageReference Include="Roslynator.CodeAnalysis.Analyzers" Version="*-*" PrivateAssets="all" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="*-*" PrivateAssets="all" />
<PackageReference Include="StyleCop.Analyzers" Version="*-*" PrivateAssets="all" />
<AdditionalFiles Include="$(MSBuildThisFileDirectory)/stylecop.json" Link="stylecop.json" Visible="false" />
</ItemGroup>
</Project>
+9 -6
View File
@@ -1,14 +1,17 @@
using MiraAPI.Utilities.Assets;
using System.Reflection;
using MiraAPI.Utilities.Assets;
namespace MiraAPI.Example;
public static class ExampleAssets
{
public static LoadableResourceAsset ExampleButton { get; } = new("MiraAPI.Example.Resources.ExampleButton.png");
public static LoadableResourceAsset CallMeetingButton { get; } = new("MiraAPI.Example.Resources.CallMeeting.png");
private static readonly Assembly _assembly = typeof(ExampleAssets).Assembly;
public static LoadableResourceAsset ExampleButton { get; } = new("MiraAPI.Example.Resources.ExampleButton.png", _assembly);
public static LoadableResourceAsset CallMeetingButton { get; } = new("MiraAPI.Example.Resources.CallMeeting.png", _assembly);
// 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");
public static LoadableResourceAsset TeleportButton { get; } = new("MiraAPI.Example.Resources.TeleportButton.png", _assembly);
public static LoadableResourceAsset SharpshootButton { get; } = new("MiraAPI.Example.Resources.SharpshootButton.png", _assembly);
public static LoadableResourceAsset Banner { get; } = new("MiraAPI.Example.Resources.FortniteBanner.jpeg", _assembly);
}
+5 -11
View File
@@ -5,20 +5,14 @@ using UnityEngine;
namespace MiraAPI.Example;
[RegisterCustomColors]
[RegisterCustomColors("color.")]
public static class ExampleColors
{
public static CustomColor Cerulean { get; } = new("color.cerulean", new Color(0.0f, 0.48f, 0.65f))
{
ColorBrightness = CustomColorBrightness.Lighter,
};
public static CustomColor Cerulean { get; } = new("cerulean", new Color(0.0f, 0.48f, 0.65f), CustomColorBrightness.Lighter);
public static CustomColor Rose { get; } = new("color.rose", new Color(0.98f, 0.26f, 0.62f));
public static CustomColor Rose { get; } = new("rose", new Color(0.98f, 0.26f, 0.62f), CustomColorBrightness.Lighter);
public static CustomColor Gold { get; } = new("color.gold", new Color(1.0f, 0.84f, 0.0f));
public static CustomColor Gold { get; } = new("gold", new Color(1.0f, 0.84f, 0.0f), CustomColorBrightness.Lighter);
public static VariableColor Rainbow { get; } = new("color.rainbow", t => new HsbColor(MathUtilities.PingPong(t, 1f, 0.3f), 1f, 1f))
{
ColorBrightness = CustomColorBrightness.Lighter,
};
public static VariableColor Rainbow { get; } = new("rainbow", t => new HsbColor(MathUtilities.PingPong(t, 1f, 0.3f), 1f, 1f), CustomColorBrightness.Lighter);
}
+3 -2
View File
@@ -14,6 +14,7 @@ using Reactor.Utilities;
namespace MiraAPI.Example;
[RegisterEventContainer]
public static class ExampleEventHandlers
{
public static void Initialize()
@@ -31,7 +32,7 @@ public static class ExampleEventHandlers
MiraEventManager.RegisterEventHandler<CompleteTaskEvent>(@event =>
{
Logger<ExamplePlugin>.Info($"{@event.Player.Data.PlayerName} completed {@event.Task.TaskType.ToString()}");
Logger<ExamplePlugin>.Info($"{@event.Player.Data.PlayerName} completed {@event.Task.TaskType}");
});
// You can also unregister event handlers using the handle returned from RegisterEventHandler.
@@ -89,7 +90,7 @@ public static class ExampleEventHandlers
[RegisterEvent]
public static void UpdateSystemEventHandler(UpdateSystemEvent @event)
{
Logger<ExamplePlugin>.Error(@event.SystemType.ToString());
Logger<ExamplePlugin>.Error(@event.SystemType);
}
// Example event handler
+4 -1
View File
@@ -19,13 +19,16 @@ public partial class ExamplePlugin : BasePlugin, IMiraPlugin
{
public ExamplePlugin()
{
MiraLocaleManager.Register("mira.example");
MiraLocaleManager.Register("mira.example", typeof(ExamplePlugin).Assembly);
}
public Harmony Harmony { get; } = new(Id);
public string OptionsTitleText { get; } = "Mira API\nExample Mod";
public string CustomOptionMenuNameTwo { get; } = "Example Options";
/// <inheritdoc />
public bool ForceRegisterEvents => false;
public ConfigFile GetConfigFile()
{
return Config;
+2 -6
View File
@@ -30,16 +30,12 @@ public class ExampleOptions : AbstractOptionGroup
[ModdedNumberOption("options.exampleOptions1.numberOpt", min: 0, max: 10, suffixType: MiraNumberSuffixes.Distance)]
public int NumberOpt2 { get; set; } = 4; // Can also be int!
[ModdedEnumOption("options.exampleOptions1.bestApi", typeof(Api), ["Mira API", "Mitochondria", "Reactor"])]
public Api BestApi { get; set; } = Api.MiraAPI;
[ModdedEnumOption<Api>("options.exampleOptions1.worstApi", ["Mira API", "Mitochondria", "Reactor"])]
// These three can target both instance and static methods
[ModdedOptionGetter(nameof(GetApi))] // Can also automatically resolve to {Option Name}Getter
[ModdedOptionSetter(nameof(SetApi))] // Can also automatically resolve to {Option Name}Setter
[ModdedOptionChanged(nameof(ApiChanged))] // Can also automatically resolve to {Option Name}Changed
public Api WorstApi { get; set; } = Api.MiraAPI;
[ModdedEnumOption<Api>("options.exampleOptions1.bestApi", ["Mira API", "Mitochondria", "Reactor"])]
public Api BestApi { get; set; } = Api.MiraAPI;
[ModdedEnumOptionList<ValueState>("Value State {0}", ["None", "Primary", "Secondary"])]
public ModdedArray<ValueState> ValueStates { get; set; } = [ValueState.Primary, ValueState.Secondary, ValueState.None, ValueState.None, ValueState.None];
@@ -47,7 +47,6 @@ Eliminate every other faction.</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.exampleOptions1.worstApi">Worst API</string>
<string name="options.exampleOptions1.players">Choose A Player</string>
<string name="options.exampleOptions2">Example Options 2</string>
<string name="options.exampleOptions2.youMustChoseAPlayer">YOU MUST CHOSE A PLAYER</string>
+1 -1
View File
@@ -40,7 +40,7 @@ public class ChameleonRole : CrewmateRole, ICustomRole
return;
}
if (Player.MyPhysics.Velocity.magnitude > 0)
if (Player.MyPhysics.Velocity.sqrMagnitude > 0)
{
var rend = Player.cosmetics.currentBodySprite.BodySprite;
var tmp = Player.cosmetics.nameText;
+1
View File
@@ -15,6 +15,7 @@ namespace MiraAPI.Colors.ColorSpaces;
/// <param name="a">The alpha component.</param>
[Serializable]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element should begin with upper-case letter", Justification = "Unity parity.")]
// ReSharper disable InconsistentNaming (Justification: Read above.)
public record struct CmykColor(float c, float m, float y, float k, float a = 1f)
{
/// <summary>
+1
View File
@@ -14,6 +14,7 @@ namespace MiraAPI.Colors.ColorSpaces;
/// <param name="a">The alpha component.</param>
[Serializable]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element should begin with upper-case letter", Justification = "Unity parity.")]
// ReSharper disable InconsistentNaming (Justification: Read above.)
public record struct HsbColor(float h, float s, float b, float a = 1f)
{
/// <summary>
+1
View File
@@ -14,6 +14,7 @@ namespace MiraAPI.Colors.ColorSpaces;
/// <param name="a">The alpha component.</param>
[Serializable]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element should begin with upper-case letter", Justification = "Unity parity.")]
// ReSharper disable InconsistentNaming (Justification: Read above.)
public record struct HslColor(float h, float s, float l, float a = 1f)
{
/// <summary>
+84 -39
View File
@@ -1,4 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using System;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
@@ -8,69 +9,113 @@ namespace MiraAPI.Colors;
/// <summary>
/// Represents a custom color with a main color and a shadow color.
/// </summary>
/// <param name="name">The name of the option.</param>
/// <param name="nameId">The name of the option as a <see cref="StringNames"/> value.</param>
/// <param name="rawId">The name of the option as a <see cref="string"/> value.</param>
/// <param name="mainColor">The main color.</param>
/// <param name="shadowColor">The shadow color.</param>
/// <param name="brightness">The brightness type of the color.</param>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Internal code.")]
[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1513:Closing brace should be followed by blank line", Justification = "Looks weird.")]
public class CustomColor(StringNames name, Color32 mainColor, Color32 shadowColor)
public class CustomColor(StringNames? nameId, string? rawId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness)
{
private StringNames? name = nameId;
private CustomColorBrightness colorBrightness = brightness;
/// <summary>
/// Gets or sets the main color.
/// Gets the main color.
/// </summary>
public Color32 MainColor
public Color32 MainColor => mainColor;
/// <summary>
/// Gets the shadow color.
/// </summary>
public Color32 ShadowColor => shadowColor;
/// <summary>
/// Gets the name of the color.
/// </summary>
public StringNames Name
{
get;
set
get
{
field = value;
InternalMainColor = value;
if (!name.HasValue && !string.IsNullOrEmpty(RawId))
name = MiraLocaleManager.GetOrCreateLocaleString(RawId);
return name.GetValueOrDefault();
}
internal set
{
name = value;
}
}
= mainColor;
/// <summary>
/// Gets or sets the shadow color.
/// Gets the id of the color.
/// </summary>
public Color32 ShadowColor
public int ColorId { get; internal set; } = -1;
/// <summary>
/// Gets or sets whether the color is lighter or darker.
/// </summary>
public CustomColorBrightness ColorBrightness
{
get;
set
{
field = value;
InternalShadowColor = value;
}
get => colorBrightness;
[Obsolete("Use the constructor to set ColorBrightness instead. This will be removed in a future version.")]
set => colorBrightness = value;
}
= shadowColor;
/// <summary>
/// Gets or sets the name of the color.
/// </summary>
public StringNames Name { get; set; } = name;
/// <summary>
/// Gets or sets whether the color is lighter or darker. Can be used to help with colorblind stuff.
/// </summary>
public CustomColorBrightness ColorBrightness { get; set; } = CustomColorBrightness.Darker;
internal string? RawId = rawId;
internal Color InternalMainColor = mainColor;
internal Color InternalShadowColor = shadowColor;
/// <inheritdoc cref="CustomColor"/>
public CustomColor(StringNames name, Color32 mainColor)
: this(name, mainColor, mainColor.GetShadowColor(60))
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(StringNames nameId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness)
: this(nameId, null, mainColor, shadowColor, brightness)
{
}
/// <inheritdoc cref="CustomColor"/>
public CustomColor(string name, Color32 mainColor)
: this(name, mainColor, mainColor.GetShadowColor(60))
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(StringNames nameId, Color32 mainColor, CustomColorBrightness brightness)
: this(nameId, null, mainColor, mainColor.DarkenAbsolute(60), brightness)
{
}
/// <inheritdoc cref="CustomColor"/>
public CustomColor(string name, Color32 mainColor, Color32 shadowColor)
: this(MiraLocaleManager.GetOrCreateLocaleString(name), mainColor, shadowColor)
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(string rawId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness)
: this(null, rawId, mainColor, shadowColor, brightness)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(string rawId, Color32 mainColor, CustomColorBrightness brightness)
: this(null, rawId, mainColor, mainColor.DarkenAbsolute(60), brightness)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public CustomColor(StringNames nameId, Color32 mainColor, Color32 shadowColor)
: this(nameId, null, mainColor, shadowColor, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public CustomColor(StringNames nameId, Color32 mainColor)
: this(nameId, null, mainColor, mainColor.DarkenAbsolute(60), CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public CustomColor(string rawId, Color32 mainColor, Color32 shadowColor)
: this(null, rawId, mainColor, shadowColor, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public CustomColor(string rawId, Color32 mainColor)
: this(null, rawId, mainColor, mainColor.DarkenAbsolute(60), CustomColorBrightness.Darker)
{
}
}
+57 -4
View File
@@ -1,7 +1,11 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Colors;
@@ -16,9 +20,8 @@ public static class PaletteManager
/// </summary>
public static CustomColor[] RegisteredColors => [.. CustomColors];
internal static readonly List<CustomColor> CustomColors = [];
internal static readonly HashSet<StringNames> VariableColorNames = [];
private static readonly List<CustomColor> CustomColors = [];
private static readonly HashSet<StringNames> VariableColorNames = [];
private static readonly CustomColorBrightness[] ColorBrightnessMap =
[
CustomColorBrightness.Darker, // Red
@@ -43,6 +46,49 @@ public static class PaletteManager
private static int originalLength;
internal static bool RegisterColors(Type type, in MiraPluginManager.RegistrationContext context)
{
if (!type.TryGetCustomAttribute<RegisterCustomColorsAttribute>(out var attribute))
{
return false;
}
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers))
{
if (!property.PropertyType.IsAssignableTo(typeof(CustomColor)))
{
continue;
}
if (property.GetValue(null) is not CustomColor color)
{
Error($"Color property {property.Name} in {type.Name} is not a CustomColor.");
continue;
}
if (!string.IsNullOrEmpty(color.RawId) && !string.IsNullOrEmpty(attribute.IdPrefix))
{
color.Name = MiraLocaleManager.GetOrCreateLocaleString(attribute.IdPrefix + color.RawId);
}
CustomColors.Add(color);
if (color is VariableColor)
VariableColorNames.Add(color.Name);
}
if (!context.MiraPlugin.DebugMode)
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers)
.Where(f => !f.IsAutoPropertyBackingField() && f.FieldType.IsAssignableTo(typeof(CustomColor))))
{
Error($"{field.Name} is a field, not a property. Use properties for colors.");
}
return true;
}
internal static void RegisterAllColors()
{
originalLength = Palette.PlayerColors.Length;
@@ -51,6 +97,13 @@ public static class PaletteManager
var shadowColors = CustomColors.Select(x => x.ShadowColor).ToArray();
var stringNames = CustomColors.Select(x => x.Name).ToArray();
var newColorId = originalLength;
foreach (var color in CustomColors)
{
color.ColorId = newColorId++;
}
Palette.PlayerColors = Palette.PlayerColors.ToArray().AddRangeToArray(colors);
Palette.ShadowColors = Palette.ShadowColors.ToArray().AddRangeToArray(shadowColors);
Palette.ColorNames = Palette.ColorNames.ToArray().AddRangeToArray(stringNames);
@@ -5,5 +5,20 @@ namespace MiraAPI.Colors;
/// <summary>
/// Used to mark a class for <see cref="CustomColor"/> registration.
/// </summary>
/// <param name="idPrefix">The group translation ID prefix to attach to color names before registration.</param>
[AttributeUsage(AttributeTargets.Class)]
public class RegisterCustomColorsAttribute : Attribute;
public class RegisterCustomColorsAttribute(string idPrefix) : Attribute
{
/// <summary>
/// Gets the translation ID prefix for all colors within the container type.
/// </summary>
public string IdPrefix => idPrefix;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterCustomColorsAttribute"/> class.
/// </summary>
public RegisterCustomColorsAttribute()
: this(string.Empty)
{
}
}
+109 -17
View File
@@ -1,6 +1,5 @@
using System;
using MiraAPI.LocalSettings;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
@@ -9,40 +8,133 @@ namespace MiraAPI.Colors;
/// <summary>
/// Represents a dynamic custom color that changes over time.
/// </summary>
/// <param name="name">The name of the color.</param>
/// <param name="nameId">The name of the option as a <see cref="StringNames"/> value.</param>
/// <param name="rawId">The name of the option as a <see cref="string"/> value.</param>
/// <param name="mainEvaluator">The function to evaluate the dynamic main color.</param>
/// <param name="shadowEvaluator">The function to evaluate the dynamic shadow color.</param>
/// <param name="mainColor">The static main color used when dynamic colors are disabled.</param>
/// <param name="shadowColor">The static shadow color used when dynamic colors are disabled.</param>
/// <param name="defaultTime">The default time that is used to automatically fill in the static colors when the latter is not provided.</param>
public sealed class VariableColor(StringNames name, Func<float, Color> mainEvaluator, Func<float, Color>? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f)
: CustomColor(name, mainColor ?? mainEvaluator(defaultTime), shadowColor ?? shadowEvaluator?.Invoke(defaultTime) ?? (mainColor ?? mainEvaluator(defaultTime)).GetShadowColor(60))
/// <param name="brightness">The brightness type of the color.</param>
public sealed class VariableColor(
StringNames? nameId,
string? rawId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
Color32? mainColor,
Color32? shadowColor,
float defaultTime,
CustomColorBrightness brightness)
: CustomColor(
nameId,
rawId,
mainColor ?? mainEvaluator(defaultTime),
shadowColor ?? shadowEvaluator?.Invoke(defaultTime) ?? (mainColor ?? mainEvaluator(defaultTime)).DarkenAbsolute(60),
brightness)
{
/// <summary>
/// Gets or sets a delegate that takes in a time value and returns the dynamic main color.
/// Gets a delegate that takes in a time value and returns the dynamic main color.
/// </summary>
public Func<float, Color> MainEvaluator { get; set; } = mainEvaluator;
public Func<float, Color> MainEvaluator => mainEvaluator;
/// <summary>
/// Gets or sets a delegate that takes in a time value and returns the dynamic shadow color.
/// Gets a delegate that takes in a time value and returns the dynamic shadow color.
/// </summary>
public Func<float, Color> ShadowEvaluator { get; set; } = shadowEvaluator ?? (t => mainEvaluator(t).GetShadowColor(0.24f));
public Func<float, Color> ShadowEvaluator { get; } = shadowEvaluator ?? (t => mainEvaluator(t).DarkenAbsolute(0.24f));
/// <inheritdoc cref="VariableColor"/>
public VariableColor(StringNames name, Func<float, Color> mainEvaluator, Color32? mainColor = null, float defaultTime = 0f)
: this(name, mainEvaluator, null, mainColor, null, defaultTime)
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor"/>
public VariableColor(string name, Func<float, Color> mainEvaluator, Color32? mainColor = null, float defaultTime = 0f)
: this(name, mainEvaluator, null, mainColor, null, defaultTime)
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, null, mainColor, null, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor"/>
public VariableColor(string name, Func<float, Color> mainEvaluator, Func<float, Color>? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f)
: this(MiraLocaleManager.GetOrCreateLocaleString(name), mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime)
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, null, mainColor, null, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
Color32? mainColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, null, mainColor, null, defaultTime, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
[Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")]
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
Color32? mainColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, null, mainColor, null, defaultTime, CustomColorBrightness.Darker)
{
}
@@ -13,7 +13,7 @@ public sealed class MiraButtonCancelledEvent<T>(T button) : MiraEvent
/// <summary>
/// Gets the <see cref="CustomActionButton"/> whose click was cancelled.
/// </summary>
public T Button { get; } = button;
public T Button => button;
}
/// <summary>
@@ -25,5 +25,5 @@ public sealed class MiraButtonCancelledEvent(CustomActionButton button) : MiraEv
/// <summary>
/// Gets the <see cref="CustomActionButton"/> whose click was cancelled.
/// </summary>
public CustomActionButton Button { get; } = button;
public CustomActionButton Button => button;
}
+3 -3
View File
@@ -14,12 +14,12 @@ public class MiraButtonClickEvent<T>(T button, MiraButtonClickEvent genericClick
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
/// </summary>
public T Button { get; } = button;
public T Button => button;
/// <summary>
/// Gets the generic <see cref="MiraButtonClickEvent"/> that is invoked before this button-specific event.
/// </summary>
public MiraButtonClickEvent GenericClickEvent { get; } = genericClickEvent;
public MiraButtonClickEvent GenericClickEvent => genericClickEvent;
}
/// <summary>
@@ -31,5 +31,5 @@ public class MiraButtonClickEvent(CustomActionButton button) : MiraCancelableEve
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
/// </summary>
public CustomActionButton Button { get; } = button;
public CustomActionButton Button => button;
}
@@ -12,10 +12,10 @@ public class UiButtonPostResetEvent(GameObject topUiRow, GameObject secondUiRow)
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the very top UI row.
/// </summary>
public GameObject MainTopUiRow { get; } = topUiRow;
public GameObject MainTopUiRow => topUiRow;
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the second top UI row.
/// </summary>
public GameObject SecondTopUiRow { get; } = secondUiRow;
public GameObject SecondTopUiRow => secondUiRow;
}
+31 -4
View File
@@ -3,7 +3,8 @@
namespace MiraAPI.Events;
/// <summary>
/// Event handle to use when unregistering a <see cref="MiraEvent"/>.
/// Wrapper for <see cref="MiraEvent"/> handlers.
/// Also used when unregistering a <see cref="MiraEvent"/>.
/// </summary>
public class MiraEventHandle
{
@@ -12,11 +13,37 @@ public class MiraEventHandle
/// </summary>
public Type EventType { get; }
internal MiraEventWrapper EventWrapper { get; }
/// <summary>
/// Gets the priority of the handler. Lower values are called first.
/// </summary>
public int Priority { get; }
internal MiraEventHandle(Type type, MiraEventWrapper eventWrapper)
/// <summary>
/// Gets the event handler delegate.
/// </summary>
public Delegate EventHandler { get; }
/// <summary>
/// Gets a value indicating whether the event handler should also be
/// triggered by subclasses of <see cref="EventType"/>.
/// </summary>
public bool InvokeOnSubtype { get; }
internal MiraEventHandle(Delegate eventHandler, int priority, Type type, bool invokeOnSubtype)
{
EventHandler = eventHandler;
Priority = priority;
EventType = type;
EventWrapper = eventWrapper;
InvokeOnSubtype = invokeOnSubtype;
}
internal bool IsTriggeredBy(Type type)
{
if (InvokeOnSubtype)
{
return EventType.IsAssignableTo(type);
}
return EventType == type;
}
}
+266 -52
View File
@@ -1,6 +1,10 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
namespace MiraAPI.Events;
@@ -9,7 +13,21 @@ namespace MiraAPI.Events;
/// </summary>
public static class MiraEventManager
{
private static readonly Dictionary<Type, List<MiraEventWrapper>> EventWrappers = [];
private static readonly Dictionary<Type, List<MiraEventHandle>> EventHandlers = [];
private static readonly Dictionary<Type, List<MiraEventHandle>> EventHandlersToLoad = [];
private static readonly Comparer<MiraEventHandle> EventComparer = Comparer<MiraEventHandle>.Create((a, b) => a.Priority.CompareTo(b.Priority));
/// <summary>
/// Gets the list of all registered <see cref="MiraEvent"/> types.
/// Generic event types are registered as their generic type definitions.
/// </summary>
public static IReadOnlyList<Type> EventTypes { get; internal set; } = [];
internal static List<Type> InternalEventTypes { get; } = [];
private static readonly Dictionary<Type, HashSet<Type>> TrackedEventTypes = [];
private static bool loadFinalized = false;
/// <summary>
/// Invoke a <see cref="MiraEvent"/>.
@@ -20,26 +38,7 @@ public static class MiraEventManager
public static bool InvokeEvent<T>(this T eventInstance)
where T : MiraEvent
{
EventWrappers.TryGetValue(typeof(T), out var handlers);
if (handlers == null || handlers.Count == 0)
{
return false;
}
foreach (var handler in handlers)
{
try
{
((Action<T>)handler.EventHandler).Invoke(eventInstance);
}
catch (Exception ex)
{
Error($"Error invoking event handler for {typeof(T).Name}: {ex.ToString()}");
}
}
return true;
return eventInstance.InvokeEvent(typeof(T));
}
/// <summary>
@@ -50,14 +49,27 @@ public static class MiraEventManager
/// <returns>If there was an event handler invoked for this event, return <see langword="true"/>. Otherwise, return <see langword="false"/>.</returns>
public static bool InvokeEvent(this MiraEvent eventInstance, Type type)
{
EventWrappers.TryGetValue(type, out var handlers);
var trackedType = type.GetTrackedType();
var callableHandlers = new List<MiraEventHandle>();
if (handlers == null || handlers.Count == 0)
if (EventHandlers.TryGetValue(trackedType, out var handlers))
{
callableHandlers.AddRange(handlers.Where(x => x.IsTriggeredBy(type)));
}
if (!loadFinalized && EventHandlersToLoad.TryGetValue(trackedType, out var pendingHandlers))
{
callableHandlers.AddRange(pendingHandlers.Where(x => x.IsTriggeredBy(type)));
}
if (callableHandlers.Count == 0)
{
return false;
}
foreach (var handler in handlers)
callableHandlers.Sort(EventComparer);
foreach (var handler in callableHandlers)
{
try
{
@@ -65,42 +77,117 @@ public static class MiraEventManager
}
catch (Exception ex)
{
Error($"Error invoking event handler for {type.Name}: {ex.ToString()}");
Error($"Error invoking event handler for {type.Name}: {ex}");
}
}
return true;
}
internal static bool RegisterEventType(Type type, in MiraPluginManager.RegistrationContext context)
{
if (type.IsAbstract || !type.IsSubclassOf(typeof(MiraEvent)))
{
return false;
}
AddTypeToTracked(type);
// subtypes are added to their supertypes, regardless of which were added first
TrackedEventTypes[type].UnionWith(InternalEventTypes.Where(x => x.IsSubclassOfWithGeneric(type)));
foreach (var supertype in InternalEventTypes.Where(x => type.IsSubclassOfWithGeneric(x)))
{
AddTypeToTracked(supertype, type);
}
context.PluginInfo.InternalEventTypes.Add(type);
InternalEventTypes.Add(type);
return true;
}
private static void AddTypeToTracked(Type eventType, Type trackedAs = null!)
{
if (eventType.IsAbstract)
{
return;
}
if (!TrackedEventTypes.TryGetValue(eventType, out var trackedEvents))
{
trackedEvents = [];
TrackedEventTypes.Add(eventType, trackedEvents);
}
trackedAs ??= eventType;
trackedEvents.Add(trackedAs);
}
/// <summary>
/// Register a <see cref="MiraEvent"/> handler.
/// </summary>
/// <param name="type">The type of <see cref="MiraEvent"/> event.</param>
/// <param name="methodInfo">The <see cref="MethodInfo"/> of the event handler.</param>
/// <param name="priority">The priority of the event handler. Lower values are called first.</param>
/// <param name="invokeOnSubtype">Whether the event handler should also be triggered by subclasses of the <see cref="MiraEvent"/> type of the handler.</param>
/// <returns>A <see cref="MiraEventHandle"/> to use when unregistering the event.</returns>
public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, int priority = 0)
public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, int priority, bool invokeOnSubtype)
{
if (!type.IsSubclassOf(typeof(MiraEvent)))
if (!type.IsAssignableTo(typeof(MiraEvent)))
{
throw new InvalidOperationException($"Type must be a subclass of MiraEvent: {type.FullName}");
}
EventWrappers.TryAdd(type, []);
var handlers = EventWrappers[type];
var @delegate = Delegate.CreateDelegate(typeof(Action<>).MakeGenericType(type), methodInfo);
var eventWrapper = new MiraEventWrapper(@delegate, priority);
return RegisterEventHandler(type, @delegate, priority, invokeOnSubtype);
}
var index = handlers.BinarySearch(eventWrapper, Comparer<MiraEventWrapper>.Create((a, b) => a.Priority.CompareTo(b.Priority)));
/// <inheritdoc cref="RegisterEventHandler(Type, MethodInfo, int, bool)"/>
public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, int priority)
{
return RegisterEventHandler(type, methodInfo, priority, false);
}
if (index < 0)
{
index = ~index;
}
/// <inheritdoc cref="RegisterEventHandler(Type, MethodInfo, int, bool)"/>
public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, bool invokeOnSubtype)
{
return RegisterEventHandler(type, methodInfo, 0, invokeOnSubtype);
}
handlers.Insert(index, eventWrapper);
return new MiraEventHandle(type, eventWrapper);
/// <inheritdoc cref="RegisterEventHandler(Type, MethodInfo, int, bool)"/>
public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo)
{
return RegisterEventHandler(type, methodInfo, 0, false);
}
/// <summary>
/// Register a <see cref="MiraEvent"/> handler.
/// </summary>
/// <param name="methodInfo">The <see cref="MethodInfo"/> of the event handler.</param>
/// <param name="priority">The priority of the event handler. Lower values are called first.</param>
/// <param name="invokeOnSubtype">Whether the event handler should also be triggered by subclasses of the <see cref="MiraEvent"/> type of the handler.</param>
/// <returns>A <see cref="MiraEventHandle"/> to use when unregistering the event.</returns>
public static MiraEventHandle RegisterEventHandler(MethodInfo methodInfo, int priority, bool invokeOnSubtype)
{
return RegisterEventHandler(methodInfo.GetParameters()[0].ParameterType, methodInfo, priority, invokeOnSubtype);
}
/// <inheritdoc cref="RegisterEventHandler(MethodInfo, int, bool)"/>
public static MiraEventHandle RegisterEventHandler(MethodInfo methodInfo, int priority)
{
return RegisterEventHandler(methodInfo, priority, false);
}
/// <inheritdoc cref="RegisterEventHandler(MethodInfo, int, bool)"/>
public static MiraEventHandle RegisterEventHandler(MethodInfo methodInfo, bool invokeOnSubtype)
{
return RegisterEventHandler(methodInfo, 0, invokeOnSubtype);
}
/// <inheritdoc cref="RegisterEventHandler(MethodInfo, int, bool)"/>
public static MiraEventHandle RegisterEventHandler(MethodInfo methodInfo)
{
return RegisterEventHandler(methodInfo, 0, false);
}
/// <summary>
@@ -108,25 +195,87 @@ public static class MiraEventManager
/// </summary>
/// <param name="handler">The callback method/handler for the event.</param>
/// <param name="priority">The priority of the event handler. Lower values are called first.</param>
/// <param name="invokeOnSubtype">Whether the event handler should also be triggered by subclasses of the <see cref="MiraEvent"/> type of the handler.</param>
/// <typeparam name="T">Type of <see cref="MiraEvent"/> event.</typeparam>
/// <returns>A <see cref="MiraEventHandle"/> to use when unregistering the event.</returns>
public static MiraEventHandle RegisterEventHandler<T>(Action<T> handler, int priority = 0)
public static MiraEventHandle RegisterEventHandler<T>(Action<T> handler, int priority, bool invokeOnSubtype)
where T : MiraEvent
{
EventWrappers.TryAdd(typeof(T), []);
return RegisterEventHandler(typeof(T), handler, priority, invokeOnSubtype);
}
var handlers = EventWrappers[typeof(T)];
var eventWrapper = new MiraEventWrapper(handler, priority);
/// <inheritdoc cref="RegisterEventHandler{T}(Action{T}, int, bool)"/>
public static MiraEventHandle RegisterEventHandler<T>(Action<T> handler, int priority)
where T : MiraEvent
{
return RegisterEventHandler(handler, priority, false);
}
var index = handlers.BinarySearch(eventWrapper, Comparer<MiraEventWrapper>.Create((a, b) => a.Priority.CompareTo(b.Priority)));
/// <inheritdoc cref="RegisterEventHandler{T}(Action{T}, int, bool)"/>
public static MiraEventHandle RegisterEventHandler<T>(Action<T> handler, bool invokeOnSubtype)
where T : MiraEvent
{
return RegisterEventHandler(handler, 0, invokeOnSubtype);
}
if (index < 0)
/// <inheritdoc cref="RegisterEventHandler{T}(Action{T}, int, bool)"/>
public static MiraEventHandle RegisterEventHandler<T>(Action<T> handler)
where T : MiraEvent
{
return RegisterEventHandler(handler, 0, false);
}
/// <summary>
/// Register a <see cref="MiraEvent"/> handler.
/// </summary>
/// <param name="type">The type of <see cref="MiraEvent"/> event.</param>
/// <param name="delegate">The <see cref="Delegate"/> method/handler for the event.</param>
/// <param name="priority">The priority of the event handler. Lower values are called first.</param>
/// <param name="invokeOnSubtype">Whether the event handler should also be triggered by subclasses of the <see cref="MiraEvent"/> type of the handler.</param>
/// <returns>A <see cref="MiraEventHandle"/> to use when unregistering the event.</returns>
private static MiraEventHandle RegisterEventHandler(Type type, Delegate @delegate, int priority, bool invokeOnSubtype)
{
var eventHandler = new MiraEventHandle(@delegate, priority, type, invokeOnSubtype);
EventHandlerAdded(type, eventHandler);
return eventHandler;
}
private static Type GetTrackedType(this Type type)
{
if (type.IsGenericType)
{
index = ~index;
return type.GetGenericTypeDefinition();
}
handlers.Insert(index, eventWrapper);
return new MiraEventHandle(typeof(T), eventWrapper);
return type;
}
private static void EventHandlerAdded(Type type, MiraEventHandle eventHandler)
{
if (!loadFinalized)
{
EventHandlersToLoad.TryAdd(type, []);
EventHandlersToLoad[type].Add(eventHandler);
return;
}
if (!TrackedEventTypes.TryGetValue(type.GetTrackedType(), out var trackedEvents))
{
return;
}
foreach (Type eventType in trackedEvents)
{
var handlers = EventHandlers[eventType];
var index = handlers.BinarySearch(eventHandler, EventComparer);
if (index < 0)
{
index = ~index;
}
handlers.Insert(index, eventHandler);
}
}
/// <summary>
@@ -136,21 +285,86 @@ public static class MiraEventManager
/// <returns><see langword="true"/> if the event was unregistered successfully, <see langword="false"/> otherwise.</returns>
public static bool UnregisterEventHandler(MiraEventHandle eventHandle)
{
if (!EventWrappers.TryGetValue(eventHandle.EventType, out var handlers))
if (!loadFinalized)
{
if (!EventHandlersToLoad.TryGetValue(eventHandle.EventType, out var handlersToLoad))
{
return false;
}
if (!handlersToLoad.Remove(eventHandle))
{
return false;
}
return true;
}
if (!TrackedEventTypes.TryGetValue(eventHandle.EventType.GetTrackedType(), out var eventTypes))
{
return false;
}
if (!handlers.Remove(eventHandle.EventWrapper))
var removed = false;
foreach (var type in eventTypes)
{
if (EventHandlers.TryGetValue(type, out var handlers))
{
removed |= handlers.Remove(eventHandle);
}
}
return removed;
}
internal static void OnLoadFinalize()
{
loadFinalized = true;
EventTypes = new ReadOnlyCollection<Type>(InternalEventTypes);
foreach (var eventType in EventTypes)
{
EventHandlers.Add(eventType, []);
}
foreach (var (concreteType, eventHandlers) in EventHandlersToLoad)
{
foreach (var eventHandler in eventHandlers)
{
EventHandlerAdded(concreteType, eventHandler);
}
eventHandlers.Clear();
}
EventHandlersToLoad.Clear();
}
internal static bool RegisterEvents(Type type, in MiraPluginManager.RegistrationContext context)
{
var hasContainerAttribute = type.IsDefined<RegisterEventContainerAttribute>();
if (!context.MiraPlugin.ForceRegisterEvents && !hasContainerAttribute)
{
return false;
}
if (handlers.Count == 0)
foreach (var method in type.GetMethods(MiraPluginManager.DeclaredStaticMembers))
{
EventWrappers.Remove(eventHandle.EventType);
if (!method.TryGetCustomAttribute<RegisterEventAttribute>(out var eventAttribute))
continue;
var parameters = method.GetParameters();
if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent)))
{
Error($"Invalid event registration method {method.Name} in {type.Name}");
continue;
}
RegisterEventHandler(parameters[0].ParameterType, method, eventAttribute.Priority, eventAttribute.InvokeOnSubtype);
}
return true;
return hasContainerAttribute;
}
}
+3 -2
View File
@@ -7,15 +7,16 @@ namespace MiraAPI.Events;
/// </summary>
/// <param name="eventHandler">The action for the event handler.</param>
/// <param name="priority">The priority of the handler.</param>
[Obsolete("Use MiraEventHandle instead. This will be removed in a future version.")]
public class MiraEventWrapper(Delegate eventHandler, int priority)
{
/// <summary>
/// Gets the event handler delegate.
/// </summary>
public Delegate EventHandler { get; } = eventHandler;
public Delegate EventHandler => eventHandler;
/// <summary>
/// Gets the priority of the handler. Lower values are called first.
/// </summary>
public int Priority { get; } = priority;
public int Priority => priority;
}
+27 -2
View File
@@ -6,11 +6,36 @@ namespace MiraAPI.Events;
/// Register a <see cref="MiraEvent"/> handler.
/// </summary>
/// <param name="priority">The priority of the event. Lower values are called first.</param>
/// <param name="invokeOnSubtype">Whether the event handler should also be triggered by subclasses of the <see cref="MiraEvent"/> type of the handler.</param>
[AttributeUsage(AttributeTargets.Method)]
public class RegisterEventAttribute(int priority = 0) : Attribute
public class RegisterEventAttribute(int priority, bool invokeOnSubtype) : Attribute
{
/// <summary>
/// Gets the priority of the event. Lower values are called first.
/// </summary>
public int Priority { get; } = priority;
public int Priority => priority;
/// <summary>
/// Gets a value indicating whether the event handler should also be
/// triggered by subclasses of the <see cref="MiraEvent"/> type of the handler.
/// </summary>
public bool InvokeOnSubtype => invokeOnSubtype;
/// <inheritdoc cref="RegisterEventAttribute"/>
public RegisterEventAttribute(int priority)
: this(priority, false)
{
}
/// <inheritdoc cref="RegisterEventAttribute"/>
public RegisterEventAttribute(bool invokeOnSubtype)
: this(0, invokeOnSubtype)
{
}
/// <inheritdoc cref="RegisterEventAttribute"/>
public RegisterEventAttribute()
: this(0, false)
{
}
}
@@ -0,0 +1,9 @@
using System;
namespace MiraAPI.Events;
/// <summary>
/// Register a container of <see cref="MiraEvent"/>s.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class RegisterEventContainerAttribute : Attribute;
@@ -14,33 +14,33 @@ public class AfterMurderEvent(PlayerControl source, PlayerControl target, Player
/// <summary>
/// Gets the <see cref="PlayerControl"/> that killed the <see cref="Target"/>.
/// </summary>
public PlayerControl Source { get; } = source;
public PlayerControl Source => source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was killed.
/// </summary>
public PlayerControl Target { get; } = target;
public PlayerControl Target => target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was framed, if any.
/// </summary>
public PlayerControl? Framed { get; } = framed;
public PlayerControl? Framed => framed;
/// <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; } = isIndirect;
public bool IsIndirectAttack => isIndirect;
/// <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; } = ignoreDefense;
public bool IgnoreDefense => ignoreDefense;
/// <summary>
/// Gets the <see cref="Target"/>'s <see cref="DeadBody"/>, if it exists.
/// </summary>
public DeadBody? DeadBody { get; } = deadBody;
public DeadBody? DeadBody => deadBody;
/// <summary>
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
@@ -9,5 +9,5 @@ public class BeforeGameEndEvent(GameOverReason reason) : MiraCancelableEvent
/// <summary>
/// Gets the reason for the game end.
/// </summary>
public GameOverReason Reason { get; } = reason;
public GameOverReason Reason => reason;
}
@@ -17,17 +17,22 @@ public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is killing the <see cref="Target"/>.
/// </summary>
public PlayerControl Source { get; } = source;
public PlayerControl Source => source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being killed.
/// </summary>
public PlayerControl Target { get; } = target;
public PlayerControl Target => target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being framed, if any.
/// </summary>
public PlayerControl? Framed { get; } = framed;
public PlayerControl? Framed => framed;
/// <summary>
/// Gets whether the murder was meant to be done in a meeting, via an enum.
/// </summary>
public MeetingCheck InMeeting => inMeeting;
/// <summary>
/// Gets or sets a value indicating whether the murder is done indirectly.
@@ -40,11 +45,6 @@ public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target
/// </summary>
public bool IgnoreDefense { get; set; } = ignoreDefense;
/// <summary>
/// Gets whether the murder was meant to be done in a meeting, via an enum.
/// </summary>
public MeetingCheck InMeeting { get; } = inMeeting;
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
@@ -9,5 +9,5 @@ public class BeforeRoundStartEvent(bool triggeredByIntro) : MiraCancelableEvent
/// <summary>
/// Gets a value indicating whether the event was triggered by the <see cref="IntroCutscene"/> or <see cref="ExileController"/>.
/// </summary>
public bool TriggeredByIntro { get; } = triggeredByIntro;
public bool TriggeredByIntro => triggeredByIntro;
}
@@ -9,5 +9,5 @@ public class GameEndEvent(EndGameManager manager) : MiraEvent
/// <summary>
/// Gets the <see cref="global::EndGameManager"/> instance.
/// </summary>
public EndGameManager EndGameManager { get; } = manager;
public EndGameManager EndGameManager => manager;
}
@@ -9,5 +9,5 @@ public class IntroBeginEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; } = introCutscene;
public IntroCutscene IntroCutscene => introCutscene;
}
@@ -9,5 +9,5 @@ public class IntroEndEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; } = introCutscene;
public IntroCutscene IntroCutscene => introCutscene;
}
@@ -9,5 +9,5 @@ public class IntroRoleRevealEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; } = introCutscene;
public IntroCutscene IntroCutscene => introCutscene;
}
@@ -10,5 +10,5 @@ public class RoundStartEvent(bool triggeredByIntro) : MiraEvent
/// <summary>
/// Gets a value indicating whether the event was triggered by the <see cref="IntroCutscene"/> or <see cref="ExileController"/>.
/// </summary>
public bool TriggeredByIntro { get; } = triggeredByIntro;
public bool TriggeredByIntro => triggeredByIntro;
}
@@ -12,10 +12,10 @@ public class SetRoleEvent(PlayerControl player, RoleTypes role) : MiraEvent
/// <summary>
/// Gets the <see cref="PlayerControl"/> whose role was changed.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the role that the player was set to.
/// </summary>
public RoleTypes Role { get; } = role;
public RoleTypes Role => role;
}
@@ -2,20 +2,6 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// Invoked when a Vanilla <see cref="AbilityButton"/> click is cancelled. Do not use for <see cref="CustomActionButton"/>.
/// </summary>
/// <typeparam name="T">The vanilla <see cref="AbilityButton"/> type.</typeparam>
/// <param name="button">The vanilla <see cref="AbilityButton"/> whose click was cancelled.</param>
public sealed class VanillaButtonCancelledEvent<T>(T button) : MiraEvent
where T : AbilityButton
{
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> whose click was cancelled.
/// </summary>
public T Button { get; } = button;
}
/// <summary>
/// Invoked when a Vanilla <see cref="AbilityButton"/> click is cancelled. Do not use for <see cref="CustomActionButton"/>s.
/// </summary>
@@ -25,5 +11,5 @@ public sealed class VanillaButtonCancelledEvent(AbilityButton button) : MiraEven
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> whose click was cancelled.
/// </summary>
public AbilityButton Button { get; } = button;
public AbilityButton Button => button;
}
@@ -2,26 +2,6 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// Button click event for Vanilla <see cref="AbilityButton"/>s only. Do not use for <see cref="CustomActionButton"/>s.
/// </summary>
/// <typeparam name="T">The vanilla <see cref="AbilityButton"/> type.</typeparam>
/// <param name="button">The vanilla <see cref="AbilityButton"/> that was clicked.</param>
/// <param name="genericClickEvent">The generic <see cref="VanillaButtonClickEvent"/> invoked before button-specific events.</param>
public sealed class VanillaButtonClickEvent<T>(T button, VanillaButtonClickEvent genericClickEvent) : MiraCancelableEvent
where T : AbilityButton
{
/// <summary>
/// Gets the vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public T Button { get; } = button;
/// <summary>
/// Gets the generic <see cref="VanillaButtonClickEvent"/> that is invoked before this button-specific event.
/// </summary>
public VanillaButtonClickEvent GenericClickEvent { get; } = genericClickEvent;
}
/// <summary>
/// Button click event for Vanilla <see cref="AbilityButton"/> only. Do not use for <see cref="CustomActionButton"/>s.
/// </summary>
@@ -33,15 +13,15 @@ public sealed class VanillaButtonClickEvent(AbilityButton button, PlayerControl?
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public AbilityButton Button { get; } = button;
public AbilityButton Button => button;
/// <summary>
/// Gets the target <see cref="PlayerControl"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public PlayerControl? PlayerTarget { get; } = playerTarget;
public PlayerControl? PlayerTarget => playerTarget;
/// <summary>
/// Gets the target <see cref="Vent"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public Vent? VentTarget { get; } = ventTarget;
public Vent? VentTarget => ventTarget;
}
@@ -9,5 +9,5 @@ public class CloseDoorsEvent(SystemTypes room) : MiraCancelableEvent
/// <summary>
/// Gets the room that the doors were closed in.
/// </summary>
public SystemTypes Room { get; } = room;
public SystemTypes Room => room;
}
@@ -9,5 +9,5 @@ public class PlayerOpenSabotageEvent(MapBehaviour mapBehaviour) : MiraCancelable
/// <summary>
/// Gets the <see cref="global::MapBehaviour"/>.
/// </summary>
public MapBehaviour MapBehaviour { get; } = mapBehaviour;
public MapBehaviour MapBehaviour => mapBehaviour;
}
@@ -11,15 +11,15 @@ public class UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byt
/// <summary>
/// Gets the type of system that will be updated.
/// </summary>
public SystemTypes SystemType { get; } = systemType;
public SystemTypes SystemType => systemType;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is updating the system.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the byte amount the system is being updated by.
/// </summary>
public byte Amount { get; } = amount;
public byte Amount => amount;
}
@@ -9,5 +9,5 @@ public class EjectionEvent(ExileController controller) : MiraEvent
/// <summary>
/// Gets the <see cref="global::ExileController"/> instance.
/// </summary>
public ExileController ExileController { get; } = controller;
public ExileController ExileController => controller;
}
@@ -3,10 +3,11 @@
/// <summary>
/// The event that is invoked when the meeting has ended.
/// </summary>
/// <param name="meetingHud">The meeting hud of the meeting that invoked the event.</param>
public class EndMeetingEvent(MeetingHud meetingHud) : MiraEvent
{
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; } = meetingHud;
public MeetingHud MeetingHud => meetingHud;
}
@@ -12,15 +12,15 @@ public class ReportBodyEvent(PlayerControl reporter, NetworkedPlayerInfo? target
/// <summary>
/// Gets the player that is reporting the body.
/// </summary>
public PlayerControl Reporter { get; } = reporter;
public PlayerControl Reporter => reporter;
/// <summary>
/// Gets the player that is being reported. Will be <see langword="null"/> for emergency meeting.
/// </summary>
public NetworkedPlayerInfo? Target { get; } = target;
public NetworkedPlayerInfo? Target => target;
/// <summary>
/// Gets the <see cref="DeadBody"/> that is being reported. Will be <see langword="null"/> for emergency meeting.
/// </summary>
public DeadBody? Body { get; } = body;
public DeadBody? Body => body;
}
@@ -10,5 +10,5 @@ public class StartMeetingEvent(MeetingHud meetingHud) : MiraEvent
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; } = meetingHud;
public MeetingHud MeetingHud => meetingHud;
}
@@ -10,10 +10,10 @@ public class AfterVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter)
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteArea"/>.
/// </summary>
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
public PlayerVoteArea VoteArea => playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; } = voter;
public PlayerControl Player => voter;
}
@@ -10,10 +10,10 @@ public class BeforeVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter)
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteArea"/>.
/// </summary>
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
public PlayerVoteArea VoteArea => playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; } = voter;
public PlayerControl Player => voter;
}
@@ -9,10 +9,10 @@ public class CheckForEndVotingEvent(bool isVotingComplete) : MiraCancelableEvent
/// <summary>
/// Gets a value indicating whether default voting logic determines that voting is complete.
/// </summary>
public bool IsVotingComplete { get; } = isVotingComplete;
public bool IsVotingComplete => isVotingComplete;
/// <summary>
/// Gets or sets a value indicating whether the voting should be forced to end, regardless of the default logic.
/// </summary>
public bool ForceEndVoting { get; set; }
public bool ForceEndVoting { get; set; } = false;
}
@@ -13,7 +13,7 @@ public class DummyVoteEvent(DummyBehaviour dummy) : MiraCancelableEvent
/// <summary>
/// Gets the dummy that needs to vote.
/// </summary>
public DummyBehaviour Dummy { get; } = dummy;
public DummyBehaviour Dummy => dummy;
/// <summary>
/// Gets the instance of the dummy's <see cref="PlayerVoteData"/>.
@@ -17,23 +17,18 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; } = playerVoteData;
public PlayerVoteData VoteData => playerVoteData;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public byte TargetId => targetId;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; } = playerVoteData.Owner;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public byte TargetId { get; } = targetId;
/// <summary>
/// Gets or sets a value indicating whether to prevent the vote from commencing.
/// </summary>
public bool PreventVote { get; set; } = false;
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
/// </summary>
@@ -43,4 +38,9 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool
/// Gets or sets a value indicating whether the vote event is an Overrule caused by a Judge.
/// </summary>
public bool IsOverruling { get; set; } = isOverruling;
/// <summary>
/// Gets or sets a value indicating whether to prevent the vote from commencing.
/// </summary>
public bool PreventVote { get; set; } = false;
}
@@ -13,12 +13,12 @@ public class MeetingSelectEvent(PlayerVoteData playerVoteData, int targetId, boo
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; } = playerVoteData;
public PlayerVoteData VoteData => playerVoteData;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public int TargetId { get; } = targetId;
public int TargetId => targetId;
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
@@ -15,5 +15,5 @@ public class PopulateResultsEvent(List<CustomVote> votes) : MiraCancelableEvent
/// <summary>
/// Gets a list of networked <see cref="CustomVote"/>s.
/// </summary>
public List<CustomVote> Votes { get; } = votes;
public List<CustomVote> Votes => votes;
}
@@ -12,7 +12,7 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting;
/// <param name="exiledPlayer">The player to be exiled. Will be <see langword="null"/> if no player is to be exiled.</param>
public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exiledPlayer = null) : MiraEvent
{
private readonly List<CustomVote> originalVotes = [.. votes];
private readonly CustomVote[] originalVotes = [.. votes];
/// <summary>
/// Gets a value indicating whether the exiled player has been modified by the event.
@@ -27,7 +27,7 @@ public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exil
/// <summary>
/// Gets the list of <see cref="CustomVote"/>s that are being processed.
/// </summary>
public List<CustomVote> Votes { get; } = votes;
public List<CustomVote> Votes => votes;
/// <summary>
/// Gets or sets a value indicating whether an overruling was done. Normally set by judge but can be overwritten.
@@ -48,6 +48,9 @@ public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exil
get;
set
{
if (field == value)
return;
field = value;
ExiledPlayerModified = true;
}
@@ -9,5 +9,5 @@ public class VotingCompleteEvent(MeetingHud meetingHud) : MiraEvent
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; } = meetingHud;
public MeetingHud MeetingHud => meetingHud;
}
@@ -11,15 +11,15 @@ public class CompleteHnsTaskEvent(HideAndSeekManager hnsManager, PlayerControl p
/// <summary>
/// Gets the instance of the <see cref="PlayerControl"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task { get; } = task;
public PlayerTask Task => task;
/// <summary>
/// Gets the instance of the <see cref="HideAndSeekManager"/> attached to the game.
/// </summary>
public HideAndSeekManager HnsManager { get; } = hnsManager;
public HideAndSeekManager HnsManager => hnsManager;
}
@@ -10,10 +10,10 @@ public class CompleteTaskEvent(PlayerControl player, PlayerTask task) : MiraEven
/// <summary>
/// Gets the instance of the <see cref="PlayerControl"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task { get; } = task;
public PlayerTask Task => task;
}
@@ -11,15 +11,15 @@ public class PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody
/// <summary>
/// Gets the player who died.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the reason the player died.
/// </summary>
public DeathReason DeathReason { get; } = reason;
public DeathReason DeathReason => reason;
/// <summary>
/// Gets the <see cref="global::DeadBody"/> associated with the player, if any.
/// </summary>
public DeadBody? DeadBody { get; } = deadBody;
public DeadBody? DeadBody => deadBody;
}
@@ -11,5 +11,5 @@ public class PlayerJoinEvent(ClientData data) : MiraEvent
/// <summary>
/// Gets the player who joined.
/// </summary>
public ClientData ClientData { get; } = data;
public ClientData ClientData => data;
}
@@ -12,10 +12,10 @@ public class PlayerLeaveEvent(ClientData data, DisconnectReasons reason) : MiraE
/// <summary>
/// Gets the player who left.
/// </summary>
public ClientData ClientData { get; } = data;
public ClientData ClientData => data;
/// <summary>
/// Gets the reason why the player left.
/// </summary>
public DisconnectReasons Reason { get; } = reason;
public DisconnectReasons Reason => reason;
}
@@ -10,10 +10,10 @@ public class EnterVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEv
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is entering the <see cref="Vent"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is entering.
/// </summary>
public Vent? Vent { get; } = vent;
public Vent? Vent => vent;
}
@@ -10,10 +10,10 @@ public class ExitVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEve
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is exiting the <see cref="Vent"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is exiting.
/// </summary>
public Vent? Vent { get; } = vent;
public Vent? Vent => vent;
}
@@ -9,7 +9,7 @@ public class PlayerUseEvent(IUsable usable) : MiraCancelableEvent
/// <summary>
/// Gets the instance of <see cref="IUsable"/> that was used.
/// </summary>
public IUsable Usable { get; } = usable;
public IUsable Usable => usable;
/// <summary>
/// Gets a value indicating whether the <see cref="Usable"/> is a <see cref="Console"/>, <see cref="MapConsole"/>, or <see cref="SystemConsole"/>.
+6 -17
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.PluginLoading;
namespace MiraAPI.GameEnd;
@@ -14,33 +15,21 @@ public static class GameOverManager
private static int nextId = Enum.GetNames<GameOverReason>().Length;
/// <summary>
/// Register a <see cref="CustomGameOver"/>.
/// </summary>
/// <param name="gameOverType">Type of the <see cref="CustomGameOver"/>.</param>
/// <exception cref="ArgumentException">Thrown when the type is not a subclass of <see cref="CustomGameOver"/>, is abstract, or does not have a parameterless constructor.</exception>
/// <returns><see langword="true"/> if the game over was registered successfully, <see langword="false"/> otherwise.</returns>
public static bool RegisterGameOver(Type gameOverType)
internal static bool RegisterGameOver(Type type, in MiraPluginManager.RegistrationContext _)
{
if (!typeof(CustomGameOver).IsAssignableFrom(gameOverType))
if (type.IsAbstract || !typeof(CustomGameOver).IsAssignableFrom(type))
{
return false;
}
if (gameOverType.IsAbstract)
{
Error("The type must not be abstract.");
return false;
}
if (gameOverType.GetConstructor(Type.EmptyTypes) == null)
if (type.GetConstructor(Type.EmptyTypes) == null)
{
Error("The type must have a parameterless constructor.");
return false;
}
GameOverIds.Add(gameOverType, nextId);
GameOverTypes.Add(nextId, gameOverType);
GameOverIds.Add(type, nextId);
GameOverTypes.Add(nextId, type);
nextId++;
return true;
}
+2
View File
@@ -77,6 +77,8 @@ public abstract class AbstractGameMode : IOptionable
/// </summary>
public virtual float DefaultImpostorKillCooldown => GameOptionsManager.Instance.CurrentGameOptions.GetFloat(FloatOptionNames.KillCooldown);
internal StringNames StringName { get; set; }
/// <summary>
/// Called on GameManager.GetBodyType().
/// </summary>
+19 -30
View File
@@ -12,41 +12,33 @@ public static class CustomGameModeManager
{
internal static readonly Dictionary<uint, AbstractGameMode> IdToModeMap = [];
private static uint lastId;
private static uint GetNextId()
{
return ++LastId;
return ++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)
internal static bool RegisterGameMode(Type type, in MiraPluginManager.RegistrationContext context)
{
if (!typeof(AbstractGameMode).IsAssignableFrom(gameModeType))
if (type.IsAbstract || !typeof(AbstractGameMode).IsAssignableFrom(type))
{
Warning($"{gameModeType.Name} does not inherit CustomGameMode!");
return false;
}
var instance = Activator.CreateInstance(gameModeType);
if (instance is not AbstractGameMode mode)
if (Activator.CreateInstance(type) is not AbstractGameMode mode)
{
Error($"Failed to create instance of {gameModeType.Name}");
Error($"Failed to create instance of {type.Name}");
return false;
}
if (mode.HideMode)
return true;
IdToModeMap.Add(GetNextId(), mode);
pluginInfo.GameModes.Add(LastId, mode);
mode.ID = LastId;
var id = GetNextId();
mode.ID = id;
IdToModeMap.Add(id, mode);
context.PluginInfo.GameModes.Add(id, mode);
GameModeOption.AddOption(mode);
return true;
}
@@ -107,34 +99,31 @@ public static class CustomGameModeManager
internal static void RegisterDefaultMode()
{
var defaultMode = new ClassicMode();
var defaultMode = new ClassicMode { ID = 0 };
IdToModeMap.Add(0, defaultMode);
GameModeOption.AddOption(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();
var hnsMode = new HideAndSeekMode() { ID = 1 };
if (hnsMode.HideMode)
return;
IdToModeMap.Add(1, hnsMode);
hnsMode.ID = 1;
GameModeOption.AddOption(hnsMode);
LastId++;
lastId++;
}
internal static void GetAndSetGameMode()
{
var id = (uint)GameModeOption.Value;
var index = GameModeOption.Value;
if (IdToModeMap.TryGetValue(id, out var mode))
if ((uint)index < (uint)GameModeOption.Values.Count)
{
ActiveMode = mode;
ActiveMode = GameModeOption.Values[index];
return;
}
ActiveMode = IdToModeMap[0];
Warning($"Unable to find game mode of id {id}!");
Warning($"Unable to find game mode at index {index}!");
}
}
+31 -84
View File
@@ -1,6 +1,5 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Networking;
@@ -17,6 +16,8 @@ namespace MiraAPI.GameModes;
/// The game mode option.
/// </summary>
[HarmonyPatch]
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public static class GameModeOption
{
/// <summary>
@@ -25,116 +26,63 @@ public static class GameModeOption
/// </summary>
public static int Value
{
get =>
OptionBehaviour != null
? OptionBehaviour.GetInt()
: LastValue;
get => OptionBehaviour != null
? OptionBehaviour.GetInt()
: LastValue;
private set
{
LastValue = value;
if (OptionBehaviour == null)
return;
OptionBehaviour.Value = value;
OptionBehaviour.UpdateValue();
LastValue = value;
}
}
internal static readonly StringNames GamemodeName = MiraLocaleManager.GetOrCreateLocaleString("MiraApi.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 readonly List<AbstractGameMode> Values = [];
internal static StringOption OptionBehaviour { get; set; } = null!;
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] // why so many warnings???
internal static StringOption OptionBehaviour = null!;
internal static int LastValue;
internal static void AddOption(AbstractGameMode mode)
{
if (!Values.ContainsKey(mode.ID))
Values.Add(mode.ID, MiraLocaleManager.GetOrCreateLocaleString(mode.Name));
mode.StringName = MiraLocaleManager.GetOrCreateLocaleString(mode.Name);
Values.Add(mode);
}
/*[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);
HudPatches.SetGameModeText(Values[LastValue].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);
if (MenuState.Instance)
{
// should force reset roles for gamemodes properly
foreach (var roleMenu in MenuState.Instance.QueuedRoleMenuRefresh)
{
MenuState.Instance.QueuedRoleMenuRefresh[roleMenu.Key] = true;
}
}
if (gm == previousMode)
return;
GameOptionsMenuPatch.RefreshForGameMode();
RoleGuidePatches.RefreshSettingsForGameMode();
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
GamemodeName,
gm.ColoredName,
new Color(0.7333f, 0.7333f, 0.7333f, 1),
gm.TmpIcon);
if (MenuState.Instance)
{
// should force reset roles for gamemodes properly
foreach (var roleMenu in MenuState.Instance.QueuedRoleMenuRefresh)
{
MenuState.Instance.QueuedRoleMenuRefresh[roleMenu.Key] = true;
}
}
// TODO: could make Values a dict of AbstractGameMode too
GameOptionsMenuPatch.RefreshForGameMode();
RoleGuidePatches.RefreshSettingsForGameMode();
}
[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.ValueChanged))]
@@ -151,8 +99,7 @@ public static class GameModeOption
}
[MethodRpc((uint)MiraRpc.SyncGamemodeOption)]
[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Intentionally unused because the main intent is for it to be used by dependent mods to add to a blacklist.")]
internal static void RpcSyncGamemode(PlayerControl host, int data)
internal static void RpcSyncGamemode(PlayerControl _, int data)
{
Set(data);
}
+2 -2
View File
@@ -92,9 +92,9 @@ public class HideAndSeekMode : AbstractGameMode
runOriginal = false;
CppCollections.List<ClientData> list = new();
AmongUsClient.Instance.GetAllClients(list);
List<NetworkedPlayerInfo> list2 = [.. list.ToArray()
var 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)];
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data).ToList();
foreach (var networkedPlayerInfo in GameData.Instance.AllPlayers)
{
+16 -13
View File
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Modifiers;
@@ -19,16 +18,31 @@ public abstract class AbstractOptionGroup
{
internal List<IModdedOption> Options { get; } = [];
private readonly ReadOnlyCollection<IModdedOption> children;
/// <summary>
/// Initializes a new instance of the <see cref="AbstractOptionGroup"/> class.
/// </summary>
protected AbstractOptionGroup()
{
children = new(Options);
}
/// <summary>
/// Gets a list of the options which are a part of this group.
/// </summary>
public ReadOnlyCollection<IModdedOption> Children => new(Options);
public ReadOnlyCollection<IModdedOption> Children => children;
/// <summary>
/// Gets the name of the group. Visible in options menu.
/// </summary>
public abstract string GroupName { get; }
/// <summary>
/// Gets the ID prefix used for options in this group (e.g., "Options.Teleporter.").
/// </summary>
public virtual string GroupPrefix => string.Empty;
/// <summary>
/// Gets the sprite of the group that is displayed in the match info guide.
/// </summary>
@@ -40,14 +54,6 @@ public abstract class AbstractOptionGroup
/// </summary>
public virtual Type? OptionableType => null;
/// <summary>
/// Gets a value indicating whether the group should be shown in the modifiers menu.
/// </summary>
// Completed: make this not a boolean
[Obsolete("Use ParentMenu instead.", true)]
[SuppressMessage("Info Code Smell", "S1133:Deprecated code should be removed", Justification = "Retained.")]
public virtual bool ShowInModifiersMenu => false;
/// <summary>
/// Gets a value indicating which menu the group is in.
/// </summary>
@@ -154,9 +160,6 @@ public abstract class AbstractOptionGroup<T> : AbstractOptionGroup
public abstract class AbstractRoleOptionGroup<T> : AbstractOptionGroup<T>
where T : ICustomRole
{
/// <inheritdoc />
public override Type OptionableType => typeof(T);
/// <inheritdoc />
public override MenuCategory ParentMenu => MenuCategory.Roles;
@@ -166,7 +166,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
{
flags |= BindingFlags.Instance;
var canSearchPrivates = type.GetCustomAttribute<SearchPrivateAttribute>() != null;
var canSearchPrivates = type.IsDefined<SearchPrivateAttribute>();
if (canSearchPrivates)
flags |= BindingFlags.NonPublic;
@@ -175,7 +175,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
foreach (var method in type.GetMethods(getterFlags))
{
if (method.GetParameters().Length > 0 || (method.GetCustomAttribute<InstanceGetterAttribute>() == null && method.Name != "GetInstance"))
if (method.GetParameters().Length > 0 || (!method.IsDefined<InstanceGetterAttribute>() && method.Name != "GetInstance"))
continue;
instanceGetter = method;
@@ -186,7 +186,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
{
foreach (var prop in type.GetProperties(getterFlags))
{
if (prop.GetCustomAttribute<InstanceGetterAttribute>() == null && prop.Name != "Instance")
if (!prop.IsDefined<InstanceGetterAttribute>() && prop.Name != "Instance")
continue;
var getMethod = prop.GetGetMethod(canSearchPrivates);
@@ -213,12 +213,12 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
return null;
}
}
else if (type.GetCustomAttribute<SearchPrivateAttribute>() != null)
else if (type.IsDefined<SearchPrivateAttribute>())
{
flags |= BindingFlags.NonPublic;
}
var member = type.GetMember(MemberName, flags).FirstOrDefault();
var member = type.GetMember(MemberName, flags).OrderBy(GetGenericArgsLength).FirstOrDefault();
notFound = true;
if (member == null)
@@ -237,7 +237,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
}
else
{
var method = (member as PropertyInfo)?.GetGetMethod(true) ?? member as MethodInfo;
var method = (member as PropertyInfo)?.GetGetMethod(true) ?? (member as MethodInfo);
isStatic = method is { IsStatic: true };
}
@@ -261,7 +261,33 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
/// <returns>The resolved <see cref="MethodInfo"/> if found; otherwise, <see langword="null"/>.</returns>
protected MethodInfo? ResolveMethod(AbstractOptionGroup group, PropertyInfo property, out Type type, out MethodInfo? instanceGetter, out bool notFound)
{
return ResolveMember(group, property, out type, out instanceGetter, out notFound) as MethodInfo;
var method = ResolveMember(group, property, out type, out instanceGetter, out notFound) as MethodInfo;
if (method == null)
return null;
if (method.IsGenericMethodDefinition)
{
if (method.GetGenericArguments().Length == 1)
{
method = method.MakeGenericMethod(property.PropertyType);
}
else
{
Error($"Found method {method.Name}, but it has too many generic parameters, and is therefore invalid.");
return null;
}
}
return method;
}
private static int GetGenericArgsLength(MemberInfo member)
{
if (member is not MethodInfo method)
return -1;
return method.IsGenericMethodDefinition ? method.GetGenericArguments().Length : 0;
}
/// <summary>
@@ -273,7 +299,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
/// The static getter <see cref="MethodInfo"/> used to push the target instance onto the evaluation stack for instance methods,
/// or <see langword="null"/> if <paramref name="method"/> is static.
/// </param>
/// <param name="returnType">The return <see cref="Type"/> of the generated delegate (or <see cref="void"/> for actions).</param>
/// <param name="returnType">The return <see cref="Type"/> of the generated delegate (or <see cref="Void"/> for actions).</param>
/// <param name="paramTypes">The parameter types accepted by the generated delegate.</param>
/// <param name="delegateType">The concrete delegate <see cref="Type"/> to create (e.g., <see cref="Func{T, TResult}"/> or <see cref="Action{T}"/>).</param>
/// <param name="suffix">A descriptive suffix appended to the generated <see cref="DynamicMethod"/> name for debugging and stack traces.</param>
@@ -346,7 +372,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
/// The static getter <see cref="MethodInfo"/> used to push the target instance onto the evaluation stack for instance methods,
/// or <see langword="null"/> if <paramref name="method"/> is static.
/// </param>
/// <param name="returnType">The return <see cref="Type"/> of the generated delegate (or <see cref="void"/> for actions).</param>
/// <param name="returnType">The return <see cref="Type"/> of the generated delegate (or <see cref="Void"/> for actions).</param>
/// <param name="baseParamTypes">The parameter types accepted by the generated delegate.</param>
/// <param name="delegateType">The concrete delegate <see cref="Type"/> to create.</param>
/// <param name="suffix">A descriptive suffix appended to the generated <see cref="DynamicMethod"/> name for debugging and stack traces.</param>
@@ -20,7 +20,7 @@ public sealed class ModdedOptionVisibilityAttribute(string? memberName = null, T
internal Func<bool>? GetVisibility(AbstractOptionGroup group, PropertyInfo property)
{
if (ResolveMember(group, property, out Type type, out var instanceGetter, out var notFound) is not { } member)
if (ResolveMember(group, property, out var type, out var instanceGetter, out var notFound) is not { } member)
{
if (notFound)
Error($"Member {MemberName} does not exist in {type.FullName}");
@@ -6,10 +6,12 @@ namespace MiraAPI.GameOptions.Attributes;
/// An attribute used to mark a method or property as one that returns an instance of the class it's declared in.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Used by dependant code.)
public sealed class InstanceGetterAttribute : Attribute;
/// <summary>
/// An attribute used to mark a class as one whose reflection search should include private members.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Used by dependant code.)
public sealed class SearchPrivateAttribute : Attribute;
@@ -0,0 +1,20 @@
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Provides unboxed access to option values to prevent memory allocations.
/// </summary>
/// <typeparam name="T">The type of the value that the option carries.</typeparam>
public interface ITypedOption<T>
{
/// <summary>
/// Gets the unboxed value of the option.
/// </summary>
/// <returns>The unboxed option value.</returns>
T GetValueUnboxed();
/// <summary>
/// Sets the unboxed value of the option.
/// </summary>
/// <param name="value">The new value to set.</param>
void SetValueUnboxed(T value);
}
@@ -9,22 +9,56 @@ namespace MiraAPI.GameOptions.Attributes;
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? values = null)
[Obsolete("Use ModdedEnumOptionAttribute<T> instead. This will be removed in a future version.")]
public class ModdedEnumOptionAttribute(string? title, Type enumType, string idPrefix, string[]? values = null)
: ModdedOptionAttribute(title)
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionAttribute"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
public ModdedEnumOptionAttribute(string? title, Type enumType, string[]? values = null)
: this(title, enumType, string.Empty, values)
{
var opt = new ModdedEnumOption(Title, (int)(value ?? 0), enumType, values);
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionAttribute"/> class.
/// </summary>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
public ModdedEnumOptionAttribute(Type enumType, string idPrefix, string[]? values = null)
: this(null, enumType, idPrefix, values)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionAttribute"/> class.
/// </summary>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
public ModdedEnumOptionAttribute(Type enumType, string[]? values = null)
: this(null, enumType, string.Empty, values)
{
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property, AbstractOptionGroup group)
{
var opt = new ModdedEnumOption(group.GroupPrefix, Title ?? property.Name, (int)(value ?? 0), enumType, idPrefix, values);
Title = opt.Title;
return opt;
}
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedEnumOption;
opt?.SetValue((int)value);
(HolderOption as ModdedEnumOption)?.SetValue((int)value);
}
/// <inheritdoc />
@@ -32,7 +66,7 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va
{
return HolderOption is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {enumType.FullName} is not a ModdedEnumOption");
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedEnumOption with enum type {enumType.FullName}");
}
}
@@ -41,30 +75,62 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
/// <param name="title">The title of the option.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionAttribute<T>(string title, string[]? values = null)
: ModdedOptionAttribute(title)
public class ModdedEnumOptionAttribute<T>(string? title, string idPrefix, string[]? values = null)
: ModdedOptionAttribute(title), ITypedOption<T>
where T : struct, Enum
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionAttribute{T}"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
public ModdedEnumOptionAttribute(string? title, string[]? values = null)
: this(title, string.Empty, values)
{
var opt = new ModdedEnumOption<T>(Title, (T)(value ?? 0), values);
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionAttribute{T}"/> class.
/// </summary>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
public ModdedEnumOptionAttribute(string[]? values = null)
: this(null, string.Empty, values)
{
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property, AbstractOptionGroup group)
{
var opt = new ModdedEnumOption<T>(group.GroupPrefix, Title ?? property.Name, (T)(value ?? 0), idPrefix, values);
Title = opt.Title;
return opt;
}
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedEnumOption<T>;
opt?.SetValue((T)value);
SetValueUnboxed((T)value);
}
/// <inheritdoc />
public void SetValueUnboxed(T value)
{
(HolderOption as ModdedEnumOption<T>)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue()
{
return GetValueUnboxed();
}
/// <inheritdoc />
public T GetValueUnboxed()
{
return HolderOption is ModdedEnumOption<T> opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {typeof(T).FullName} is not a ModdedEnumOption<{typeof(T).Name}>");
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedEnumOption<{typeof(T).Name}>");
}
}
@@ -19,7 +19,7 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="halfIncrements">Whether increments can be split in half (using Shift).</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedNumberOptionAttribute(
string title,
string? title,
float min,
float max,
float increment,
@@ -28,8 +28,32 @@ public class ModdedNumberOptionAttribute(
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool halfIncrements = false)
: ModdedOptionAttribute(title)
: ModdedOptionAttribute(title), ITypedOption<int>, ITypedOption<float>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionAttribute"/> class.
/// </summary>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="zeroBehavior">Determines what is shown for zero.</param>
/// <param name="negativeBehavior">Determines what is shown for negative 1.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="halfIncrements">Whether increments can be split in half (using Shift).</param>
public ModdedNumberOptionAttribute(
float min,
float max,
float increment,
string zeroBehavior,
string negativeBehavior,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool halfIncrements = false)
: this(null, min, max, increment, zeroBehavior, negativeBehavior, suffixType, formatString, halfIncrements)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionAttribute"/> class.
/// </summary>
@@ -41,7 +65,7 @@ public class ModdedNumberOptionAttribute(
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
public ModdedNumberOptionAttribute(
string title,
string? title,
float min,
float max,
float increment = 1,
@@ -52,7 +76,27 @@ public class ModdedNumberOptionAttribute(
{
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionAttribute"/> class.
/// </summary>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
public ModdedNumberOptionAttribute(
float min,
float max,
float increment = 1,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool zeroInfinity = false)
: this(null, min, max, increment, suffixType, formatString, zeroInfinity)
{
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property, AbstractOptionGroup group)
{
var final = value switch
{
@@ -61,8 +105,9 @@ public class ModdedNumberOptionAttribute(
_ => (float)value,
};
return new ModdedNumberOption(
Title,
var opt = new ModdedNumberOption(
group.GroupPrefix,
Title ?? property.Name,
final,
min,
max,
@@ -72,6 +117,8 @@ public class ModdedNumberOptionAttribute(
suffixType,
formatString,
halfIncrements);
Title = opt.Title;
return opt;
}
/// <inheritdoc />
@@ -88,6 +135,18 @@ public class ModdedNumberOptionAttribute(
opt.SetValue(final);
}
/// <inheritdoc />
public void SetValueUnboxed(float value)
{
(HolderOption as ModdedNumberOption)?.SetValue(value);
}
/// <inheritdoc />
void ITypedOption<int>.SetValueUnboxed(int value)
{
(HolderOption as ModdedNumberOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue()
{
@@ -97,8 +156,22 @@ public class ModdedNumberOptionAttribute(
var value = opt.Value;
if (ValueType == typeof(int))
return (int)Math.Round(value);
return (int)MathF.Round(value, MidpointRounding.AwayFromZero);
return value;
}
/// <inheritdoc />
public float GetValueUnboxed()
{
return HolderOption is ModdedNumberOption opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedNumberOption");
}
/// <inheritdoc />
int ITypedOption<int>.GetValueUnboxed()
{
return (int)MathF.Round(GetValueUnboxed(), MidpointRounding.AwayFromZero);
}
}
@@ -1,4 +1,5 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace MiraAPI.GameOptions.Attributes;
@@ -10,25 +11,27 @@ namespace MiraAPI.GameOptions.Attributes;
/// <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, Type? modeType = null) : PropertyOptionAttribute
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public abstract class ModdedOptionAttribute(string? title = null, Type? roleType = null, Type? modeType = null) : PropertyOptionAttribute
{
internal IModdedOption? HolderOption { get; set; }
internal Type ValueType { get; set; }
/// <summary>
/// Gets the title of the option.
/// </summary>
public string Title => title;
internal IModdedOption? HolderOption;
internal Type ValueType;
/// <summary>
/// Gets the role type of the option.
/// </summary>
protected Type? RoleType { get; private set; } = roleType;
protected Type? RoleType => roleType;
/// <summary>
/// Gets the game mode type of the option.
/// </summary>
protected Type? ModeType { get; private set; } = modeType;
protected Type? ModeType => modeType;
internal abstract IModdedOption? CreateOption(object? value, PropertyInfo property);
/// <summary>
/// Gets or sets the title of the option.
/// </summary>
public string? Title { get; protected set; } = title;
internal abstract IModdedOption? CreateOption(object? value, PropertyInfo property, AbstractOptionGroup group);
}
@@ -10,15 +10,23 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="title">The title of the option.</param>
/// <param name="allowNone">Whether the option includes a none option. If None is selected, value will return -1.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedPlayerOptionAttribute(
string title,
bool allowNone = true)
: ModdedOptionAttribute(title)
public class ModdedPlayerOptionAttribute(string? title, bool allowNone = true)
: ModdedOptionAttribute(title), ITypedOption<int>, ITypedOption<NetworkedPlayerInfo?>
{
internal override IModdedOption? CreateOption(object? value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedPlayerOptionAttribute"/> class.
/// </summary>
/// <param name="allowNone">Whether the option includes a none option. If None is selected, value will return -1.</param>
public ModdedPlayerOptionAttribute(bool allowNone = true)
: this(null, allowNone)
{
var option = new ModdedPlayerOption(Title, allowNone);
return option;
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property, AbstractOptionGroup group)
{
var opt = new ModdedPlayerOption(group.GroupPrefix, Title ?? property.Name, allowNone);
Title = opt.Title;
return opt;
}
/// <inheritdoc />
@@ -30,7 +38,23 @@ public class ModdedPlayerOptionAttribute(
if (ValueType == typeof(int))
return opt.Value;
return opt.SelectedPlayer!;
return opt.GetPlayerValue()!;
}
/// <inheritdoc />
public NetworkedPlayerInfo? GetValueUnboxed()
{
return HolderOption is ModdedPlayerOption opt
? opt.GetPlayerValue()
: throw new InvalidOperationException($"Holder option for {Title} is not a ModdedPlayerOption.");
}
/// <inheritdoc />
int ITypedOption<int>.GetValueUnboxed()
{
return HolderOption is ModdedPlayerOption opt
? opt.Value
: throw new InvalidOperationException($"Holder option for {Title} is not a ModdedPlayerOption.");
}
/// <inheritdoc />
@@ -41,9 +65,32 @@ public class ModdedPlayerOptionAttribute(
var final = value switch
{
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0),
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : -1,
_ => (int)value,
};
if (final == -1 && !allowNone)
throw new ArgumentException("Cannot assign -1 or null to a ModdedPlayerOption that does not allow none as an option.");
opt?.SetValue(final);
}
/// <inheritdoc />
public void SetValueUnboxed(NetworkedPlayerInfo? value)
{
if (!value && !allowNone)
throw new ArgumentException("Cannot assign null to a ModdedPlayerOption that does not allow none as an option.");
if (HolderOption is ModdedPlayerOption opt)
opt.SetValue(value ? opt.Values.IndexOf(value!) : -1);
}
/// <inheritdoc />
void ITypedOption<int>.SetValueUnboxed(int value)
{
if (value == -1 && !allowNone)
throw new ArgumentException("Cannot assign -1 to a ModdedPlayerOption that does not allow none as an option.");
(HolderOption as ModdedPlayerOption)?.SetValue(value);
}
}
@@ -10,19 +10,33 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="title">The title of the option.</param>
/// <param name="values">An option list of string value.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedStringOptionAttribute(
string title,
string[] values)
: ModdedOptionAttribute(title)
public class ModdedStringOptionAttribute(string? title, string[] values)
: ModdedOptionAttribute(title), ITypedOption<string>
{
internal override IModdedOption? CreateOption(object? value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedStringOptionAttribute"/> class.
/// </summary>
/// <param name="values">An option list of string value.</param>
public ModdedStringOptionAttribute(string[] values)
: this(null, values)
{
var option = new ModdedStringOption(Title, (string)(value ?? string.Empty), values);
return option;
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property, AbstractOptionGroup group)
{
var opt = new ModdedStringOption(group.GroupPrefix, Title ?? property.Name, value as string ?? string.Empty, values);
Title = opt.Title;
return opt;
}
/// <inheritdoc />
public override object GetValue()
{
return GetValueUnboxed();
}
/// <inheritdoc />
public string GetValueUnboxed()
{
return HolderOption is ModdedStringOption opt
? opt.Value
@@ -32,7 +46,12 @@ public class ModdedStringOptionAttribute(
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedStringOption;
opt?.SetValue((string)value);
SetValueUnboxed((string)value);
}
/// <inheritdoc />
public void SetValueUnboxed(string value)
{
(HolderOption as ModdedStringOption)?.SetValue(value);
}
}
@@ -11,36 +11,64 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="on">What the option displays when toggled on.</param>
/// <param name="off">What the option displays when toggled off.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedToggleOptionAttribute(
string title,
string on,
string off)
: ModdedOptionAttribute(title)
public class ModdedToggleOptionAttribute(string? title, string on, string off)
: ModdedOptionAttribute(title), ITypedOption<bool>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionAttribute"/> class.
/// </summary>
/// <param name="on">What the option displays when toggled on.</param>
/// <param name="off">What the option displays when toggled off.</param>
public ModdedToggleOptionAttribute(string on, string off)
: this(null, on, off)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionAttribute"/> class.
/// </summary>
/// <param name="title">The option title.</param>
public ModdedToggleOptionAttribute(string title)
public ModdedToggleOptionAttribute(string? title)
// ReSharper disable once IntroduceOptionalParameters.Global (Justification: Kept for backwards compatibility.)
: this(title, "On", "Off")
{
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionAttribute"/> class.
/// </summary>
public ModdedToggleOptionAttribute()
: this(null, "On", "Off")
{
var toggleOpt = new ModdedToggleOption(Title, (bool)(value ?? false), on, off);
return toggleOpt;
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property, AbstractOptionGroup group)
{
var opt = new ModdedToggleOption(group.GroupPrefix, Title ?? property.Name, (bool)(value ?? false), on, off);
Title = opt.Title;
return opt;
}
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedToggleOption;
opt?.SetValue((bool)value);
SetValueUnboxed((bool)value);
}
/// <inheritdoc />
public void SetValueUnboxed(bool value)
{
(HolderOption as ModdedToggleOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue()
{
return GetValueUnboxed();
}
/// <inheritdoc />
public bool GetValueUnboxed()
{
return HolderOption is ModdedToggleOption opt
? opt.Value
@@ -0,0 +1,22 @@
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Provides unboxed access to option list values to prevent memory allocations.
/// </summary>
/// <typeparam name="T">The type of the value that the option list carries.</typeparam>
public interface ITypedOptionList<T>
{
/// <summary>
/// Gets the unboxed value of the option at the specified index.
/// </summary>
/// <param name="idx">The index of the option.</param>
/// <returns>The option at the provided index.</returns>
T GetValueUnboxed(int idx);
/// <summary>
/// Sets the unboxed value of the option at the specified index.
/// </summary>
/// <param name="idx">The index of the option.</param>
/// <param name="value">The new value of the option to set.</param>
void SetValueUnboxed(int idx, T value);
}
@@ -10,31 +10,65 @@ namespace MiraAPI.GameOptions.Attributes;
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionListAttribute(string title, Type enumType, string[]? values = null)
[Obsolete("Use ModdedEnumOptionListAttribute<T> instead. This will be removed in a future version.")]
public class ModdedEnumOptionListAttribute(string? title, Type enumType, string idPrefix, string[]? values = null)
: ModdedOptionListAttribute(title)
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionListAttribute"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
public ModdedEnumOptionListAttribute(string? title, Type enumType, string[]? values = null)
: this(title, enumType, string.Empty, values)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionListAttribute"/> class.
/// </summary>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
public ModdedEnumOptionListAttribute(Type enumType, string idPrefix, string[]? values = null)
: this(null, enumType, idPrefix, values)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionListAttribute"/> class.
/// </summary>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
public ModdedEnumOptionListAttribute(Type enumType, string[]? values = null)
: this(null, enumType, string.Empty, values)
{
}
internal override IBaseModdedOptionList CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group)
{
var optList = new ModdedOptionList<ModdedEnumOption>(
value.Count, idx => new(GetFormattedTitle(idx), (int)(value[idx] ?? 0), enumType, values));
list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), (int)(list[idx] ?? 0), enumType, idPrefix, values));
return optList;
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedEnumOption;
var opt = HolderOptionList?.ElementAt(idx) as ModdedEnumOption;
opt?.SetValue((int)value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return HolderOptionList?[idx] is ModdedEnumOption opt
return HolderOptionList?.ElementAt(idx) is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {enumType.FullName} is not a ModdedEnumOption");
: throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedEnumOption with enum type {enumType.FullName}");
}
}
@@ -43,31 +77,63 @@ public class ModdedEnumOptionListAttribute(string title, Type enumType, string[]
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
/// <param name="title">The option's title.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">The option's possible values.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionListAttribute<T>(string title, string[]? values = null)
: ModdedOptionListAttribute(title)
public class ModdedEnumOptionListAttribute<T>(string? title, string idPrefix, string[]? values = null)
: ModdedOptionListAttribute(title), ITypedOptionList<T>
where T : struct, Enum
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionListAttribute{T}"/> class.
/// </summary>
/// <param name="title">The option's title.</param>
/// <param name="values">The option's possible values.</param>
public ModdedEnumOptionListAttribute(string? title, string[]? values = null)
: this(title, string.Empty, values)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionListAttribute{T}"/> class.
/// </summary>
/// <param name="values">The option's possible values.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
public ModdedEnumOptionListAttribute(string[]? values = null, string idPrefix = "")
: this(null, idPrefix, values)
{
}
internal override IBaseModdedOptionList CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group)
{
var optList = new ModdedOptionList<ModdedEnumOption<T>>(
value.Count, idx => new(GetFormattedTitle(idx), (T)(value[idx] ?? 0), values));
list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), (T)(list[idx] ?? 0), idPrefix, values));
return optList;
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedEnumOption<T>;
opt?.SetValue((T)value);
SetValueUnboxed(idx, (T)value);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, T value)
{
(HolderOptionList?.ElementAt(idx) as ModdedEnumOption<T>)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return HolderOptionList?[idx] is ModdedEnumOption<T> opt
return GetValueUnboxed(idx);
}
/// <inheritdoc />
public T GetValueUnboxed(int idx)
{
return HolderOptionList?.ElementAt(idx) is ModdedEnumOption<T> opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {typeof(T).FullName} is not a ModdedEnumOption<{typeof(T).FullName}>");
: throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedEnumOption<{typeof(T).FullName}>");
}
}
@@ -20,7 +20,7 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="halfIncrements">Whether increments can be split in half (using Shift).</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedNumberOptionListAttribute(
string title,
string? title,
float min,
float max,
float increment,
@@ -29,8 +29,32 @@ public class ModdedNumberOptionListAttribute(
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool halfIncrements = false)
: ModdedOptionListAttribute(title)
: ModdedOptionListAttribute(title), ITypedOptionList<int>, ITypedOptionList<float>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionListAttribute"/> class.
/// </summary>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="zeroBehavior">Determines what is shown for zero.</param>
/// <param name="negativeBehavior">Determines what is shown for negative 1.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="halfIncrements">Whether increments can be split in half (using Shift).</param>
public ModdedNumberOptionListAttribute(
float min,
float max,
float increment,
string zeroBehavior,
string negativeBehavior,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool halfIncrements = false)
: this(null, min, max, increment, zeroBehavior, negativeBehavior, suffixType, formatString, halfIncrements)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionListAttribute"/> class.
/// </summary>
@@ -42,7 +66,7 @@ public class ModdedNumberOptionListAttribute(
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
public ModdedNumberOptionListAttribute(
string title,
string? title,
float min,
float max,
float increment = 1,
@@ -53,19 +77,40 @@ public class ModdedNumberOptionListAttribute(
{
}
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionListAttribute"/> class.
/// </summary>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
public ModdedNumberOptionListAttribute(
float min,
float max,
float increment = 1,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool zeroInfinity = false)
: this(null, min, max, increment, suffixType, formatString, zeroInfinity)
{
return new ModdedOptionList<ModdedNumberOption>(value.Count, idx =>
}
internal override IBaseModdedOptionList CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group)
{
return new ModdedOptionList<ModdedNumberOption>(list.Count, idx =>
{
var final = value[idx] switch
var final = list[idx] switch
{
null => min + increment,
int integer => integer,
_ => (float)value[idx]!,
_ => (float)list[idx]!,
};
return new(
GetFormattedTitle(idx),
group.GroupPrefix,
GetFormattedTitle(idx, property),
final,
min,
max,
@@ -81,7 +126,7 @@ public class ModdedNumberOptionListAttribute(
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
if (HolderOptionList?[idx] is not ModdedNumberOption opt)
if (HolderOptionList?.ElementAt(idx) is not ModdedNumberOption opt)
return;
var final = value switch
@@ -92,17 +137,43 @@ public class ModdedNumberOptionListAttribute(
opt.SetValue(final);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, float value)
{
(HolderOptionList?.ElementAt(idx) as ModdedNumberOption)?.SetValue(value);
}
/// <inheritdoc />
void ITypedOptionList<int>.SetValueUnboxed(int idx, int value)
{
(HolderOptionList?.ElementAt(idx) as ModdedNumberOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
if (HolderOptionList?[idx] is not ModdedNumberOption opt)
throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedNumberOption");
if (HolderOptionList?.ElementAt(idx) is not ModdedNumberOption opt)
throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedNumberOption");
var value = opt.Value;
if (ValueType == typeof(int))
return (int)Math.Round(value);
return (int)MathF.Round(value, MidpointRounding.AwayFromZero);
return value;
}
/// <inheritdoc />
public float GetValueUnboxed(int idx)
{
return HolderOptionList?.ElementAt(idx) is ModdedNumberOption opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedNumberOption");
}
/// <inheritdoc />
int ITypedOptionList<int>.GetValueUnboxed(int idx)
{
return (int)MathF.Round(GetValueUnboxed(idx), MidpointRounding.AwayFromZero);
}
}
@@ -1,9 +1,9 @@
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
@@ -12,19 +12,24 @@ namespace MiraAPI.GameOptions.Attributes;
/// </summary>
/// <param name="title">The title of the options.</param>
[AttributeUsage(AttributeTargets.Property)]
public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAttribute
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public abstract class ModdedOptionListAttribute(string? title = null) : PropertyOptionAttribute
{
internal IModdedOptionList? HolderOptionList { get; set; }
internal IList? Value { get; set; }
internal Type ValueType { get; set; }
internal IBaseModdedOptionList? HolderOptionList;
internal IList? Value;
internal Type ValueType;
internal string[] Titles;
private static readonly Regex FormatParams = new(@"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout);
/// <summary>
/// Gets the title of the options.
/// Gets or sets the title of the options.
/// If the string contains a format parameter, e.g., <c>{0}</c>, then the option's index will be given to it.
/// The string cannot contain more than one parameter.
/// If no parameter is given, the title will simply append the index to the end of it.
/// </summary>
public string Title => title;
public string? Title { get; protected set; } = title;
/// <summary>
/// Sets the value of all the options.
@@ -68,29 +73,33 @@ public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAt
/// <returns>The value of the option as an object.</returns>
public abstract object GetValue(int idx);
internal abstract IModdedOptionList? CreateOptionList(IList value, PropertyInfo property);
internal abstract IBaseModdedOptionList? CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group);
/// <summary>
/// Gets the <see cref="Title"/> formatted with the option's index.
/// </summary>
/// <param name="index">The option's index.</param>
/// <param name="property">The property info for fallback title.</param>
/// <returns>The formatted option's title.</returns>
[SuppressMessage("Globalization", "CA1305:Specify IFormatProvider", Justification = "I don't even know if this is worth it.")]
protected string GetFormattedTitle(int index)
protected string GetFormattedTitle(int index, PropertyInfo property)
{
var match = Regex.Match(Title.Translate(), @"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout);
var baseTitle = Title ??= property.Name;
return Titles[index] = GetFormattedTitle(baseTitle, index, FormatParams.Match(baseTitle));
}
private static string GetFormattedTitle(string baseTitle, int index, Match match)
{
if (!match.Success)
{
return Title + index;
return baseTitle + index;
}
if (match.Value == "{0}" && !match.NextMatch().Success)
{
return string.Format(Title, index);
return string.Format(CultureInfo.InvariantCulture, baseTitle, index);
}
Error($"ModdedOptionList Title of {Title} cannot contain more than the first parameter for formatting.");
return Title + index;
Error($"ModdedOptionList Title of {baseTitle} cannot contain more than the first parameter for formatting.");
return baseTitle + index;
}
}
@@ -11,42 +11,85 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="title">The option title.</param>
/// <param name="allowNone">Whether the option includes a none option. If None is selected, value will return -1.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedPlayerOptionListAttribute(
string title,
bool allowNone = true)
: ModdedOptionListAttribute(title)
public class ModdedPlayerOptionListAttribute(string? title, bool allowNone = true)
: ModdedOptionListAttribute(title), ITypedOptionList<int>, ITypedOptionList<NetworkedPlayerInfo?>
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedPlayerOptionListAttribute"/> class.
/// </summary>
/// <param name="allowNone">Whether the option includes a none option. If None is selected, value will return -1.</param>
public ModdedPlayerOptionListAttribute(bool allowNone = true)
: this(null, allowNone)
{
return new ModdedOptionList<ModdedPlayerOption>(value.Count, idx =>
{
return new(GetFormattedTitle(idx), allowNone);
});
}
internal override IBaseModdedOptionList CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group)
{
return new ModdedOptionList<ModdedPlayerOption>(list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), allowNone));
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
if (HolderOptionList?[idx] is not ModdedPlayerOption opt)
if (HolderOptionList?.ElementAt(idx) is not ModdedPlayerOption opt)
return;
var final = value switch
{
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0),
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : -1,
_ => (int)value,
};
opt?.SetValue(final);
if (final == -1 && !allowNone)
throw new ArgumentException("Cannot assign -1 or null to a ModdedPlayerOption that does not allow none as an option.");
opt.SetValue(final);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, NetworkedPlayerInfo? value)
{
if (!value && !allowNone)
throw new ArgumentException("Cannot assign null to a ModdedPlayerOption that does not allow none as an option.");
if (HolderOptionList?.ElementAt(idx) is ModdedPlayerOption opt)
opt.SetValue(value ? opt.Values.IndexOf(value!) : -1);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, int value)
{
if (value == -1 && !allowNone)
throw new ArgumentException("Cannot assign -1 to a ModdedPlayerOption that does not allow none as an option.");
(HolderOptionList?.ElementAt(idx) as ModdedPlayerOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
if (HolderOptionList?[idx] is not ModdedPlayerOption opt)
throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedPlayerOption");
if (HolderOptionList?.ElementAt(idx) is not ModdedPlayerOption opt)
throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedPlayerOption");
if (ValueType == typeof(int))
return opt.Value;
return opt.SelectedPlayer!;
return opt.GetPlayerValue()!;
}
/// <inheritdoc />
public NetworkedPlayerInfo? GetValueUnboxed(int idx)
{
return HolderOptionList?.ElementAt(idx) is ModdedPlayerOption opt
? opt.GetPlayerValue()
: throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedPlayerOption");
}
/// <inheritdoc />
int ITypedOptionList<int>.GetValueUnboxed(int idx)
{
return HolderOptionList?.ElementAt(idx) is ModdedPlayerOption opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedPlayerOption");
}
}
@@ -2,7 +2,6 @@ using System;
using System.Collections;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
@@ -12,31 +11,46 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="title">The title of the option.</param>
/// <param name="values">An option list of string value.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedStringOptionListAttribute(
string title,
string[] values)
: ModdedOptionListAttribute(title)
public class ModdedStringOptionListAttribute(string? title, string[] values)
: ModdedOptionListAttribute(title), ITypedOptionList<string>
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedStringOptionListAttribute"/> class.
/// </summary>
/// <param name="values">An option list of string value.</param>
public ModdedStringOptionListAttribute(string[] values)
: this(null, values)
{
return new ModdedOptionList<ModdedStringOption>(value.Count, idx =>
{
return new ModdedStringOption(Title.Translate(), (string)(value[idx] ?? string.Empty), values);
});
}
internal override IBaseModdedOptionList CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group)
{
return new ModdedOptionList<ModdedStringOption>(list.Count, idx => new ModdedStringOption(group.GroupPrefix, GetFormattedTitle(idx, property), (string)(list[idx] ?? string.Empty), values));
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedStringOption;
opt?.SetValue((string)value);
SetValueUnboxed(idx, (string)value);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, string value)
{
(HolderOptionList?.ElementAt(idx) as ModdedStringOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return HolderOptionList?[idx] is ModdedStringOption opt
return GetValueUnboxed(idx);
}
/// <inheritdoc />
public string GetValueUnboxed(int idx)
{
return HolderOptionList?.ElementAt(idx) is ModdedStringOption opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedStringOption");
: throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedStringOption");
}
}
@@ -12,40 +12,67 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="on">What the option displays when toggled on.</param>
/// <param name="off">What the option displays when toggled off.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedToggleOptionListAttribute(
string title,
string on,
string off)
: ModdedOptionListAttribute(title)
public class ModdedToggleOptionListAttribute(string? title, string on, string off)
: ModdedOptionListAttribute(title), ITypedOptionList<bool>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionListAttribute"/> class.
/// </summary>
/// <param name="on">What the option displays when toggled on.</param>
/// <param name="off">What the option displays when toggled off.</param>
public ModdedToggleOptionListAttribute(string on, string off)
: this(null, on, off)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionListAttribute"/> class.
/// </summary>
/// <param name="title">The option's title.</param>
public ModdedToggleOptionListAttribute(string title)
public ModdedToggleOptionListAttribute(string? title)
// ReSharper disable once IntroduceOptionalParameters.Global (Justification: Kept for backwards compatibility.)
: this(title, "On", "Off")
{
}
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionListAttribute"/> class.
/// </summary>
public ModdedToggleOptionListAttribute()
: this(null, "On", "Off")
{
}
internal override IBaseModdedOptionList CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group)
{
var optList = new ModdedOptionList<ModdedToggleOption>(
value.Count, idx => new(GetFormattedTitle(idx), (bool)(value[idx] ?? false), on, off));
list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), (bool)(list[idx] ?? false), on, off));
return optList;
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedToggleOption;
opt?.SetValue((bool)value);
SetValueUnboxed(idx, (bool)value);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, bool value)
{
(HolderOptionList?.ElementAt(idx) as ModdedToggleOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return HolderOptionList?[idx] is ModdedToggleOption opt
return GetValueUnboxed(idx);
}
/// <inheritdoc />
public bool GetValueUnboxed(int idx)
{
return HolderOptionList?.ElementAt(idx) is ModdedToggleOption opt
? opt.Value
: throw new InvalidOperationException($"Holder option for {GetFormattedTitle(idx)} is not a ModdedToggleOption.");
: throw new InvalidOperationException($"Holder option \"{Titles[idx]}\" is not a ModdedToggleOption.");
}
}
+2 -2
View File
@@ -3,6 +3,6 @@ namespace System.Runtime.CompilerServices;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)]
internal sealed class CollectionBuilderAttribute(Type builderType, string methodName) : Attribute
{
public Type BuilderType { get; } = builderType;
public string MethodName { get; } = methodName;
public Type BuilderType => builderType;
public string MethodName => methodName;
}
+39 -8
View File
@@ -1,5 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
@@ -77,6 +79,11 @@ public interface IModdedOption
/// </summary>
bool IncludeInPreset { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the option should show a notification, toggled on by an overall option synchronization.
/// </summary>
public bool ShowNotification { get; set; }
/// <summary>
/// Gets or sets the <see cref="BepInEx.Configuration.ConfigDefinition"/> for the option, used for BepInEx configuration.
/// </summary>
@@ -93,6 +100,12 @@ public interface IModdedOption
/// <returns>The created <see cref="global::OptionBehaviour"/> object.</returns>
OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, PlayerOption playerOpt, Transform container);
/// <summary>
/// Gets the translated display value of the option.
/// </summary>
/// <returns>The display value.</returns>
string GetDisplayValue();
/// <summary>
/// Gets the value as a <see langword="float"/>.
/// </summary>
@@ -138,9 +151,11 @@ public interface IModdedOption
}
/// <summary>
/// Interface for list of modded options.
/// Base interface for list of modded options.
/// <para/>
/// Do not implement directly, implement <see cref="IModdedOptionList"/> or <see cref="IModdedOptionList{T}"/> instead.
/// </summary>
public interface IModdedOptionList : IReadOnlyList<IModdedOption>
public interface IBaseModdedOptionList : IEnumerable
{
/// <summary>
/// Gets the function to name the keys of the individual options in the configuration file.
@@ -148,18 +163,34 @@ public interface IModdedOptionList : IReadOnlyList<IModdedOption>
/// Return <see langword="null"/> to use the default of the property's name with its index appended.
/// </summary>
Func<int, string>? ConfigName { get; init; }
/// <inheritdoc cref="IReadOnlyCollection{T}.Count"/>
int Count { get; }
/// <inheritdoc cref="Enumerable.ElementAt{TSource}(IEnumerable{TSource}, int)"/>
IModdedOption ElementAt(int index);
}
/// <summary>
/// Interface for list of modded options.
/// </summary>
public interface IModdedOptionList : IBaseModdedOptionList, IReadOnlyList<IModdedOption>
{
IModdedOption IBaseModdedOptionList.ElementAt(int index)
{
return this[index];
}
}
/// <summary>
/// Interface for list of <typeparamref name="T"/> options.
/// </summary>
/// <typeparam name="T">The type of <see cref="IModdedOption"/>.</typeparam>
public interface IModdedOptionList<out T> : IModdedOptionList
public interface IModdedOptionList<out T> : IBaseModdedOptionList, IReadOnlyList<T>
where T : IModdedOption
{
/// <inheritdoc cref="IReadOnlyList{T}.this[int]"/>
new T this[int index] { get; }
/// <inheritdoc cref="IEnumerable{T}.GetEnumerator"/>
new IEnumerator<T> GetEnumerator();
IModdedOption IBaseModdedOptionList.ElementAt(int index)
{
return this[index];
}
}
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
namespace MiraAPI.GameOptions;
@@ -6,6 +7,7 @@ namespace MiraAPI.GameOptions;
/// Allows an option group to compress noisy option blocks in the wiki "Options" section.
/// Implementers can hide specific option keys and replace them with one or more summary lines.
/// </summary>
[Obsolete("Use IWikiSummaryProvider instead, as it allows for multiple summarisations. This will be removed in future versions.")]
public interface ISummarizedOptions
{
/// <summary>
@@ -17,5 +19,6 @@ public interface ISummarizedOptions
/// Gets summary lines to insert when the first hidden option would have appeared.
/// Lines should already be formatted as "Title: Value".
/// </summary>
/// <returns>The summarisation of the hidden options.</returns>
IEnumerable<string> GetWikiOptionSummaryLines();
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
namespace MiraAPI.GameOptions;
/// <summary>
/// A holder option for a summary and option string names that are hidden behind it.
/// </summary>
/// <param name="hiddenKeys">The <see cref="StringNames"/> of the options being hidden.</param>
/// <param name="summaryLines">A delegate that produces the summary to replace the default text of the options being hidden.</param>
public sealed class WikiSummaryGroup(IReadOnlySet<StringNames>? hiddenKeys, Func<IEnumerable<string>>? summaryLines)
{
/// <summary>
/// Gets the option string keys (StringNames) to omit from the wiki options list (e.g., a large set of related options).
/// </summary>
public IReadOnlySet<StringNames> HiddenKeys { get; } = hiddenKeys ?? new HashSet<StringNames>(0);
/// <summary>
/// Gets summary lines to insert when the first hidden option would have appeared.
/// Lines should already be formatted as "Title: Value".
/// </summary>
public Func<IEnumerable<string>> SummaryLines { get; } = summaryLines ?? Array.Empty<string>;
}
/// <summary>
/// Allows an option group to compress and format blocks or noisy options in the wiki "Options" section.
/// </summary>
public interface IWikiSummaryProvider
{
/// <summary>
/// Gets a dictionary where the key is the target option's <see cref="StringNames"/> to insert the
/// summary at, and the value is the specific group of options being replaced by a summary.
/// </summary>
IReadOnlyDictionary<StringNames, WikiSummaryGroup> SummaryGroups { get; }
}
@@ -9,6 +9,7 @@ namespace MiraAPI.GameOptions;
/// <summary>
/// Component added onto options generated via MiraAPI. This allows developers to hook patches onto options in general, without using a list.
/// </summary>
/// <param name="cppPtr">The pointer to the C++ object.</param>
[RegisterInIl2Cpp]
public class MiraNumberOptionComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
{
@@ -0,0 +1,21 @@
using System;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.GameOptions.OptionTypes;
using Reactor.Utilities.Attributes;
using UnityEngine;
namespace MiraAPI.GameOptions;
/// <summary>
/// Component added onto options generated via MiraAPI. This allows developers to hook patches onto options in general, without using a list.
/// </summary>
/// <param name="cppPtr">The pointer to the C++ object.</param>
[RegisterInIl2Cpp]
public class MiraPlayerOptionComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
{
/// <summary>
/// Gets or sets the <see cref="ModdedPlayerOption"/> associated with the object.
/// </summary>
[HideFromIl2Cpp]
public ModdedPlayerOption PlayerOption { get; set; }
}
+87 -16
View File
@@ -2,6 +2,7 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using MiraAPI.GameOptions.Attributes;
namespace MiraAPI.GameOptions;
@@ -10,16 +11,22 @@ namespace MiraAPI.GameOptions;
/// </summary>
/// <typeparam name="T">The type of the values that the array holds.</typeparam>
[CollectionBuilder(typeof(ModdedArrayBuilder), nameof(ModdedArrayBuilder.Create))]
public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList
public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList, IModdedArrayBinding
{
private readonly T[] items;
private int version;
private ModdedOptionListAttribute? listAttribute;
private ITypedOptionList<T>? typedAttribute;
/// <inheritdoc/>
public int Count => items.Length;
/// <inheritdoc/>
public bool IsReadOnly => false;
bool ICollection<T>.IsReadOnly => true;
/// <inheritdoc/>
bool IList.IsReadOnly => false;
/// <inheritdoc/>
bool IList.IsFixedSize => true;
@@ -72,17 +79,47 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList
/// <param name="index">The index of the value.</param>
public T this[int index]
{
get => ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute)
? (T)attribute.GetValue(index)
: items[index];
get
{
if (listAttribute == null)
return items[index];
return items[index] = typedAttribute != null
? typedAttribute.GetValueUnboxed(index)
: (T)listAttribute.GetValue(index);
}
set
{
if (ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute))
attribute.SetValue(index, value!);
else
items[index] = value;
var old = items[index];
version++;
if (listAttribute == null)
{
if (!EqualityComparer<T>.Default.Equals(old, value))
{
items[index] = value;
version++;
}
return;
}
T current;
if (typedAttribute != null)
{
typedAttribute.SetValueUnboxed(index, value);
current = typedAttribute.GetValueUnboxed(index);
}
else
{
listAttribute.SetValue(index, value!);
current = (T)listAttribute.GetValue(index);
}
items[index] = current;
if (!EqualityComparer<T>.Default.Equals(old, current))
version++;
}
}
@@ -96,18 +133,21 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList
/// <inheritdoc/>
public bool Contains(T item)
{
Refresh();
return Array.IndexOf(items, item) >= 0;
}
/// <inheritdoc/>
public void CopyTo(T[] array, int arrayIndex)
{
Refresh();
items.CopyTo(array, arrayIndex);
}
/// <inheritdoc/>
public int IndexOf(T item)
{
Refresh();
return Array.IndexOf(items, item);
}
@@ -117,21 +157,47 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList
return new(this);
}
/// <summary>
/// Re-reads every element from its backing option, updating the cached values. Does nothing if the array isn't bound to an option list.
/// </summary>
public void Refresh()
{
if (typedAttribute != null)
{
for (var i = 0; i < items.Length; i++)
items[i] = typedAttribute.GetValueUnboxed(i);
}
else if (listAttribute != null)
{
for (var i = 0; i < items.Length; i++)
items[i] = (T)listAttribute.GetValue(i);
}
}
void IModdedArrayBinding.Bind(ModdedOptionListAttribute attribute)
{
listAttribute = attribute;
typedAttribute = attribute as ITypedOptionList<T>;
}
/// <inheritdoc/>
bool IList.Contains(object? value)
{
Refresh();
return ((IList)items).Contains(value);
}
/// <inheritdoc/>
int IList.IndexOf(object? value)
{
Refresh();
return ((IList)items).IndexOf(value);
}
/// <inheritdoc/>
void ICollection.CopyTo(Array array, int index)
{
Refresh();
items.CopyTo(array, index);
}
@@ -178,31 +244,31 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList
}
/// <inheritdoc/>
public void Insert(int index, T item)
void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
/// <inheritdoc/>
public void RemoveAt(int index)
void IList<T>.RemoveAt(int index)
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
/// <inheritdoc/>
public void Add(T item)
void ICollection<T>.Add(T item)
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
/// <inheritdoc/>
public void Clear()
void ICollection<T>.Clear()
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
/// <inheritdoc/>
public bool Remove(T item)
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
@@ -284,7 +350,7 @@ public static class ModdedArrayBuilder
/// <summary>
/// Creates a new <see cref="ModdedArray{T}"/> from a span of values.
/// </summary>
/// <typeparam name="T">The the type of the values.</typeparam>
/// <typeparam name="T">The type of the values.</typeparam>
/// <param name="values">The values to initialise with.</param>
/// <returns>The <see cref="ModdedArray{T}"/> instance initialised with the provided values.</returns>
public static ModdedArray<T> Create<T>(ReadOnlySpan<T> values)
@@ -292,3 +358,8 @@ public static class ModdedArrayBuilder
return new(values);
}
}
internal interface IModdedArrayBinding
{
void Bind(ModdedOptionListAttribute attribute);
}
+184 -128
View File
@@ -4,12 +4,10 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx.Configuration;
using HarmonyLib;
using MiraAPI.GameModes;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
@@ -25,20 +23,27 @@ namespace MiraAPI.GameOptions;
/// </summary>
public static class ModdedOptionsManager
{
private static readonly Dictionary<MethodBase, PropertyOptionAttribute> GetterLookups = [];
private static readonly Dictionary<MethodBase, PropertyOptionAttribute> SetterLookups = [];
private static readonly Dictionary<Type, AbstractOptionGroup> TypeToGroup = [];
private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> GetterLookup = [];
private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> SetterLookup = [];
private static readonly HashSet<PropertyInfo> OptionAttributes = [];
private static readonly HashSet<Type> Types = [];
private static readonly HarmonyMethod CachedGetterPatch = new(typeof(ModdedOptionsManager), nameof(PropertyGetterPatch));
private static readonly HarmonyMethod CachedSetterPatch = new(typeof(ModdedOptionsManager), nameof(PropertySetterPatch));
private static readonly MethodInfo OpenGetterPatch = typeof(ModdedOptionsManager)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.First(m => m.Name == nameof(PropertyGetterPatch) && m.IsGenericMethodDefinition);
private static readonly MethodInfo OpenSetterPatch = typeof(ModdedOptionsManager)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.First(m => m.Name == nameof(PropertySetterPatch) && m.IsGenericMethodDefinition);
private static readonly Dictionary<RuntimeTypeHandle, HarmonyMethod> ConcretisedGetters = [];
private static readonly Dictionary<RuntimeTypeHandle, HarmonyMethod> ConcretisedSetters = [];
private static readonly Type OptionType = typeof(IModdedOption);
private static readonly Type OptionListType = typeof(IBaseModdedOptionList);
internal static readonly ConditionalWeakTable<object, ModdedOptionListAttribute> ListInstanceCache = [];
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 = [];
internal static readonly Comparer<AbstractOptionGroup> Comparer = Comparer<AbstractOptionGroup>.Create((x, y) => x.GroupPriority.CompareTo(y.GroupPriority));
internal static uint NextId => _nextId++;
private static uint _nextId = 1;
@@ -66,26 +71,14 @@ public static class ModdedOptionsManager
notif.SettingsChangeMessageLogic(key, item, playSound);
}
internal static bool RegisterGroup(Type type)
internal static bool RegisterGroup(Type type, in MiraPluginManager.RegistrationContext context)
{
if (TypeToGroup.ContainsKey(type))
{
Error($"Group {type.Name} already exists.");
return false;
}
if (Activator.CreateInstance(type) is not AbstractOptionGroup group)
if (type.IsAbstract || !type.IsAssignableTo(typeof(AbstractOptionGroup)))
{
return false;
}
RegisterGroupInternal(group, type);
return true;
}
internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo)
{
if (TypeToGroup.ContainsKey(type))
if (!Types.Add(type))
{
Error($"Group {type.Name} already exists.");
return false;
@@ -108,47 +101,106 @@ public static class ModdedOptionsManager
}
}
var pluginInfo = context.PluginInfo;
pluginInfo.InternalOptionGroups.Add(group);
RegisterGroupInternal(group, type);
Groups.Add(group);
Helpers.SetInstance(typeof(OptionGroupSingleton<>), type, group);
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers))
{
var propType = property.PropertyType;
if (propType.IsAssignableTo(OptionType))
{
RegisterPropertyOption(type, group, property, pluginInfo);
continue;
}
if (propType.IsAssignableTo(OptionListType))
{
RegisterPropertyOptionList(type, group, property, pluginInfo);
continue;
}
var attributes = property.GetCustomAttributes(false);
foreach (var attr in attributes)
{
if (attr is ModdedOptionAttribute moddedAttr)
{
RegisterAttributeOption(type, group, moddedAttr, property, pluginInfo, propType, attributes);
break;
}
if (attr is ModdedOptionListAttribute listAttr)
{
RegisterAttributeOptionList(type, group, listAttr, property, pluginInfo, propType, attributes);
break;
}
}
}
if (!pluginInfo.DebugMode)
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers)
.Where(f => !f.IsAutoPropertyBackingField()
&& (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IBaseModdedOptionList)))))
{
Error($"{field.Name} is a field, not a property. Use properties for options.");
}
return true;
}
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
private static void RegisterGroupInternal(AbstractOptionGroup group, Type type)
private static void PatchProperty(PropertyInfo property, Type propType, PropertyOptionAttribute attribute)
{
Groups.Add(group);
TypeToGroup.Add(type, group);
typeof(OptionGroupSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
.SetValue(null, group);
var handle = propType.TypeHandle;
ApplyPatch(handle, propType, ConcretisedGetters, GetterLookup, property.GetGetMethod(true), OpenGetterPatch, attribute);
ApplyPatch(handle, propType, ConcretisedSetters, SetterLookup, property.GetSetMethod(true), OpenSetterPatch, attribute);
}
internal static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
private static void ApplyPatch(
RuntimeTypeHandle handle,
Type propType,
Dictionary<RuntimeTypeHandle, HarmonyMethod> concretised,
Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> lookup,
MethodInfo? toPatch,
MethodInfo patch,
PropertyOptionAttribute attribute)
{
if (!TypeToGroup.TryGetValue(type, out var group))
{
Error($"Failed to get group for {type.Name}");
if (toPatch == null)
return;
}
if (!concretised.TryGetValue(handle, out var concrete))
concretised[handle] = concrete = new(patch.MakeGenericMethod(propType));
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(toPatch, prefix: concrete);
lookup[toPatch.MethodHandle] = attribute;
}
private static void RegisterPropertyOption(Type type, AbstractOptionGroup group, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (property.GetValue(group) is not IModdedOption option)
{
Error($"Failed to get option for {property.Name}");
return;
}
RegisterOption(option, group, property.Name, pluginInfo);
RegisterOption(type, option, group, property.Name, pluginInfo);
}
internal static void RegisterAttributeOption(
private static void RegisterAttributeOption(
Type type,
AbstractOptionGroup group,
ModdedOptionAttribute attribute,
PropertyInfo property,
MiraPluginInfo pluginInfo)
MiraPluginInfo pluginInfo,
Type propType,
object[] attributes)
{
if (!OptionAttributes.Add(property))
{
@@ -156,13 +208,7 @@ public static class ModdedOptionsManager
return;
}
if (!TypeToGroup.TryGetValue(type, out var group))
{
Error($"Failed to get group for {type.Name}");
return;
}
var option = attribute.CreateOption(property.GetValue(group), property);
var option = attribute.CreateOption(property.GetValue(group), property, group);
if (option == null)
{
@@ -170,24 +216,12 @@ public static class ModdedOptionsManager
return;
}
var getterOriginal = property.GetGetMethod(true)!;
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: CachedGetterPatch);
GetterLookups[getterOriginal] = attribute;
var setterOriginal = property.GetSetMethod(true);
if (setterOriginal != null)
{
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: CachedSetterPatch);
SetterLookups[setterOriginal] = attribute;
}
PatchProperty(property, propType, attribute);
attribute.HolderOption = option;
attribute.ValueType = property.PropertyType;
attribute.ValueType = propType;
var customAttributes = property.GetCustomAttributes(false);
foreach (var attr in customAttributes)
foreach (var attr in attributes)
{
switch (attr)
{
@@ -206,18 +240,12 @@ public static class ModdedOptionsManager
}
}
RegisterOption(option, group, property.Name, pluginInfo);
RegisterOption(type, option, group, property.Name, pluginInfo);
}
internal static void RegisterPropertyOptionList(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
private static void RegisterPropertyOptionList(Type type, AbstractOptionGroup group, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (!TypeToGroup.TryGetValue(type, out var group))
{
Error($"Failed to get group for {type.Name}");
return;
}
if (property.GetValue(group) is not IModdedOptionList optionList)
if (property.GetValue(group) is not IBaseModdedOptionList optionList)
{
Error($"Failed to get option list for {property.Name}");
return;
@@ -227,15 +255,18 @@ public static class ModdedOptionsManager
for (var i = 0; i < optionList.Count; i++)
{
RegisterOption(optionList[i], group, configName(i), pluginInfo);
RegisterOption(type, optionList.ElementAt(i), group, configName(i), pluginInfo);
}
}
internal static void RegisterAttributeOptionList(
private static void RegisterAttributeOptionList(
Type type,
AbstractOptionGroup group,
ModdedOptionListAttribute attribute,
PropertyInfo property,
MiraPluginInfo pluginInfo)
MiraPluginInfo pluginInfo,
Type propType,
object[] attributes)
{
if (!OptionAttributes.Add(property))
{
@@ -243,9 +274,10 @@ public static class ModdedOptionsManager
return;
}
if (!TypeToGroup.TryGetValue(type, out var group))
if (!propType.IsGenericType || propType.GetGenericTypeDefinition() != typeof(ModdedArray<>))
{
Error($"Failed to get group for {type.Name}");
var typeName = propType.IsGenericType ? propType.GetGenericArguments()[0].Name : "T";
Error($"Please use ModdedArray<{typeName}> for modded option lists: {property.Name}");
return;
}
@@ -257,8 +289,11 @@ public static class ModdedOptionsManager
return;
}
var propertyList = (IList)propertyVal;
var optionList = attribute.CreateOptionList(propertyList, property);
var list = (IList)propertyVal;
attribute.Titles = new string[list.Count];
var optionList = attribute.CreateOptionList(list, property, group);
if (optionList == null)
{
@@ -266,44 +301,19 @@ public static class ModdedOptionsManager
return;
}
if (propertyList.Count != optionList.Count)
{
Error("Mismatch in count between values and created options.");
return;
}
PatchProperty(property, propType, attribute);
var listType = propertyList.GetType();
var valueType = listType.GetGenericArguments()[0];
if (!listType.IsGenericType || listType.GetGenericTypeDefinition() != typeof(ModdedArray<>))
{
Error($"Please use ModdedList<{valueType.Name}> for modded option lists.");
return;
}
var getterOriginal = property.GetGetMethod(true)!;
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: CachedGetterPatch);
GetterLookups[getterOriginal] = attribute;
var setterOriginal = property.GetSetMethod(true);
if (setterOriginal != null)
{
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: CachedSetterPatch);
SetterLookups[setterOriginal] = attribute;
}
var valueType = propType.GetGenericArguments()[0];
attribute.HolderOptionList = optionList;
attribute.Value = propertyList;
attribute.Value = list;
attribute.ValueType = valueType;
ListInstanceCache.Add(propertyVal, attribute);
var customAttributes = property.GetCustomAttributes(false);
((IModdedArrayBinding)propertyVal).Bind(attribute);
Func<int, Delegate?>? visibilityFactory = null, getterFactory = null, setterFactory = null, changedFactory = null;
foreach (var attr in customAttributes)
foreach (var attr in attributes)
{
switch (attr)
{
@@ -324,10 +334,10 @@ public static class ModdedOptionsManager
for (var i = 0; i < optionList.Count; i++)
{
var option = optionList[i];
var option = optionList.ElementAt(i);
if (visibilityFactory != null)
option.Visible = (Func<bool>)(visibilityFactory(i) ?? DelegateUtilities.AlwaysTrue);
option.Visible = visibilityFactory(i) as Func<bool> ?? DelegateUtilities.AlwaysTrue;
if (getterFactory != null)
option.Getter = getterFactory(i);
@@ -338,22 +348,21 @@ public static class ModdedOptionsManager
if (changedFactory != null)
option.ChangedEvent = changedFactory(i);
RegisterOption(option, group, property.Name + (i + 1), pluginInfo);
RegisterOption(type, option, group, property.Name + (i + 1), pluginInfo);
}
}
internal static void RegisterOption(
private static void RegisterOption(
Type type,
IModdedOption option,
AbstractOptionGroup group,
string propertyName,
MiraPluginInfo pluginInfo)
{
var groupName = group.GetType().FullName;
option.ConfigDefinition = new ConfigDefinition(groupName, propertyName);
option.ConfigDefinition = new ConfigDefinition(type.FullName, propertyName);
option.ParentGroup = group;
option.ParentMod = pluginInfo.MiraPlugin;
pluginInfo.InternalOptions.Add(option);
ModdedOptions.Add(option.Id, option);
group.Options.Add(option);
@@ -363,13 +372,13 @@ public static class ModdedOptionsManager
{
var chunks = ModdedOptions.Values.Select(option => option.GetNetData()).ChunkNetData(1000);
while (chunks.Count > 0)
while (chunks.TryDequeue(out var netData))
{
Rpc<SyncOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, chunks.Dequeue());
Rpc<SyncGameOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData));
}
}
internal static void HandleSyncOptions(NetData[] data)
internal static void HandleSyncOptions(bool showNotifs, NetData[] data)
{
// necessary to disable then re-enable this setting
// we don't know how other plugins handle their configs
@@ -388,6 +397,7 @@ public static class ModdedOptionsManager
continue;
}
option.ShowNotification = showNotifs;
option.HandleNetData(netData.Data);
}
@@ -397,7 +407,7 @@ public static class ModdedOptionsManager
plugin.PluginConfig.SaveOnConfigSet = oldConfigSetting[plugin];
}
if (LobbyInfoPane.Instance)
if (LobbyInfoPane.InstanceExists)
{
LobbyInfoPane.Instance.RefreshPane();
}
@@ -410,15 +420,38 @@ public static class ModdedOptionsManager
/// <param name="value">The new object value.</param>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention.")]
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")]
[Obsolete("Use PropertySetterPatch<T> instead. This will be removed in a future version.")]
public static void PropertySetterPatch(MethodBase __originalMethod, object value)
{
if (!SetterLookups.TryGetValue(__originalMethod, out var attribute))
if (!SetterLookup.TryGetValue(__originalMethod.MethodHandle, out var attribute))
return;
attribute.SetValue(value);
if (attribute is ModdedOptionListAttribute listAttribute && value != null)
ListInstanceCache.AddOrUpdate(value, listAttribute);
if (attribute is ModdedOptionListAttribute listAttribute && value is IModdedArrayBinding binding)
binding.Bind(listAttribute);
}
/// <summary>
/// Patches the setter of a property to update the value of the option.
/// </summary>
/// <typeparam name="T">The type of the option value.</typeparam>
/// <param name="__originalMethod">The original setter method.</param>
/// <param name="value">The new object value.</param>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention.")]
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")]
public static void PropertySetterPatch<T>(MethodBase __originalMethod, T value)
{
if (!SetterLookup.TryGetValue(__originalMethod.MethodHandle, out var attribute))
return;
if (attribute is ITypedOption<T> typedAttribute)
typedAttribute.SetValueUnboxed(value);
else
attribute.SetValue(value!);
if (attribute is ModdedOptionListAttribute listAttribute && value is IModdedArrayBinding binding)
binding.Bind(listAttribute);
}
/// <summary>
@@ -429,12 +462,35 @@ public static class ModdedOptionsManager
/// <returns><see langword="false"/> so the original getter gets skipped.</returns>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")]
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")]
[Obsolete("Use PropertyGetterPatch<T> instead. This will be removed in a future version.")]
public static bool PropertyGetterPatch(MethodBase __originalMethod, ref object __result)
{
if (!GetterLookups.TryGetValue(__originalMethod, out var attribute))
if (!GetterLookup.TryGetValue(__originalMethod.MethodHandle, out var attribute))
return true;
__result = attribute.GetValue();
return false;
}
/// <summary>
/// Patches the getter of a property to return the value of the option.
/// </summary>
/// <typeparam name="T">The type of the option value.</typeparam>
/// <param name="__originalMethod">The original getter method.</param>
/// <param name="__result">The result of the property getter.</param>
/// <returns><see langword="false"/> so the original getter gets skipped.</returns>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")]
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")]
public static bool PropertyGetterPatch<T>(MethodBase __originalMethod, ref T __result)
{
if (!GetterLookup.TryGetValue(__originalMethod.MethodHandle, out var attribute))
return true;
if (attribute is ITypedOption<T> typedAttribute)
__result = typedAttribute.GetValueUnboxed();
else
__result = (T)attribute.GetValue();
return false;
}
}
@@ -1,17 +0,0 @@
using System.Linq;
using MiraAPI.PluginLoading;
namespace MiraAPI.GameOptions;
[MiraIgnore]
internal sealed class ModifierOptionGroup : AbstractOptionGroup
{
public override string GroupName { get; }
public ModifierOptionGroup(string name, IModdedOption[] options, params AbstractOptionGroup[] groups)
{
GroupName = name;
Options.AddRange(options);
Options.AddRange(groups.SelectMany(x => x.Options));
}
}
@@ -1,6 +1,5 @@
using System;
using System.Diagnostics.CodeAnalysis;
using Il2CppInterop.Runtime.Attributes;
using TMPro;
using UnityEngine;
@@ -49,6 +48,5 @@ public record struct OptionNotifConfiguration
/// <summary>
/// Gets or sets the <see cref="Color"/> for the text on the options pop-up.
/// </summary>
[HideFromIl2Cpp]
public Color PopUpTextColor { get; set; }
}
@@ -0,0 +1,125 @@
using System;
using UnityEngine;
using Object = UnityEngine.Object;
namespace MiraAPI.GameOptions.OptionTypes;
/// <summary>
/// A base class for modded options that utilize a string-based interface.
/// </summary>
/// <typeparam name="T">The underlying option type.</typeparam>
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public abstract class ModdedBaseStringOption<T>(string groupPrefix, string title, T defaultValue, bool includeInPreset = true)
: ModdedOption<T>(groupPrefix, title, defaultValue, includeInPreset)
{
/// <summary>
/// Gets or sets the string values of the option.
/// </summary>
public string[] Values { get; protected set; } = [];
/// <summary>
/// Gets or sets the underlying values of the option.
/// </summary>
public T[] UnderlyingValues { get; protected set; } = [];
/// <summary>
/// Gets or sets the String Name values of the option.
/// </summary>
public StringNames[] StringNameValues { get; protected set; } = [];
/// <summary>
/// Gets the option type name used for naming the generated GameObject.
/// </summary>
protected abstract string OptionTypeName { get; }
/// <summary>
/// Initializes the common StringGameSetting data for this option.
/// </summary>
/// <param name="defaultIndex">The default index to assign.</param>
protected void InitializeData(int defaultIndex)
{
var data = ScriptableObject.CreateInstance<StringGameSetting>();
data.Title = StringName;
data.Type = global::OptionTypes.String;
data.Values = StringNameValues;
data.Index = defaultIndex;
Data = data;
}
/// <summary>
/// Gets the index of a specific value.
/// </summary>
/// <param name="value">The option's value.</param>
/// <returns>The index of the value in the underlying array.</returns>
public int GetIndex(T value)
{
var index = Array.IndexOf(UnderlyingValues, value);
if (index == -1)
Info($"Cannot find a valid index for {value}. Returning -1 instead. Values: {string.Join(", ", Values)}");
return index;
}
/// <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}.{OptionTypeName}.{Title}";
stringOption.SetUpFromData(Data, 20);
// SetUpFromData method doesn't work correctly so we must set the values manually
stringOption.Title = StringName;
stringOption.Value = GetIndex(Value);
stringOption.Values = StringNameValues;
stringOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
// Changing the button text to make them more distinct from number options
stringOption.MinusBtn.ChangeButtonText("<");
stringOption.PlusBtn.ChangeButtonText(">");
OptionBehaviour = stringOption;
return stringOption;
}
/// <inheritdoc />
protected override void OnValueChanged(T newValue)
{
if (OptionBehaviour && OptionBehaviour is StringOption opt)
{
opt.Value = GetIndex(newValue);
}
}
/// <inheritdoc />
public override string GetDisplayValue()
{
var index = GetIndex(Value);
return (uint)index < (uint)StringNameValues.Length
? TranslationController.Instance.GetString(StringNameValues[index])
: Value!.ToString()!;
}
/// <inheritdoc />
public override float GetFloatData()
{
return GetIndex(Value);
}
/// <inheritdoc />
public override T GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
var index = optionBehaviour.GetInt();
if ((uint)index < (uint)UnderlyingValues.Length)
return UnderlyingValues[index];
return UnderlyingValues.Length > 0 ? UnderlyingValues[0] : default!;
}
}
@@ -1,24 +1,75 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using System.Runtime.CompilerServices;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.Translation;
using UnityEngine;
using Object = UnityEngine.Object;
using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.OptionTypes;
/// <summary>
/// The base class for enum options. Exists mainly to get rid of an abstract implementation.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an int.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public abstract class ModdedBaseEnumOption<T>(string groupPrefix, string title, T defaultValue, bool includeInPreset = true)
: ModdedBaseStringOption<T>(groupPrefix, title, defaultValue, includeInPreset)
{
/// <inheritdoc />
protected override string OptionTypeName => "EnumOption";
}
/// <summary>
/// An option for selecting an <see langword="enum"/> value.
/// </summary>
public class ModdedEnumOption : ModdedOption<int>
[Obsolete("Use ModdedEnumOption<T> instead. This will be removed in a future version.")]
public class ModdedEnumOption : ModdedBaseEnumOption<int>
{
/// <summary>
/// Gets the string values of the enum.
/// Initializes a new instance of the <see cref="ModdedEnumOption"/> class.
/// </summary>
public string[] Values { get; }
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an int.</param>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedEnumOption(string groupPrefix, string title, int defaultValue, Type enumType, string idPrefix, string[]? values = null, bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset)
{
idPrefix = idPrefix.Replace("%type%", enumType.Name);
var rawValues = Enum.GetValues(enumType);
UnderlyingValues = new int[rawValues.Length];
for (var i = 0; i < rawValues.Length; i++)
UnderlyingValues[i] = Convert.ToInt32(rawValues.GetValue(i), NumberFormatInfo.InvariantInfo);
Values = values ?? Enum.GetNames(enumType);
StringNameValues = [.. Values.Select(x => MiraLocaleManager.GetOrCreateLocaleString($"{idPrefix}{x}"))];
InitializeData(GetIndex(defaultValue));
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption"/> class.
/// </summary>
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an int.</param>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedEnumOption(string groupPrefix, string title, int defaultValue, Type enumType, string[]? values = null, bool includeInPreset = true)
: this(groupPrefix, title, defaultValue, enumType, string.Empty, values, includeInPreset)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption"/> class.
@@ -29,53 +80,28 @@ public class ModdedEnumOption : ModdedOption<int>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedEnumOption(string title, int defaultValue, Type enumType, string[]? values = null, bool includeInPreset = true)
: base(title, defaultValue, includeInPreset)
: this(string.Empty, title, defaultValue, enumType, values, includeInPreset)
{
Values = values ?? Enum.GetNames(enumType);
var data = ScriptableObject.CreateInstance<StringGameSetting>();
data.Title = StringName;
data.Type = global::OptionTypes.String;
data.Values = Values.Select(MiraLocaleManager.GetOrCreateLocaleString).ToArray();
data.Index = Value;
Data = data;
}
/// <inheritdoc />
public override OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, PlayerOption playerOpt, Transform container)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an int.</param>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedEnumOption(string title, int defaultValue, Type enumType, string idPrefix, string[]? values = null, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, enumType, idPrefix, values, includeInPreset)
{
var stringOption = Object.Instantiate(stringOpt, container);
stringOption.name =
$"{ParentMod!.OptionsTitleText}.EnumOption.{TranslationController.Instance.GetString(StringName)}";
stringOption.SetUpFromData(Data, 20);
stringOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
// Changing the button text to make them more distinct from number options
stringOption.MinusBtn.ChangeButtonText("<");
stringOption.PlusBtn.ChangeButtonText(">");
// SetUpFromData method doesn't work correctly so we must set the values manually
stringOption.Title = StringName;
stringOption.Values = (Data as StringGameSetting)?.Values ?? new Il2CppStructArray<StringNames>(0);
stringOption.Value = Value;
OptionBehaviour = stringOption;
return stringOption;
}
/// <inheritdoc />
public override float GetFloatData()
{
return Value;
}
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, BitConverter.GetBytes(Value));
return new(Id, BitConverter.GetBytes(Value));
}
/// <inheritdoc />
@@ -85,30 +111,9 @@ public class ModdedEnumOption : ModdedOption<int>
}
/// <inheritdoc />
public override int GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
protected internal override ConfigDescription? CreateDescription()
{
return optionBehaviour.GetInt();
}
/// <inheritdoc />
protected override void OnValueChanged(int newValue)
{
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
StringName,
Data.GetValueString(newValue),
Configuration.PopUpTextColor,
Configuration.PopUpIconTmp,
false);
if (!OptionBehaviour)
{
return;
}
if (OptionBehaviour is StringOption opt)
{
opt.Value = newValue;
}
return new(string.Empty, new AcceptableValueList<int>(UnderlyingValues));
}
}
@@ -116,13 +121,41 @@ public class ModdedEnumOption : ModdedOption<int>
/// An option for selecting an <see langword="enum"/> value.
/// </summary>
/// <typeparam name="T">The <see cref="Enum"/> type.</typeparam>
public class ModdedEnumOption<T> : ModdedOption<T>
public class ModdedEnumOption<T> : ModdedBaseEnumOption<T>
where T : struct, Enum
{
/// <summary>
/// Gets the string values of the <see langword="enum"/>.
/// Initializes a new instance of the <see cref="ModdedEnumOption{T}"/> class.
/// </summary>
public string[] Values { get; }
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an <see langword="int"/>.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedEnumOption(string groupPrefix, string title, T defaultValue, string idPrefix, string[]? values = null, bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset)
{
idPrefix = idPrefix.Replace("%type%", typeof(T).Name);
UnderlyingValues = Enum.GetValues<T>();
Values = values ?? Enum.GetNames<T>();
StringNameValues = [.. Values.Select(x => MiraLocaleManager.GetOrCreateLocaleString($"{idPrefix}{x}"))];
InitializeData(GetIndex(defaultValue));
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption{T}"/> class.
/// </summary>
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an <see langword="int"/>.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedEnumOption(string groupPrefix, string title, T defaultValue, string[]? values = null, bool includeInPreset = true)
: this(groupPrefix, title, defaultValue, string.Empty, values, includeInPreset)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption{T}"/> class.
@@ -132,85 +165,40 @@ public class ModdedEnumOption<T> : ModdedOption<T>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedEnumOption(string title, T defaultValue, string[]? values = null, bool includeInPreset = true)
: base(title, defaultValue, includeInPreset)
: this(string.Empty, title, defaultValue, values, includeInPreset)
{
Values = values ?? Enum.GetNames<T>();
var data = ScriptableObject.CreateInstance<StringGameSetting>();
data.Title = StringName;
data.Type = global::OptionTypes.String;
data.Values = Values.Select(MiraLocaleManager.GetOrCreateLocaleString).ToArray();
data.Index = Convert.ToInt32(Value, NumberFormatInfo.InvariantInfo);
Data = data;
}
/// <inheritdoc />
public override OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, PlayerOption playerOpt, Transform container)
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption{T}"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an <see langword="int"/>.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedEnumOption(string title, T defaultValue, string idPrefix, string[]? values = null, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, idPrefix, values, includeInPreset)
{
var stringOption = Object.Instantiate(stringOpt, container);
stringOption.name =
$"{ParentMod!.OptionsTitleText}.EnumOption.{TranslationController.Instance.GetString(StringName)}";
stringOption.SetUpFromData(Data, 20);
stringOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
// Changing the button text to make them more distinct from number options
stringOption.MinusBtn.ChangeButtonText("<");
stringOption.PlusBtn.ChangeButtonText(">");
// SetUpFromData method doesn't work correctly so we must set the values manually
stringOption.Title = StringName;
stringOption.Values = (Data as StringGameSetting)?.Values ?? new Il2CppStructArray<StringNames>(0);
stringOption.Value = Convert.ToInt32(Value, NumberFormatInfo.InvariantInfo);
OptionBehaviour = stringOption;
return stringOption;
}
/// <inheritdoc />
public override float GetFloatData()
{
return Convert.ToSingle(Value, NumberFormatInfo.InvariantInfo);
}
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value, NumberFormatInfo.InvariantInfo)!));
var buffer = new byte[Unsafe.SizeOf<T>()];
Unsafe.WriteUnaligned(ref buffer[0], Value);
return new(Id, buffer);
}
/// <inheritdoc />
public override void HandleNetData(byte[] data)
{
SetValue(Enum.Parse<T>(Encoding.Unicode.GetString(data)));
SetValue(Unsafe.ReadUnaligned<T>(ref data[0]));
}
/// <inheritdoc />
public override T GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
protected internal override ConfigDescription? CreateDescription()
{
return Enum.Parse<T>(optionBehaviour.GetInt().ToString(NumberFormatInfo.InvariantInfo));
}
/// <inheritdoc />
protected override void OnValueChanged(T newValue)
{
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
StringName,
Data.GetValueString(Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo)),
Configuration.PopUpTextColor,
Configuration.PopUpIconTmp,
false);
if (!OptionBehaviour)
{
return;
}
if (OptionBehaviour is StringOption opt)
{
opt.Value = Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo);
}
return new(string.Empty, new AcceptableEnumValues<T>(UnderlyingValues));
}
}
@@ -1,5 +1,6 @@
using System;
using AmongUs.GameOptions;
using System.Text.RegularExpressions;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.Utilities;
using UnityEngine;
@@ -43,15 +44,131 @@ public class ModdedNumberOption : ModdedOption<float>
public string NegativeWordValue { get; }
/// <summary>
/// Gets a value indicating whether zero is infinity.
/// Gets the format string used to display the values.
/// </summary>
public bool ZeroInfinity => ZeroWordValue == "∞";
public string FormatString { get; }
/// <summary>
/// Gets a value indicating whether holding shift will divide the increment.
/// </summary>
public bool ShiftIncrement { get; }
/// <summary>
/// Gets a value indicating whether the option is an int option.
/// </summary>
public bool IsInt { get; }
/// <summary>
/// Gets a value indicating whether zero is infinity.
/// </summary>
public bool ZeroInfinity => ZeroWordValue == "∞";
private static readonly Regex TrailingZeroRegex = new(@"\.0+(?!\d)", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOption"/> class.
/// </summary>
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as a float.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="zeroBehavior">Determines what is shown for zero.</param>
/// <param name="negativeBehavior">Determines what is shown for negative 1.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="halfIncrements">Whether increments can be split in half.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedNumberOption(
string groupPrefix,
string title,
float defaultValue,
float min,
float max,
float increment,
string zeroBehavior,
string negativeBehavior,
MiraNumberSuffixes suffixType,
string? formatString = null,
bool halfIncrements = false,
bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset)
{
Min = min;
Max = max;
Increment = increment;
SuffixType = suffixType;
ZeroWordValue = zeroBehavior;
ShiftIncrement = halfIncrements;
NegativeWordValue = negativeBehavior;
IsInt = defaultValue.IsInteger() &&
Increment.IsInteger() &&
Value.IsInteger() &&
Min.IsInteger() &&
Max.IsInteger();
FormatString = formatString ?? (IsInt ? "0" : "0.0");
Value = Mathf.Clamp(defaultValue, min, max);
if (IsInt)
{
var data = ScriptableObject.CreateInstance<IntGameSetting>();
data.Type = global::OptionTypes.Int;
data.Title = StringName;
data.Value = (int)Value;
data.Increment = (int)Increment;
data.ValidRange = new IntRange((int)Min, (int)Max);
data.FormatString = FormatString;
data.ZeroIsInfinity = ZeroInfinity;
data.SuffixType = (NumberSuffixes)SuffixType;
Data = data;
}
else
{
var data = ScriptableObject.CreateInstance<FloatGameSetting>();
data.Type = global::OptionTypes.Float;
data.Title = StringName;
data.Value = Value;
data.Increment = Increment;
data.ValidRange = new FloatRange(Min, Max);
data.FormatString = FormatString;
data.ZeroIsInfinity = ZeroInfinity;
data.SuffixType = (NumberSuffixes)SuffixType;
Data = data;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOption"/> class.
/// </summary>
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as a float.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedNumberOption(
string groupPrefix,
string title,
float defaultValue,
float min,
float max,
float increment,
MiraNumberSuffixes suffixType,
string? formatString = null,
bool zeroInfinity = false,
bool includeInPreset = true)
: this(groupPrefix, title, defaultValue, min, max, increment, zeroInfinity ? "∞" : "#", "#", suffixType, formatString, increment == 1f, includeInPreset)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOption"/> class.
/// </summary>
@@ -60,11 +177,11 @@ public class ModdedNumberOption : ModdedOption<float>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="zeroBehavior">Determines what is shown for zero.</param>
/// <param name="negativeBehavior">Determines what is shown for negative 1.</param>
/// <param name="halfIncrements">Whether increments can be split in half.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="halfIncrements">Whether increments can be split in half.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedNumberOption(
string title,
@@ -78,36 +195,8 @@ public class ModdedNumberOption : ModdedOption<float>
string? formatString = null,
bool halfIncrements = false,
bool includeInPreset = true)
: base(title, defaultValue, includeInPreset)
: this(string.Empty, title, defaultValue, min, max, increment, zeroBehavior, negativeBehavior, suffixType, formatString, halfIncrements, includeInPreset)
{
Min = min;
Max = max;
Increment = increment;
SuffixType = suffixType;
ZeroWordValue = zeroBehavior;
ShiftIncrement = halfIncrements;
NegativeWordValue = negativeBehavior;
Value = Mathf.Clamp(defaultValue, min, max);
var data = ScriptableObject.CreateInstance<FloatGameSetting>();
data.Type = global::OptionTypes.Float;
data.Title = StringName;
data.Value = Value;
data.Increment = Increment;
data.ValidRange = new FloatRange(Min, Max);
data.FormatString = formatString ??
(defaultValue.IsInteger() &&
Increment.IsInteger() &&
Value.IsInteger() &&
Min.IsInteger() &&
Max.IsInteger() ? "0" : "0.0");
data.ZeroIsInfinity = ZeroInfinity;
data.SuffixType = (NumberSuffixes)SuffixType;
data.OptionName = FloatOptionNames.Invalid;
Data = data;
}
/// <summary>
@@ -119,8 +208,8 @@ public class ModdedNumberOption : ModdedOption<float>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedNumberOption(
string title,
@@ -132,7 +221,7 @@ public class ModdedNumberOption : ModdedOption<float>
string? formatString = null,
bool zeroInfinity = false,
bool includeInPreset = true)
: this(title, defaultValue, min, max, increment, zeroInfinity ? "∞" : "#", "#", suffixType, formatString, increment == 1f, includeInPreset)
: this(string.Empty, title, defaultValue, min, max, increment, suffixType, formatString, zeroInfinity, includeInPreset)
{
}
@@ -144,9 +233,21 @@ public class ModdedNumberOption : ModdedOption<float>
PlayerOption playerOpt,
Transform container)
{
var numberOption = Object.Instantiate(numberOpt, Vector3.zero, Quaternion.identity, container);
numberOption.name =
$"{ParentMod!.OptionsTitleText}.NumberOption.{TranslationController.Instance.GetString(StringName)}";
var numberOption = Object.Instantiate(numberOpt, container);
numberOption.name = $"{ParentMod!.OptionsTitleText}.NumberOption.{Title}";
numberOption.SetUpFromData(Data, 20);
// SetUpFromData method doesn't work correctly so we must set the values manually
numberOption.Title = StringName;
numberOption.Value = Value;
numberOption.Increment = Increment;
numberOption.ValidRange = new FloatRange(Min, Max);
numberOption.FormatString = FormatString;
numberOption.ZeroIsInfinity = ZeroInfinity;
numberOption.SuffixType = (NumberSuffixes)SuffixType;
numberOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
var optionComponent = numberOption.gameObject.AddComponent<MiraNumberOptionComponent>();
optionComponent.NumberOption = this;
optionComponent.DefaultIncrement = Increment;
@@ -154,23 +255,27 @@ public class ModdedNumberOption : ModdedOption<float>
optionComponent.NegativeValue = NegativeWordValue;
optionComponent.ZeroValue = ZeroWordValue;
numberOption.SetUpFromData(Data, 20);
numberOption.OnValueChanged = (Il2CppSystem.Action<OptionBehaviour>)ValueChanged;
numberOption.Title = StringName;
numberOption.Value = Value;
numberOption.Increment = Increment;
numberOption.ValidRange = new FloatRange(Min, Max);
numberOption.FormatString = (Data as FloatGameSetting)?.FormatString ?? "0.0";
numberOption.ZeroIsInfinity = ZeroInfinity;
numberOption.SuffixType = (NumberSuffixes)SuffixType;
numberOption.floatOptionName = FloatOptionNames.Invalid;
OptionBehaviour = numberOption;
return numberOption;
}
/// <inheritdoc />
public override string GetDisplayValue()
{
if (this is { NegativeWordValue: not "#", Value: -1 })
{
return NegativeWordValue;
}
if (this is { ZeroWordValue: not "#", Value: 0 })
{
return ZeroWordValue;
}
return TrailingZeroRegex.Replace(Data.GetValueString(Value), string.Empty);
}
/// <inheritdoc />
public override float GetFloatData()
{
@@ -198,21 +303,24 @@ public class ModdedNumberOption : ModdedOption<float>
/// <inheritdoc />
protected override void OnValueChanged(float newValue)
{
Value = Mathf.Clamp(newValue, Min, Max);
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
StringName,
Data.GetValueString(newValue),
Configuration.PopUpTextColor,
Configuration.PopUpIconTmp,
false);
if (OptionBehaviour is NumberOption opt)
if (OptionBehaviour && OptionBehaviour is NumberOption opt)
{
opt.Value = Value;
}
}
/// <inheritdoc />
protected override float ModifyValue(float newValue, float oldValue)
{
return Math.Clamp(newValue, Min, Max);
}
/// <inheritdoc />
protected internal override ConfigDescription? CreateDescription()
{
return new(string.Empty, new AcceptableValueRange<float>(Min, Max));
}
/// <summary>
/// Implicitly converts the option to an <see langword="int"/>.
/// </summary>
@@ -220,6 +328,6 @@ public class ModdedNumberOption : ModdedOption<float>
/// <returns>Integer value.</returns>
public static implicit operator int(ModdedNumberOption option)
{
return (int)option.Value;
return (int)MathF.Round(option.Value, MidpointRounding.AwayFromZero);
}
}
+78 -39
View File
@@ -14,33 +14,20 @@ namespace MiraAPI.GameOptions.OptionTypes;
/// Represents a modded option.
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
public abstract class ModdedOption<T> : IModdedOption
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The option title.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="includeInPreset">Whether to include the option in the preset.</param>
public abstract class ModdedOption<T>(string groupPrefix, string title, T defaultValue, bool includeInPreset = true) : IModdedOption
{
/// <inheritdoc />
public uint Id { get; }
public uint Id { get; } = ModdedOptionsManager.NextId;
/// <inheritdoc />
public string Title { get; set; }
public string Title { get; set; } = groupPrefix + title;
/// <inheritdoc />
public StringNames StringName { get; }
/// <inheritdoc />
public BaseGameSetting Data { get; protected set; } = null!;
/// <inheritdoc />
public IMiraPlugin? ParentMod
{
get;
set
{
if (field != null || value == null) return;
field = value;
var entry = field.GetConfigFile().Bind(ConfigDefinition, DefaultValue);
Value = entry.Value;
}
}
public StringNames StringName { get; } = MiraLocaleManager.GetOrCreateLocaleString(groupPrefix + title);
/// <summary>
/// Gets or sets the value of the option.
@@ -50,6 +37,8 @@ public abstract class ModdedOption<T> : IModdedOption
get => Getter != null ? Getter(_value) : _value;
protected set
{
value = ModifyValue(value, _value);
if (Setter != null)
value = Setter(value, _value);
@@ -57,12 +46,24 @@ public abstract class ModdedOption<T> : IModdedOption
}
}
private T _value;
private T _value = defaultValue;
/// <summary>
/// Gets the default value of the option.
/// </summary>
public T DefaultValue { get; }
public T DefaultValue { get; } = defaultValue;
/// <inheritdoc />
public Func<bool> Visible { get; set; } = DelegateUtilities.AlwaysTrue;
/// <inheritdoc />
public bool IncludeInPreset { get; set; } = includeInPreset;
/// <inheritdoc />
public bool ShowNotification { get; set; } = true;
/// <inheritdoc />
public BaseGameSetting Data { get; protected set; } = null!;
/// <inheritdoc cref="IModdedOption.Getter"/>
public Func<T, T>? Getter { get; set; }
@@ -73,12 +74,6 @@ public abstract class ModdedOption<T> : IModdedOption
/// <inheritdoc cref="IModdedOption.ChangedEvent"/>
public Action<T>? ChangedEvent { get; set; }
/// <inheritdoc />
public Func<bool> Visible { get; set; }
/// <inheritdoc />
public bool IncludeInPreset { get; set; }
/// <inheritdoc />
public OptionBehaviour? OptionBehaviour { get; protected set; }
@@ -89,7 +84,18 @@ public abstract class ModdedOption<T> : IModdedOption
public AbstractOptionGroup ParentGroup { get; set; }
/// <inheritdoc />
public virtual OptionNotifConfiguration Configuration => new(ParentGroup);
public IMiraPlugin? ParentMod
{
get;
set
{
if (field != null || value == null) return;
field = value;
var entry = field.GetConfigFile().Bind(ConfigDefinition, DefaultValue, CreateDescription());
Value = entry.Value;
}
}
/// <inheritdoc />
Delegate? IModdedOption.Getter
@@ -112,6 +118,9 @@ public abstract class ModdedOption<T> : IModdedOption
set => ChangedEvent = value as Action<T>;
}
/// <inheritdoc />
public virtual OptionNotifConfiguration Configuration => new(ParentGroup);
/// <summary>
/// Initializes a new instance of the <see cref="ModdedOption{T}"/> class.
/// </summary>
@@ -119,14 +128,8 @@ public abstract class ModdedOption<T> : IModdedOption
/// <param name="defaultValue">The default value.</param>
/// <param name="includeInPreset">Whether to include the option in the preset.</param>
protected ModdedOption(string title, T defaultValue, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, includeInPreset)
{
Id = ModdedOptionsManager.NextId;
Title = title.Translate();
DefaultValue = defaultValue;
Value = defaultValue;
StringName = MiraLocaleManager.GetOrCreateLocaleString(Title);
Visible = DelegateUtilities.AlwaysTrue;
IncludeInPreset = includeInPreset;
}
internal void ValueChanged(OptionBehaviour optionBehaviour)
@@ -156,10 +159,22 @@ public abstract class ModdedOption<T> : IModdedOption
entry.Value = _value;
}
Rpc<SyncOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, [GetNetData()], true);
Rpc<SyncGameOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, new MiraOptionNetData(true, [GetNetData()]), true);
}
if (ShowNotification)
{
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
StringName,
GetDisplayValue(),
Configuration.PopUpTextColor,
Configuration.PopUpIconTmp,
false);
}
OnValueChanged(_value);
ShowNotification = true;
}
/// <inheritdoc />
@@ -178,7 +193,7 @@ public abstract class ModdedOption<T> : IModdedOption
/// <inheritdoc />
public void Bind(ConfigFile config)
{
config.Bind(ConfigDefinition, DefaultValue);
config.Bind(ConfigDefinition, DefaultValue, CreateDescription());
}
/// <inheritdoc />
@@ -230,6 +245,30 @@ public abstract class ModdedOption<T> : IModdedOption
PlayerOption playerOpt,
Transform container);
/// <inheritdoc />
public virtual string GetDisplayValue()
{
return Data.GetValueString(GetFloatData());
}
/// <summary>
/// Modifies the incoming value with respect to the previous value. This is invoked before the <see cref="ModdedOption{T}.Setter"/> (if it's set).
/// </summary>
/// <param name="newValue">The new value.</param>
/// <param name="oldValue">The old value.</param>
/// <returns>The modified value.</returns>
protected virtual T ModifyValue(T newValue, T oldValue)
{
return newValue;
}
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member (Justification: Internal code.)
protected internal virtual ConfigDescription? CreateDescription()
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
{
return null;
}
/// <summary>
/// Implicitly converts the option to type of <typeparamref name="T"/>.
/// </summary>
@@ -40,8 +40,8 @@ public class ModdedOptionList<T> : IModdedOptionList<T>
/// <param name="options">The options list.</param>
public ModdedOptionList(IEnumerable<T> options)
{
Count = options.Count();
Options = [.. options];
Count = Options.Count;
}
/// <summary>
@@ -62,13 +62,4 @@ public class ModdedOptionList<T> : IModdedOptionList<T>
{
return Options.GetEnumerator();
}
/// <inheritdoc cref="IEnumerable{T}.GetEnumerator"/>
IEnumerator<IModdedOption> IEnumerable<IModdedOption>.GetEnumerator()
{
return ((IEnumerable<IModdedOption>)Options).GetEnumerator();
}
/// <inheritdoc cref="IReadOnlyList{T}.this"/>
IModdedOption IReadOnlyList<IModdedOption>.this[int index] => this[index];
}
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Networking;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -29,18 +28,14 @@ public class ModdedPlayerOption : ModdedOption<int>
/// </summary>
public bool AllowNone { get; set; }
/// <summary>
/// Gets the player selected by this option. May be <c>null</c> if allowed to have <c>None</c> as an option.
/// </summary>
public NetworkedPlayerInfo? SelectedPlayer => Value == -1 ? null : Values[Value];
/// <summary>
/// Initializes a new instance of the <see cref="ModdedPlayerOption"/> class.
/// </summary>
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="allowNone">Whether the option includes a none option. If None is selected, value will return -1.</param>
public ModdedPlayerOption(string title, bool allowNone = true)
: base(title, allowNone ? -1 : 0, false)
/// <param name="allowNone">Whether the option includes a none option. If None is selected, value can return -1.</param>
public ModdedPlayerOption(string groupPrefix, string title, bool allowNone = true)
: base(groupPrefix, title, allowNone ? -1 : 0, false)
{
Values = [];
AllowNone = allowNone;
@@ -54,6 +49,16 @@ public class ModdedPlayerOption : ModdedOption<int>
Data = data;
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedPlayerOption"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="allowNone">Whether the option includes a none option. If None is selected, value can return -1.</param>
public ModdedPlayerOption(string title, bool allowNone = true)
: this(string.Empty, title, allowNone)
{
}
/// <inheritdoc />
public override OptionBehaviour CreateOption(
ToggleOption toggleOpt,
@@ -62,27 +67,27 @@ public class ModdedPlayerOption : ModdedOption<int>
PlayerOption playerOpt,
Transform container)
{
var playerOption = Object.Instantiate(playerOpt, container);
playerOption.name =
$"{ParentMod!.OptionsTitleText}.PlayerOption.{TranslationController.Instance.GetString(StringName)}";
Values = GetFilteredPlayers();
playerOption.SetUpFromData(Data, 20);
playerOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
var playerOption = Object.Instantiate(playerOpt, container);
playerOption.name = $"{ParentMod!.OptionsTitleText}.PlayerOption.{Title}";
playerOption.SetUpFromData(Data, 20);
// SetUpFromData method doesn't work correctly so we must set the values manually
playerOption.Title = StringName;
playerOption.TitleText.text = Title.Translate();
playerOption.Values = Values.ToIl2CppList();
playerOption.Value = Value;
playerOption.playerIndex = Values.FindIndex(p => p.PlayerId == Value);
OptionBehaviour = playerOption;
ModdedOptionsManager.CreatedPlayerOptions.TryAdd(playerOption, this);
playerOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
playerOption.SetValueText();
playerOption.AdjustButtonsActiveState();
playerOption.gameObject.AddComponent<MiraPlayerOptionComponent>().PlayerOption = this;
OptionBehaviour = playerOption;
return playerOption;
}
@@ -108,7 +113,7 @@ public class ModdedPlayerOption : ModdedOption<int>
/// <returns>A player or <see langword="null"/> if chosen none.</returns>
public NetworkedPlayerInfo? GetPlayerValue()
{
return Value < 0 ? null : Values[Value];
return (uint)Value >= (uint)Values.Count ? null : Values[Value];
}
/// <inheritdoc />
@@ -138,21 +143,18 @@ public class ModdedPlayerOption : ModdedOption<int>
/// <inheritdoc />
protected override void OnValueChanged(int newValue)
{
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
StringName,
Data.GetValueString(newValue),
Configuration.PopUpTextColor,
Configuration.PopUpIconTmp,
false);
if (!OptionBehaviour)
{
return;
}
if (OptionBehaviour is PlayerOption opt)
if (OptionBehaviour && OptionBehaviour is PlayerOption opt)
{
opt.Value = newValue;
}
}
/// <inheritdoc />
public override string GetDisplayValue()
{
var player = GetPlayerValue();
return !player
? TranslationController.Instance.GetString(StringNames.None)
: player!.PlayerName;
}
}
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff. Show more