Compare commits

...
Author SHA1 Message Date
Az 9548225991 Update ModdedOptionVisibilityAttribute.cs 2026-11-19 18:15:02 -05:00
Az 32a7dab31c some fixes and improvements 2026-11-19 18:13:22 -05:00
Az cc8d1ae878 some multi-select progress + code improvements 2026-11-19 17:32:08 -05:00
Az 8340ebba4e WIP multi select options 2026-11-19 02:53:28 -05:00
Az 13c6db4d64 use Math/MathF instead of Mathf because il2cpp 2026-11-19 01:38:44 -05:00
Az b9f1f2fcf2 some non-generic safety 2026-11-18 23:42:27 -05:00
Az c98d133648 clear some warnings 2026-11-18 23:35:01 -05:00
Az 5c2216dfc9 allow enum value filtering + minor improvements 2026-11-18 23:31:26 -05:00
Az 33fdd86b56 minor improvements 2026-11-18 19:32:39 -05:00
Az 133cec9c38 begone warning 2026-11-18 18:04:56 -05:00
Az f677acb6c8 update xml debug comment to current translation system 2026-11-18 17:45:25 -05:00
Az c57901ef6d minor improvements + explicit string comparisons 2026-11-18 17:36:05 -05:00
Az 38ee19e996 allow referring to vanilla strings 2026-11-18 14:33:14 -05:00
Az 8ba03db883 slightly better constructor 2026-11-18 14:14:29 -05:00
Az 5885d211f5 make config ranges safe + more config descriptions 2026-11-18 14:06:04 -05:00
Atony 80357f0f3e remove AcceptableValueRange for 0 chance roles 2026-11-18 11:20:57 -06:00
Atony f43ede10f5 Stop checking wiki preloading each frame 2026-11-18 11:11:54 -06:00
Az 0a4f2f84b1 several more options improvements 2026-11-18 03:38:46 -05:00
Az 5a09d3c996 actually move the guard out 2026-11-18 01:42:30 -05:00
Az c013599127 apply notification behaviour
tou mira gets vip treatment
2026-11-18 01:41:16 -05:00
Az fc4f3d1aa0 some minor improvements 2026-11-18 01:37:41 -05:00
64 changed files with 1357 additions and 446 deletions

No files matched your search

