Compare commits

..
5 Commits
Author SHA1 Message Date
Atony aa0c251662 Merge branch 'dev' into test-fixes 2026-11-01 11:53:37 -06:00
Atony 90be4ef253 Merge branch 'dev' into test-fixes 2026-10-30 15:07:11 -05:00
Atony 3bca3faafb Merge branch 'dev' into test-fixes 2026-10-28 20:29:59 -05:00
Az 1947c536d3 minor code fixes and nitpicks 2026-10-26 01:56:44 -04:00
Atony 28b276b9e2 Merge branch 'pr/115' into test-fixes 2026-10-25 18:35:34 -05:00
218 changed files with 3141 additions and 4669 deletions

No files matched your search

+2 -11
View File
@@ -106,19 +106,10 @@ dotnet_diagnostic.S1244.severity = none
dotnet_diagnostic.S2325.severity = none
# CA1710: Identifiers should have correct suffix
dotnet_diagnostic.CA1710.severity = none
dotnet_diagnostic.CA1710.severity = silent
# CA1010: Generic interface should also be implemented
dotnet_diagnostic.CA1010.severity = none
dotnet_diagnostic.CA1010.severity = silent
# 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
+3 -13
View File
@@ -5,9 +5,6 @@ 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:
@@ -41,21 +38,14 @@ 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 ${{ steps.login.outputs.NUGET_API_KEY }}
dotnet nuget push MiraAPI/bin/Release/AllOfUs.MiraAPI.*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
+6 -8
View File
@@ -5,12 +5,10 @@
<DebugType>embedded</DebugType>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GenerateFullPaths>false</GenerateFullPaths>
<PathMap>$(MSBuildProjectDirectory)=.</PathMap>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<VersionPrefix>0.6.1</VersionPrefix>
<VersionPrefix>0.6.0</VersionPrefix>
<VersionSuffix>dev</VersionSuffix>
<Authors>All Of Us, XtraCube, Angxl</Authors>
@@ -34,11 +32,11 @@
</PropertyGroup>
<ItemGroup>
<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" />
<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" />
<AdditionalFiles Include="$(MSBuildThisFileDirectory)/stylecop.json" Link="stylecop.json" Visible="false" />
</ItemGroup>
</Project>
+11 -5
View File
@@ -5,14 +5,20 @@ using UnityEngine;
namespace MiraAPI.Example;
[RegisterCustomColors("color.")]
[RegisterCustomColors]
public static class ExampleColors
{
public static CustomColor Cerulean { get; } = new("cerulean", new Color(0.0f, 0.48f, 0.65f), CustomColorBrightness.Lighter);
public static CustomColor Cerulean { get; } = new("color.cerulean", new Color(0.0f, 0.48f, 0.65f))
{
ColorBrightness = CustomColorBrightness.Lighter,
};
public static CustomColor Rose { get; } = new("rose", new Color(0.98f, 0.26f, 0.62f), CustomColorBrightness.Lighter);
public static CustomColor Rose { get; } = new("color.rose", new Color(0.98f, 0.26f, 0.62f));
public static CustomColor Gold { get; } = new("gold", new Color(1.0f, 0.84f, 0.0f), CustomColorBrightness.Lighter);
public static CustomColor Gold { get; } = new("color.gold", new Color(1.0f, 0.84f, 0.0f));
public static VariableColor Rainbow { get; } = new("rainbow", t => new HsbColor(MathUtilities.PingPong(t, 1f, 0.3f), 1f, 1f), CustomColorBrightness.Lighter);
public static VariableColor Rainbow { get; } = new("color.rainbow", t => new HsbColor(MathUtilities.PingPong(t, 1f, 0.3f), 1f, 1f))
{
ColorBrightness = CustomColorBrightness.Lighter,
};
}
-1
View File
@@ -14,7 +14,6 @@ using Reactor.Utilities;
namespace MiraAPI.Example;
[RegisterEventContainer]
public static class ExampleEventHandlers
{
public static void Initialize()
-3
View File
@@ -26,9 +26,6 @@ public partial class ExamplePlugin : BasePlugin, IMiraPlugin
public string OptionsTitleText { get; } = "Mira API\nExample Mod";
public string CustomOptionMenuNameTwo { get; } = "Example Options";
/// <inheritdoc />
public bool ForceRegisterEvents => false;
public ConfigFile GetConfigFile()
{
return Config;
+6 -2
View File
@@ -30,12 +30,16 @@ 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
[ModdedEnumOption<Api>("options.exampleOptions1.bestApi", ["Mira API", "Mitochondria", "Reactor"])]
public Api BestApi { get; set; } = Api.MiraAPI;
public Api WorstApi { 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,6 +47,7 @@ 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.sqrMagnitude > 0)
if (Player.MyPhysics.Velocity.magnitude > 0)
{
var rend = Player.cosmetics.currentBodySprite.BodySprite;
var tmp = Player.cosmetics.nameText;
-1
View File
@@ -15,7 +15,6 @@ 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,7 +14,6 @@ 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,7 +14,6 @@ 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>
+41 -81
View File
@@ -1,5 +1,4 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
@@ -9,44 +8,45 @@ namespace MiraAPI.Colors;
/// <summary>
/// Represents a custom color with a main color and a shadow color.
/// </summary>
/// <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="name">The name of the option.</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.")]
public class CustomColor(StringNames? nameId, string? rawId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness)
[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)
{
private StringNames? name = nameId;
private CustomColorBrightness colorBrightness = brightness;
/// <summary>
/// Gets the main color.
/// Gets or sets the main color.
/// </summary>
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
public Color32 MainColor
{
get
get;
set
{
if (!name.HasValue && !string.IsNullOrEmpty(RawId))
name = MiraLocaleManager.GetOrCreateLocaleString(RawId);
return name.GetValueOrDefault();
}
internal set
{
name = value;
field = value;
InternalMainColor = value;
}
}
= mainColor;
/// <summary>
/// Gets or sets the shadow color.
/// </summary>
public Color32 ShadowColor
{
get;
set
{
field = value;
InternalShadowColor = value;
}
}
= shadowColor;
/// <summary>
/// Gets or sets the name of the color.
/// </summary>
public StringNames Name { get; set; } = name;
/// <summary>
/// Gets the id of the color.
@@ -54,68 +54,28 @@ public class CustomColor(StringNames? nameId, string? rawId, Color32 mainColor,
public int ColorId { get; internal set; } = -1;
/// <summary>
/// Gets or sets whether the color is lighter or darker.
/// Gets or sets whether the color is lighter or darker. Can be used to help with colorblind stuff.
/// </summary>
public CustomColorBrightness ColorBrightness
{
get => colorBrightness;
[Obsolete("Use the constructor to set ColorBrightness instead. This will be removed in a future version.")]
set => colorBrightness = value;
}
public CustomColorBrightness ColorBrightness { get; set; } = CustomColorBrightness.Darker;
internal string? RawId = rawId;
internal Color InternalMainColor = mainColor;
internal Color InternalShadowColor = shadowColor;
/// <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(StringNames name, Color32 mainColor)
: this(name, mainColor, mainColor.DarkenAbsolute(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)
: this(name, mainColor, mainColor.DarkenAbsolute(60))
{
}
/// <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)
/// <inheritdoc cref="CustomColor"/>
public CustomColor(string name, Color32 mainColor, Color32 shadowColor)
: this(MiraLocaleManager.GetOrCreateLocaleString(name), mainColor, shadowColor)
{
}
}
+4 -52
View File
@@ -1,11 +1,7 @@
using System;
using System.Collections.Generic;
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;
@@ -20,8 +16,9 @@ public static class PaletteManager
/// </summary>
public static CustomColor[] RegisteredColors => [.. CustomColors];
private static readonly List<CustomColor> CustomColors = [];
private static readonly HashSet<StringNames> VariableColorNames = [];
internal static readonly List<CustomColor> CustomColors = [];
internal static readonly HashSet<StringNames> VariableColorNames = [];
private static readonly CustomColorBrightness[] ColorBrightnessMap =
[
CustomColorBrightness.Darker, // Red
@@ -46,49 +43,6 @@ 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;
@@ -96,9 +50,7 @@ public static class PaletteManager
var colors = CustomColors.Select(x => x.MainColor).ToArray();
var shadowColors = CustomColors.Select(x => x.ShadowColor).ToArray();
var stringNames = CustomColors.Select(x => x.Name).ToArray();
var newColorId = originalLength;
foreach (var color in CustomColors)
{
color.ColorId = newColorId++;
@@ -5,20 +5,5 @@ 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(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)
{
}
}
public class RegisterCustomColorsAttribute : Attribute;
+17 -109
View File
@@ -1,5 +1,6 @@
using System;
using MiraAPI.LocalSettings;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
@@ -8,133 +9,40 @@ namespace MiraAPI.Colors;
/// <summary>
/// Represents a dynamic custom color that changes over time.
/// </summary>
/// <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="name">The name of the color.</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>
/// <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)
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)).DarkenAbsolute(60))
{
/// <summary>
/// Gets a delegate that takes in a time value and returns the dynamic main color.
/// Gets or sets a delegate that takes in a time value and returns the dynamic main color.
/// </summary>
public Func<float, Color> MainEvaluator => mainEvaluator;
public Func<float, Color> MainEvaluator { get; set; } = mainEvaluator;
/// <summary>
/// Gets a delegate that takes in a time value and returns the dynamic shadow color.
/// Gets or sets a delegate that takes in a time value and returns the dynamic shadow color.
/// </summary>
public Func<float, Color> ShadowEvaluator { get; } = shadowEvaluator ?? (t => mainEvaluator(t).DarkenAbsolute(0.24f));
public Func<float, Color> ShadowEvaluator { get; set; } = shadowEvaluator ?? (t => mainEvaluator(t).DarkenAbsolute(0.24f));
/// <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(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,
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, 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(
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)
/// <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)
{
}
@@ -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 => button;
public T Button { get; } = 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 => button;
public CustomActionButton Button { get; } = 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 => button;
public T Button { get; } = button;
/// <summary>
/// Gets the generic <see cref="MiraButtonClickEvent"/> that is invoked before this button-specific event.
/// </summary>
public MiraButtonClickEvent GenericClickEvent => genericClickEvent;
public MiraButtonClickEvent GenericClickEvent { get; } = 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 => button;
public CustomActionButton Button { get; } = 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 => topUiRow;
public GameObject MainTopUiRow { get; } = topUiRow;
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the second top UI row.
/// </summary>
public GameObject SecondTopUiRow => secondUiRow;
public GameObject SecondTopUiRow { get; } = secondUiRow;
}
+4 -31
View File
@@ -3,8 +3,7 @@
namespace MiraAPI.Events;
/// <summary>
/// Wrapper for <see cref="MiraEvent"/> handlers.
/// Also used when unregistering a <see cref="MiraEvent"/>.
/// Event handle to use when unregistering a <see cref="MiraEvent"/>.
/// </summary>
public class MiraEventHandle
{
@@ -13,37 +12,11 @@ public class MiraEventHandle
/// </summary>
public Type EventType { get; }
/// <summary>
/// Gets the priority of the handler. Lower values are called first.
/// </summary>
public int Priority { get; }
internal MiraEventWrapper EventWrapper { get; }
/// <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)
internal MiraEventHandle(Type type, MiraEventWrapper eventWrapper)
{
EventHandler = eventHandler;
Priority = priority;
EventType = type;
InvokeOnSubtype = invokeOnSubtype;
}
internal bool IsTriggeredBy(Type type)
{
if (InvokeOnSubtype)
{
return EventType.IsAssignableTo(type);
}
return EventType == type;
EventWrapper = eventWrapper;
}
}
+51 -265
View File
@@ -1,10 +1,6 @@
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;
@@ -13,21 +9,7 @@ namespace MiraAPI.Events;
/// </summary>
public static class MiraEventManager
{
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;
private static readonly Dictionary<Type, List<MiraEventWrapper>> EventWrappers = [];
/// <summary>
/// Invoke a <see cref="MiraEvent"/>.
@@ -38,7 +20,26 @@ public static class MiraEventManager
public static bool InvokeEvent<T>(this T eventInstance)
where T : MiraEvent
{
return eventInstance.InvokeEvent(typeof(T));
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}");
}
}
return true;
}
/// <summary>
@@ -49,27 +50,14 @@ 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)
{
var trackedType = type.GetTrackedType();
var callableHandlers = new List<MiraEventHandle>();
EventWrappers.TryGetValue(type, out var handlers);
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)
if (handlers == null || handlers.Count == 0)
{
return false;
}
callableHandlers.Sort(EventComparer);
foreach (var handler in callableHandlers)
foreach (var handler in handlers)
{
try
{
@@ -84,110 +72,35 @@ public static class MiraEventManager
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, bool invokeOnSubtype)
public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, int priority = 0)
{
if (!type.IsAssignableTo(typeof(MiraEvent)))
if (!type.IsSubclassOf(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);
return RegisterEventHandler(type, @delegate, priority, invokeOnSubtype);
}
var eventWrapper = new MiraEventWrapper(@delegate, priority);
/// <inheritdoc cref="RegisterEventHandler(Type, MethodInfo, int, bool)"/>
public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, int priority)
{
return RegisterEventHandler(type, methodInfo, priority, false);
}
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, bool invokeOnSubtype)
{
return RegisterEventHandler(type, methodInfo, 0, invokeOnSubtype);
}
if (index < 0)
{
index = ~index;
}
/// <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);
handlers.Insert(index, eventWrapper);
return new MiraEventHandle(type, eventWrapper);
}
/// <summary>
@@ -195,87 +108,25 @@ 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, bool invokeOnSubtype)
public static MiraEventHandle RegisterEventHandler<T>(Action<T> handler, int priority = 0)
where T : MiraEvent
{
return RegisterEventHandler(typeof(T), handler, priority, invokeOnSubtype);
}
EventWrappers.TryAdd(typeof(T), []);
/// <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 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, bool invokeOnSubtype)
where T : MiraEvent
{
return RegisterEventHandler(handler, 0, invokeOnSubtype);
}
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)
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)
if (index < 0)
{
return type.GetGenericTypeDefinition();
index = ~index;
}
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);
}
handlers.Insert(index, eventWrapper);
return new MiraEventHandle(typeof(T), eventWrapper);
}
/// <summary>
@@ -285,86 +136,21 @@ 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 (!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))
if (!EventWrappers.TryGetValue(eventHandle.EventType, out var handlers))
{
return false;
}
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)
if (!handlers.Remove(eventHandle.EventWrapper))
{
return false;
}
foreach (var method in type.GetMethods(MiraPluginManager.DeclaredStaticMembers))
if (handlers.Count == 0)
{
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);
EventWrappers.Remove(eventHandle.EventType);
}
return hasContainerAttribute;
return true;
}
}
+2 -3
View File
@@ -7,16 +7,15 @@ 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 => eventHandler;
public Delegate EventHandler { get; } = eventHandler;
/// <summary>
/// Gets the priority of the handler. Lower values are called first.
/// </summary>
public int Priority => priority;
public int Priority { get; } = priority;
}
+2 -27
View File
@@ -6,36 +6,11 @@ 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, bool invokeOnSubtype) : Attribute
public class RegisterEventAttribute(int priority = 0) : Attribute
{
/// <summary>
/// Gets the priority of the event. Lower values are called first.
/// </summary>
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)
{
}
public int Priority { get; } = priority;
}
@@ -1,9 +0,0 @@
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 => source;
public PlayerControl Source { get; } = source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was killed.
/// </summary>
public PlayerControl Target => target;
public PlayerControl Target { get; } = target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was framed, if any.
/// </summary>
public PlayerControl? Framed => framed;
public PlayerControl? Framed { get; } = 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 => isIndirect;
public bool IsIndirectAttack { get; } = 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 => ignoreDefense;
public bool IgnoreDefense { get; } = ignoreDefense;
/// <summary>
/// Gets the <see cref="Target"/>'s <see cref="DeadBody"/>, if it exists.
/// </summary>
public DeadBody? DeadBody => deadBody;
public DeadBody? DeadBody { get; } = 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 => reason;
public GameOverReason Reason { get; } = reason;
}
@@ -17,22 +17,17 @@ 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 => source;
public PlayerControl Source { get; } = source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being killed.
/// </summary>
public PlayerControl Target => target;
public PlayerControl Target { get; } = target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being framed, if any.
/// </summary>
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;
public PlayerControl? Framed { get; } = framed;
/// <summary>
/// Gets or sets a value indicating whether the murder is done indirectly.
@@ -45,6 +40,11 @@ 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 => triggeredByIntro;
public bool TriggeredByIntro { get; } = triggeredByIntro;
}
@@ -9,5 +9,5 @@ public class GameEndEvent(EndGameManager manager) : MiraEvent
/// <summary>
/// Gets the <see cref="global::EndGameManager"/> instance.
/// </summary>
public EndGameManager EndGameManager => manager;
public EndGameManager EndGameManager { get; } = manager;
}
@@ -9,5 +9,5 @@ public class IntroBeginEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene => introCutscene;
public IntroCutscene IntroCutscene { get; } = introCutscene;
}
@@ -9,5 +9,5 @@ public class IntroEndEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene => introCutscene;
public IntroCutscene IntroCutscene { get; } = introCutscene;
}
@@ -9,5 +9,5 @@ public class IntroRoleRevealEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene => introCutscene;
public IntroCutscene IntroCutscene { get; } = 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 => triggeredByIntro;
public bool TriggeredByIntro { get; } = 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 => player;
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the role that the player was set to.
/// </summary>
public RoleTypes Role => role;
public RoleTypes Role { get; } = role;
}
@@ -2,6 +2,20 @@
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>
@@ -11,5 +25,5 @@ public sealed class VanillaButtonCancelledEvent(AbilityButton button) : MiraEven
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> whose click was cancelled.
/// </summary>
public AbilityButton Button => button;
public AbilityButton Button { get; } = button;
}
@@ -2,6 +2,26 @@
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>
@@ -13,15 +33,15 @@ public sealed class VanillaButtonClickEvent(AbilityButton button, PlayerControl?
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public AbilityButton Button => button;
public AbilityButton Button { get; } = button;
/// <summary>
/// Gets the target <see cref="PlayerControl"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public PlayerControl? PlayerTarget => playerTarget;
public PlayerControl? PlayerTarget { get; } = playerTarget;
/// <summary>
/// Gets the target <see cref="Vent"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public Vent? VentTarget => ventTarget;
public Vent? VentTarget { get; } = 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 => room;
public SystemTypes Room { get; } = room;
}
@@ -9,5 +9,5 @@ public class PlayerOpenSabotageEvent(MapBehaviour mapBehaviour) : MiraCancelable
/// <summary>
/// Gets the <see cref="global::MapBehaviour"/>.
/// </summary>
public MapBehaviour MapBehaviour => mapBehaviour;
public MapBehaviour MapBehaviour { get; } = 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 => systemType;
public SystemTypes SystemType { get; } = systemType;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is updating the system.
/// </summary>
public PlayerControl Player => player;
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the byte amount the system is being updated by.
/// </summary>
public byte Amount => amount;
public byte Amount { get; } = amount;
}
@@ -9,5 +9,5 @@ public class EjectionEvent(ExileController controller) : MiraEvent
/// <summary>
/// Gets the <see cref="global::ExileController"/> instance.
/// </summary>
public ExileController ExileController => controller;
public ExileController ExileController { get; } = controller;
}
@@ -3,11 +3,10 @@
/// <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 => meetingHud;
public MeetingHud MeetingHud { get; } = 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 => reporter;
public PlayerControl Reporter { get; } = reporter;
/// <summary>
/// Gets the player that is being reported. Will be <see langword="null"/> for emergency meeting.
/// </summary>
public NetworkedPlayerInfo? Target => target;
public NetworkedPlayerInfo? Target { get; } = target;
/// <summary>
/// Gets the <see cref="DeadBody"/> that is being reported. Will be <see langword="null"/> for emergency meeting.
/// </summary>
public DeadBody? Body => body;
public DeadBody? Body { get; } = body;
}
@@ -10,5 +10,5 @@ public class StartMeetingEvent(MeetingHud meetingHud) : MiraEvent
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud => meetingHud;
public MeetingHud MeetingHud { get; } = 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 => playerVoteArea;
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player => voter;
public PlayerControl Player { get; } = 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 => playerVoteArea;
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player => voter;
public PlayerControl Player { get; } = 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 => isVotingComplete;
public bool IsVotingComplete { get; } = 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; } = false;
public bool ForceEndVoting { get; set; }
}
@@ -13,7 +13,7 @@ public class DummyVoteEvent(DummyBehaviour dummy) : MiraCancelableEvent
/// <summary>
/// Gets the dummy that needs to vote.
/// </summary>
public DummyBehaviour Dummy => dummy;
public DummyBehaviour Dummy { get; } = dummy;
/// <summary>
/// Gets the instance of the dummy's <see cref="PlayerVoteData"/>.
@@ -17,18 +17,23 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData => playerVoteData;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public byte TargetId => targetId;
public PlayerVoteData VoteData { get; } = playerVoteData;
/// <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>
@@ -38,9 +43,4 @@ 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 => playerVoteData;
public PlayerVoteData VoteData { get; } = playerVoteData;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public int TargetId => targetId;
public int TargetId { get; } = 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 => votes;
public List<CustomVote> Votes { get; } = 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 CustomVote[] originalVotes = [.. votes];
private readonly List<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 => votes;
public List<CustomVote> Votes { get; } = votes;
/// <summary>
/// Gets or sets a value indicating whether an overruling was done. Normally set by judge but can be overwritten.
@@ -48,9 +48,6 @@ 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 => meetingHud;
public MeetingHud MeetingHud { get; } = 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 => player;
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task => task;
public PlayerTask Task { get; } = task;
/// <summary>
/// Gets the instance of the <see cref="HideAndSeekManager"/> attached to the game.
/// </summary>
public HideAndSeekManager HnsManager => hnsManager;
public HideAndSeekManager HnsManager { get; } = 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 => player;
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task => task;
public PlayerTask Task { get; } = task;
}
@@ -11,15 +11,15 @@ public class PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody
/// <summary>
/// Gets the player who died.
/// </summary>
public PlayerControl Player => player;
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the reason the player died.
/// </summary>
public DeathReason DeathReason => reason;
public DeathReason DeathReason { get; } = reason;
/// <summary>
/// Gets the <see cref="global::DeadBody"/> associated with the player, if any.
/// </summary>
public DeadBody? DeadBody => deadBody;
public DeadBody? DeadBody { get; } = deadBody;
}
@@ -11,5 +11,5 @@ public class PlayerJoinEvent(ClientData data) : MiraEvent
/// <summary>
/// Gets the player who joined.
/// </summary>
public ClientData ClientData => data;
public ClientData ClientData { get; } = data;
}
@@ -12,10 +12,10 @@ public class PlayerLeaveEvent(ClientData data, DisconnectReasons reason) : MiraE
/// <summary>
/// Gets the player who left.
/// </summary>
public ClientData ClientData => data;
public ClientData ClientData { get; } = data;
/// <summary>
/// Gets the reason why the player left.
/// </summary>
public DisconnectReasons Reason => reason;
public DisconnectReasons Reason { get; } = 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 => player;
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is entering.
/// </summary>
public Vent? Vent => vent;
public Vent? Vent { get; } = 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 => player;
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is exiting.
/// </summary>
public Vent? Vent => vent;
public Vent? Vent { get; } = 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 => usable;
public IUsable Usable { get; } = usable;
/// <summary>
/// Gets a value indicating whether the <see cref="Usable"/> is a <see cref="Console"/>, <see cref="MapConsole"/>, or <see cref="SystemConsole"/>.
+13 -7
View File
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.PluginLoading;
namespace MiraAPI.GameEnd;
@@ -15,26 +14,33 @@ public static class GameOverManager
private static int nextId = Enum.GetNames<GameOverReason>().Length;
internal static bool RegisterGameOver(Type type, in MiraPluginManager.RegistrationContext _)
/// <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)
{
if (!typeof(CustomGameOver).IsAssignableFrom(type))
if (!typeof(CustomGameOver).IsAssignableFrom(gameOverType))
{
return false;
}
if (type.IsAbstract)
if (gameOverType.IsAbstract)
{
Error("The type must not be abstract.");
return false;
}
if (type.GetConstructor(Type.EmptyTypes) == null)
if (gameOverType.GetConstructor(Type.EmptyTypes) == null)
{
Error("The type must have a parameterless constructor.");
return false;
}
GameOverIds.Add(type, nextId);
GameOverTypes.Add(nextId, type);
GameOverIds.Add(gameOverType, nextId);
GameOverTypes.Add(nextId, gameOverType);
nextId++;
return true;
}
-2
View File
@@ -77,8 +77,6 @@ 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>
+30 -19
View File
@@ -12,33 +12,41 @@ public static class CustomGameModeManager
{
internal static readonly Dictionary<uint, AbstractGameMode> IdToModeMap = [];
private static uint lastId;
private static uint GetNextId()
{
return ++lastId;
return ++LastId;
}
internal static bool RegisterGameMode(Type type, in MiraPluginManager.RegistrationContext context)
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)
{
if (!typeof(AbstractGameMode).IsAssignableFrom(type))
if (!typeof(AbstractGameMode).IsAssignableFrom(gameModeType))
{
Warning($"{gameModeType.Name} does not inherit CustomGameMode!");
return false;
}
if (Activator.CreateInstance(type) is not AbstractGameMode mode)
var instance = Activator.CreateInstance(gameModeType);
if (instance is not AbstractGameMode mode)
{
Error($"Failed to create instance of {type.Name}");
Error($"Failed to create instance of {gameModeType.Name}");
return false;
}
if (mode.HideMode)
return true;
var id = GetNextId();
mode.ID = id;
IdToModeMap.Add(id, mode);
context.PluginInfo.GameModes.Add(id, mode);
IdToModeMap.Add(GetNextId(), mode);
pluginInfo.GameModes.Add(LastId, mode);
mode.ID = LastId;
GameModeOption.AddOption(mode);
return true;
}
@@ -99,31 +107,34 @@ public static class CustomGameModeManager
internal static void RegisterDefaultMode()
{
var defaultMode = new ClassicMode { ID = 0 };
var defaultMode = new ClassicMode();
IdToModeMap.Add(0, defaultMode);
GameModeOption.AddOption(defaultMode);
var hnsMode = new HideAndSeekMode() { ID = 1 };
// no need to add to game mode option as it already contains it
// because we cannot have the option be created with no values
defaultMode.ID = 0;
var hnsMode = new HideAndSeekMode();
if (hnsMode.HideMode)
return;
IdToModeMap.Add(1, hnsMode);
hnsMode.ID = 1;
GameModeOption.AddOption(hnsMode);
lastId++;
LastId++;
}
internal static void GetAndSetGameMode()
{
var index = GameModeOption.Value;
var id = (uint)GameModeOption.Value;
if ((uint)index < (uint)GameModeOption.Values.Count)
if (IdToModeMap.TryGetValue(id, out var mode))
{
ActiveMode = GameModeOption.Values[index];
ActiveMode = mode;
return;
}
ActiveMode = IdToModeMap[0];
Warning($"Unable to find game mode at index {index}!");
Warning($"Unable to find game mode of id {id}!");
}
}
+82 -29
View File
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Networking;
@@ -16,8 +17,6 @@ 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>
@@ -26,63 +25,116 @@ 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 List<AbstractGameMode> Values = [];
internal static readonly Dictionary<uint, StringNames> Values = new()
{
[0] = MiraLocaleManager.GetOrCreateLocaleString("MiraApi.Gamemode.Classic"),
};
internal static StringOption OptionBehaviour = null!;
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 int LastValue;
internal static void AddOption(AbstractGameMode mode)
{
mode.StringName = MiraLocaleManager.GetOrCreateLocaleString(mode.Name);
Values.Add(mode);
if (!Values.ContainsKey(mode.ID))
Values.Add(mode.ID, MiraLocaleManager.GetOrCreateLocaleString(mode.Name));
}
/*[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.CreateSettings))]
[HarmonyPostfix]
private static void CreateSettingsPatch(GameOptionsMenu __instance)
{
if (MenuState.Instance.CurrentModIdx != 0 || GameManager.Instance.IsHideAndSeek() || CustomGameModeManager.ActiveMode == null)
{
return;
}
var num = 0.713f;
foreach (var category in __instance.settingsContainer.GetComponentsInChildren<CategoryHeaderMasked>())
{
if (category)
category.gameObject.transform.localPosition -= new Vector3(0, 1.3f, 0);
}
CategoryHeaderMasked categoryHeaderMasked = Object.Instantiate(__instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer);
categoryHeaderMasked.SetHeader(CustomName, 20);
categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f;
categoryHeaderMasked.transform.localPosition = new Vector3(-0.903f, num, -2f);
OptionBehaviour = Object.Instantiate(
__instance.stringOptionOrigin,
Vector3.zero,
Quaternion.identity,
__instance.settingsContainer);
num -= 0.63f;
OptionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f);
OptionBehaviour.SetClickMask(__instance.ButtonClickMask);
StringGameSetting setting = ScriptableObject.CreateInstance<StringGameSetting>();
setting.Type = OptionTypes.MultipleChoice;
setting.Title = GamemodeName;
setting.Index = _lastValue;
setting.Values = new Il2CppStructArray<StringNames>([Values[0]]);
OptionBehaviour.SetUpFromData(setting, 20);
Set(_lastValue);
OptionBehaviour.TitleText.fontSize = 3;
foreach (var optionBehaviour in __instance.Children.ToArray().Skip(1))
{
optionBehaviour.gameObject.transform.localPosition -= new Vector3(0, 1.3f, 0);
}
__instance.Children.Add(OptionBehaviour);
for (var i = 1; i < Values.Count; i++)
OptionBehaviour.Values = (Il2CppStructArray<StringNames>)OptionBehaviour.Values.Add(Values.ElementAt(i).Value);
__instance.scrollBar.SetYBoundsMax(__instance.scrollBar.GetYBounds().max + 1);
}*/
internal static void Set(int val)
{
Value = val;
var previousMode = CustomGameModeManager.ActiveMode;
CustomGameModeManager.GetAndSetGameMode();
HudPatches.SetGameModeText(Values[LastValue].ColoredName);
HudPatches.SetGameModeText(CustomGameModeManager.GetMode(Values.ElementAt(LastValue).Key).ColoredName);
var gm = CustomGameModeManager.ActiveMode!;
if (gm == previousMode)
return;
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
GamemodeName,
gm.ColoredName,
new Color(0.7333f, 0.7333f, 0.7333f, 1),
gm.TmpIcon);
if (MenuState.Instance)
if (gm != previousMode)
{
// should force reset roles for gamemodes properly
foreach (var roleMenu in MenuState.Instance.QueuedRoleMenuRefresh)
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
GamemodeName,
gm.ColoredName,
new Color(0.7333f, 0.7333f, 0.7333f, 1),
gm.TmpIcon);
if (MenuState.Instance)
{
MenuState.Instance.QueuedRoleMenuRefresh[roleMenu.Key] = true;
// should force reset roles for gamemodes properly
foreach (var roleMenu in MenuState.Instance.QueuedRoleMenuRefresh)
{
MenuState.Instance.QueuedRoleMenuRefresh[roleMenu.Key] = true;
}
}
GameOptionsMenuPatch.RefreshForGameMode();
RoleGuidePatches.RefreshSettingsForGameMode();
}
GameOptionsMenuPatch.RefreshForGameMode();
RoleGuidePatches.RefreshSettingsForGameMode();
// TODO: could make Values a dict of AbstractGameMode too
}
[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.ValueChanged))]
@@ -99,7 +151,8 @@ public static class GameModeOption
}
[MethodRpc((uint)MiraRpc.SyncGamemodeOption)]
internal static void RpcSyncGamemode(PlayerControl _, int data)
[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)
{
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);
var list2 = list.ToArray()
List<NetworkedPlayerInfo> list2 = [.. list.ToArray()
.Where(c => c.Character != null && c.Character.Data != null && !c.Character.Data.Disconnected &&
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data).ToList();
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data)];
foreach (var networkedPlayerInfo in GameData.Instance.AllPlayers)
{
+13 -16
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Modifiers;
@@ -18,31 +19,16 @@ 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 => children;
public ReadOnlyCollection<IModdedOption> Children => new(Options);
/// <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>
@@ -54,6 +40,14 @@ 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>
@@ -160,6 +154,9 @@ 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.IsDefined<SearchPrivateAttribute>();
var canSearchPrivates = type.GetCustomAttribute<SearchPrivateAttribute>() != null;
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.IsDefined<InstanceGetterAttribute>() && method.Name != "GetInstance"))
if (method.GetParameters().Length > 0 || (method.GetCustomAttribute<InstanceGetterAttribute>() == null && 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.IsDefined<InstanceGetterAttribute>() && prop.Name != "Instance")
if (prop.GetCustomAttribute<InstanceGetterAttribute>() == null && 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.IsDefined<SearchPrivateAttribute>())
else if (type.GetCustomAttribute<SearchPrivateAttribute>() != null)
{
flags |= BindingFlags.NonPublic;
}
var member = type.GetMember(MemberName, flags).OrderBy(GetGenericArgsLength).FirstOrDefault();
var member = type.GetMember(MemberName, flags).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,33 +261,7 @@ 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)
{
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;
return ResolveMember(group, property, out type, out instanceGetter, out notFound) as MethodInfo;
}
/// <summary>
@@ -299,7 +273,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>
@@ -372,7 +346,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 var type, out var instanceGetter, out var notFound) is not { } member)
if (ResolveMember(group, property, out Type type, out var instanceGetter, out var notFound) is not { } member)
{
if (notFound)
Error($"Member {MemberName} does not exist in {type.FullName}");
@@ -6,12 +6,10 @@ 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;
@@ -1,20 +0,0 @@
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,49 +9,14 @@ 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)]
[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)
public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? values = null)
: ModdedOptionAttribute(title)
{
/// <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)
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
}
/// <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;
var opt = new ModdedEnumOption(Title, (int)(value ?? 0), enumType, values);
return opt;
}
@@ -67,7 +32,7 @@ public class ModdedEnumOptionAttribute(string? title, Type enumType, string idPr
{
return HolderOption is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedEnumOption with enum type {enumType.FullName}");
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {enumType.FullName} is not a ModdedEnumOption");
}
}
@@ -76,62 +41,30 @@ public class ModdedEnumOptionAttribute(string? title, Type enumType, string idPr
/// </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 idPrefix, string[]? values = null)
: ModdedOptionAttribute(title), ITypedOption<T>
public class ModdedEnumOptionAttribute<T>(string title, string[]? values = null)
: ModdedOptionAttribute(title)
where T : struct, Enum
{
/// <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)
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
}
/// <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;
var opt = new ModdedEnumOption<T>(Title, (T)(value ?? 0), values);
return opt;
}
/// <inheritdoc />
public override void SetValue(object value)
{
SetValueUnboxed((T)value);
}
/// <inheritdoc />
public void SetValueUnboxed(T value)
{
(HolderOption as ModdedEnumOption<T>)?.SetValue(value);
var opt = HolderOption as ModdedEnumOption<T>;
opt?.SetValue((T)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}\" is not a ModdedEnumOption<{typeof(T).Name}>");
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {typeof(T).FullName} 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,32 +28,8 @@ public class ModdedNumberOptionAttribute(
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool halfIncrements = false)
: ModdedOptionAttribute(title), ITypedOption<int>, ITypedOption<float>
: ModdedOptionAttribute(title)
{
/// <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>
@@ -65,7 +41,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,
@@ -76,27 +52,7 @@ public class ModdedNumberOptionAttribute(
{
}
/// <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)
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
var final = value switch
{
@@ -105,9 +61,8 @@ public class ModdedNumberOptionAttribute(
_ => (float)value,
};
var opt = new ModdedNumberOption(
group.GroupPrefix,
Title ?? property.Name,
return new ModdedNumberOption(
Title,
final,
min,
max,
@@ -117,8 +72,6 @@ public class ModdedNumberOptionAttribute(
suffixType,
formatString,
halfIncrements);
Title = opt.Title;
return opt;
}
/// <inheritdoc />
@@ -135,18 +88,6 @@ 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()
{
@@ -156,22 +97,8 @@ public class ModdedNumberOptionAttribute(
var value = opt.Value;
if (ValueType == typeof(int))
return (int)MathF.Round(value, MidpointRounding.AwayFromZero);
return (int)MathF.Round(value);
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,5 +1,4 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace MiraAPI.GameOptions.Attributes;
@@ -11,27 +10,25 @@ 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)]
[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
public abstract class ModdedOptionAttribute(string title, Type? roleType = null, Type? modeType = null) : PropertyOptionAttribute
{
internal IModdedOption? HolderOption;
internal Type ValueType;
internal IModdedOption? HolderOption { get; set; }
internal Type ValueType { get; set; }
/// <summary>
/// Gets the title of the option.
/// </summary>
public string Title => title;
/// <summary>
/// Gets the role type of the option.
/// </summary>
protected Type? RoleType => roleType;
protected Type? RoleType { get; private set; } = roleType;
/// <summary>
/// Gets the game mode type of the option.
/// </summary>
protected Type? ModeType => modeType;
protected Type? ModeType { get; private set; } = modeType;
/// <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);
internal abstract IModdedOption? CreateOption(object? value, PropertyInfo property);
}
@@ -10,23 +10,15 @@ 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), ITypedOption<int>, ITypedOption<NetworkedPlayerInfo?>
public class ModdedPlayerOptionAttribute(
string title,
bool allowNone = true)
: ModdedOptionAttribute(title)
{
/// <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)
internal override IModdedOption? CreateOption(object? value, PropertyInfo property)
{
}
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;
var option = new ModdedPlayerOption(Title, allowNone);
return option;
}
/// <inheritdoc />
@@ -38,23 +30,7 @@ public class ModdedPlayerOptionAttribute(string? title, bool allowNone = true)
if (ValueType == typeof(int))
return opt.Value;
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.");
return opt.SelectedPlayer!;
}
/// <inheritdoc />
@@ -65,32 +41,9 @@ public class ModdedPlayerOptionAttribute(string? title, bool allowNone = true)
var final = value switch
{
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : -1,
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0),
_ => (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,33 +10,19 @@ 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), ITypedOption<string>
public class ModdedStringOptionAttribute(
string title,
string[] values)
: ModdedOptionAttribute(title)
{
/// <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)
internal override IModdedOption? CreateOption(object? value, PropertyInfo property)
{
}
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;
var option = new ModdedStringOption(Title, (string)(value ?? string.Empty), values);
return option;
}
/// <inheritdoc />
public override object GetValue()
{
return GetValueUnboxed();
}
/// <inheritdoc />
public string GetValueUnboxed()
{
return HolderOption is ModdedStringOption opt
? opt.Value
@@ -46,12 +32,7 @@ public class ModdedStringOptionAttribute(string? title, string[] values)
/// <inheritdoc />
public override void SetValue(object value)
{
SetValueUnboxed((string)value);
}
/// <inheritdoc />
public void SetValueUnboxed(string value)
{
(HolderOption as ModdedStringOption)?.SetValue(value);
var opt = HolderOption as ModdedStringOption;
opt?.SetValue((string)value);
}
}
@@ -11,64 +11,36 @@ 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), ITypedOption<bool>
public class ModdedToggleOptionAttribute(
string title,
string on,
string off)
: ModdedOptionAttribute(title)
{
/// <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)
// ReSharper disable once IntroduceOptionalParameters.Global (Justification: Kept for backwards compatibility.)
public ModdedToggleOptionAttribute(string title)
: this(title, "On", "Off")
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionAttribute"/> class.
/// </summary>
public ModdedToggleOptionAttribute()
: this(null, "On", "Off")
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
}
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;
var toggleOpt = new ModdedToggleOption(Title, (bool)(value ?? false), on, off);
return toggleOpt;
}
/// <inheritdoc />
public override void SetValue(object value)
{
SetValueUnboxed((bool)value);
}
/// <inheritdoc />
public void SetValueUnboxed(bool value)
{
(HolderOption as ModdedToggleOption)?.SetValue(value);
var opt = HolderOption as ModdedToggleOption;
opt?.SetValue((bool)value);
}
/// <inheritdoc />
public override object GetValue()
{
return GetValueUnboxed();
}
/// <inheritdoc />
public bool GetValueUnboxed()
{
return HolderOption is ModdedToggleOption opt
? opt.Value
@@ -1,22 +0,0 @@
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,49 +10,15 @@ 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)]
[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)
public class ModdedEnumOptionListAttribute(string title, Type enumType, string[]? values = null)
: ModdedOptionListAttribute(title)
{
/// <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)
internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
var optList = new ModdedOptionList<ModdedEnumOption>(
list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), (int)(list[idx] ?? 0), enumType, idPrefix, values));
value.Count, idx => new(GetFormattedTitle(idx), (int)(value[idx] ?? 0), enumType, values));
return optList;
}
@@ -68,7 +34,7 @@ public class ModdedEnumOptionListAttribute(string? title, Type enumType, string
{
return HolderOptionList?.ElementAt(idx) is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
: throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedEnumOption with enum type {enumType.FullName}");
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {enumType.FullName} is not a ModdedEnumOption");
}
}
@@ -77,63 +43,31 @@ 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 idPrefix, string[]? values = null)
: ModdedOptionListAttribute(title), ITypedOptionList<T>
public class ModdedEnumOptionListAttribute<T>(string title, string[]? values = null)
: ModdedOptionListAttribute(title)
where T : struct, Enum
{
/// <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)
internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
var optList = new ModdedOptionList<ModdedEnumOption<T>>(
list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), (T)(list[idx] ?? 0), idPrefix, values));
value.Count, idx => new(GetFormattedTitle(idx), (T)(value[idx] ?? 0), values));
return optList;
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
SetValueUnboxed(idx, (T)value);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, T value)
{
(HolderOptionList?.ElementAt(idx) as ModdedEnumOption<T>)?.SetValue(value);
var opt = HolderOptionList?.ElementAt(idx) as ModdedEnumOption<T>;
opt?.SetValue((T)value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
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 \"{Titles[idx]}\" is not a ModdedEnumOption<{typeof(T).FullName}>");
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {typeof(T).FullName} 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,32 +29,8 @@ public class ModdedNumberOptionListAttribute(
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool halfIncrements = false)
: ModdedOptionListAttribute(title), ITypedOptionList<int>, ITypedOptionList<float>
: ModdedOptionListAttribute(title)
{
/// <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>
@@ -66,7 +42,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,
@@ -77,40 +53,19 @@ public class ModdedNumberOptionListAttribute(
{
}
/// <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)
internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
}
internal override IBaseModdedOptionList CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group)
{
return new ModdedOptionList<ModdedNumberOption>(list.Count, idx =>
return new ModdedOptionList<ModdedNumberOption>(value.Count, idx =>
{
var final = list[idx] switch
var final = value[idx] switch
{
null => min + increment,
int integer => integer,
_ => (float)list[idx]!,
_ => (float)value[idx]!,
};
return new(
group.GroupPrefix,
GetFormattedTitle(idx, property),
GetFormattedTitle(idx),
final,
min,
max,
@@ -137,43 +92,17 @@ 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?.ElementAt(idx) is not ModdedNumberOption opt)
throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedNumberOption");
throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedNumberOption");
var value = opt.Value;
if (ValueType == typeof(int))
return (int)MathF.Round(value, MidpointRounding.AwayFromZero);
return (int)MathF.Round(value);
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,24 +12,19 @@ namespace MiraAPI.GameOptions.Attributes;
/// </summary>
/// <param name="title">The title of the options.</param>
[AttributeUsage(AttributeTargets.Property)]
[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
public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAttribute
{
internal IBaseModdedOptionList? HolderOptionList;
internal IList? Value;
internal Type ValueType;
internal string[] Titles;
private static readonly Regex FormatParams = new(@"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout);
internal IBaseModdedOptionList? HolderOptionList { get; set; }
internal IList? Value { get; set; }
internal Type ValueType { get; set; }
/// <summary>
/// Gets or sets the title of the options.
/// Gets 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 { get; protected set; } = title;
public string Title => title;
/// <summary>
/// Sets the value of all the options.
@@ -73,33 +68,29 @@ public abstract class ModdedOptionListAttribute(string? title = null) : Property
/// <returns>The value of the option as an object.</returns>
public abstract object GetValue(int idx);
internal abstract IBaseModdedOptionList? CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group);
internal abstract IBaseModdedOptionList? CreateOptionList(IList value, PropertyInfo property);
/// <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>
protected string GetFormattedTitle(int index, PropertyInfo property)
[SuppressMessage("Globalization", "CA1305:Specify IFormatProvider", Justification = "I don't even know if this is worth it.")]
protected string GetFormattedTitle(int index)
{
var baseTitle = Title ??= property.Name;
return Titles[index] = GetFormattedTitle(baseTitle, index, FormatParams.Match(baseTitle));
}
var match = Regex.Match(Title.Translate(), @"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout);
private static string GetFormattedTitle(string baseTitle, int index, Match match)
{
if (!match.Success)
{
return baseTitle + index;
return Title + index;
}
if (match.Value == "{0}" && !match.NextMatch().Success)
{
return string.Format(CultureInfo.InvariantCulture, baseTitle, index);
return string.Format(Title, index);
}
Error($"ModdedOptionList Title of {baseTitle} cannot contain more than the first parameter for formatting.");
return baseTitle + index;
Error($"ModdedOptionList Title of {Title} cannot contain more than the first parameter for formatting.");
return Title + index;
}
}
@@ -11,21 +11,17 @@ 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), ITypedOptionList<int>, ITypedOptionList<NetworkedPlayerInfo?>
public class ModdedPlayerOptionListAttribute(
string title,
bool allowNone = true)
: ModdedOptionListAttribute(title)
{
/// <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)
internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
}
internal override IBaseModdedOptionList CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group)
{
return new ModdedOptionList<ModdedPlayerOption>(list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), allowNone));
return new ModdedOptionList<ModdedPlayerOption>(value.Count, idx =>
{
return new(GetFormattedTitle(idx), allowNone);
});
}
/// <inheritdoc />
@@ -36,60 +32,21 @@ public class ModdedPlayerOptionListAttribute(string? title, bool allowNone = tru
var final = value switch
{
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : -1,
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0),
_ => (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(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);
opt?.SetValue(final);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
if (HolderOptionList?.ElementAt(idx) is not ModdedPlayerOption opt)
throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedPlayerOption");
throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedPlayerOption");
if (ValueType == typeof(int))
return opt.Value;
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");
return opt.SelectedPlayer!;
}
}
@@ -2,6 +2,7 @@ using System;
using System.Collections;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
@@ -11,46 +12,31 @@ 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), ITypedOptionList<string>
public class ModdedStringOptionListAttribute(
string title,
string[] values)
: ModdedOptionListAttribute(title)
{
/// <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)
internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
}
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));
return new ModdedOptionList<ModdedStringOption>(value.Count, idx =>
{
return new ModdedStringOption(Title.Translate(), (string)(value[idx] ?? string.Empty), values);
});
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
SetValueUnboxed(idx, (string)value);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, string value)
{
(HolderOptionList?.ElementAt(idx) as ModdedStringOption)?.SetValue(value);
var opt = HolderOptionList?.ElementAt(idx) as ModdedStringOption;
opt?.SetValue((string)value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return GetValueUnboxed(idx);
}
/// <inheritdoc />
public string GetValueUnboxed(int idx)
{
return HolderOptionList?.ElementAt(idx) is ModdedStringOption opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedStringOption");
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedStringOption");
}
}
@@ -12,67 +12,40 @@ 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), ITypedOptionList<bool>
public class ModdedToggleOptionListAttribute(
string title,
string on,
string off)
: ModdedOptionListAttribute(title)
{
/// <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)
// ReSharper disable once IntroduceOptionalParameters.Global (Justification: Kept for backwards compatibility.)
public ModdedToggleOptionListAttribute(string title)
: this(title, "On", "Off")
{
}
/// <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)
internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
var optList = new ModdedOptionList<ModdedToggleOption>(
list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), (bool)(list[idx] ?? false), on, off));
value.Count, idx => new(GetFormattedTitle(idx), (bool)(value[idx] ?? false), on, off));
return optList;
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
SetValueUnboxed(idx, (bool)value);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, bool value)
{
(HolderOptionList?.ElementAt(idx) as ModdedToggleOption)?.SetValue(value);
var opt = HolderOptionList?.ElementAt(idx) as ModdedToggleOption;
opt?.SetValue((bool)value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return GetValueUnboxed(idx);
}
/// <inheritdoc />
public bool GetValueUnboxed(int idx)
{
return HolderOptionList?.ElementAt(idx) is ModdedToggleOption opt
? opt.Value
: throw new InvalidOperationException($"Holder option \"{Titles[idx]}\" is not a ModdedToggleOption.");
: throw new InvalidOperationException($"Holder option for {GetFormattedTitle(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 => builderType;
public string MethodName => methodName;
public Type BuilderType { get; } = builderType;
public string MethodName { get; } = methodName;
}
+1 -8
View File
@@ -1,7 +1,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
@@ -100,12 +99,6 @@ 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>
@@ -167,7 +160,7 @@ public interface IBaseModdedOptionList : IEnumerable
/// <inheritdoc cref="IReadOnlyCollection{T}.Count"/>
int Count { get; }
/// <inheritdoc cref="Enumerable.ElementAt{TSource}(IEnumerable{TSource}, int)"/>
/// <inheritdoc cref="System.Linq.Enumerable.ElementAt{TSource}(IEnumerable{TSource}, int)"/>
IModdedOption ElementAt(int index);
}
@@ -1,4 +1,3 @@
using System;
using System.Collections.Generic;
namespace MiraAPI.GameOptions;
@@ -7,7 +6,6 @@ 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>
@@ -19,6 +17,5 @@ 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();
}
@@ -1,35 +0,0 @@
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,7 +9,6 @@ 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)
{
@@ -1,21 +0,0 @@
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; }
}
+15 -86
View File
@@ -2,7 +2,6 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using MiraAPI.GameOptions.Attributes;
namespace MiraAPI.GameOptions;
@@ -11,22 +10,16 @@ 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, IModdedArrayBinding
public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList
{
private readonly T[] items;
private int version;
private ModdedOptionListAttribute? listAttribute;
private ITypedOptionList<T>? typedAttribute;
/// <inheritdoc/>
public int Count => items.Length;
/// <inheritdoc/>
bool ICollection<T>.IsReadOnly => true;
/// <inheritdoc/>
bool IList.IsReadOnly => false;
public bool IsReadOnly => false;
/// <inheritdoc/>
bool IList.IsFixedSize => true;
@@ -79,47 +72,17 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList, IModdedA
/// <param name="index">The index of the value.</param>
public T this[int index]
{
get
{
if (listAttribute == null)
return items[index];
return items[index] = typedAttribute != null
? typedAttribute.GetValueUnboxed(index)
: (T)listAttribute.GetValue(index);
}
get => ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute)
? (T)attribute.GetValue(index)
: items[index];
set
{
var old = items[index];
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);
}
if (ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute))
attribute.SetValue(index, value!);
else
{
listAttribute.SetValue(index, value!);
current = (T)listAttribute.GetValue(index);
}
items[index] = value;
items[index] = current;
if (!EqualityComparer<T>.Default.Equals(old, current))
version++;
version++;
}
}
@@ -133,21 +96,18 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList, IModdedA
/// <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);
}
@@ -157,47 +117,21 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList, IModdedA
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);
}
@@ -244,31 +178,31 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList, IModdedA
}
/// <inheritdoc/>
void IList<T>.Insert(int index, T item)
public void Insert(int index, T item)
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
/// <inheritdoc/>
void IList<T>.RemoveAt(int index)
public void RemoveAt(int index)
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
/// <inheritdoc/>
void ICollection<T>.Add(T item)
public void Add(T item)
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
/// <inheritdoc/>
void ICollection<T>.Clear()
public void Clear()
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
/// <inheritdoc/>
bool ICollection<T>.Remove(T item)
public bool Remove(T item)
{
throw new NotSupportedException("ModdedArray is of a fixed size.");
}
@@ -350,7 +284,7 @@ public static class ModdedArrayBuilder
/// <summary>
/// Creates a new <see cref="ModdedArray{T}"/> from a span of values.
/// </summary>
/// <typeparam name="T">The type of the values.</typeparam>
/// <typeparam name="T">The 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)
@@ -358,8 +292,3 @@ public static class ModdedArrayBuilder
return new(values);
}
}
internal interface IModdedArrayBinding
{
void Bind(ModdedOptionListAttribute attribute);
}
+124 -179
View File
@@ -4,10 +4,12 @@ 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;
@@ -23,27 +25,20 @@ namespace MiraAPI.GameOptions;
/// </summary>
public static class ModdedOptionsManager
{
private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> GetterLookup = [];
private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> SetterLookup = [];
private static readonly Dictionary<MethodBase, PropertyOptionAttribute> GetterLookups = [];
private static readonly Dictionary<MethodBase, PropertyOptionAttribute> SetterLookups = [];
private static readonly Dictionary<Type, AbstractOptionGroup> TypeToGroup = [];
private static readonly HashSet<PropertyInfo> OptionAttributes = [];
private static readonly HashSet<Type> Types = [];
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);
private static readonly HarmonyMethod CachedGetterPatch = new(typeof(ModdedOptionsManager), nameof(PropertyGetterPatch));
private static readonly HarmonyMethod CachedSetterPatch = new(typeof(ModdedOptionsManager), nameof(PropertySetterPatch));
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;
@@ -71,14 +66,26 @@ public static class ModdedOptionsManager
notif.SettingsChangeMessageLogic(key, item, playSound);
}
internal static bool RegisterGroup(Type type, in MiraPluginManager.RegistrationContext context)
internal static bool RegisterGroup(Type type)
{
if (!type.IsAssignableTo(typeof(AbstractOptionGroup)))
if (TypeToGroup.ContainsKey(type))
{
Error($"Group {type.Name} already exists.");
return false;
}
if (Activator.CreateInstance(type) is not AbstractOptionGroup group)
{
return false;
}
if (!Types.Add(type))
RegisterGroupInternal(group, type);
return true;
}
internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo)
{
if (TypeToGroup.ContainsKey(type))
{
Error($"Group {type.Name} already exists.");
return false;
@@ -101,106 +108,47 @@ public static class ModdedOptionsManager
}
}
var pluginInfo = context.PluginInfo;
pluginInfo.InternalOptionGroups.Add(group);
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.");
}
RegisterGroupInternal(group, type);
return true;
}
private static void PatchProperty(PropertyInfo property, Type propType, PropertyOptionAttribute attribute)
[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)
{
var handle = propType.TypeHandle;
ApplyPatch(handle, propType, ConcretisedGetters, GetterLookup, property.GetGetMethod(true), OpenGetterPatch, attribute);
ApplyPatch(handle, propType, ConcretisedSetters, SetterLookup, property.GetSetMethod(true), OpenSetterPatch, attribute);
Groups.Add(group);
TypeToGroup.Add(type, group);
typeof(OptionGroupSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
.SetValue(null, group);
}
private static void ApplyPatch(
RuntimeTypeHandle handle,
Type propType,
Dictionary<RuntimeTypeHandle, HarmonyMethod> concretised,
Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> lookup,
MethodInfo? toPatch,
MethodInfo patch,
PropertyOptionAttribute attribute)
internal static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (toPatch == null)
if (!TypeToGroup.TryGetValue(type, out var group))
{
Error($"Failed to get group for {type.Name}");
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(type, option, group, property.Name, pluginInfo);
RegisterOption(option, group, property.Name, pluginInfo);
}
private static void RegisterAttributeOption(
internal static void RegisterAttributeOption(
Type type,
AbstractOptionGroup group,
ModdedOptionAttribute attribute,
PropertyInfo property,
MiraPluginInfo pluginInfo,
Type propType,
object[] attributes)
MiraPluginInfo pluginInfo)
{
if (!OptionAttributes.Add(property))
{
@@ -208,7 +156,13 @@ public static class ModdedOptionsManager
return;
}
var option = attribute.CreateOption(property.GetValue(group), property, group);
if (!TypeToGroup.TryGetValue(type, out var group))
{
Error($"Failed to get group for {type.Name}");
return;
}
var option = attribute.CreateOption(property.GetValue(group), property);
if (option == null)
{
@@ -216,12 +170,24 @@ public static class ModdedOptionsManager
return;
}
PatchProperty(property, propType, attribute);
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;
}
attribute.HolderOption = option;
attribute.ValueType = propType;
attribute.ValueType = property.PropertyType;
foreach (var attr in attributes)
var customAttributes = property.GetCustomAttributes(false);
foreach (var attr in customAttributes)
{
switch (attr)
{
@@ -240,11 +206,17 @@ public static class ModdedOptionsManager
}
}
RegisterOption(type, option, group, property.Name, pluginInfo);
RegisterOption(option, group, property.Name, pluginInfo);
}
private static void RegisterPropertyOptionList(Type type, AbstractOptionGroup group, PropertyInfo property, MiraPluginInfo pluginInfo)
internal static void RegisterPropertyOptionList(Type type, 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 IBaseModdedOptionList optionList)
{
Error($"Failed to get option list for {property.Name}");
@@ -255,18 +227,15 @@ public static class ModdedOptionsManager
for (var i = 0; i < optionList.Count; i++)
{
RegisterOption(type, optionList.ElementAt(i), group, configName(i), pluginInfo);
RegisterOption(optionList.ElementAt(i), group, configName(i), pluginInfo);
}
}
private static void RegisterAttributeOptionList(
internal static void RegisterAttributeOptionList(
Type type,
AbstractOptionGroup group,
ModdedOptionListAttribute attribute,
PropertyInfo property,
MiraPluginInfo pluginInfo,
Type propType,
object[] attributes)
MiraPluginInfo pluginInfo)
{
if (!OptionAttributes.Add(property))
{
@@ -274,10 +243,9 @@ public static class ModdedOptionsManager
return;
}
if (!propType.IsGenericType || propType.GetGenericTypeDefinition() != typeof(ModdedArray<>))
if (!TypeToGroup.TryGetValue(type, out var group))
{
var typeName = propType.IsGenericType ? propType.GetGenericArguments()[0].Name : "T";
Error($"Please use ModdedArray<{typeName}> for modded option lists: {property.Name}");
Error($"Failed to get group for {type.Name}");
return;
}
@@ -289,11 +257,8 @@ public static class ModdedOptionsManager
return;
}
var list = (IList)propertyVal;
attribute.Titles = new string[list.Count];
var optionList = attribute.CreateOptionList(list, property, group);
var propertyList = (IList)propertyVal;
var optionList = attribute.CreateOptionList(propertyList, property);
if (optionList == null)
{
@@ -301,19 +266,44 @@ public static class ModdedOptionsManager
return;
}
PatchProperty(property, propType, attribute);
if (propertyList.Count != optionList.Count)
{
Error("Mismatch in count between values and created options.");
return;
}
var valueType = propType.GetGenericArguments()[0];
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;
}
attribute.HolderOptionList = optionList;
attribute.Value = list;
attribute.Value = propertyList;
attribute.ValueType = valueType;
((IModdedArrayBinding)propertyVal).Bind(attribute);
ListInstanceCache.Add(propertyVal, attribute);
var customAttributes = property.GetCustomAttributes(false);
Func<int, Delegate?>? visibilityFactory = null, getterFactory = null, setterFactory = null, changedFactory = null;
foreach (var attr in attributes)
foreach (var attr in customAttributes)
{
switch (attr)
{
@@ -337,7 +327,7 @@ public static class ModdedOptionsManager
var option = optionList.ElementAt(i);
if (visibilityFactory != null)
option.Visible = visibilityFactory(i) as Func<bool> ?? DelegateUtilities.AlwaysTrue;
option.Visible = (Func<bool>)(visibilityFactory(i) ?? DelegateUtilities.AlwaysTrue);
if (getterFactory != null)
option.Getter = getterFactory(i);
@@ -348,21 +338,22 @@ public static class ModdedOptionsManager
if (changedFactory != null)
option.ChangedEvent = changedFactory(i);
RegisterOption(type, option, group, property.Name + (i + 1), pluginInfo);
RegisterOption(option, group, property.Name + (i + 1), pluginInfo);
}
}
private static void RegisterOption(
Type type,
internal static void RegisterOption(
IModdedOption option,
AbstractOptionGroup group,
string propertyName,
MiraPluginInfo pluginInfo)
{
option.ConfigDefinition = new ConfigDefinition(type.FullName, propertyName);
var groupName = group.GetType().FullName;
option.ConfigDefinition = new ConfigDefinition(groupName, propertyName);
option.ParentGroup = group;
option.ParentMod = pluginInfo.MiraPlugin;
pluginInfo.InternalOptions.Add(option);
ModdedOptions.Add(option.Id, option);
group.Options.Add(option);
@@ -372,9 +363,9 @@ public static class ModdedOptionsManager
{
var chunks = ModdedOptions.Values.Select(option => option.GetNetData()).ChunkNetData(1000);
while (chunks.TryDequeue(out var netData))
while (chunks.Count > 0)
{
Rpc<SyncGameOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData));
Rpc<SyncOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, chunks.Dequeue()));
}
}
@@ -420,38 +411,15 @@ 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 (!SetterLookup.TryGetValue(__originalMethod.MethodHandle, out var attribute))
if (!SetterLookups.TryGetValue(__originalMethod, out var attribute))
return;
attribute.SetValue(value);
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);
if (attribute is ModdedOptionListAttribute listAttribute && value != null)
ListInstanceCache.AddOrUpdate(value, listAttribute);
}
/// <summary>
@@ -462,35 +430,12 @@ 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 (!GetterLookup.TryGetValue(__originalMethod.MethodHandle, out var attribute))
if (!GetterLookups.TryGetValue(__originalMethod, 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;
}
}
@@ -0,0 +1,17 @@
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,5 +1,6 @@
using System;
using System.Diagnostics.CodeAnalysis;
using Il2CppInterop.Runtime.Attributes;
using TMPro;
using UnityEngine;
@@ -48,5 +49,6 @@ 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; }
}
@@ -1,125 +0,0 @@
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,75 +1,24 @@
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using BepInEx.Configuration;
using System.Text;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Networking;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
using Object = UnityEngine.Object;
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>
[Obsolete("Use ModdedEnumOption<T> instead. This will be removed in a future version.")]
public class ModdedEnumOption : ModdedBaseEnumOption<int>
public class ModdedEnumOption : ModdedOption<int>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption"/> class.
/// Gets the string values of the enum.
/// </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="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)
{
}
public string[] Values { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption"/> class.
@@ -80,28 +29,53 @@ public class ModdedEnumOption : ModdedBaseEnumOption<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)
: this(string.Empty, title, defaultValue, enumType, values, includeInPreset)
: base(title, defaultValue, 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;
}
/// <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)
/// <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}.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(Id, BitConverter.GetBytes(Value));
return new NetData(Id, BitConverter.GetBytes(Value));
}
/// <inheritdoc />
@@ -111,9 +85,34 @@ public class ModdedEnumOption : ModdedBaseEnumOption<int>
}
/// <inheritdoc />
protected internal override ConfigDescription? CreateDescription()
public override int GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
return new(string.Empty, new AcceptableValueList<int>(UnderlyingValues));
return optionBehaviour.GetInt();
}
/// <inheritdoc />
protected override void OnValueChanged(int newValue)
{
if (ShowNotification)
{
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;
}
}
}
@@ -121,41 +120,13 @@ public class ModdedEnumOption : ModdedBaseEnumOption<int>
/// An option for selecting an <see langword="enum"/> value.
/// </summary>
/// <typeparam name="T">The <see cref="Enum"/> type.</typeparam>
public class ModdedEnumOption<T> : ModdedBaseEnumOption<T>
public class ModdedEnumOption<T> : ModdedOption<T>
where T : struct, Enum
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption{T}"/> class.
/// Gets the string values of the <see langword="enum"/>.
/// </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="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)
{
}
public string[] Values { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption{T}"/> class.
@@ -165,40 +136,89 @@ public class ModdedEnumOption<T> : ModdedBaseEnumOption<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)
: this(string.Empty, title, defaultValue, values, includeInPreset)
: base(title, defaultValue, 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;
}
/// <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)
/// <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}.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()
{
var buffer = new byte[Unsafe.SizeOf<T>()];
Unsafe.WriteUnaligned(ref buffer[0], Value);
return new(Id, buffer);
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value, NumberFormatInfo.InvariantInfo)!));
}
/// <inheritdoc />
public override void HandleNetData(byte[] data)
{
SetValue(Unsafe.ReadUnaligned<T>(ref data[0]));
SetValue(Enum.Parse<T>(Encoding.Unicode.GetString(data)));
}
/// <inheritdoc />
protected internal override ConfigDescription? CreateDescription()
public override T GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
return new(string.Empty, new AcceptableEnumValues<T>(UnderlyingValues));
return Enum.Parse<T>(optionBehaviour.GetInt().ToString(NumberFormatInfo.InvariantInfo));
}
/// <inheritdoc />
protected override void OnValueChanged(T newValue)
{
if (ShowNotification)
{
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);
}
}
}
@@ -1,6 +1,5 @@
using System;
using System.Text.RegularExpressions;
using BepInEx.Configuration;
using AmongUs.GameOptions;
using MiraAPI.Networking;
using MiraAPI.Utilities;
using UnityEngine;
@@ -44,44 +43,30 @@ public class ModdedNumberOption : ModdedOption<float>
public string NegativeWordValue { get; }
/// <summary>
/// Gets the format string used to display the values.
/// Gets a value indicating whether zero is infinity.
/// </summary>
public string FormatString { get; }
public bool ZeroInfinity => ZeroWordValue == "∞";
/// <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="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="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="formatString">Optional format string for the option screen.</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,
@@ -93,7 +78,7 @@ public class ModdedNumberOption : ModdedOption<float>
string? formatString = null,
bool halfIncrements = false,
bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset)
: base(title, defaultValue, includeInPreset)
{
Min = min;
Max = max;
@@ -102,114 +87,40 @@ public class ModdedNumberOption : ModdedOption<float>
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;
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 = 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.ZeroIsInfinity = ZeroInfinity;
data.SuffixType = (NumberSuffixes)SuffixType;
data.OptionName = FloatOptionNames.Invalid;
Data = data;
}
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>
/// <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 title,
float defaultValue,
float min,
float max,
float increment,
string zeroBehavior,
string negativeBehavior,
MiraNumberSuffixes suffixType,
string? formatString = null,
bool halfIncrements = false,
bool includeInPreset = true)
: this(string.Empty, title, defaultValue, min, max, increment, zeroBehavior, negativeBehavior, suffixType, formatString, halfIncrements, includeInPreset)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOption"/> class.
/// </summary>
/// <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 title,
@@ -221,7 +132,7 @@ public class ModdedNumberOption : ModdedOption<float>
string? formatString = null,
bool zeroInfinity = false,
bool includeInPreset = true)
: this(string.Empty, title, defaultValue, min, max, increment, suffixType, formatString, zeroInfinity, includeInPreset)
: this(title, defaultValue, min, max, increment, zeroInfinity ? "∞" : "#", "#", suffixType, formatString, increment == 1f, includeInPreset)
{
}
@@ -233,21 +144,9 @@ public class ModdedNumberOption : ModdedOption<float>
PlayerOption playerOpt,
Transform container)
{
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 numberOption = Object.Instantiate(numberOpt, Vector3.zero, Quaternion.identity, container);
numberOption.name =
$"{ParentMod!.OptionsTitleText}.NumberOption.{TranslationController.Instance.GetString(StringName)}";
var optionComponent = numberOption.gameObject.AddComponent<MiraNumberOptionComponent>();
optionComponent.NumberOption = this;
optionComponent.DefaultIncrement = Increment;
@@ -255,27 +154,23 @@ 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()
{
@@ -303,24 +198,24 @@ public class ModdedNumberOption : ModdedOption<float>
/// <inheritdoc />
protected override void OnValueChanged(float newValue)
{
if (OptionBehaviour && OptionBehaviour is NumberOption opt)
Value = Mathf.Clamp(newValue, Min, Max);
if (ShowNotification)
{
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
StringName,
Data.GetValueString(newValue),
Configuration.PopUpTextColor,
Configuration.PopUpIconTmp,
false);
}
if (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>
@@ -328,6 +223,6 @@ public class ModdedNumberOption : ModdedOption<float>
/// <returns>Integer value.</returns>
public static implicit operator int(ModdedNumberOption option)
{
return (int)MathF.Round(option.Value, MidpointRounding.AwayFromZero);
return (int)option.Value;
}
}
+42 -77
View File
@@ -14,20 +14,33 @@ namespace MiraAPI.GameOptions.OptionTypes;
/// Represents a modded option.
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
/// <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
public abstract class ModdedOption<T> : IModdedOption
{
/// <inheritdoc />
public uint Id { get; } = ModdedOptionsManager.NextId;
public uint Id { get; }
/// <inheritdoc />
public string Title { get; set; } = groupPrefix + title;
public string Title { get; set; }
/// <inheritdoc />
public StringNames StringName { get; } = MiraLocaleManager.GetOrCreateLocaleString(groupPrefix + title);
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;
}
}
/// <summary>
/// Gets or sets the value of the option.
@@ -37,8 +50,6 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
get => Getter != null ? Getter(_value) : _value;
protected set
{
value = ModifyValue(value, _value);
if (Setter != null)
value = Setter(value, _value);
@@ -46,24 +57,12 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
}
}
private T _value = defaultValue;
private T _value;
/// <summary>
/// Gets the default value of the option.
/// </summary>
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!;
public T DefaultValue { get; }
/// <inheritdoc cref="IModdedOption.Getter"/>
public Func<T, T>? Getter { get; set; }
@@ -74,6 +73,15 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
/// <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 bool ShowNotification { get; set; } = true;
/// <inheritdoc />
public OptionBehaviour? OptionBehaviour { get; protected set; }
@@ -84,18 +92,7 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
public AbstractOptionGroup ParentGroup { get; set; }
/// <inheritdoc />
public IMiraPlugin? ParentMod
{
get;
set
{
if (field != null || value == null) return;
field = value;
var entry = field.GetConfigFile().Bind(ConfigDefinition, DefaultValue, CreateDescription());
Value = entry.Value;
}
}
public virtual OptionNotifConfiguration Configuration => new(ParentGroup);
/// <inheritdoc />
Delegate? IModdedOption.Getter
@@ -118,9 +115,6 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
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>
@@ -128,8 +122,14 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
/// <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)
@@ -159,18 +159,7 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
entry.Value = _value;
}
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);
Rpc<SyncOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, new MiraOptionNetData(true, [GetNetData()]), true);
}
OnValueChanged(_value);
@@ -193,7 +182,7 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
/// <inheritdoc />
public void Bind(ConfigFile config)
{
config.Bind(ConfigDefinition, DefaultValue, CreateDescription());
config.Bind(ConfigDefinition, DefaultValue);
}
/// <inheritdoc />
@@ -245,30 +234,6 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
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>
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Networking;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -28,14 +29,18 @@ 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 can return -1.</param>
public ModdedPlayerOption(string groupPrefix, string title, bool allowNone = true)
: base(groupPrefix, title, allowNone ? -1 : 0, false)
/// <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)
{
Values = [];
AllowNone = allowNone;
@@ -49,16 +54,6 @@ 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,
@@ -67,27 +62,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();
var playerOption = Object.Instantiate(playerOpt, container);
playerOption.name = $"{ParentMod!.OptionsTitleText}.PlayerOption.{Title}";
playerOption.SetUpFromData(Data, 20);
playerOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
// 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);
playerOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
OptionBehaviour = playerOption;
ModdedOptionsManager.CreatedPlayerOptions.TryAdd(playerOption, this);
playerOption.SetValueText();
playerOption.AdjustButtonsActiveState();
playerOption.gameObject.AddComponent<MiraPlayerOptionComponent>().PlayerOption = this;
OptionBehaviour = playerOption;
return playerOption;
}
@@ -113,7 +108,7 @@ public class ModdedPlayerOption : ModdedOption<int>
/// <returns>A player or <see langword="null"/> if chosen none.</returns>
public NetworkedPlayerInfo? GetPlayerValue()
{
return (uint)Value >= (uint)Values.Count ? null : Values[Value];
return Value < 0 ? null : Values[Value];
}
/// <inheritdoc />
@@ -143,18 +138,21 @@ public class ModdedPlayerOption : ModdedOption<int>
/// <inheritdoc />
protected override void OnValueChanged(int newValue)
{
if (OptionBehaviour && OptionBehaviour is PlayerOption opt)
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
StringName,
Data.GetValueString(newValue),
Configuration.PopUpTextColor,
Configuration.PopUpIconTmp,
false);
if (!OptionBehaviour)
{
return;
}
if (OptionBehaviour is PlayerOption opt)
{
opt.Value = newValue;
}
}
/// <inheritdoc />
public override string GetDisplayValue()
{
var player = GetPlayerValue();
return !player
? TranslationController.Instance.GetString(StringNames.None)
: player!.PlayerName;
}
}
@@ -2,37 +2,28 @@
using System.Globalization;
using System.Linq;
using System.Text;
using BepInEx.Configuration;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Networking;
using MiraAPI.Translation;
using UnityEngine;
using Object = UnityEngine.Object;
namespace MiraAPI.GameOptions.OptionTypes;
/// <summary>
/// An option for selecting a string value from a predefined list.
/// An option for selecting an enum value.
/// </summary>
public class ModdedStringOption : ModdedBaseStringOption<string>
public class ModdedStringOption : ModdedOption<string>
{
/// <inheritdoc />
protected override string OptionTypeName => "StringOption";
/// <summary>
/// Gets or sets the string values of the option.
/// </summary>
public string[] Values { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ModdedStringOption"/> class.
/// Gets or sets the String Name values of the option.
/// </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 string.</param>
/// <param name="values">An option list of string values to use.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedStringOption(string groupPrefix, string title, string defaultValue, string[] values, bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset)
{
Values = values;
UnderlyingValues = values;
StringNameValues = [.. values.Select(MiraLocaleManager.GetOrCreateLocaleString)];
InitializeData(GetIndex(defaultValue));
}
public StringNames[] StringNameValues { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ModdedStringOption"/> class.
@@ -42,16 +33,41 @@ public class ModdedStringOption : ModdedBaseStringOption<string>
/// <param name="values">An option list of string values to use.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedStringOption(string title, string defaultValue, string[] values, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, values, includeInPreset)
: base(title, defaultValue, includeInPreset)
{
Values = values;
StringNameValues = [.. values.Select(MiraLocaleManager.GetOrCreateLocaleString)];
var data = ScriptableObject.CreateInstance<StringGameSetting>();
data.Title = StringName;
data.Type = global::OptionTypes.String;
data.Values = StringNameValues;
data.Index = GetIndex(Value);
Data = data;
}
/// <summary>
/// Adds a value to the option dynamically.
/// Gets the string's index.
/// </summary>
/// <param name="value">The option's string value.</param>
/// <returns>The option's value in the index.</returns>
public int GetIndex(string value)
{
if (Values.Contains(value))
{
return Array.IndexOf(Values, value);
}
Info($"Cannot find a valid index for {value}. Returning -1 instead. Values: {string.Join(", ", Values)}");
return -1;
}
/// <summary>
/// Adds a value to the option.
/// </summary>
/// <param name="value">The option's string value.</param>
/// <param name="index">The additional value's index on the list.</param>
[Obsolete("Use the Setter feature of modded options to simulate conditional values. This wil be removed in a future version.")]
public void RegisterExtraValue(string value, int index = -1)
{
if (!Values.Contains(value))
@@ -62,8 +78,6 @@ public class ModdedStringOption : ModdedBaseStringOption<string>
var newVals = Values.ToList();
newVals.Insert(index, value);
Values = [.. newVals];
UnderlyingValues = Values;
var newStrVals = StringNameValues.ToList();
newStrVals.Insert(index, MiraLocaleManager.GetOrCreateLocaleString(value));
StringNameValues = [.. newStrVals];
@@ -71,6 +85,7 @@ public class ModdedStringOption : ModdedBaseStringOption<string>
if (Data == null)
{
Error("Data is null.");
return;
}
@@ -78,20 +93,58 @@ public class ModdedStringOption : ModdedBaseStringOption<string>
data.Values = StringNameValues;
data.Index = GetIndex(Value);
Warning("Data is valid");
if (OptionBehaviour == null)
{
Error("OptionBehaviour is null.");
return;
}
var strOpt = OptionBehaviour.TryCast<StringOption>();
Warning("OptionBehaviour is valid");
if (strOpt == null)
{
Error("StringOption is null.");
return;
}
strOpt.Values = StringNameValues;
strOpt.Value = GetIndex(Value);
Warning("StringOption is valid");
}
/// <inheritdoc />
public override OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, PlayerOption playerOpt, Transform container)
{
var stringOption = Object.Instantiate(stringOpt, container);
stringOption.name =
$"{ParentMod!.OptionsTitleText}.StringOption.{TranslationController.Instance.GetString(StringName)}";
stringOption.SetUpFromData(Data, 20);
stringOption.OnValueChanged = (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 = GetIndex(Value);
OptionBehaviour = stringOption;
ModdedOptionsManager.CreatedStringOptions.TryAdd(stringOption, this);
return stringOption;
}
/// <inheritdoc />
public override float GetFloatData()
{
return Array.IndexOf(Values, Value);
}
/// <inheritdoc />
@@ -107,8 +160,23 @@ public class ModdedStringOption : ModdedBaseStringOption<string>
}
/// <inheritdoc />
protected internal override ConfigDescription? CreateDescription()
public override string GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
return new(string.Empty, new AcceptableValueList<string>(UnderlyingValues));
return Values[optionBehaviour.GetInt()];
}
/// <inheritdoc />
protected override void OnValueChanged(string newValue)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(GetIndex(newValue)), false);
if (!OptionBehaviour)
{
return;
}
if (OptionBehaviour is StringOption opt)
{
opt.Value = GetIndex(newValue);
}
}
}
Loaded 100 of 218 files, more files were not shown because too many files have changed in this diff. Show more