+6
View File
@@ -122,3 +122,9 @@ dotnet_diagnostic.SA1143.severity = none
# SA1504: All accessors should be single-line or multi-line
dotnet_diagnostic.SA1504.severity = none
# S2386: Mutable fields should not be "public static"
dotnet_diagnostic.S2386.severity = none
# S3887: Mutable, non-private fields should not be "readonly"
dotnet_diagnostic.S3887.severity = none
+3 -2
View File
@@ -34,10 +34,10 @@ public class ExampleOptions : AbstractOptionGroup
[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"])]
[ModdedEnumOption<Api>("options.exampleOptions1.bestApi")] // Not specifying strings will automatically build translation ids based on the defined enum values
public Api BestApi { get; set; } = Api.MiraAPI;
[ModdedEnumOptionList<ValueState>("Value State {0}", ["None", "Primary", "Secondary"])]
[ModdedEnumOptionList<ValueState>("Value State {0}", [ValueState.None, ValueState.Primary, ValueState.Secondary])] // You can even filter out specific values!
public ModdedArray<ValueState> ValueStates { get; set; } = [ValueState.Primary, ValueState.Secondary, ValueState.None, ValueState.None, ValueState.None];
[ModdedPlayerOption("options.exampleOptions1.players")]
@@ -81,4 +81,5 @@ public enum ValueState
None,
Primary,
Secondary,
Tertiary,
}
+4 -3
View File
@@ -1,4 +1,5 @@
using System.Collections;
using System;
using System.Collections;
using System.Collections.Generic;
using AmongUs.GameOptions;
using MiraAPI.GameOptions;
@@ -300,8 +301,8 @@ public abstract class AbstractGameMode : IOptionable
instance.closedPosition = new Vector3(xPos, yPos, instance.closedPosition.z);
instance.openPosition = new Vector3(instance.openPosition.x, yPos, instance.openPosition.z);
instance.timer = instance.open
? Mathf.Min(1f, instance.timer + (Time.deltaTime / instance.animationTimeSeconds))
: Mathf.Max(0f, instance.timer - (Time.deltaTime / instance.animationTimeSeconds));
? Math.Min(1f, instance.timer + (Time.deltaTime / instance.animationTimeSeconds))
: Math.Max(0f, instance.timer - (Time.deltaTime / instance.animationTimeSeconds));
Vector3 relativePos = new(
Mathf.SmoothStep(instance.closedPosition.x, instance.openPosition.x, instance.timer),
+3 -3
View File
@@ -73,7 +73,7 @@ public class HideAndSeekMode : AbstractGameMode
private static int ImpostorPlayerID()
{
return OptionGroupSingleton<HnsImpostorOptions>.Instance.SelectedSeeker.Value;
return OptionGroupSingleton<HnsImpostorOptions>.Instance.SelectedSeeker;
}
private static bool HasImpostorPlayerID()
@@ -516,8 +516,8 @@ public class HideAndSeekMode : AbstractGameMode
instance.closedPosition = new Vector3(xPos, yPos, instance.closedPosition.z);
instance.openPosition = new Vector3(instance.openPosition.x, yPos, instance.openPosition.z);
instance.timer = instance.open
? Mathf.Min(1f, instance.timer + (Time.deltaTime / instance.animationTimeSeconds))
: Mathf.Max(0f, instance.timer - (Time.deltaTime / instance.animationTimeSeconds));
? Math.Min(1f, instance.timer + (Time.deltaTime / instance.animationTimeSeconds))
: Math.Max(0f, instance.timer - (Time.deltaTime / instance.animationTimeSeconds));
Vector3 relativePos = new(
Mathf.SmoothStep(instance.closedPosition.x, instance.openPosition.x, instance.timer),
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
using MiraAPI.Utilities;
@@ -46,7 +45,6 @@ public abstract class AbstractOptionGroup
/// <summary>
/// Gets the sprite of the group that is displayed in the match info guide.
/// </summary>
[HideFromIl2Cpp]
public virtual LoadableAsset<Sprite> Sprite => MiraAssets.IconSettings;
/// <summary>
@@ -17,7 +17,7 @@ namespace MiraAPI.GameOptions.Attributes;
[AttributeUsage(AttributeTargets.Property)]
public abstract class ModdedOptionMemberAttribute(string? memberName, Type? holderType, string defaultSuffix) : Attribute
{
private static readonly Dictionary<MethodInfo, Delegate> DelegateCache = [];
private static readonly Dictionary<(MethodInfo, Type), Delegate> DelegateCache = [];
/// <summary>
/// A helper class to bind a specific list index to a dynamically compiled delegate.
@@ -218,7 +218,10 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
flags |= BindingFlags.NonPublic;
}
var member = type.GetMember(MemberName, flags).OrderBy(GetGenericArgsLength).FirstOrDefault();
var member = type.GetMember(MemberName, flags)
.OrderBy(GetGenericArgsLength)
.ThenBy(GetArgsLength)
.FirstOrDefault();
notFound = true;
if (member == null)
@@ -290,6 +293,14 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
return method.IsGenericMethodDefinition ? method.GetGenericArguments().Length : 0;
}
private static int GetArgsLength(MemberInfo member)
{
if (member is not MethodInfo method)
return -1;
return method.GetParameters().Length;
}
/// <summary>
/// Compiles a <see cref="DynamicMethod"/> using IL generation to invoke the resolved static or instance <paramref name="method"/>.
/// </summary>
@@ -317,7 +328,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
bool forwardParameters = true,
Action<ILGenerator>? postProcessCall = null)
{
if (postProcessCall == null && DelegateCache.TryGetValue(method, out var cachedDelegate))
if (postProcessCall == null && DelegateCache.TryGetValue((method, delegateType), out var cachedDelegate))
return cachedDelegate;
var dm = new DynamicMethod($"{ownerType.Name}_{method.Name}_{suffix}", returnType, paramTypes, ownerType, true);
@@ -356,7 +367,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
var compiledDelegate = dm.CreateDelegate(delegateType);
if (postProcessCall == null)
DelegateCache[method] = compiledDelegate;
DelegateCache[(method, delegateType)] = compiledDelegate;
return compiledDelegate;
}
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.Attributes;
@@ -81,12 +82,14 @@ public sealed class ModdedOptionVisibilityAttribute(string? memberName = null, T
return null;
}
if (field.IsLiteral)
return (bool)field.GetRawConstantValue()! ? DelegateUtilities.AlwaysTrue : DelegateUtilities.AlwaysFalse;
var dynamicMethod = new DynamicMethod($"GetVisibility_{type.Name}_{field.Name}", typeof(bool), Type.EmptyTypes, type, true);
var il = dynamicMethod.GetILGenerator();
if (instanceGetter != null)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, instanceGetter);
il.Emit(OpCodes.Ldfld, field);
}
@@ -109,7 +112,7 @@ public sealed class ModdedOptionVisibilityAttribute(string? memberName = null, T
internal Func<int, Delegate?>? GetListVisibility(AbstractOptionGroup group, PropertyInfo property)
{
if (ResolveMember(group, property, out Type type, out var instanceGetter, out var notFound) is not { } member)
if (ResolveMember(group, property, out var type, out var instanceGetter, out var notFound) is not { } member)
{
if (notFound)
Error($"Member {MemberName} does not exist in {type.FullName}");
@@ -225,12 +228,17 @@ public sealed class ModdedOptionVisibilityAttribute(string? memberName = null, T
return null;
}
if (field.IsLiteral)
{
var constant = (bool)field.GetRawConstantValue()! ? DelegateUtilities.AlwaysTrue : DelegateUtilities.AlwaysFalse;
return _ => constant;
}
var dynamicMethod = new DynamicMethod($"GetListVisibility_{type.Name}_{field.Name}", typeof(bool), [typeof(int)], type, true);
var il = dynamicMethod.GetILGenerator();
if (instanceGetter != null)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, instanceGetter);
il.Emit(OpCodes.Ldfld, field);
}
@@ -65,7 +65,7 @@ public class ModdedEnumOptionAttribute(string? title, Type enumType, string idPr
public override object GetValue()
{
return HolderOption is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
? Enum.ToObject(enumType, opt.UnderlyingValues[opt.Value])
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedEnumOption with enum type {enumType.FullName}");
}
}
@@ -76,34 +76,59 @@ public class ModdedEnumOptionAttribute(string? title, Type enumType, string idPr
/// <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>
/// <param name="allowedValues">An option array of enum values to filter down what values can actually be used.</param>
/// <param name="values">An optional array 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)
public class ModdedEnumOptionAttribute<T>(string? title, string idPrefix, T[]? allowedValues = null, string[]? values = null)
: ModdedOptionAttribute(title), ITypedOption<T>
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)
private const string ObsoleteMsg = "This constructor is deprecated. Please use the equivalent constructor that includes the 'T[]? allowedValues' parameter. This will be removed in a future version.";
/// <inheritdoc cref="ModdedEnumOptionAttribute{T}(string, string, T[], string[])"/>
public ModdedEnumOptionAttribute(string? title, T[]? allowedValues = null, string[]? values = null)
: this(title, string.Empty, allowedValues, values)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOptionAttribute{T}"/> class.
/// </summary>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
public ModdedEnumOptionAttribute(string[]? values = null)
: this(null, string.Empty, values)
/// <inheritdoc cref="ModdedEnumOptionAttribute{T}(string, string, T[], string[])"/>
public ModdedEnumOptionAttribute(T[]? allowedValues = null, string[]? values = null, string idPrefix = "")
: this(null, idPrefix, allowedValues, values)
{
}
/// <inheritdoc cref="ModdedEnumOptionAttribute{T}(string, string, T[], string[])"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOptionAttribute(string? title, string idPrefix, string[] values)
: this(title, idPrefix, null, values)
{
}
/// <inheritdoc cref="ModdedEnumOptionAttribute{T}(string, string, T[], string[])"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOptionAttribute(string? title, string[] values)
: this(title, string.Empty, null, values)
{
}
/// <inheritdoc cref="ModdedEnumOptionAttribute{T}(string, string, T[], string[])"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOptionAttribute(string[] values, string idPrefix)
: this(null, idPrefix, null, values)
{
}
/// <inheritdoc cref="ModdedEnumOptionAttribute{T}(string, string, T[], string[])"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOptionAttribute(string[] values)
: this(null, string.Empty, null, values)
{
}
/// <inheritdoc />
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);
var opt = new ModdedEnumOption<T>(group.GroupPrefix, Title ?? property.Name, (T)(value ?? 0), idPrefix, allowedValues, values);
Title = opt.Title;
return opt;
}
@@ -67,7 +67,7 @@ public class ModdedEnumOptionListAttribute(string? title, Type enumType, string
public override object GetValue(int idx)
{
return HolderOptionList?.ElementAt(idx) is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
? Enum.ToObject(enumType, opt.UnderlyingValues[opt.Value])
: throw new InvalidOperationException($"HolderOption for option \"{Titles[idx]}\" is not a ModdedEnumOption with enum type {enumType.FullName}");
}
}
@@ -78,36 +78,60 @@ public class ModdedEnumOptionListAttribute(string? title, Type enumType, string
/// <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>
/// <param name="allowedValues">An option array of enum values to filter down what values can actually be used.</param>
/// <param name="values">An optional array of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionListAttribute<T>(string? title, string idPrefix, string[]? values = null)
public class ModdedEnumOptionListAttribute<T>(string? title, string idPrefix, T[]? allowedValues = null, string[]? values = null)
: ModdedOptionListAttribute(title), ITypedOptionList<T>
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)
private const string ObsoleteMsg = "This constructor is deprecated. Please use the equivalent constructor that includes the 'T[]? allowedValues' parameter. This will be removed in a future version.";
/// <inheritdoc cref="ModdedEnumOptionListAttribute{T}(string, string, T[], string[])"/>
public ModdedEnumOptionListAttribute(string? title, T[]? allowedValues = null, string[]? values = null)
: this(title, string.Empty, allowedValues, 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)
/// <inheritdoc cref="ModdedEnumOptionListAttribute{T}(string, string, T[], string[])"/>
public ModdedEnumOptionListAttribute(T[]? allowedValues = null, string[]? values = null, string idPrefix = "")
: this(null, idPrefix, allowedValues, values)
{
}
/// <inheritdoc cref="ModdedEnumOptionListAttribute{T}(string, string, T[], string[])"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOptionListAttribute(string? title, string idPrefix, string[] values)
: this(title, idPrefix, null, values)
{
}
/// <inheritdoc cref="ModdedEnumOptionListAttribute{T}(string, string, T[], string[])"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOptionListAttribute(string? title, string[] values)
: this(title, string.Empty, null, values)
{
}
/// <inheritdoc cref="ModdedEnumOptionListAttribute{T}(string, string, T[], string[])"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOptionListAttribute(string[] values, string idPrefix)
: this(null, idPrefix, null, values)
{
}
/// <inheritdoc cref="ModdedEnumOptionListAttribute{T}(string, string, T[], string[])"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOptionListAttribute(string[] values)
: this(null, string.Empty, null, values)
{
}
/// <inheritdoc />
internal override IBaseModdedOptionList CreateOptionList(IList list, PropertyInfo property, AbstractOptionGroup group)
{
var optList = new ModdedOptionList<ModdedEnumOption<T>>(
list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), (T)(list[idx] ?? 0), idPrefix, values));
list.Count, idx => new(group.GroupPrefix, GetFormattedTitle(idx, property), (T)(list[idx] ?? 0), idPrefix, allowedValues, values));
return optList;
}
@@ -0,0 +1,101 @@
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Translation;
using Reactor.Utilities.Attributes;
namespace MiraAPI.GameOptions.Components;
/// <summary>
/// A <see cref="BaseGameSetting"/> implementation that supports multi-select options.
/// </summary>
/// <param name="cppPtr">The C++ pointer to the object.</param>
[RegisterInIl2Cpp]
public class FlagsGameSetting(nint cppPtr) : BaseGameSetting(cppPtr)
{
/// <summary>
/// Gets or sets the value currently held by the setting.
/// </summary>
public int Value { get; set; }
/// <summary>
/// Gets or sets the integer value used to denote that all flags have been selected.
/// </summary>
public int All { get; set; }
/// <summary>
/// Gets or sets every defined flag within the enum.
/// </summary>
public Il2CppStructArray<int> Flags { get; set; }
/// <summary>
/// Gets or sets the string names associated with every flag.
/// </summary>
public Il2CppStructArray<StringNames> Values { get; set; }
/// <summary>
/// Gets or sets the string name for when no value is selected.
/// </summary>
public StringNames NoneName { get; set; }
/// <summary>
/// Gets or sets the string name for when all values are selected.
/// </summary>
public StringNames AllName { get; set; }
/// <inheritdoc/>
public override string GetValueString(float value)
{
return GetValueString((int)value);
}
/// <summary>
/// Gets a value display string.
/// </summary>
/// <param name="value">The enum value as an int.</param>
/// <returns>A value string.</returns>
public string GetValueString(int value)
{
if (value == 0)
{
return TranslationController.Instance.GetString(NoneName).Translate();
}
if (value == All)
{
return TranslationController.Instance.GetString(AllName).Translate();
}
var activeCount = 0;
var firstActiveName = StringNames.None;
var foundFirst = false;
for (var i = 0; i < Flags.Length; i++)
{
var flag = Flags[i];
if (flag == 0 || (value & flag) != flag)
continue;
if (!foundFirst)
{
firstActiveName = Values[i];
foundFirst = true;
}
activeCount++;
}
if (activeCount == 0)
{
return TranslationController.Instance.GetString(NoneName).Translate();
}
var firstNameString = TranslationController.Instance.GetString(firstActiveName).Translate();
if (activeCount == 1)
{
return firstNameString;
}
return MiraLocaleManager.GetParsed("MiraApi.Compound", string.Empty, firstNameString, activeCount - 1);
}
}
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
using Reactor.Utilities.Attributes;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace MiraAPI.GameOptions.Components;
// TODO: Add documentation once completed
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
/// <summary>
/// An option behaviour that acts as a container for dynamically generated flag toggles.
/// </summary>
/// <param name="cppPtr">The pointer to the C++ object.</param>
[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity convention.")]
[RegisterInIl2Cpp]
public class FlagsOption(nint cppPtr) : OptionBehaviour(cppPtr)
{
public TextMeshPro TitleText;
public TextMeshPro ValueText;
public GameOptionButton Button;
public bool Expanded;
public int Value;
public Il2CppStructArray<int> Flags;
public Il2CppStructArray<StringNames> Values;
public IFlagsOption Option;
private int oldValue;
private void Start()
{
Initialize();
}
public override int GetInt()
{
return Value;
}
public override void SetUpFromData(BaseGameSetting data, int maskLayer)
{
base.SetUpFromData(data, maskLayer);
var flagsGameSetting = data.TryCast<FlagsGameSetting>();
if (flagsGameSetting == null)
{
return;
}
Title = flagsGameSetting.Title;
Value = flagsGameSetting.Value;
Flags = flagsGameSetting.Flags;
Values = flagsGameSetting.Values;
}
public override void Initialize()
{
Value = Option.Value;
ValueText.text = Option.GetDisplayValue();
TitleText.text = TranslationController.Instance.GetString(Title);
Button.AddOnClickListeners((Action)UpdateList);
AdjustButtonState();
}
private void UpdateList()
{
}
private void AdjustButtonState()
{
Button.ChangeButtonText(Expanded ? "⏶" : "⏷");
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ using System.Collections.Generic;
namespace MiraAPI.GameOptions;
/// <summary>
/// A holder option for a summary and option string names that are hidden behind it.
/// A grouped data container that holds the options that need to be hidden and the summary produced from hiding them.
/// </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>
+1 -9
View File
@@ -55,15 +55,6 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList, IModdedA
items = [.. collection];
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedArray{T}"/> class with initial values.
/// </summary>
/// <param name="span">The initial span of values to initialise with.</param>
public ModdedArray(Span<T> span)
{
items = [.. span];
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedArray{T}"/> class with initial values.
/// </summary>
@@ -178,6 +169,7 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList, IModdedA
{
listAttribute = attribute;
typedAttribute = attribute as ITypedOptionList<T>;
Refresh();
}
/// <inheritdoc/>
+81 -11
View File
@@ -23,6 +23,8 @@ namespace MiraAPI.GameOptions;
/// </summary>
public static class ModdedOptionsManager
{
private static readonly Dictionary<(Type Holder, string Property), IBaseModdedOptionList> PropertyToOptionListMap = [];
private static readonly Dictionary<(Type Holder, string Property), IModdedOption> PropertyToOptionMap = [];
private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> GetterLookup = [];
private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> SetterLookup = [];
private static readonly HashSet<PropertyInfo> OptionAttributes = [];
@@ -147,8 +149,7 @@ public static class ModdedOptionsManager
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers)
.Where(f => !f.IsAutoPropertyBackingField()
&& (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IBaseModdedOptionList)))))
.Where(f => !f.IsAutoPropertyBackingField() && (f.FieldType.IsAssignableTo(OptionType) || f.FieldType.IsAssignableTo(OptionListType))))
{
Error($"{field.Name} is a field, not a property. Use properties for options.");
}
@@ -218,8 +219,8 @@ public static class ModdedOptionsManager
PatchProperty(property, propType, attribute);
attribute.HolderOption = option;
attribute.ValueType = propType;
attribute.HolderOption = option;
foreach (var attr in attributes)
{
@@ -257,6 +258,8 @@ public static class ModdedOptionsManager
{
RegisterOption(type, optionList.ElementAt(i), group, configName(i), pluginInfo);
}
PropertyToOptionListMap.Add((type, property.Name), optionList);
}
private static void RegisterAttributeOptionList(
@@ -305,9 +308,9 @@ public static class ModdedOptionsManager
var valueType = propType.GetGenericArguments()[0];
attribute.HolderOptionList = optionList;
attribute.Value = list;
attribute.ValueType = valueType;
attribute.HolderOptionList = optionList;
((IModdedArrayBinding)propertyVal).Bind(attribute);
@@ -350,6 +353,8 @@ public static class ModdedOptionsManager
RegisterOption(type, option, group, property.Name + (i + 1), pluginInfo);
}
PropertyToOptionListMap.Add((type, property.Name), optionList);
}
private static void RegisterOption(
@@ -364,8 +369,10 @@ public static class ModdedOptionsManager
option.ParentMod = pluginInfo.MiraPlugin;
pluginInfo.InternalOptions.Add(option);
ModdedOptions.Add(option.Id, option);
group.Options.Add(option);
ModdedOptions.Add(option.Id, option);
PropertyToOptionMap.Add((type, propertyName), option);
}
internal static void SyncAllOptions(int targetId = -1)
@@ -397,8 +404,16 @@ public static class ModdedOptionsManager
continue;
}
option.ShowNotification = showNotifs;
option.HandleNetData(netData.Data);
try
{
option.ShowNotification = showNotifs;
option.HandleNetData(netData.Data);
}
catch (Exception e)
{
option.ShowNotification = true;
Error(e);
}
}
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins)
@@ -413,6 +428,61 @@ public static class ModdedOptionsManager
}
}
/// <summary>
/// Gets a <see cref="StringNames"/> value associated to the option of the provided property name that is found in <typeparamref name="T"/>.<br/>
/// Use only for attribute options. Explicitly defined options should be used as they are.
/// </summary>
/// <typeparam name="T">The container option type.</typeparam>
/// <param name="propertyName">The name of the property that defines the option.</param>
/// <returns>The option's string name, or StringNames.None if not found.</returns>
public static StringNames GetStringName<T>(string propertyName)
where T : AbstractOptionGroup
{
return GetOption<T, IModdedOption>(propertyName)?.StringName ?? StringNames.None;
}
/// <summary>
/// Gets a <see cref="IModdedOption"/> associated to the provided property name that is found in <typeparamref name="TGroup"/>.<br/>
/// Use only for attribute options. Explicitly defined options should be used as they are.
/// </summary>
/// <typeparam name="TGroup">The container option type.</typeparam>
/// <typeparam name="TOption">The option type.</typeparam>
/// <param name="propertyName">The name of the property that defines the option.</param>
/// <returns>The option, if found.</returns>
public static TOption? GetOption<TGroup, TOption>(string propertyName)
where TGroup : AbstractOptionGroup
where TOption : IModdedOption
{
var type = typeof(TGroup);
if (PropertyToOptionMap.TryGetValue((type, propertyName), out var option))
return (TOption)option;
Error($"Could not find an option with the property name {propertyName} in {type.Name}");
return default;
}
/// <summary>
/// Gets a <see cref="IBaseModdedOptionList"/> associated to the provided property name that is found in <typeparamref name="TGroup"/>.<br/>
/// Use only for attribute lists. Explicitly defined lists should be used as they are.
/// </summary>
/// <typeparam name="TGroup">The container option type.</typeparam>
/// <typeparam name="TList">The option list type.</typeparam>
/// <param name="propertyName">The name of the property that defines the option list.</param>
/// <returns>The option list, if found.</returns>
public static TList? GetOptionList<TGroup, TList>(string propertyName)
where TGroup : AbstractOptionGroup
where TList : IBaseModdedOptionList
{
var type = typeof(TGroup);
if (PropertyToOptionListMap.TryGetValue((type, propertyName), out var optionList))
return (TList)optionList;
Error($"Could not find an option list with the property name {propertyName} in {type.Name}");
return default;
}
/// <summary>
/// Patches the setter of a property to update the value of the option.
/// </summary>
@@ -420,7 +490,7 @@ 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.")]
[Obsolete("Use PropertySetterPatch<T> instead. This will be removed in a future version.", true)]
public static void PropertySetterPatch(MethodBase __originalMethod, object value)
{
if (!SetterLookup.TryGetValue(__originalMethod.MethodHandle, out var attribute))
@@ -460,9 +530,9 @@ public static class ModdedOptionsManager
/// <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("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.")]
[Obsolete("Use PropertyGetterPatch<T> instead. This will be removed in a future version.", true)]
public static bool PropertyGetterPatch(MethodBase __originalMethod, ref object __result)
{
if (!GetterLookup.TryGetValue(__originalMethod.MethodHandle, out var attribute))
@@ -479,7 +549,7 @@ public static class ModdedOptionsManager
/// <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("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)
{
@@ -1,4 +1,6 @@
using System;
using System.Linq;
using MiraAPI.Translation;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -41,6 +43,8 @@ public abstract class ModdedBaseStringOption<T>(string groupPrefix, string title
/// <param name="defaultIndex">The default index to assign.</param>
protected void InitializeData(int defaultIndex)
{
StringNameValues = [.. Values.Select(MiraLocaleManager.GetOrCreateLocaleString)];
var data = ScriptableObject.CreateInstance<StringGameSetting>();
data.Title = StringName;
data.Type = global::OptionTypes.String;
@@ -60,7 +64,7 @@ public abstract class ModdedBaseStringOption<T>(string groupPrefix, string title
var index = Array.IndexOf(UnderlyingValues, value);
if (index == -1)
Info($"Cannot find a valid index for {value}. Returning -1 instead. Values: {string.Join(", ", Values)}");
Warning($"Cannot find a valid index for {value}. Returning -1 instead. Values: {string.Join(", ", Values)}");
return index;
}
@@ -120,6 +124,7 @@ public abstract class ModdedBaseStringOption<T>(string groupPrefix, string title
if ((uint)index < (uint)UnderlyingValues.Length)
return UnderlyingValues[index];
Warning($"Received an index {index} when there wasn't enough values (Length: {UnderlyingValues.Length})");
return UnderlyingValues.Length > 0 ? UnderlyingValues[0] : default!;
}
}
@@ -4,7 +4,6 @@ using System.Linq;
using System.Runtime.CompilerServices;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.Translation;
using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.OptionTypes;
@@ -43,16 +42,30 @@ public class ModdedEnumOption : ModdedBaseEnumOption<int>
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);
if (!enumType.IsEnum)
throw new ArgumentException($"The type {enumType.Name} is not an Enum.", nameof(enumType));
var rawValues = Enum.GetValues(enumType);
UnderlyingValues = new int[rawValues.Length];
var underlyingValues = new int[rawValues.Length];
for (var i = 0; i < rawValues.Length; i++)
UnderlyingValues[i] = Convert.ToInt32(rawValues.GetValue(i), NumberFormatInfo.InvariantInfo);
underlyingValues[i] = Convert.ToInt32(rawValues.GetValue(i), NumberFormatInfo.InvariantInfo);
Values = values ?? Enum.GetNames(enumType);
StringNameValues = [.. Values.Select(x => MiraLocaleManager.GetOrCreateLocaleString($"{idPrefix}{x}"))];
UnderlyingValues = [.. underlyingValues.Distinct()];
if (values != null && values.Length != UnderlyingValues.Length)
{
throw new ArgumentException($"The number of custom values ({values.Length}) must exactly match the number of enum values ({UnderlyingValues.Length}) in {enumType.Name}.", nameof(values));
}
if (Array.IndexOf(UnderlyingValues, defaultValue) == -1)
{
throw new ArgumentException($"The defaultValue '{defaultValue}' is not present in the allowed enum values.", nameof(defaultValue));
}
idPrefix = idPrefix.Replace("%type%", enumType.Name);
Values = [.. (values ?? rawValues.Cast<object>()).Select(x => idPrefix + x)];
InitializeData(GetIndex(defaultValue));
}
@@ -101,7 +114,7 @@ public class ModdedEnumOption : ModdedBaseEnumOption<int>
/// <inheritdoc />
public override NetData GetNetData()
{
return new(Id, BitConverter.GetBytes(Value));
return new(Id, BitConverter.GetBytes(_value));
}
/// <inheritdoc />
@@ -111,7 +124,7 @@ public class ModdedEnumOption : ModdedBaseEnumOption<int>
}
/// <inheritdoc />
protected internal override ConfigDescription? CreateDescription()
protected override ConfigDescription? CreateDescription()
{
return new(string.Empty, new AcceptableValueList<int>(UnderlyingValues));
}
@@ -124,6 +137,8 @@ public class ModdedEnumOption : ModdedBaseEnumOption<int>
public class ModdedEnumOption<T> : ModdedBaseEnumOption<T>
where T : struct, Enum
{
private const string ObsoleteMsg = "This constructor is deprecated. Please use the equivalent constructor that includes the 'T[]? allowedValues' parameter. This will be removed in a future version.";
/// <summary>
/// Initializes a new instance of the <see cref="ModdedEnumOption{T}"/> class.
/// </summary>
@@ -131,54 +146,102 @@ public class ModdedEnumOption<T> : ModdedBaseEnumOption<T>
/// <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="allowedValues">An option array of enum values to filter down what values can actually be used.</param>
/// <param name="values">An optional array 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)
public ModdedEnumOption(string groupPrefix, string title, T defaultValue, string idPrefix, T[]? allowedValues = null, string[]? values = null, bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset)
{
UnderlyingValues = [.. (allowedValues ?? Enum.GetValues<T>()).Distinct()];
if (values != null && values.Length != UnderlyingValues.Length)
{
throw new ArgumentException($"The number of custom values ({values.Length}) must exactly match the number of enum values ({UnderlyingValues.Length}) in {typeof(T).Name}.", nameof(values));
}
if (Array.IndexOf(UnderlyingValues, defaultValue) == -1)
{
throw new ArgumentException($"The defaultValue '{defaultValue}' is not present in the allowed enum values.", nameof(defaultValue));
}
idPrefix = idPrefix.Replace("%type%", typeof(T).Name);
UnderlyingValues = Enum.GetValues<T>();
Values = values ?? Enum.GetNames<T>();
StringNameValues = [.. Values.Select(x => MiraLocaleManager.GetOrCreateLocaleString($"{idPrefix}{x}"))];
Values = [.. (values ?? UnderlyingValues.Cast<object>()).Select(x => 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)
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
public ModdedEnumOption(string groupPrefix, string title, T defaultValue, T[]? allowedValues = null, string[]? values = null, bool includeInPreset = true)
: this(groupPrefix, title, defaultValue, string.Empty, allowedValues, values, includeInPreset)
{
}
/// <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="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)
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
public ModdedEnumOption(string title, T defaultValue, T[]? allowedValues = null, string[]? values = null, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, string.Empty, allowedValues, values, includeInPreset)
{
}
/// <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 cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
public ModdedEnumOption(string title, T defaultValue, string idPrefix, T[]? allowedValues = null, string[]? values = null, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, idPrefix, allowedValues, values, includeInPreset)
{
}
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOption(string groupPrefix, string title, T defaultValue, string idPrefix, string[] values, bool includeInPreset)
: this(groupPrefix, title, defaultValue, idPrefix, null, values, includeInPreset)
{
}
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOption(string groupPrefix, string title, T defaultValue, string idPrefix, string[] values)
: this(groupPrefix, title, defaultValue, idPrefix, null, values, true)
{
}
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOption(string groupPrefix, string title, T defaultValue, string[] values, bool includeInPreset)
: this(groupPrefix, title, defaultValue, string.Empty, null, values, includeInPreset)
{
}
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOption(string groupPrefix, string title, T defaultValue, string[] values)
: this(groupPrefix, title, defaultValue, string.Empty, null, values, true)
{
}
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOption(string title, T defaultValue, string[] values, bool includeInPreset)
: this(string.Empty, title, defaultValue, string.Empty, null, values, includeInPreset)
{
}
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOption(string title, T defaultValue, string[] values)
: this(string.Empty, title, defaultValue, string.Empty, null, values, true)
{
}
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOption(string title, T defaultValue, string idPrefix, string[] values, bool includeInPreset)
: this(string.Empty, title, defaultValue, idPrefix, null, values, includeInPreset)
{
}
/// <inheritdoc cref="ModdedEnumOption{T}(string, string, T, string, T[], string[], bool)"/>
[Obsolete(ObsoleteMsg)]
public ModdedEnumOption(string title, T defaultValue, string idPrefix, string[] values)
: this(string.Empty, title, defaultValue, idPrefix, null, values, true)
{
}
@@ -186,7 +249,7 @@ public class ModdedEnumOption<T> : ModdedBaseEnumOption<T>
public override NetData GetNetData()
{
var buffer = new byte[Unsafe.SizeOf<T>()];
Unsafe.WriteUnaligned(ref buffer[0], Value);
Unsafe.WriteUnaligned(ref buffer[0], _value);
return new(Id, buffer);
}
@@ -197,7 +260,7 @@ public class ModdedEnumOption<T> : ModdedBaseEnumOption<T>
}
/// <inheritdoc />
protected internal override ConfigDescription? CreateDescription()
protected override ConfigDescription? CreateDescription()
{
return new(string.Empty, new AcceptableEnumValues<T>(UnderlyingValues));
}
@@ -0,0 +1,290 @@
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using BepInEx.Configuration;
using MiraAPI.GameOptions.Components;
using MiraAPI.Networking;
using MiraAPI.Patches.Options;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.GameOptions.OptionTypes;
/// <summary>
/// An interface used to mark an option class as a flags option.
/// </summary>
public interface IFlagsOption
{
/// <summary>
/// Gets the combined bits value of the option's selected flags.
/// </summary>
int Value { get; }
/// <inheritdoc cref="IModdedOption.GetDisplayValue"/>
string GetDisplayValue();
}
/// <summary>
/// An option for selecting multiple <typeparamref name="T"/> values.
/// </summary>
/// <typeparam name="T">The type of the flag enum used as the backing value.</typeparam>
public class ModdedFlagsOption<T> : ModdedOption<T>, IFlagsOption
where T : struct, Enum
{
/// <summary>
/// Gets an array of int values where only a bit is turned on to denote each flag contained within <typeparamref name="T"/>.
/// </summary>
public int[] Flags { get; }
/// <summary>
/// Gets the string values of the option.
/// </summary>
public string[] Values { get; } = [];
/// <summary>
/// Gets the String Name values of the option.
/// </summary>
public StringNames[] StringNameValues { get; } = [];
/// <summary>
/// Gets the <see cref="StringNames"/> ID of the translation that corresponds to when no options are selected.
/// </summary>
public StringNames NoneName { get; }
/// <summary>
/// Gets the <see cref="StringNames"/> ID of the translation that corresponds to when all options are selected.
/// </summary>
public StringNames AllName { get; }
/// <summary>
/// Gets the "maximum" value of the flag option, which is where all defined flags are turned on.
/// </summary>
public int All { get; }
/// <summary>
/// Gets a (possibly) filtered array of strongly typed values that are allowed to be used by the option.
/// </summary>
public T[] AllowedValues { get; }
private readonly string allTranslationId;
private readonly string noneTranslationId;
private int value;
int IFlagsOption.Value => value;
/// <summary>
/// Initializes a new instance of the <see cref="ModdedFlagsOption{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="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="allowedValues">An option array of enum values to filter down what values can actually be used.</param>
/// <param name="values">An optional array of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="noneId">The core part of the translation ID corresponding to when no options are selected.</param>
/// <param name="allId">The core part of the translation ID corresponding to when all options are selected.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedFlagsOption(string groupPrefix, string title, T defaultValue, string idPrefix, T[]? allowedValues = null, string[]? values = null, string? noneId = null, string? allId = null, bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset)
{
var enumType = typeof(T);
if (!enumType.IsDefined<FlagsAttribute>(false))
throw new ArgumentException($"{enumType.Name} does not have [Flags], and therefore cannot be used for multi-select options.");
if (allowedValues == null)
allowedValues = Enum.GetValues<T>();
allowedValues = [.. allowedValues.Distinct()];
var tuples = allowedValues
.Select(x => (Val: x, Bit: Convert.ToInt32(x, NumberFormatInfo.InvariantInfo)))
.Where(val => val.Bit > 0 && (val.Bit & (val.Bit - 1)) == 0)
.ToArray();
if (values != null && values.Length != tuples.Length)
{
throw new ArgumentException($"The number of custom values ({values.Length}) must exactly match the number of allowed single-bit flags ({tuples.Length}).", nameof(values));
}
var all = 0;
foreach (var (_, bit) in tuples)
{
all |= bit;
}
var defaultBits = Convert.ToInt32(defaultValue, NumberFormatInfo.InvariantInfo);
if ((defaultBits & ~all) != 0)
{
throw new ArgumentException($"The defaultValue contains flags that are not present in the allowed subset.", nameof(defaultValue));
}
idPrefix = idPrefix.Replace("%type%", enumType.Name);
value = defaultBits;
allTranslationId = idPrefix + (allId ?? "All");
noneTranslationId = idPrefix + (noneId ?? "None");
All = all;
Flags = [.. tuples.Select(x => x.Bit)];
AllowedValues = [.. tuples.Select(x => x.Val)];
Values = values ?? [.. tuples.Select(x => x.Val.ToString())];
AllName = MiraLocaleManager.GetOrCreateLocaleString(allTranslationId);
NoneName = MiraLocaleManager.GetOrCreateLocaleString(noneTranslationId);
StringNameValues = [.. Values.Select(x => MiraLocaleManager.GetOrCreateLocaleString(idPrefix + x))];
var data = ScriptableObject.CreateInstance<FlagsGameSetting>();
data.Type = global::OptionTypes.MultipleChoice; // How nice of Innersloth to provide us with a pre-defined enum value
data.Value = defaultBits;
data.All = All;
data.Flags = Flags;
data.Values = StringNameValues;
Data = data;
}
/// <inheritdoc cref="ModdedFlagsOption(string, string, T, string, T[], string[], string, string, bool)"/>
public ModdedFlagsOption(string groupPrefix, string title, T defaultValue, T[]? allowedValues = null, string[]? values = null, string? noneId = null, string? allId = null, bool includeInPreset = true)
: this(groupPrefix, title, defaultValue, string.Empty, allowedValues, values, noneId, allId, includeInPreset)
{
}
/// <inheritdoc cref="ModdedFlagsOption(string, string, T, string, T[], string[], string, string, bool)"/>
public ModdedFlagsOption(string title, T defaultValue, string idPrefix, T[]? allowedValues = null, string[]? values = null, string? noneId = null, string? allId = null, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, idPrefix, allowedValues, values, noneId, allId, includeInPreset)
{
}
/// <inheritdoc cref="ModdedFlagsOption(string, string, T, string, T[], string[], string, string, bool)"/>
public ModdedFlagsOption(string title, T defaultValue, T[]? allowedValues = null, string[]? values = null, string? noneId = null, string? allId = null, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, string.Empty, allowedValues, values, noneId, allId, includeInPreset)
{
}
/// <inheritdoc />
public override OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, PlayerOption playerOpt, Transform container)
{
var multiSelectOption = GameOptionsMenuPatch.CreateOption(stringOpt, container);
multiSelectOption.name = $"{ParentMod!.OptionsTitleText}.FlagsOption.{Title}";
multiSelectOption.SetUpFromData(Data, 20);
multiSelectOption.Option = this;
multiSelectOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
OptionBehaviour = multiSelectOption;
return multiSelectOption;
}
/// <inheritdoc />
public override float GetFloatData()
{
return value;
}
/// <inheritdoc />
public override NetData GetNetData()
{
var buffer = new byte[Unsafe.SizeOf<T>()];
Unsafe.WriteUnaligned(ref buffer[0], _value);
return new(Id, buffer);
}
/// <inheritdoc />
public override void HandleNetData(byte[] data)
{
SetValue(Unsafe.ReadUnaligned<T>(ref data[0]));
}
/// <inheritdoc />
public override string GetDisplayValue()
{
if (value == 0)
{
return noneTranslationId.Translate();
}
if (value == All)
{
return allTranslationId.Translate();
}
var activeCount = 0;
var firstActiveName = string.Empty;
var foundFirst = false;
for (var i = 0; i < Flags.Length; i++)
{
var flag = Flags[i];
if (flag == 0 || (value & flag) != flag)
continue;
if (!foundFirst)
{
firstActiveName = Values[i];
foundFirst = true;
}
activeCount++;
}
if (activeCount == 0)
{
return noneTranslationId.Translate();
}
var firstNameString = firstActiveName.Translate();
if (activeCount == 1)
{
return firstNameString;
}
return "MiraApi.Compound".Translate(firstNameString, activeCount - 1);
}
/// <inheritdoc />
public override T GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
return (T)Enum.ToObject(typeof(T), optionBehaviour.GetInt());
}
/// <inheritdoc />
protected override void OnValueChanged(T newValue)
{
if (OptionBehaviour && OptionBehaviour is FlagsOption opt)
{
opt.Value = value;
}
}
/// <inheritdoc />
protected override ConfigDescription? CreateDescription()
{
return new(string.Empty, new AcceptableFlagValues<T>(AllowedValues));
}
/// <inheritdoc />
protected override T ModifyValue(T newValue, T oldValue)
{
value = Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo) & All;
return (T)Enum.ToObject(typeof(T), value);
}
/// <summary>
/// Implicitly converts the option to an <see langword="int"/>.
/// </summary>
/// <param name="option">The option.</param>
/// <returns>Integer value.</returns>
public static implicit operator int(ModdedFlagsOption<T> option)
{
return option.value;
}
}
@@ -93,7 +93,7 @@ public class ModdedNumberOption : ModdedOption<float>
string? formatString = null,
bool halfIncrements = false,
bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset)
: base(groupPrefix, title, Math.Clamp(defaultValue, min, max), includeInPreset)
{
Min = min;
Max = max;
@@ -102,15 +102,12 @@ public class ModdedNumberOption : ModdedOption<float>
ZeroWordValue = zeroBehavior;
ShiftIncrement = halfIncrements;
NegativeWordValue = negativeBehavior;
IsInt = defaultValue.IsInteger() &&
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>();
@@ -285,7 +282,7 @@ public class ModdedNumberOption : ModdedOption<float>
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, BitConverter.GetBytes(Value));
return new NetData(Id, BitConverter.GetBytes(_value));
}
/// <inheritdoc />
@@ -297,7 +294,7 @@ public class ModdedNumberOption : ModdedOption<float>
/// <inheritdoc />
public override float GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
return Mathf.Clamp(optionBehaviour.GetFloat(), Min, Max);
return Math.Clamp(optionBehaviour.GetFloat(), Min, Max);
}
/// <inheritdoc />
@@ -316,9 +313,9 @@ public class ModdedNumberOption : ModdedOption<float>
}
/// <inheritdoc />
protected internal override ConfigDescription? CreateDescription()
protected override ConfigDescription? CreateDescription()
{
return new(string.Empty, new AcceptableValueRange<float>(Min, Max));
return new(string.Empty, new SafeAcceptableValueRange<float>(Min, Max));
}
/// <summary>
+50 -23
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
@@ -14,20 +15,16 @@ 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;
/// <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; }
/// <summary>
/// Gets or sets the value of the option.
@@ -46,18 +43,23 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
}
}
private T _value = defaultValue;
/// <summary>
/// The backing value field. Use only for raw and quick comparisons, otherwise use <see cref="Value"/>.
/// </summary>
[SuppressMessage("Design", "CA1051:Do not declare visible instance fields", Justification = "Useful for raw checks that do not need modifications upon read or write.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
protected T _value;
/// <summary>
/// Gets the default value of the option.
/// </summary>
public T DefaultValue { get; } = defaultValue;
public T DefaultValue { get; }
/// <inheritdoc />
public Func<bool> Visible { get; set; } = DelegateUtilities.AlwaysTrue;
/// <inheritdoc />
public bool IncludeInPreset { get; set; } = includeInPreset;
public bool IncludeInPreset { get; set; }
/// <inheritdoc />
public bool ShowNotification { get; set; } = true;
@@ -121,6 +123,23 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
/// <inheritdoc />
public virtual OptionNotifConfiguration Configuration => new(ParentGroup);
/// <summary>
/// Initializes a new instance of the <see cref="ModdedOption{T}"/> class.
/// </summary>
/// <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>
protected ModdedOption(string groupPrefix, string title, T defaultValue, bool includeInPreset = true)
{
var translationId = groupPrefix + title;
Title = translationId;
StringName = MiraLocaleManager.GetOrCreateLocaleString(translationId);
DefaultValue = _value = defaultValue;
IncludeInPreset = includeInPreset;
}
/// <summary>
/// Initializes a new instance of the <see cref="ModdedOption{T}"/> class.
/// </summary>
@@ -162,16 +181,8 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
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);
}
if (ShowNotification && HudManager.InstanceExists)
ShowNotif();
OnValueChanged(_value);
ShowNotification = true;
@@ -262,13 +273,29 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
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
/// <summary>
/// Creates a <see cref="ConfigDescription"/> instance for the option's backing config.
/// </summary>
/// <returns>The option's config description, or null if there is none.</returns>
protected virtual ConfigDescription? CreateDescription()
{
return null;
}
/// <summary>
/// Pops the notification modifier.
/// </summary>
protected virtual void ShowNotif()
{
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
StringName,
GetDisplayValue(),
Configuration.PopUpTextColor,
Configuration.PopUpIconTmp,
false);
}
/// <summary>
/// Implicitly converts the option to type of <typeparamref name="T"/>.
/// </summary>
@@ -67,8 +67,12 @@ public class ModdedPlayerOption : ModdedOption<int>
PlayerOption playerOpt,
Transform container)
{
var oldPlayer = GetPlayerValue();
Values = GetFilteredPlayers();
var newIndex = oldPlayer ? Values.IndexOf(oldPlayer!) : -1;
Value = newIndex >= 0 ? newIndex : (AllowNone ? -1 : 0);
var playerOption = Object.Instantiate(playerOpt, container);
playerOption.name = $"{ParentMod!.OptionsTitleText}.PlayerOption.{Title}";
@@ -78,7 +82,7 @@ public class ModdedPlayerOption : ModdedOption<int>
playerOption.Title = StringName;
playerOption.Values = Values.ToIl2CppList();
playerOption.Value = Value;
playerOption.playerIndex = Values.FindIndex(p => p.PlayerId == Value);
playerOption.playerIndex = Value;
playerOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
playerOption.SetValueText();
@@ -125,7 +129,7 @@ public class ModdedPlayerOption : ModdedOption<int>
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, BitConverter.GetBytes(Value));
return new NetData(Id, BitConverter.GetBytes(_value));
}
/// <inheritdoc />
@@ -153,8 +157,8 @@ public class ModdedPlayerOption : ModdedOption<int>
public override string GetDisplayValue()
{
var player = GetPlayerValue();
return !player
? TranslationController.Instance.GetString(StringNames.None)
: player!.PlayerName;
return player
? player!.PlayerName
: TranslationController.Instance.GetString(StringNames.None);
}
}
@@ -1,7 +1,5 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.Translation;
@@ -29,7 +27,6 @@ public class ModdedStringOption : ModdedBaseStringOption<string>
{
Values = values;
UnderlyingValues = values;
StringNameValues = [.. values.Select(MiraLocaleManager.GetOrCreateLocaleString)];
InitializeData(GetIndex(defaultValue));
}
@@ -54,6 +51,8 @@ public class ModdedStringOption : ModdedBaseStringOption<string>
[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)
{
Warning("Use the Setter feature of modded options to simulate conditional values.");
if (!Values.Contains(value))
{
if (index <= -1)
@@ -97,17 +96,17 @@ public class ModdedStringOption : ModdedBaseStringOption<string>
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value, NumberFormatInfo.InvariantInfo)));
return new NetData(Id, BitConverter.GetBytes(GetIndex(_value)));
}
/// <inheritdoc />
public override void HandleNetData(byte[] data)
{
SetValue(Encoding.Unicode.GetString(data));
SetValue(UnderlyingValues[BitConverter.ToInt32(data)]);
}
/// <inheritdoc />
protected internal override ConfigDescription? CreateDescription()
protected override ConfigDescription? CreateDescription()
{
return new(string.Empty, new AcceptableValueList<string>(UnderlyingValues));
}
@@ -118,7 +118,7 @@ public class ModdedToggleOption : ModdedOption<bool>
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, BitConverter.GetBytes(Value));
return new NetData(Id, BitConverter.GetBytes(_value));
}
/// <inheritdoc />
@@ -1,4 +1,5 @@
using System.Collections;
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using BepInEx.Unity.IL2CPP.Utils.Collections;
@@ -69,7 +70,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr)
var item = Helpers.GetAlivePlayers().Count(x => !x.Data.Role.IsImpostor);
return !player.inVent && player.Data != null && player.Data.Role != null &&
((!player.inVent && player.Data.Role.IsImpostor && IsFinalCountdown &&
OptionGroupSingleton<HnsFinalHideOptions>.Instance.FinalHideSeekMap.Value) ||
OptionGroupSingleton<HnsFinalHideOptions>.Instance.FinalHideSeekMap) ||
(player.Data.Role.IsImpostor &&
item <=
(GameData.Instance.PlayerCount - 1) / 3));
@@ -95,8 +96,8 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr)
/// <returns>The match duration in seconds.</returns>
public static float GetTotalRoundTime()
{
var escapeTime = OptionGroupSingleton<HnsCrewmateOptions>.Instance.HidingTime.Value;
var finalCountdownTime = OptionGroupSingleton<HnsFinalHideOptions>.Instance.FinalHideTime.Value;
var escapeTime = OptionGroupSingleton<HnsCrewmateOptions>.Instance.HidingTime;
var finalCountdownTime = OptionGroupSingleton<HnsFinalHideOptions>.Instance.FinalHideTime;
return escapeTime + finalCountdownTime;
}
@@ -120,9 +121,9 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr)
private void Start()
{
totalHideTime = OptionGroupSingleton<HnsCrewmateOptions>.Instance.HidingTime.Value;
totalHideTime = OptionGroupSingleton<HnsCrewmateOptions>.Instance.HidingTime;
currentHideTime = totalHideTime;
totalFinalHideTime = OptionGroupSingleton<HnsFinalHideOptions>.Instance.FinalHideTime.Value;
totalFinalHideTime = OptionGroupSingleton<HnsFinalHideOptions>.Instance.FinalHideTime;
currentFinalHideTime = totalFinalHideTime;
if (timerBar != null)
{
@@ -244,7 +245,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr)
{
playerControl.ClearTasks();
PlayerTask.GetOrCreateTask<ImportantTextTask>(playerControl).Text =
DestroyableSingleton<TranslationController>.Instance.GetString(StringNames.HideActionButton);
TranslationController.Instance.GetString(StringNames.HideActionButton);
}
}
@@ -259,14 +260,14 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr)
timerBar.StartFinalHide();
SoundManager.Instance.PlaySound(finalHideAlertSfx, false);
DestroyableSingleton<HudManager>.Instance.SetAlertOverlay(true);
HudManager.Instance.SetAlertOverlay(true);
}
private void AdjustEscapeTimer(float timeDeduction, bool forceDirty)
{
var num = currentHideTime;
currentHideTime -= timeDeduction;
currentHideTime = Mathf.Max(currentHideTime, 0f);
currentHideTime = Math.Max(currentHideTime, 0f);
if (currentHideTime <= 10f && beepCoroutine == null)
{
beepCoroutine = StartCoroutine(BeepAlmostEverySecond().WrapToIl2Cpp());
@@ -308,7 +309,7 @@ public sealed class HideAndSeekHudHelper(nint cppPtr) : MonoBehaviour(cppPtr)
private void AdjustFinalEscapeTimer(float timeDeduction)
{
currentFinalHideTime -= timeDeduction;
currentFinalHideTime = Mathf.Max(currentFinalHideTime, 0f);
currentFinalHideTime = Math.Max(currentFinalHideTime, 0f);
timerBar.UpdateTimer(currentFinalHideTime, totalFinalHideTime);
if (secondsSinceLastSetDirty > 1f)
{
+3 -3
View File
@@ -91,9 +91,9 @@ public sealed class HnsDangerMeter(nint cppPtr) : MonoBehaviour(cppPtr)
}
}
dangerLevel1 = Mathf.Clamp01(
dangerLevel1 = MathUtilities.Clamp01(
(scaryMusicDistance - num) / (scaryMusicDistance - veryScaryMusicDistance));
dangerLevel2 = Mathf.Clamp01((veryScaryMusicDistance - num) / veryScaryMusicDistance);
dangerLevel2 = MathUtilities.Clamp01((veryScaryMusicDistance - num) / veryScaryMusicDistance);
}
UpdateDangerMeter();
@@ -137,7 +137,7 @@ public sealed class HnsDangerMeter(nint cppPtr) : MonoBehaviour(cppPtr)
impostors = [.. Helpers.GetAlivePlayers().Where(x => x.Data.Role.IsImpostor)];
var baseSpeed = OptionGroupSingleton<HnsCrewmateOptions>.Instance.PlayerSpeed.Value;
var baseSpeed = OptionGroupSingleton<HnsCrewmateOptions>.Instance.PlayerSpeed;
scaryMusicDistance = 55f * baseSpeed;
veryScaryMusicDistance = 15f * baseSpeed;
if (scaryMusicDistance >= veryScaryMusicDistance) return;
+6 -5
View File
@@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis;
using Amongus.GameModes.HideAndSeek;
using MiraAPI.GameOptions;
using MiraAPI.HnsReimplemented.Options;
using MiraAPI.Utilities;
using Reactor.Utilities.Attributes;
using UnityEngine;
@@ -145,7 +146,7 @@ public sealed class HnsMusicHandler(nint cppPtr) : MonoBehaviour(cppPtr)
public void StartMusicWithIntro()
{
if (!PlayerControl.LocalPlayer.Data.Role.IsImpostor) return;
var clip = OptionGroupSingleton<HnsCrewmateOptions>.Instance.HidingTime.Value <= 180f
var clip = OptionGroupSingleton<HnsCrewmateOptions>.Instance.HidingTime <= 180f
? musicCollection.ImpostorShortMusic
: musicCollection.ImpostorLongMusic;
if (AprilFoolsMode.ShouldHorseAround())
@@ -178,19 +179,19 @@ public sealed class HnsMusicHandler(nint cppPtr) : MonoBehaviour(cppPtr)
SyncMusic();
}
normalSource.volume = Mathf.Lerp(
normalSource.volume = MathUtilities.Lerp(
normalSource.volume,
normalVolume,
Time.fixedDeltaTime * musicLerpSpeed);
taskSource.volume = Mathf.Lerp(
taskSource.volume = MathUtilities.Lerp(
taskSource.volume,
taskVolume,
Time.fixedDeltaTime * musicLerpSpeed);
dangerLevel1Source.volume = Mathf.Lerp(
dangerLevel1Source.volume = MathUtilities.Lerp(
dangerLevel1Source.volume,
dangerLevel1Volume,
Time.fixedDeltaTime * musicLerpSpeed);
dangerLevel2Source.volume = Mathf.Lerp(
dangerLevel2Source.volume = MathUtilities.Lerp(
dangerLevel2Source.volume,
dangerLevel2Volume,
Time.fixedDeltaTime * musicLerpSpeed);
@@ -1,5 +1,6 @@
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
@@ -9,108 +10,67 @@ namespace MiraAPI.HnsReimplemented.Options;
/// Crewmate options for Hide and Seek.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.)
[SearchPrivate]
public class HnsCrewmateOptions : AbstractOptionGroup<HideAndSeekMode>
{
/// <inheritdoc />
public override string GroupName => "Crewmates";
public override string GroupName => "MiraApi.Option.Group.HnsCrewmate";
/// <inheritdoc />
public override string GroupPrefix => "MiraApi.HnsCrewmate.Option.";
/// <summary>
/// Gets the player speed.
/// </summary>
public ModdedNumberOption PlayerSpeed { get; } = new(
"Player Speed",
1f,
0.5f,
3f,
0.25f,
"#",
"#",
MiraNumberSuffixes.Multiplier,
"0.00");
[ModdedNumberOption(0.5f, 3f, 0.25f, "#", "#", MiraNumberSuffixes.Multiplier, "0.00")]
public float PlayerSpeed { get; } = 1f;
/// <summary>
/// Gets the hiding time.
/// </summary>
public ModdedNumberOption HidingTime { get; } = new(
"Hiding Time",
200,
160,
300,
20,
"#",
"#",
MiraNumberSuffixes.Seconds);
[ModdedNumberOption(160, 300, 20, "#", "#", MiraNumberSuffixes.Seconds)]
public float HidingTime { get; } = 200f;
/// <summary>
/// Gets the limits of a crewmate's vision.
/// </summary>
public ModdedNumberOption CrewmateVision { get; } = new(
"Crewmate Vision",
0.6f,
0.25f,
1,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier,
"0.00");
[ModdedNumberOption(0.25f, 1, 0.05f, "#", "#", MiraNumberSuffixes.Multiplier, "0.00")]
public float CrewmateVision { get; } = 0.6f;
/// <summary>
/// Gets a flag that toggles flashlight vision.
/// Gets a value indicating whether flashlight vision is turned on or not.
/// </summary>
public ModdedToggleOption FlashlightMode { get; } = new(
"Flashlight Mode",
true);
[ModdedToggleOption]
public bool FlashlightMode { get; } = true;
/// <summary>
/// Gets the range of a crewmate's flashlight.
/// </summary>
public ModdedNumberOption CrewmateFlashlightSize { get; } = new(
"Crewmate Flashlight Size",
0.35f,
0.1f,
0.5f,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier)
{
Visible = () => OptionGroupSingleton<HnsCrewmateOptions>.Instance.FlashlightMode.Value,
};
[ModdedNumberOption(0.1f, 0.5f, 0.05f, "#", "#", MiraNumberSuffixes.Multiplier)]
[ModdedOptionVisibility(nameof(FlashlightMode))]
public float CrewmateFlashlightSize { get; } = 0.35f;
/// <summary>
/// Gets the maximum number of times a crewmate can vent.
/// </summary>
public ModdedNumberOption MaxVentUses { get; } = new(
"Max Vent Uses",
1,
0,
5,
1,
"#",
"#",
MiraNumberSuffixes.None);
[ModdedNumberOption(0, 5, 1, "#", "#", MiraNumberSuffixes.None)]
public int MaxVentUses { get; } = 1;
/// <summary>
/// Gets the maximum amount of time a crewmate can spend inside a vent.
/// </summary>
public ModdedNumberOption MaxTimeInVent { get; } = new(
"Max Time in Vent",
3,
1,
10,
1,
"#",
"#",
MiraNumberSuffixes.Seconds)
{
Visible = () => (int)OptionGroupSingleton<HnsCrewmateOptions>.Instance.MaxVentUses.Value > 0,
};
[ModdedNumberOption(1, 10, 1, "#", "#", MiraNumberSuffixes.Seconds)]
[ModdedOptionVisibility(nameof(LimitedVentUses))]
public float MaxTimeInVent { get; } = 3f;
/// <summary>
/// Gets the visibility of player names.
/// Gets a value indicating whether player names are visible.
/// </summary>
public ModdedToggleOption ShowNames { get; } = new(
"Show Names",
false);
[ModdedToggleOption]
public bool ShowNames { get; } = false;
private bool LimitedVentUses()
{
return MaxVentUses > 0;
}
}
@@ -1,5 +1,6 @@
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
@@ -9,62 +10,43 @@ namespace MiraAPI.HnsReimplemented.Options;
/// Final Hide options for Hide and Seek.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.)
[SearchPrivate]
public class HnsFinalHideOptions : AbstractOptionGroup<HideAndSeekMode>
{
/// <inheritdoc />
public override string GroupName => "Final Hide";
public override string GroupName => "MiraApi.Option.Group.HnsFinalHide";
/// <inheritdoc />
public override string GroupPrefix => "MiraApi.HnsFinalHide.Option.";
/// <summary>
/// Gets the duration of the Final Hide phase.
/// </summary>
public ModdedNumberOption FinalHideTime { get; } = new(
"Hiding Time",
50,
30,
120,
5,
"#",
"#",
MiraNumberSuffixes.Seconds);
[ModdedNumberOption(30f, 120f, 5f, "#", "#", MiraNumberSuffixes.Seconds)]
public float FinalHideTime { get; } = 50f;
/// <summary>
/// Gets the Seeker's speed when the Final Hide phase begins.
/// </summary>
public ModdedNumberOption FinalHideImpostorSpeed { get; } = new(
"Final Hide Impostor Speed",
1.2f,
1f,
3,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier,
"0.00");
[ModdedNumberOption(1f, 3f, 0.05f, "#", "#", MiraNumberSuffixes.Multiplier, "0.00")]
public float FinalHideImpostorSpeed { get; } = 1.2f;
/// <summary>
/// Gets whether the Seeker sees the Final hide player pings.
/// Gets a value indicating whether the Seeker sees the Final hide player pings.
/// </summary>
public ModdedToggleOption FinalHidePings { get; } = new(
"Final Hide Pings",
true);
[ModdedToggleOption]
public bool FinalHidePings { get; } = true;
/// <summary>
/// Gets the interval between each ping.
/// </summary>
public ModdedNumberOption PingInterval { get; } = new(
"Ping Interval",
6,
3,
10,
5,
"#",
"#",
MiraNumberSuffixes.Seconds);
[ModdedNumberOption(3f, 10f, 1f, "#", "#", MiraNumberSuffixes.Seconds)]
[ModdedOptionVisibility(nameof(FinalHidePings))]
public float PingInterval { get; } = 6f;
/// <summary>
/// Gets whether the Seeker can see players on an admin map.
/// Gets a value indicating whether the Seeker can see players on an admin map.
/// </summary>
public ModdedToggleOption FinalHideSeekMap { get; } = new(
"Final Hide Seek Map",
true);
[ModdedToggleOption]
public bool FinalHideSeekMap { get; } = true;
}
@@ -1,5 +1,6 @@
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
@@ -9,44 +10,36 @@ namespace MiraAPI.HnsReimplemented.Options;
/// Seeker settings on Hide and Seek.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.)
[SearchPrivate]
public class HnsImpostorOptions : AbstractOptionGroup<HideAndSeekMode>
{
/// <inheritdoc />
public override string GroupName => "Impostors";
public override string GroupName => "MiraApi.Option.Group.HnsImpostor";
/// <inheritdoc />
public override string GroupPrefix => "MiraApi.HnsImpostor.Option.";
/// <summary>
/// Gets the player who will be the seeker.
/// </summary>
public ModdedPlayerOption SelectedSeeker { get; } = new(
"Forced Impostor");
[ModdedPlayerOption]
public int SelectedSeeker { get; } = 0;
/// <summary>
/// Gets the range of a seeker's vision.
/// </summary>
public ModdedNumberOption ImpostorVision { get; } = new(
"Impostor Vision",
0.6f,
0.25f,
1,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier,
"0.00");
[ModdedNumberOption(0.25f, 1f, 0.05f, "#", "#", MiraNumberSuffixes.Multiplier, "0.00")]
public float ImpostorVision { get; } = 0.6f;
/// <summary>
/// Gets the range of a seeker's flashlight.
/// </summary>
public ModdedNumberOption ImpostorFlashlightSize { get; } = new(
"Impostor Flashlight Size",
0.35f,
0.1f,
0.5f,
0.05f,
"#",
"#",
MiraNumberSuffixes.Multiplier)
[ModdedNumberOption(0.1f, 0.5f, 0.05f, "#", "#", MiraNumberSuffixes.Multiplier)]
[ModdedOptionVisibility(nameof(IsFlashlightModeEnabled))]
public float ImpostorFlashlightSize { get; } = 0.35f;
private static bool IsFlashlightModeEnabled()
{
Visible = () => OptionGroupSingleton<HnsCrewmateOptions>.Instance.FlashlightMode.Value,
};
return OptionGroupSingleton<HnsCrewmateOptions>.Instance.FlashlightMode;
}
}
@@ -1,5 +1,6 @@
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
@@ -9,47 +10,30 @@ namespace MiraAPI.HnsReimplemented.Options;
/// Task options for Hide and Seek.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated via Activator.CreateInstance.)
[SearchPrivate]
public class HnsTaskOptions : AbstractOptionGroup<HideAndSeekMode>
{
/// <inheritdoc />
public override string GroupName => "Tasks";
public override string GroupName => "MiraApi.Option.Group.HnsTask";
/// <inheritdoc />
public override string GroupPrefix => "MiraApi.HnsTask.Option.";
/// <summary>
/// Gets the umber of common tasks.
/// Gets the number of common tasks.
/// </summary>
public ModdedNumberOption CommonTasks { get; } = new(
"# Common Tasks",
1,
0,
4,
1,
"#",
"#",
MiraNumberSuffixes.None);
[ModdedNumberOption(0, 4, 1, "#", "#", MiraNumberSuffixes.None)]
public int CommonTasks { get; } = 1;
/// <summary>
/// Gets the number of long tasks.
/// </summary>
public ModdedNumberOption LongTasks { get; } = new(
"# Long Tasks",
1,
0,
4,
1,
"#",
"#",
MiraNumberSuffixes.None);
[ModdedNumberOption(0, 4, 1, "#", "#", MiraNumberSuffixes.None)]
public int LongTasks { get; } = 1;
/// <summary>
/// Gets the number of short tasks.
/// </summary>
public ModdedNumberOption ShortTasks { get; } = new(
"# Short Tasks",
2,
0,
8,
1,
"#",
"#",
MiraNumberSuffixes.None);
[ModdedNumberOption(0, 8, 1, "#", "#", MiraNumberSuffixes.None)]
public int ShortTasks { get; } = 2;
}
+2 -2
View File
@@ -297,7 +297,7 @@ public abstract class CustomActionButton
/// <param name="time">The time you want to set to.</param>
public virtual void SetTimer(float time)
{
Timer = Mathf.Clamp(time, -1, float.MaxValue);
Timer = Math.Clamp(time, -1, float.MaxValue);
}
/// <summary>
@@ -333,7 +333,7 @@ public abstract class CustomActionButton
/// <param name="amount">The amount you want to set to.</param>
public virtual void SetUses(int amount)
{
UsesLeft = Mathf.Clamp(amount, 0, int.MaxValue);
UsesLeft = Math.Clamp(amount, 0, int.MaxValue);
Button?.SetUsesRemaining(UsesLeft);
if (Button != null) Button.usesRemainingSprite.color = UsesLeft == 0 ? Color.red : Color.white;
+2 -2
View File
@@ -121,7 +121,7 @@ public abstract class CustomPaginableMenu : CustomPhoneMenu<CustomPaginableMenu.
private static int GetTotalPages(int itemCount)
{
return Mathf.Max(1, Mathf.CeilToInt(itemCount / (float)ItemsPerPage));
return Math.Max(1, Mathf.CeilToInt(itemCount / (float)ItemsPerPage));
}
private void RefreshControllerOverlay(CppCollections.List<UiElement> list)
@@ -170,7 +170,7 @@ public abstract class CustomPaginableMenu : CustomPhoneMenu<CustomPaginableMenu.
var filtered = GetFilteredEntries();
noResultsText?.gameObject.SetActive(filtered.Count == 0 && !string.IsNullOrWhiteSpace(searchText));
var totalPages = GetTotalPages(filtered.Count);
currentPage = Mathf.Clamp(currentPage, 0, totalPages - 1);
currentPage = Math.Clamp(currentPage, 0, totalPages - 1);
var list = filtered.Skip(currentPage * ItemsPerPage).Take(ItemsPerPage).ToList();
var list2 = new CppCollections.List<UiElement>();
+1 -1
View File
@@ -145,7 +145,7 @@ public abstract class LocalSettingsTab(ConfigFile config)
TabButton.Content = tab.gameObject;
}
Dictionary<string, List<ILocalSetting>> entriesByGroup = [];
Dictionary<string, List<ILocalSetting>> entriesByGroup = new(StringComparer.Ordinal);
foreach (var entry in Settings)
{
@@ -88,8 +88,8 @@ public class LocalSliderSetting(
newSlider.OnValueChange.AddListener((UnityAction)(() =>
{
SetValue(RoundValue
? Mathf.Round(Mathf.Lerp(SliderRange.min, SliderRange.max, newSlider.Value))
: Mathf.Lerp(SliderRange.min, SliderRange.max, newSlider.Value));
? MathF.Round(MathUtilities.Lerp(SliderRange.min, SliderRange.max, newSlider.Value))
: MathUtilities.Lerp(SliderRange.min, SliderRange.max, newSlider.Value));
newSlider.Title.text = GetValueText();
}));
@@ -1,3 +1,4 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Il2CppInterop.Runtime.Attributes;
@@ -125,7 +126,7 @@ public class MeetingAbilityBehaviour : MonoBehaviour
/// <param name="maxTimer">The maximum timer.</param>
public void SetFillUp(float timer, float maxTimer)
{
var percentCool = Mathf.Clamp(timer / maxTimer, 0.001f, 1f);
var percentCool = Math.Clamp(timer / maxTimer, 0.001f, 1f);
if (percentCool <= 0) percentCool = 1f;
Renderer.material.SetFloat(ShaderID.Percent, percentCool);
}
@@ -1,3 +1,4 @@
using System;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
@@ -179,7 +180,7 @@ public abstract class MeetingActionButton
/// <param name="time">The time you want to set to.</param>
public virtual void SetTimer(float time)
{
Timer = Mathf.Clamp(time, -1, float.MaxValue);
Timer = Math.Clamp(time, -1, float.MaxValue);
}
/// <summary>
@@ -215,7 +216,7 @@ public abstract class MeetingActionButton
/// <param name="amount">The amount you want to set to.</param>
public virtual void SetUses(int amount)
{
UsesLeft = Mathf.Clamp(amount, 0, int.MaxValue);
UsesLeft = Math.Clamp(amount, 0, int.MaxValue);
Button?.SetUsesRemaining(UsesLeft);
if (Button != null)
@@ -115,7 +115,7 @@ public abstract class TargetedMeetingButton
public virtual void UpdateHandler()
{
Timer -= Time.deltaTime;
Timer = Mathf.Clamp(Timer, 0, int.MaxValue);
Timer = System.Math.Clamp(Timer, 0, int.MaxValue);
FixedUpdate();
}
+8 -4
View File
@@ -195,19 +195,22 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config)
/// Gets the scale of the ability buttons.
/// </summary>
[LocalSliderSetting(min: 0.5f, max: 1.5f, suffixType: MiraNumberSuffixes.Multiplier, formatString: "0.00", displayValue: true)]
public ConfigEntry<float> ButtonUIFactorSlider { get; } = config.Bind("MiraApi.VisualsUi", "MiraApi.ButtonScaleFactor", 0.75f);
public ConfigEntry<float> ButtonUIFactorSlider { get; } =
config.Bind("MiraApi.VisualsUi", "MiraApi.ButtonScaleFactor", 0.75f, new ConfigDescription(string.Empty, new SafeAcceptableValueRange<float>(0.5f, 1.5f)));
/// <summary>
/// Gets the scale of the UI buttons.
/// </summary>
[LocalSliderSetting(min: 0.3f, max: 2f, suffixType: MiraNumberSuffixes.Multiplier, formatString: "0.00", displayValue: true)]
public ConfigEntry<float> TopRightButtonsFactorSlider { get; } = config.Bind("MiraApi.VisualsUi", "MiraApi.TopRightButtonScaleFactor", 1f);
public ConfigEntry<float> TopRightButtonsFactorSlider { get; } =
config.Bind("MiraApi.VisualsUi", "MiraApi.TopRightButtonScaleFactor", 1f, new ConfigDescription(string.Empty, new SafeAcceptableValueRange<float>(0.3f, 2f)));
/// <summary>
/// Gets the fps specified by the player.
/// </summary>
[LocalSliderSetting(min: 60f, max: 240f, suffixType: MiraNumberSuffixes.None, formatString: "0", displayValue: true, roundValue: true)]
public ConfigEntry<float> SetFpsSlider { get; } = config.Bind("MiraApi.VisualsUi", "Max FPS", 120f);
public ConfigEntry<float> SetFpsSlider { get; } =
config.Bind("MiraApi.VisualsUi", "MiraApi.MaxFps", 120f, new ConfigDescription(string.Empty, new SafeAcceptableValueRange<float>(60f, 240f)));
/// <summary>
/// Gets whether the modifiers hud should be on the left side of the screen (under roles/task tab). Recommended for streamers.
@@ -225,7 +228,8 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config)
/// Gets the scale of the match info guide.
/// </summary>
[LocalSliderSetting(min: 0.5f, max: 1f, suffixType: MiraNumberSuffixes.Multiplier, formatString: "0.00", displayValue: true)]
public ConfigEntry<float> MatchInfoGuideScaleFactor { get; } = config.Bind("MiraApi.MatchInfoGuide", "MiraApi.MatchInfoGuideScaleFactor", 1f);
public ConfigEntry<float> MatchInfoGuideScaleFactor { get; } =
config.Bind("MiraApi.MatchInfoGuide", "MiraApi.MatchInfoGuideScaleFactor", 1f, new ConfigDescription(string.Empty, new SafeAcceptableValueRange<float>(0.5f, 1f)));
/// <summary>
/// Gets the flag indicating whether the wiki is on the bottom row.
-3
View File
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.GameOptions;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
@@ -171,7 +170,6 @@ public abstract class BaseModifier : IOptionable
/// <summary>
/// Gets the list of abilities or other similar information to display below the text of a modifier's wiki page.
/// </summary>
[HideFromIl2Cpp]
public virtual List<AdvancedWikiAbilityDescription> WikiAbilities => [];
/// <summary>
@@ -182,7 +180,6 @@ public abstract class BaseModifier : IOptionable
/// <summary>
/// Gets the <see cref="TMP_SpriteAsset"/> for the Modifier Icon.
/// </summary>
[HideFromIl2Cpp]
public virtual TMP_SpriteAsset IconTmp => null!;
/// <summary>
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -165,7 +166,7 @@ public class ModifierDisplayComponent(nint cppPtr) : MonoBehaviour(cppPtr)
private void UpdatePage()
{
var totalPages = Mathf.CeilToInt((float)_modifiers.Count / ItemsPerPage);
_currentPage = Mathf.Clamp(_currentPage, 0, Mathf.Max(0, totalPages - 1));
_currentPage = Math.Clamp(_currentPage, 0, Math.Max(0, totalPages - 1));
if (_modifiers.Count <= ItemsPerPage)
{
@@ -177,7 +178,7 @@ public class ModifierDisplayComponent(nint cppPtr) : MonoBehaviour(cppPtr)
_pagination.gameObject.SetActive(true);
if (_pageText != null)
{
_pageText.text = $"{MiraLocaleManager.Get("MiraApi.ModifierDisplay.Page", "Page")} {_currentPage + 1}/{Mathf.Max(totalPages, 1)}";
_pageText.text = $"{MiraLocaleManager.Get("MiraApi.ModifierDisplay.Page", "Page")} {_currentPage + 1}/{Math.Max(totalPages, 1)}";
}
_nextButton.gameObject.SetActive(true);
@@ -185,7 +186,7 @@ public class ModifierDisplayComponent(nint cppPtr) : MonoBehaviour(cppPtr)
_modifiers.Do(x => x.Value.gameObject.SetActive(false));
var start = _currentPage * ItemsPerPage;
var end = Mathf.Min(start + ItemsPerPage, _modifiers.Count);
var end = Math.Min(start + ItemsPerPage, _modifiers.Count);
var modifiers = _modifiers.ToArray();
for (var i = start; i < end; i++)
+4 -3
View File
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
@@ -24,7 +25,7 @@ namespace MiraAPI.Patches.Freeplay;
[HarmonyPatch(typeof(TaskAdderGame))]
public static class TaskAdderPatches
{
private static readonly Dictionary<string, TaskFolder> Folders = [];
private static readonly Dictionary<string, TaskFolder> Folders = new(StringComparer.Ordinal);
private static Scroller _scroller = null!;
public static string CrewmateName => TranslationController.Instance.GetString(StringNames.Crewmate);
@@ -237,7 +238,7 @@ public static class TaskAdderPatches
item.transform.SetParent(instance.TaskParent);
item.transform.localPosition = new Vector3(xCursor, yCursor, 0f);
item.transform.localScale = Vector3.one;
maxHeight = Mathf.Max(maxHeight, item.Text.bounds.size.y + 1.3f);
maxHeight = Math.Max(maxHeight, item.Text.bounds.size.y + 1.3f);
xCursor += instance.fileWidth;
if (xCursor > instance.lineWidth)
{
@@ -288,7 +289,7 @@ public static class TaskAdderPatches
taskFolder2.Parent = __instance;
taskFolder2.transform.localPosition = new Vector3(num, num2, 0f);
taskFolder2.transform.localScale = Vector3.one;
num3 = Mathf.Max(num3, taskFolder2.Text.bounds.size.y + 1.1f);
num3 = Math.Max(num3, taskFolder2.Text.bounds.size.y + 1.1f);
num += __instance.folderWidth;
if (num > __instance.lineWidth)
{
@@ -6,6 +6,7 @@ using BepInEx.Unity.IL2CPP.Utils.Collections;
using HarmonyLib;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Components;
using MiraAPI.Modifiers;
using MiraAPI.Presets;
using MiraAPI.Translation;
@@ -32,6 +33,29 @@ internal static class GameOptionsMenuPatch
private static TextMeshPro _gamemodeDescription = null!;
private static SpriteRenderer _modIcon = null!;
public static FlagsOption CreateOption(StringOption stringOption, Transform container)
{
var baseOption = Object.Instantiate(stringOption, container).DontUnload().DontDestroy();
var optionGO = baseOption.gameObject;
var titleText = baseOption.TitleText;
var valueText = baseOption.ValueText;
var button = baseOption.PlusBtn;
baseOption.MinusBtn.gameObject.Destroy();
baseOption.Destroy();
var flagsOption = optionGO.AddComponent<FlagsOption>();
flagsOption.TitleText = titleText;
flagsOption.ValueText = valueText;
flagsOption.Button = button;
flagsOption.buttons = new PassiveButton[] { button };
button.OnClick = new();
return flagsOption;
}
[HarmonyPrefix]
[HarmonyPatch(nameof(GameOptionsMenu.Initialize))]
public static bool InitPatch(GameOptionsMenu __instance)
@@ -93,7 +117,7 @@ internal static class GameOptionsMenuPatch
_gamemodeDescription.transform.localPosition = new Vector3(0.3f, 0, -0.01f);
_gamemodeDescription.horizontalAlignment = HorizontalAlignmentOptions.Left;
var texture = icon.LoadAsset().texture;
var scale = Mathf.Min(128f / texture.width, 128f / texture.height);
var scale = Math.Min(128f / texture.width, 128f / texture.height);
var newSprite = Sprite.Create(
texture,
@@ -590,7 +614,7 @@ internal static class GameOptionsMenuPatch
continue;
}
if (!opt.Visible.Invoke())
if (!opt.Visible())
{
newOpt.gameObject.SetActive(false);
continue;
@@ -1,9 +1,9 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Patches.Options;
@@ -52,7 +52,7 @@ public static class PlayerOptionPatches
return true;
}
var newIndex = Mathf.Clamp(index, 0, __instance.Values.Count - 1);
var newIndex = Math.Clamp(index, 0, __instance.Values.Count - 1);
__instance.playerIndex = newIndex;
__instance.Value = __instance.Values[newIndex].PlayerId;
return false;
@@ -688,8 +688,6 @@ public static class RoleSettingMenuPatches
var roleOptionSetting = Object.Instantiate(
__instance.roleOptionSettingOrigin,
Vector3.zero,
Quaternion.identity,
__instance.RoleChancesSettings.transform);
roleOptionSetting.transform.localPosition = new Vector3(-0.1f, scrollerNum, -2f);
@@ -743,7 +741,7 @@ public static class RoleSettingMenuPatches
passiveButton.interactableColor = btnRend.color = customRole.OptionsMenuColor.FindAlternateColor();
passiveButton.interactableHoveredColor = Color.white;
passiveButton.OnClick.AddListener((UnityAction)(() => { ChangeTab(role, __instance); }));
passiveButton.OnClick.AddListener((UnityAction)(() => ChangeTab(role, __instance)));
}
if (customRole.Configuration is { MaxRoleCount: 0 })
+4 -4
View File
@@ -1,9 +1,9 @@
using System.Linq;
using System;
using System.Linq;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Patches.Options;
@@ -57,7 +57,7 @@ public static class SettingPatches
{
__result = $"<b>{moddedNumberOption.NegativeWordValue}</b>";
}
else if (moddedNumberOption.ZeroWordValue != "#" && Mathf.Abs(value) < 0.0001f)
else if (moddedNumberOption.ZeroWordValue != "#" && Math.Abs(value) < 0.0001f)
{
__result = $"<b>{moddedNumberOption.ZeroWordValue}</b>";
}
@@ -66,7 +66,7 @@ public static class SettingPatches
__result = Helpers.FormatValue(value, suffix, formatString);
}
}
else if (zeroIsInfinity && Mathf.Abs(value) < 0.0001f)
else if (zeroIsInfinity && Math.Abs(value) < 0.0001f)
{
__result = "<b>∞</b>";
}
+12 -5
View File
@@ -147,7 +147,7 @@ public static class RoleGuidePatches
}
var targetSize = Helpers.MatchInfoGuideBaseScale *
Mathf.Clamp(scaleFactor, MinGuideScaleFactor, MaxGuideScaleFactor);
Math.Clamp(scaleFactor, MinGuideScaleFactor, MaxGuideScaleFactor);
instance.transitionOpen.targetSize = targetSize;
if (instance.MatchInfoParent.activeSelf)
{
@@ -228,12 +228,19 @@ public static class RoleGuidePatches
private static IEnumerator CoPreload(MatchInfoGuide instance)
{
while (instance && (!HudManager.InstanceExists || !GameManager.Instance))
var counter = 0;
while (!instance || !HudManager.InstanceExists || !GameManager.Instance)
{
yield return null;
counter++;
if (counter > 10)
{
yield break;
}
yield return new WaitForSeconds(1);
}
if (!instance || GameManager.Instance.TryCast<NormalGameManager>() == null)
if (GameManager.Instance.TryCast<NormalGameManager>() == null)
{
yield break;
}
@@ -1011,7 +1018,7 @@ public static class RoleGuidePatches
private static float GetGridScrollBounds(int count)
{
return Mathf.Clamp(Mathf.Ceil(count / 2f) * 1.3f - 1.5f, 0f, 999f);
return Math.Clamp(MathF.Ceiling(count / 2f) * 1.3f - 1.5f, 0f, 999f);
}
private static void StartPopulate(float delay = 0f)
+4 -3
View File
@@ -1,4 +1,5 @@
using HarmonyLib;
using System;
using HarmonyLib;
using UnityEngine;
namespace MiraAPI.Patches.Roles;
@@ -52,8 +53,8 @@ internal static class TaskPanelPatch
__instance.closedPosition = closePosition;
__instance.timer = __instance.open
? Mathf.Min(1f, __instance.timer + Time.deltaTime / __instance.animationTimeSeconds)
: Mathf.Max(0f, __instance.timer - Time.deltaTime / __instance.animationTimeSeconds);
? Math.Min(1f, __instance.timer + Time.deltaTime / __instance.animationTimeSeconds)
: Math.Max(0f, __instance.timer - Time.deltaTime / __instance.animationTimeSeconds);
var relativePos = new Vector3(
Mathf.SmoothStep(__instance.closedPosition.x, __instance.openPosition.x, __instance.timer),
+1 -1
View File
@@ -40,7 +40,7 @@ public sealed class MiraPluginManager
internal const BindingFlags DeclaredInstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
internal const BindingFlags DeclaredStaticMembers = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
private readonly Dictionary<string, MiraPluginInfo> _registeredPlugins = [];
private readonly Dictionary<string, MiraPluginInfo> _registeredPlugins = new(StringComparer.Ordinal);
internal MiraPluginInfo[] RegisteredPlugins { get; private set; } = [];
internal MiraPluginInfo[] RegisteredPluginsWithOptions { get; private set; } = [];
+32 -4
View File
@@ -26,11 +26,9 @@
<string name="MiraApi.CustomOptionMenuDescription">Apply game settings for this mod!</string>
<string name="MiraApi.Gamemode">Gamemode</string>
<string name="MiraApi.Gamemode.Classic">Classic</string>
<string name="MiraApi.Gamemode.Classic.Description">The classic Among Us experience!
Find the Impostors or deceive the Crew.</string>
<string name="MiraApi.Gamemode.Classic.Description">The classic Among Us experience![nl]Find the Impostors or deceive the Crew.</string>
<string name="MiraApi.Gamemode.HideAndSeek">Hide n Seek</string>
<string name="MiraApi.Gamemode.HideAndSeek.Description">You can run, but you can't hide!
Outlive the timer or eliminate the crew.</string>
<string name="MiraApi.Gamemode.HideAndSeek.Description">You can run, but you can't hide![nl]Outlive the timer or eliminate the crew.</string>
<string name="MiraApi.GameSetting.Global.ClickToClose">Click to close</string>
<string name="MiraApi.GameSetting.Global.ClickToOpen">Click to open</string>
<string name="MiraApi.GameSetting.Preset.Hint">Select or create a options preset for this game</string>
@@ -78,4 +76,34 @@ Outlive the timer or eliminate the crew.</string>
<string name="Activated">Activated</string>
<string name="Deactivated">Deactivated</string>
<string name="MiraApi.AbbreviatedDistance">unit(s)</string>
<string name="All">All</string>
<string name="None">None</string>
<string name="MiraApi.Compound">{0} + {1}</string>
<string name="MiraApi.Option.Group.HnsCrewmate">Crewmates</string>
<string name="MiraApi.HnsCrewmate.Option.PlayerSpeed">Player Speed</string>
<string name="MiraApi.HnsCrewmate.Option.HidingTime">Hiding Time</string>
<string name="MiraApi.HnsCrewmate.Option.CrewmateVision">Crewmate Vision</string>
<string name="MiraApi.HnsCrewmate.Option.FlashlightMode">Flashlight Mode</string>
<string name="MiraApi.HnsCrewmate.Option.CrewmateFlashlightSize">Crewmate Flashlight Size</string>
<string name="MiraApi.HnsCrewmate.Option.MaxVentUses">Max Vent Uses</string>
<string name="MiraApi.HnsCrewmate.Option.MaxTimeInVent">Max Time In Vent</string>
<string name="MiraApi.HnsCrewmate.Option.ShowNames">Show Names</string>
<string name="MiraApi.Option.Group.HnsFinalHide">Final Hide</string>
<string name="MiraApi.HnsFinalHide.Option.FinalHideTime">Hiding Time</string>
<string name="MiraApi.HnsFinalHide.Option.FinalHideImpostorSpeed">Final Hide Impostor Speed</string>
<string name="MiraApi.HnsFinalHide.Option.FinalHidePings">Final Hide Pings</string>
<string name="MiraApi.HnsFinalHide.Option.PingInterval">Ping Interval</string>
<string name="MiraApi.HnsFinalHide.Option.FinalHideSeekMap">Final Hide Seek Map</string>
<string name="MiraApi.Option.Group.HnsImpostor">Impostors</string>
<string name="MiraApi.HnsImpostor.Option.SelectedSeeker">Forced Impostor</string>
<string name="MiraApi.HnsImpostor.Option.ImpostorVision">Impostor Vision</string>
<string name="MiraApi.HnsImpostor.Option.ImpostorFlashlightSize">Impostor Flashlight Size</string>
<string name="MiraApi.Option.Group.HnsTask">Tasks</string>
<string name="MiraApi.HnsTask.Option.CommonTasks"># Common Tasks</string>
<string name="MiraApi.HnsTask.Option.LongTasks"># Long Tasks</string>
<string name="MiraApi.HnsTask.Option.ShortTasks"># Short Tasks</string>
</resources>
-5
View File
@@ -1,7 +1,6 @@
using System;
using System.Diagnostics.CodeAnalysis;
using AmongUs.GameOptions;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.GameModes;
using MiraAPI.Patches.Freeplay;
using MiraAPI.Utilities.Assets;
@@ -81,25 +80,21 @@ public record struct CustomRoleConfiguration
/// <summary>
/// Gets or sets the <see cref="Sprite"/> used for the Role Options menu screenshot.
/// </summary>
[HideFromIl2Cpp]
public LoadableAsset<Sprite>? OptionsScreenshot { get; set; } = null;
/// <summary>
/// Gets or sets the <see cref="Sprite"/> used for the Role Icon.
/// </summary>
[HideFromIl2Cpp]
public LoadableAsset<Sprite>? Icon { get; set; } = null;
/// <summary>
/// Gets or sets the <see cref="TMP_SpriteAsset"/> for the Role Icon.
/// </summary>
[HideFromIl2Cpp]
public TMP_SpriteAsset IconTmp { get; set; }
/// <summary>
/// Gets or sets the Intro sound for the Role.
/// </summary>
[HideFromIl2Cpp]
public LoadableAsset<AudioClip>? IntroSound { get; set; } = null;
/// <summary>
+7 -7
View File
@@ -186,11 +186,11 @@ public interface ICustomRole : IOptionable
/// <summary>
/// Binds the configuration options for this role to the provided ConfigFile.
/// </summary>
/// <param name="config">The ConfigFile to bind the options to.</param>
/// <param name="config">The <see cref="ConfigFile"/> to bind the options to.</param>
void BindConfig(ConfigFile config)
{
config.Bind(NumConfigDefinition, Configuration.DefaultRoleCount, new ConfigDescription(string.Empty, new AcceptableValueRange<int>(0, Configuration.MaxRoleCount)));
config.Bind(ChanceConfigDefinition, Configuration.DefaultChance, new ConfigDescription(string.Empty, new AcceptableValueRange<int>(0, 100)));
config.Bind(NumConfigDefinition, Configuration.DefaultRoleCount, new ConfigDescription(string.Empty, new SafeAcceptableValueRange<int>(0, Configuration.MaxRoleCount)));
config.Bind(ChanceConfigDefinition, Configuration.DefaultChance, new ConfigDescription(string.Empty, new SafeAcceptableValueRange<int>(0, 100)));
}
/// <summary>
@@ -231,7 +231,7 @@ public interface ICustomRole : IOptionable
return !Configuration.CanModifyChance
? Configuration.DefaultChance
: ParentMod.PluginConfig.TryGetEntry(ChanceConfigDefinition, out ConfigEntry<int> entry)
? Mathf.Clamp(entry.Value, 0, 100)
? Math.Clamp(entry.Value, 0, 100)
: null;
}
@@ -242,7 +242,7 @@ public interface ICustomRole : IOptionable
int? GetCount()
{
return ParentMod.PluginConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry<int> entry)
? Mathf.Clamp(entry.Value, 0, Configuration.MaxRoleCount)
? Math.Clamp(entry.Value, 0, Configuration.MaxRoleCount)
: null;
}
@@ -260,7 +260,7 @@ public interface ICustomRole : IOptionable
if (ParentMod.PluginConfig.TryGetEntry(ChanceConfigDefinition, out ConfigEntry<int> entry))
{
entry.Value = Mathf.Clamp(chance, 0, 100);
entry.Value = Math.Clamp(chance, 0, 100);
return;
}
@@ -275,7 +275,7 @@ public interface ICustomRole : IOptionable
{
if (ParentMod.PluginConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry<int> entry))
{
entry.Value = Mathf.Clamp(count, 0, Configuration.MaxRoleCount);
entry.Value = Math.Clamp(count, 0, Configuration.MaxRoleCount);
return;
}
+83 -16
View File
@@ -1,10 +1,12 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using AmongUs.Data;
using BepInEx;
using MiraAPI.Utilities;
using Reactor.Localization.Utilities;
using UnityEngine;
@@ -16,7 +18,9 @@ namespace MiraAPI.Translation;
/// </summary>
public static class MiraLocaleManager
{
private const string StringNamesPrefix = "StringNames";
private const string LangDirectory = "mira_languages";
private const string VanillaPrefix = "@vanilla:";
private const string RefPrefix = "@ref:";
private const int MaxDepth = 10;
@@ -35,9 +39,11 @@ public static class MiraLocaleManager
/// <summary>
/// Gets a dictionary mapping registered string keys to their corresponding <see cref="StringNames"/> enum values.
/// </summary>
public static readonly Dictionary<string, StringNames> RegisteredStringNames = [];
public static readonly Dictionary<string, StringNames> RegisteredStringNames = new(StringComparer.Ordinal);
internal static readonly Dictionary<StringNames, string> StringNamesLookup = [];
private static readonly Dictionary<string, StringNames> VanillaKeyMap = new(StringComparer.Ordinal);
/// <summary>
/// Gets a dictionary mapping <see cref="MiraLanguage"/> values to their standard language codes.
/// </summary>
@@ -73,7 +79,7 @@ public static class MiraLocaleManager
{ MiraLanguage.Hebrew, "heb" },
};
private static readonly Dictionary<string, MiraLanguage> ReverseLangLookup =
LangList.ToDictionary(x => x.Value, x => x.Key);
LangList.ToDictionary(x => x.Value, x => x.Key, StringComparer.Ordinal);
/// <summary>
/// Gets a dictionary mapping <see cref="MiraLanguage"/> values to their standard language codes.
@@ -147,6 +153,9 @@ public static class MiraLocaleManager
/// <returns>A <see cref="string"/> based on the key provided.</returns>
public static string Get(MiraLanguage language, string key, string fallback = "")
{
if (VanillaKeyMap.TryGetValue(key, out var stringName) && TranslationController.InstanceExists)
return TranslationController.Instance.GetString(stringName);
var text = Locale.GetValueOrDefault(language)?.GetValueOrDefault(key);
if (language != MiraLanguage.English)
@@ -173,14 +182,7 @@ public static class MiraLocaleManager
return GetParsed(CurrentLanguage, key, parseList, string.IsNullOrEmpty(fallback) ? key : fallback);
}
/// <summary>
/// Translates a key into the current language.
/// </summary>
/// <param name="language">The specific language to prioritize.</param>
/// <param name="key">The string id to find.</param>
/// <param name="parseList">List of keys to change into other text.</param>
/// <param name="fallback">Fallback string to use if no translation is found.</param>
/// <returns>A <see cref="string"/> based on the key provided.</returns>
/// <inheritdoc cref="GetParsed(MiraLanguage, string, ValueTuple{string, string}[], string)"/>
public static string GetParsed(
MiraLanguage language,
string key,
@@ -221,6 +223,49 @@ public static class MiraLocaleManager
return text;
}
/// <inheritdoc cref="GetParsed(MiraLanguage, string, ValueTuple{string, string}[], string)"/>
public static string GetParsed(
MiraLanguage language,
string key,
string fallback,
params object[] parseList)
{
var text = Get(language, key, fallback);
if (parseList == null || parseList.Length == 0)
{
return text;
}
return string.Format(CultureInfo.InvariantCulture, text, parseList);
}
/// <inheritdoc cref="GetParsed(MiraLanguage, string, ValueTuple{string, string}[], string)"/>
public static string GetParsed(
MiraLanguage language,
string key,
params object[] parseList)
{
return GetParsed(language, key, string.Empty, parseList);
}
/// <inheritdoc cref="GetParsed(MiraLanguage, string, ValueTuple{string, string}[], string)"/>
public static string GetParsed(
string key,
string fallback,
params object[] parseList)
{
return GetParsed(CurrentLanguage, key, fallback, parseList);
}
/// <inheritdoc cref="GetParsed(MiraLanguage, string, ValueTuple{string, string}[], string)"/>
public static string GetParsed(
string key,
params object[] parseList)
{
return GetParsed(CurrentLanguage, key, string.Empty, parseList);
}
/// <summary>
/// Builds a formatted translation ID string using a mod ID, a specific ID part, and a suffix.
/// </summary>
@@ -256,6 +301,11 @@ public static class MiraLocaleManager
return stringName;
}
if (VanillaKeyMap.TryGetValue(name, out stringName))
{
return stringName;
}
var newString = CustomStringName.CreateAndRegister(name);
RegisteredStringNames.Add(name, newString);
StringNamesLookup.Add(newString, name);
@@ -267,9 +317,9 @@ public static class MiraLocaleManager
/// </summary>
public static void LoadExternalLocale()
{
CheckExternalDirectory("mira.api", BepInEx.Paths.PluginPath);
CheckExternalDirectory("mira.api", BepInEx.Paths.BepInExRootPath);
CheckExternalDirectory("mira.api", BepInEx.Paths.GameRootPath);
CheckExternalDirectory("mira.api", Paths.PluginPath);
CheckExternalDirectory("mira.api", Paths.BepInExRootPath);
CheckExternalDirectory("mira.api", Paths.GameRootPath);
foreach (var mod in RegisteredModIds)
{
CheckExternalDirectory(mod, GetModLangDir(mod));
@@ -296,7 +346,7 @@ public static class MiraLocaleManager
try
{
Locale.TryAdd(lang, []);
Locale.TryAdd(lang, new(StringComparer.Ordinal));
using var fileStream = File.OpenRead(filePath);
ParseXmlFile(fileStream, lang, false);
}
@@ -332,7 +382,7 @@ public static class MiraLocaleManager
try
{
Locale.TryAdd(lang, []);
Locale.TryAdd(lang, new(StringComparer.Ordinal));
ParseXmlFile(resourceStream, lang, true);
atLeastOneLoaded = true;
}
@@ -378,7 +428,7 @@ public static class MiraLocaleManager
var dict = Locale[language];
var total = 0;
var pendingRefs = new Dictionary<string, string>();
var pendingRefs = new Dictionary<string, string>(StringComparer.Ordinal);
try
{
@@ -400,6 +450,23 @@ public static class MiraLocaleManager
{
pendingRefs[name] = value[RefPrefix.Length..];
}
else if (value.StartsWith(VanillaPrefix, StringComparison.Ordinal))
{
var enumString = value[VanillaPrefix.Length..];
if (enumString.StartsWith(StringNamesPrefix, StringComparison.Ordinal))
enumString = enumString[StringNamesPrefix.Length..];
if (Enum.TryParse<StringNames>(enumString, true, out var stringName))
{
VanillaKeyMap[name] = stringName;
total++;
}
else
{
Error($"Failed to parse vanilla StringNames enum: {enumString}");
}
}
else
{
value = value.Replace('[', '<')
@@ -69,9 +69,9 @@ public class MiraLocalizationProvider : LocalizationProvider
Warning($"<resources>");
foreach (var stringName in TranslationController.Instance.currentLanguage.AllStrings)
{
var value = stringName.Value.Replace("\n", "\\%nl\\%");
value = value.Replace("{", "[");
value = value.Replace("}", "]");
var value = stringName.Value.Replace("\n", "[nl]");
value = value.Replace("<", "[");
value = value.Replace(">", "]");
Warning($"<string name=\"{stringName.Key}\">{value}</string>");
}
Warning($"</resources>");*/
@@ -14,4 +14,15 @@ public static class TranslationExtensions
{
return MiraLocaleManager.Get(key);
}
/// <summary>
/// Translates a key to the current language.
/// </summary>
/// <param name="key">The translation key.</param>
/// <param name="args">The values to format the string with.</param>
/// <returns>The corresponding translation.</returns>
public static string Translate(this string key, params object[] args)
{
return MiraLocaleManager.GetParsed(key, string.Empty, args);
}
}
+1 -1
View File
@@ -61,6 +61,6 @@ public sealed class AcceptableEnumValues<T> : AcceptableValueBase
/// <inheritdoc/>
public override string ToDescriptionString()
{
return "# Acceptable values: " + string.Join(", ", AcceptableValues.Select(x => x.ToString()));
return "# Acceptable values: " + string.Join(", ", AcceptableValues);
}
}
+73
View File
@@ -0,0 +1,73 @@
using System;
using System.Globalization;
using BepInEx.Configuration;
namespace MiraAPI.Utilities;
/// <summary>
/// Specify the list of acceptable individual flag values for a setting.<br/>
/// Any bitwise combination of these provided flags is considered valid.
/// </summary>
/// <typeparam name="T">The type of the flag enum.</typeparam>
public sealed class AcceptableFlagValues<T> : AcceptableValueBase
where T : struct, Enum
{
/// <summary>
/// Gets a list of single-bit values that a setting can include.
/// </summary>
public T[] AcceptableValues { get; }
private readonly int allMask;
/// <summary>
/// Initializes a new instance of the <see cref="AcceptableFlagValues{T}"/> class.
/// </summary>
/// <param name="acceptableValues">The acceptable individual flags.</param>
/// <exception cref="ArgumentNullException">Thrown when the given values are null.</exception>
/// <exception cref="ArgumentException">Thrown when no values are given.</exception>
public AcceptableFlagValues(params T[] acceptableValues)
: base(typeof(T))
{
ArgumentNullException.ThrowIfNull(acceptableValues);
if (acceptableValues.Length == 0)
throw new ArgumentException("At least one acceptable value is needed", nameof(acceptableValues));
AcceptableValues = acceptableValues;
allMask = 0;
foreach (var val in acceptableValues)
allMask |= Convert.ToInt32(val, NumberFormatInfo.InvariantInfo);
}
/// <inheritdoc/>
public override object Clamp(object value)
{
if (IsValid(value))
return value;
if (value is not T)
return Enum.ToObject(typeof(T), 0);
var intVal = Convert.ToInt32(value, NumberFormatInfo.InvariantInfo);
var clampedVal = intVal & allMask;
return Enum.ToObject(typeof(T), clampedVal);
}
/// <inheritdoc/>
public override bool IsValid(object value)
{
if (value is not T)
return false;
var intVal = Convert.ToInt32(value, NumberFormatInfo.InvariantInfo);
return (intVal & ~allMask) == 0;
}
/// <inheritdoc/>
public override string ToDescriptionString()
{
return "# Acceptable Flags: " + string.Join(", ", AcceptableValues);
}
}
+2 -1
View File
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Reactor.Utilities.Extensions;
@@ -11,7 +12,7 @@ namespace MiraAPI.Utilities.Assets;
/// </summary>
public static class TmpSpriteUtils
{
private static readonly Dictionary<string, TMP_SpriteAsset> LoadedSprites = [];
private static readonly Dictionary<string, TMP_SpriteAsset> LoadedSprites = new(StringComparer.Ordinal);
private static Shader _spriteShader;
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
@@ -76,7 +76,7 @@ public class CenteredGridArrange(IntPtr iPtr) : MonoBehaviour(iPtr)
{
var row = index / MaxColumns;
var rowStartIndex = row * MaxColumns;
var itemsInRow = Mathf.Min(MaxColumns, cells.Count - rowStartIndex);
var itemsInRow = Math.Min(MaxColumns, cells.Count - rowStartIndex);
var col = index - rowStartIndex;
var rowWidth = (itemsInRow - 1) * CellSize.x;
+4 -4
View File
@@ -72,10 +72,10 @@ public class LoadingRing(IntPtr cppPtr) : MonoBehaviour(cppPtr)
{
var dx = x + 0.5f - (size / 2f);
var dy = y + 0.5f - (size / 2f);
var radius = Mathf.Sqrt((dx * dx) + (dy * dy));
var ring = Mathf.Clamp01(radius - innerRadius) * Mathf.Clamp01(outerRadius - radius);
var angle = (Mathf.Atan2(dy, dx) + Mathf.PI) / (2f * Mathf.PI);
pixels[(y * size) + x] = new Color(1f, 1f, 1f, ring * Mathf.Lerp(1f, 0.1f, angle));
var radius = MathF.Sqrt((dx * dx) + (dy * dy));
var ring = MathUtilities.Clamp01(radius - innerRadius) * MathUtilities.Clamp01(outerRadius - radius);
var angle = (MathF.Atan2(dy, dx) + MathF.PI) / (2f * MathF.PI);
pixels[(y * size) + x] = new Color(1f, 1f, 1f, ring * MathUtilities.Lerp(1f, 0.1f, angle));
}
}
+2 -2
View File
@@ -89,7 +89,7 @@ public static class Extensions
/// <param name="format">The format string to use for the timer text.</param>
public static void SetCooldownFormat(this ActionButton? button, float timer, float maxTimer, string format = "0")
{
var num = Mathf.Clamp(timer / maxTimer, 0f, 1f);
var num = Math.Clamp(timer / maxTimer, 0f, 1f);
button!.isCoolingDown = num > 0f;
button.SetCooldownFill(num);
if (button.isCoolingDown)
@@ -111,7 +111,7 @@ public static class Extensions
/// <param name="format">The format string to use for the timer text.</param>
public static void SetFillUpFormat(this ActionButton button, float timer, float maxTimer, string format = "0")
{
var num = Mathf.Clamp(timer / maxTimer, 0f, 1f);
var num = Math.Clamp(timer / maxTimer, 0f, 1f);
button.isCoolingDown = num > 0f;
if (button.isCoolingDown && timer < 3f)
{
+1 -1
View File
@@ -125,7 +125,7 @@ internal static class GuideOptionPages
item.Group.MatchInfoGuidePageOrder,
GetMenuOrder(item.Group.ParentMenu),
item.Group.GroupPriority,
Mathf.Clamp(item.Group.MatchInfoGuidePageColumns, 1, 6),
Math.Clamp(item.Group.MatchInfoGuidePageColumns, 1, 6),
item.ModAbbreviation,
modSearchTerms,
entries);
+11 -11
View File
@@ -284,7 +284,7 @@ public static class Helpers
where T : MonoBehaviour
{
T? closest = null;
var closestDistanceSqr = Mathf.Infinity;
var closestDistanceSqr = float.PositiveInfinity;
foreach (var obj in objectList)
{
@@ -805,8 +805,8 @@ public static class Helpers
obj.transform.localPosition = new Vector3(0f, 0.5f, 0f);
var scrollHeight = variableTextSizing
? desc.textBounds.size.y - 2.5f + maxTextSize + 0.475f
: desc.textBounds.size.y - 2.5f + Mathf.Ceil(num / 2f) * 1.45f;
parent.SetYBoundsMax(Mathf.Clamp(scrollHeight, 0f, 999f));
: desc.textBounds.size.y - 2.5f + MathF.Ceiling(num / 2f) * 1.45f;
parent.SetYBoundsMax(Math.Clamp(scrollHeight, 0f, 999f));
return obj;
}
@@ -888,7 +888,7 @@ public static class Helpers
const float groupHeaderContentGap = 0.05f;
const int contentSortingOrder = 151;
columns = Mathf.Clamp(columns, 1, 6);
columns = Math.Clamp(columns, 1, 6);
var inner = parent.Inner;
var layout = inner.GetComponent<GridLayoutGroup>();
if (layout)
@@ -896,11 +896,11 @@ public static class Helpers
layout.enabled = false;
}
var columnGap = layout ? Mathf.Clamp(layout.spacing.x, 0.1f, 0.6f) : 0.3f;
var columnGap = layout ? Math.Clamp(layout.spacing.x, 0.1f, 0.6f) : 0.3f;
const int baseColumnCount = 2;
var baseColumnWidth = layout ? Mathf.Clamp(layout.cellSize.x, 2f, 3.2f) : 2.7f;
var baseColumnWidth = layout ? Math.Clamp(layout.cellSize.x, 2f, 3.2f) : 2.7f;
var availableWidth = baseColumnWidth * baseColumnCount + columnGap * (baseColumnCount - 1);
var columnWidth = Mathf.Clamp(
var columnWidth = Math.Clamp(
(availableWidth - (columns - 1) * columnGap) / columns,
1f,
3.2f);
@@ -971,7 +971,7 @@ public static class Helpers
var group = groupedSettings[i].Key;
var band = i / columns;
groupColumns[group] = i % columns;
bandHeights[band] = Mathf.Max(
bandHeights[band] = Math.Max(
bandHeights[band],
rowPitch * (groupedSettings[i].Count() + 1) + groupHeaderContentGap + 0.25f);
}
@@ -979,7 +979,7 @@ public static class Helpers
var bandOffset = 0f;
for (var band = 0; band < bandCount; band++)
{
for (var i = band * columns; i < Mathf.Min((band + 1) * columns, groupedSettings.Count); i++)
for (var i = band * columns; i < Math.Min((band + 1) * columns, groupedSettings.Count); i++)
{
groupTopOffsets[groupedSettings[i].Key] = bandOffset;
groupRows[groupedSettings[i].Key] = 0;
@@ -1209,7 +1209,7 @@ public static class Helpers
{
if (renderer.enabled && renderer.gameObject.activeInHierarchy)
{
contentBottom = Mathf.Min(
contentBottom = Math.Min(
contentBottom,
inner.InverseTransformPoint(renderer.bounds.min).y);
}
@@ -1225,7 +1225,7 @@ public static class Helpers
var scrollRange = contentOverflow > 0.05f
? contentOverflow + 0.05f
: 0f;
parent.SetYBoundsMax(Mathf.Clamp(scrollRange, 0f, 999f));
parent.SetYBoundsMax(Math.Clamp(scrollRange, 0f, 999f));
return page;
}
@@ -0,0 +1,75 @@
using System;
using BepInEx.Configuration;
namespace MiraAPI.Utilities;
/// <summary>
/// Specify the range of acceptable values for a setting.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
public sealed class SafeAcceptableValueRange<T> : AcceptableValueBase
where T : IComparable<T>
{
/// <summary>
/// Gets the lowest acceptable value.
/// </summary>
public T Min { get; }
/// <summary>
/// Gets the highest acceptable value.
/// </summary>
public T Max { get; }
/// <summary>
/// Initializes a new instance of the <see cref="SafeAcceptableValueRange{T}"/> class.
/// </summary>
/// <param name="min">Lowest acceptable value.</param>
/// <param name="max">Highest acceptable value.</param>
public SafeAcceptableValueRange(T min, T max)
: base(typeof(T))
{
ArgumentNullException.ThrowIfNull(min);
ArgumentNullException.ThrowIfNull(max);
if (min.CompareTo(max) > 0)
{
Min = max;
Max = min;
}
else
{
Min = min;
Max = max;
}
}
/// <inheritdoc/>
public override object Clamp(object value)
{
if (value is not T val)
return Min;
if (val.CompareTo(Min) <= 0)
return Min;
if (val.CompareTo(Max) > 0)
return Max;
return val;
}
/// <inheritdoc/>
public override bool IsValid(object value)
{
if (value is not T val)
return false;
return val.CompareTo(Min) >= 0 && val.CompareTo(Max) <= 0;
}
/// <inheritdoc/>
public override string ToDescriptionString()
{
return $"# Acceptable value range: From {Min} to {Max}";
}
}
+3 -2
View File
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace MiraAPI.Utilities;
@@ -8,7 +9,7 @@ namespace MiraAPI.Utilities;
/// </summary>
public static class ShaderID
{
private static readonly Dictionary<string, int> Cache = [];
private static readonly Dictionary<string, int> Cache = new(StringComparer.Ordinal);
/// <summary>
/// Retrieves the cached shader property ID for the specified name. If it is not cached, it registers and caches the ID before returning it.
+1 -1
View File
@@ -46,7 +46,7 @@ public class StateMachineWrapper<T>
throw new MissingMemberException($"Could not find required properties in type '{_type}'.");
}
_propertyCache = [];
_propertyCache = new(StringComparer.Ordinal);
}
/// <summary>