reduce value boxing

This commit is contained in:
Az committed 2026-10-26 03:35:11 -04:00
1 parent 181013efec
commit 6f94e4ed21
18 files changed
+378 -52

No files matched your search

+2 -6
View File
@@ -30,16 +30,12 @@ public class ExampleOptions : AbstractOptionGroup
[ModdedNumberOption("options.exampleOptions1.numberOpt", min: 0, max: 10, suffixType: MiraNumberSuffixes.Distance)]
public int NumberOpt2 { get; set; } = 4; // Can also be int!
[ModdedEnumOption("options.exampleOptions1.bestApi", typeof(Api), ["Mira API", "Mitochondria", "Reactor"])]
public Api BestApi { get; set; } = Api.MiraAPI;
[ModdedEnumOption<Api>("options.exampleOptions1.worstApi", ["Mira API", "Mitochondria", "Reactor"])]
// These three can target both instance and static methods
[ModdedOptionGetter(nameof(GetApi))] // Can also automatically resolve to {Option Name}Getter
[ModdedOptionSetter(nameof(SetApi))] // Can also automatically resolve to {Option Name}Setter
[ModdedOptionChanged(nameof(ApiChanged))] // Can also automatically resolve to {Option Name}Changed
public Api WorstApi { get; set; } = Api.MiraAPI;
[ModdedEnumOption<Api>("options.exampleOptions1.bestApi", ["Mira API", "Mitochondria", "Reactor"])]
public Api BestApi { get; set; } = Api.MiraAPI;
[ModdedEnumOptionList<ValueState>("Value State {0}", ["None", "Primary", "Secondary"])]
public ModdedArray<ValueState> ValueStates { get; set; } = [ValueState.Primary, ValueState.Secondary, ValueState.None, ValueState.None, ValueState.None];
@@ -47,7 +47,6 @@ Eliminate every other faction.</string>
<string name="options.exampleOptions1.toggleOpt2">Toggle Opt 2</string>
<string name="options.exampleOptions1.numberOpt">Number Opt</string>
<string name="options.exampleOptions1.bestApi">Best API</string>
<string name="options.exampleOptions1.worstApi">Worst API</string>
<string name="options.exampleOptions1.players">Choose A Player</string>
<string name="options.exampleOptions2">Example Options 2</string>
<string name="options.exampleOptions2.youMustChoseAPlayer">YOU MUST CHOSE A PLAYER</string>
@@ -0,0 +1,20 @@
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Provides unboxed access to option values to prevent memory allocations.
/// </summary>
/// <typeparam name="T">The type of the value that the option carries.</typeparam>
public interface ITypedOption<T>
{
/// <summary>
/// Gets the unboxed value of the option.
/// </summary>
/// <returns>The unboxed option value.</returns>
T GetValueUnboxed();
/// <summary>
/// Sets the unboxed value of the option.
/// </summary>
/// <param name="value">The new value to set.</param>
void SetValueUnboxed(T value);
}
@@ -11,6 +11,7 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
[Obsolete("Use ModdedEnumOptionAttribute<T> instead.")]
public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? values = null)
: ModdedOptionAttribute(title)
{
@@ -32,7 +33,7 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va
{
return HolderOption is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {enumType.FullName} is not a ModdedEnumOption");
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedEnumOption with enum type {enumType.FullName}");
}
}
@@ -44,7 +45,7 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionAttribute<T>(string title, string[]? values = null)
: ModdedOptionAttribute(title)
: ModdedOptionAttribute(title), ITypedOption<T>
where T : struct, Enum
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
@@ -56,15 +57,26 @@ public class ModdedEnumOptionAttribute<T>(string title, string[]? values = null)
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedEnumOption<T>;
opt?.SetValue((T)value);
SetValueUnboxed((T)value);
}
/// <inheritdoc />
public void SetValueUnboxed(T value)
{
(HolderOption as ModdedEnumOption<T>)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue()
{
return GetValueUnboxed();
}
/// <inheritdoc />
public T GetValueUnboxed()
{
return HolderOption is ModdedEnumOption<T> opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {typeof(T).FullName} is not a ModdedEnumOption<{typeof(T).Name}>");
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedEnumOption<{typeof(T).Name}>");
}
}
@@ -28,7 +28,7 @@ public class ModdedNumberOptionAttribute(
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool halfIncrements = false)
: ModdedOptionAttribute(title)
: ModdedOptionAttribute(title), ITypedOption<int>, ITypedOption<float>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionAttribute"/> class.
@@ -88,6 +88,18 @@ public class ModdedNumberOptionAttribute(
opt.SetValue(final);
}
/// <inheritdoc />
public void SetValueUnboxed(float value)
{
(HolderOption as ModdedNumberOption)?.SetValue(value);
}
/// <inheritdoc />
void ITypedOption<int>.SetValueUnboxed(int value)
{
(HolderOption as ModdedNumberOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue()
{
@@ -101,4 +113,18 @@ public class ModdedNumberOptionAttribute(
return value;
}
/// <inheritdoc />
public float GetValueUnboxed()
{
return HolderOption is ModdedNumberOption opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedNumberOption");
}
/// <inheritdoc />
int ITypedOption<int>.GetValueUnboxed()
{
return (int)Math.Round(GetValueUnboxed());
}
}
@@ -13,7 +13,7 @@ namespace MiraAPI.GameOptions.Attributes;
public class ModdedPlayerOptionAttribute(
string title,
bool allowNone = true)
: ModdedOptionAttribute(title)
: ModdedOptionAttribute(title), ITypedOption<int>, ITypedOption<NetworkedPlayerInfo?>
{
internal override IModdedOption? CreateOption(object? value, PropertyInfo property)
{
@@ -33,6 +33,22 @@ public class ModdedPlayerOptionAttribute(
return opt.SelectedPlayer!;
}
/// <inheritdoc />
public NetworkedPlayerInfo? GetValueUnboxed()
{
return HolderOption is ModdedPlayerOption opt
? opt.SelectedPlayer
: throw new InvalidOperationException($"Holder option for {Title} is not a ModdedPlayerOption.");
}
/// <inheritdoc />
int ITypedOption<int>.GetValueUnboxed()
{
return HolderOption is ModdedPlayerOption opt
? opt.Value
: throw new InvalidOperationException($"Holder option for {Title} is not a ModdedPlayerOption.");
}
/// <inheritdoc />
public override void SetValue(object value)
{
@@ -41,9 +57,32 @@ public class ModdedPlayerOptionAttribute(
var final = value switch
{
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0),
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : -1,
_ => (int)value,
};
if (final == -1 && !allowNone)
throw new ArgumentException("Cannot assign -1 or null to a ModdedPlayerOption that does not allow none as an option.");
opt?.SetValue(final);
}
/// <inheritdoc />
public void SetValueUnboxed(NetworkedPlayerInfo? value)
{
if (!value && !allowNone)
throw new ArgumentException("Cannot assign null to a ModdedPlayerOption that does not allow none as an option.");
if (HolderOption is ModdedPlayerOption opt)
opt.SetValue(value ? opt.Values.IndexOf(value!) : -1);
}
/// <inheritdoc />
void ITypedOption<int>.SetValueUnboxed(int value)
{
if (value == -1 && !allowNone)
throw new ArgumentException("Cannot assign -1 to a ModdedPlayerOption that does not allow none as an option.");
(HolderOption as ModdedPlayerOption)?.SetValue(value);
}
}
@@ -13,7 +13,7 @@ namespace MiraAPI.GameOptions.Attributes;
public class ModdedStringOptionAttribute(
string title,
string[] values)
: ModdedOptionAttribute(title)
: ModdedOptionAttribute(title), ITypedOption<string>
{
internal override IModdedOption? CreateOption(object? value, PropertyInfo property)
{
@@ -23,6 +23,12 @@ public class ModdedStringOptionAttribute(
/// <inheritdoc />
public override object GetValue()
{
return GetValueUnboxed();
}
/// <inheritdoc />
public string GetValueUnboxed()
{
return HolderOption is ModdedStringOption opt
? opt.Value
@@ -32,7 +38,12 @@ public class ModdedStringOptionAttribute(
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedStringOption;
opt?.SetValue((string)value);
SetValueUnboxed((string)value);
}
/// <inheritdoc />
public void SetValueUnboxed(string value)
{
(HolderOption as ModdedStringOption)?.SetValue(value);
}
}
@@ -15,7 +15,7 @@ public class ModdedToggleOptionAttribute(
string title,
string on,
string off)
: ModdedOptionAttribute(title)
: ModdedOptionAttribute(title), ITypedOption<bool>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionAttribute"/> class.
@@ -35,12 +35,23 @@ public class ModdedToggleOptionAttribute(
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedToggleOption;
opt?.SetValue((bool)value);
SetValueUnboxed((bool)value);
}
/// <inheritdoc />
public void SetValueUnboxed(bool value)
{
(HolderOption as ModdedToggleOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue()
{
return GetValueUnboxed();
}
/// <inheritdoc />
public bool GetValueUnboxed()
{
return HolderOption is ModdedToggleOption opt
? opt.Value
@@ -0,0 +1,22 @@
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Provides unboxed access to option list values to prevent memory allocations.
/// </summary>
/// <typeparam name="T">The type of the value that the option list carries.</typeparam>
public interface ITypedOptionList<T>
{
/// <summary>
/// Gets the unboxed value of the option at the specified index.
/// </summary>
/// <param name="idx">The index of the option.</param>
/// <returns>The option at the provided index.</returns>
T GetValueUnboxed(int idx);
/// <summary>
/// Sets the unboxed value of the option at the specified index.
/// </summary>
/// <param name="idx">The index of the option.</param>
/// <param name="value">The new value of the option to set.</param>
void SetValueUnboxed(int idx, T value);
}
@@ -12,6 +12,7 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
[Obsolete("Use ModdedEnumOptionListAttribute<T> instead.")]
public class ModdedEnumOptionListAttribute(string title, Type enumType, string[]? values = null)
: ModdedOptionListAttribute(title)
{
@@ -34,7 +35,7 @@ public class ModdedEnumOptionListAttribute(string title, Type enumType, string[]
{
return HolderOptionList?[idx] is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {enumType.FullName} is not a ModdedEnumOption");
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedEnumOption with enum type {enumType.FullName}");
}
}
@@ -46,7 +47,7 @@ public class ModdedEnumOptionListAttribute(string title, Type enumType, string[]
/// <param name="values">The option's possible values.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionListAttribute<T>(string title, string[]? values = null)
: ModdedOptionListAttribute(title)
: ModdedOptionListAttribute(title), ITypedOptionList<T>
where T : struct, Enum
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
@@ -59,15 +60,26 @@ public class ModdedEnumOptionListAttribute<T>(string title, string[]? values = n
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedEnumOption<T>;
opt?.SetValue((T)value);
SetValueUnboxed(idx, (T)value);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, T value)
{
(HolderOptionList?[idx] as ModdedEnumOption<T>)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return GetValueUnboxed(idx);
}
/// <inheritdoc />
public T GetValueUnboxed(int idx)
{
return HolderOptionList?[idx] is ModdedEnumOption<T> opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {typeof(T).FullName} is not a ModdedEnumOption<{typeof(T).FullName}>");
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedEnumOption<{typeof(T).FullName}>");
}
}
@@ -29,7 +29,7 @@ public class ModdedNumberOptionListAttribute(
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool halfIncrements = false)
: ModdedOptionListAttribute(title)
: ModdedOptionListAttribute(title), ITypedOptionList<int>, ITypedOptionList<float>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionListAttribute"/> class.
@@ -92,6 +92,18 @@ public class ModdedNumberOptionListAttribute(
opt.SetValue(final);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, float value)
{
(HolderOptionList?[idx] as ModdedNumberOption)?.SetValue(value);
}
/// <inheritdoc />
void ITypedOptionList<int>.SetValueUnboxed(int idx, int value)
{
(HolderOptionList?[idx] as ModdedNumberOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
@@ -105,4 +117,18 @@ public class ModdedNumberOptionListAttribute(
return value;
}
/// <inheritdoc />
public float GetValueUnboxed(int idx)
{
return HolderOptionList?[idx] is ModdedNumberOption opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedNumberOption");
}
/// <inheritdoc />
int ITypedOptionList<int>.GetValueUnboxed(int idx)
{
return (int)Math.Round(GetValueUnboxed(idx));
}
}
@@ -1,9 +1,8 @@
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
@@ -75,10 +74,9 @@ public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAt
/// </summary>
/// <param name="index">The option's index.</param>
/// <returns>The formatted option's title.</returns>
[SuppressMessage("Globalization", "CA1305:Specify IFormatProvider", Justification = "I don't even know if this is worth it.")]
protected string GetFormattedTitle(int index)
{
var match = Regex.Match(Title.Translate(), @"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout);
var match = Regex.Match(Title, @"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout);
if (!match.Success)
{
@@ -87,7 +85,7 @@ public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAt
if (match.Value == "{0}" && !match.NextMatch().Success)
{
return string.Format(Title, index);
return string.Format(CultureInfo.InvariantCulture, Title, index);
}
Error($"ModdedOptionList Title of {Title} cannot contain more than the first parameter for formatting.");
@@ -14,7 +14,7 @@ namespace MiraAPI.GameOptions.Attributes;
public class ModdedPlayerOptionListAttribute(
string title,
bool allowNone = true)
: ModdedOptionListAttribute(title)
: ModdedOptionListAttribute(title), ITypedOptionList<int>, ITypedOptionList<NetworkedPlayerInfo?>
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
@@ -32,12 +32,35 @@ public class ModdedPlayerOptionListAttribute(
var final = value switch
{
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0),
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : -1,
_ => (int)value,
};
if (final == -1 && !allowNone)
throw new ArgumentException("Cannot assign -1 or null to a ModdedPlayerOption that does not allow none as an option.");
opt?.SetValue(final);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, NetworkedPlayerInfo? value)
{
if (!value && !allowNone)
throw new ArgumentException("Cannot assign null to a ModdedPlayerOption that does not allow none as an option.");
if (HolderOptionList?[idx] is ModdedPlayerOption opt)
opt.SetValue(value ? opt.Values.IndexOf(value!) : -1);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, int value)
{
if (value == -1 && !allowNone)
throw new ArgumentException("Cannot assign -1 to a ModdedPlayerOption that does not allow none as an option.");
(HolderOptionList?[idx] as ModdedPlayerOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
@@ -49,4 +72,20 @@ public class ModdedPlayerOptionListAttribute(
return opt.SelectedPlayer!;
}
/// <inheritdoc />
public NetworkedPlayerInfo? GetValueUnboxed(int idx)
{
return HolderOptionList?[idx] is ModdedPlayerOption opt
? opt.SelectedPlayer
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedPlayerOption");
}
/// <inheritdoc />
int ITypedOptionList<int>.GetValueUnboxed(int idx)
{
return HolderOptionList?[idx] is ModdedPlayerOption opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedPlayerOption");
}
}
@@ -15,7 +15,7 @@ namespace MiraAPI.GameOptions.Attributes;
public class ModdedStringOptionListAttribute(
string title,
string[] values)
: ModdedOptionListAttribute(title)
: ModdedOptionListAttribute(title), ITypedOptionList<string>
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
@@ -28,12 +28,23 @@ public class ModdedStringOptionListAttribute(
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedStringOption;
opt?.SetValue((string)value);
SetValueUnboxed(idx, (string)value);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, string value)
{
(HolderOptionList?[idx] as ModdedStringOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return GetValueUnboxed(idx);
}
/// <inheritdoc />
public string GetValueUnboxed(int idx)
{
return HolderOptionList?[idx] is ModdedStringOption opt
? opt.Value
@@ -16,7 +16,7 @@ public class ModdedToggleOptionListAttribute(
string title,
string on,
string off)
: ModdedOptionListAttribute(title)
: ModdedOptionListAttribute(title), ITypedOptionList<bool>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionListAttribute"/> class.
@@ -37,12 +37,23 @@ public class ModdedToggleOptionListAttribute(
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedToggleOption;
opt?.SetValue((bool)value);
SetValueUnboxed(idx, (bool)value);
}
/// <inheritdoc />
public void SetValueUnboxed(int idx, bool value)
{
(HolderOptionList?[idx] as ModdedToggleOption)?.SetValue(value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return GetValueUnboxed(idx);
}
/// <inheritdoc />
public bool GetValueUnboxed(int idx)
{
return HolderOptionList?[idx] is ModdedToggleOption opt
? opt.Value
+18 -4
View File
@@ -2,6 +2,7 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using MiraAPI.GameOptions.Attributes;
namespace MiraAPI.GameOptions;
@@ -72,15 +73,28 @@ public sealed class ModdedArray<T> : IList<T>, IReadOnlyList<T>, IList
/// <param name="index">The index of the value.</param>
public T this[int index]
{
get => ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute)
? (T)attribute.GetValue(index)
: items[index];
get
{
if (!ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute))
return items[index];
return attribute is ITypedOptionList<T> typedAttr
? typedAttr.GetValueUnboxed(index)
: (T)attribute.GetValue(index);
}
set
{
if (ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute))
attribute.SetValue(index, value!);
{
if (attribute is ITypedOptionList<T> typedAttr)
typedAttr.SetValueUnboxed(index, value);
else
attribute.SetValue(index, value!);
}
else
{
items[index] = value;
}
version++;
}
+86 -8
View File
@@ -30,8 +30,14 @@ public static class ModdedOptionsManager
private static readonly Dictionary<Type, AbstractOptionGroup> TypeToGroup = [];
private static readonly HashSet<PropertyInfo> OptionAttributes = [];
private static readonly HarmonyMethod CachedGetterPatch = new(typeof(ModdedOptionsManager), nameof(PropertyGetterPatch));
private static readonly HarmonyMethod CachedSetterPatch = new(typeof(ModdedOptionsManager), nameof(PropertySetterPatch));
private static readonly MethodInfo OpenGetterPatch = typeof(ModdedOptionsManager)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.First(m => m.Name == nameof(PropertyGetterPatch) && m.IsGenericMethodDefinition);
private static readonly MethodInfo OpenSetterPatch = typeof(ModdedOptionsManager)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.First(m => m.Name == nameof(PropertySetterPatch) && m.IsGenericMethodDefinition);
private static readonly Dictionary<Type, MethodInfo> ConcretisedGetters = [];
private static readonly Dictionary<Type, MethodInfo> ConcretisedSetters = [];
internal static readonly ConditionalWeakTable<object, ModdedOptionListAttribute> ListInstanceCache = [];
internal static readonly Dictionary<OptionBehaviour, ModdedPlayerOption> CreatedPlayerOptions = [];
@@ -170,20 +176,34 @@ public static class ModdedOptionsManager
return;
}
var propType = property.PropertyType;
if (!ConcretisedGetters.TryGetValue(propType, out var concreteGetter))
{
concreteGetter = OpenGetterPatch.MakeGenericMethod(propType);
ConcretisedGetters[propType] = concreteGetter;
}
var getterOriginal = property.GetGetMethod(true)!;
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: CachedGetterPatch);
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: new HarmonyMethod(concreteGetter));
GetterLookups[getterOriginal] = attribute;
var setterOriginal = property.GetSetMethod(true);
if (setterOriginal != null)
{
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: CachedSetterPatch);
if (!ConcretisedSetters.TryGetValue(propType, out var concreteSetter))
{
concreteSetter = OpenSetterPatch.MakeGenericMethod(propType);
ConcretisedSetters[propType] = concreteSetter;
}
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: new HarmonyMethod(concreteSetter));
SetterLookups[setterOriginal] = attribute;
}
attribute.HolderOption = option;
attribute.ValueType = property.PropertyType;
attribute.ValueType = propType;
var customAttributes = property.GetCustomAttributes(false);
@@ -281,15 +301,27 @@ public static class ModdedOptionsManager
return;
}
if (!ConcretisedGetters.TryGetValue(listType, out var concreteGetter))
{
concreteGetter = OpenGetterPatch.MakeGenericMethod(listType);
ConcretisedGetters[listType] = concreteGetter;
}
var getterOriginal = property.GetGetMethod(true)!;
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: CachedGetterPatch);
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: new HarmonyMethod(concreteGetter));
GetterLookups[getterOriginal] = attribute;
var setterOriginal = property.GetSetMethod(true);
if (setterOriginal != null)
{
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: CachedSetterPatch);
if (!ConcretisedSetters.TryGetValue(listType, out var concreteSetter))
{
concreteSetter = OpenSetterPatch.MakeGenericMethod(listType);
ConcretisedSetters[listType] = concreteSetter;
}
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: new HarmonyMethod(concreteSetter));
SetterLookups[setterOriginal] = attribute;
}
@@ -327,7 +359,7 @@ public static class ModdedOptionsManager
var option = optionList[i];
if (visibilityFactory != null)
option.Visible = (Func<bool>)(visibilityFactory(i) ?? DelegateUtilities.AlwaysTrue);
option.Visible = visibilityFactory(i) as Func<bool> ?? DelegateUtilities.AlwaysTrue;
if (getterFactory != null)
option.Getter = getterFactory(i);
@@ -411,6 +443,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.")]
public static void PropertySetterPatch(MethodBase __originalMethod, object value)
{
if (!SetterLookups.TryGetValue(__originalMethod, out var attribute))
@@ -422,6 +455,28 @@ public static class ModdedOptionsManager
ListInstanceCache.AddOrUpdate(value, listAttribute);
}
/// <summary>
/// Patches the setter of a property to update the value of the option.
/// </summary>
/// <typeparam name="T">The type of the option value.</typeparam>
/// <param name="__originalMethod">The original setter method.</param>
/// <param name="value">The new object value.</param>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention.")]
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")]
public static void PropertySetterPatch<T>(MethodBase __originalMethod, T value)
{
if (!SetterLookups.TryGetValue(__originalMethod, out var attribute))
return;
if (attribute is ITypedOption<T> typedAttribute)
typedAttribute.SetValueUnboxed(value);
else
attribute.SetValue(value!);
if (attribute is ModdedOptionListAttribute listAttribute && value is not null)
ListInstanceCache.AddOrUpdate(value, listAttribute);
}
/// <summary>
/// Patches the getter of a property to return the value of the option.
/// </summary>
@@ -430,6 +485,7 @@ public static class ModdedOptionsManager
/// <returns><see langword="false"/> so the original getter gets skipped.</returns>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")]
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")]
[Obsolete("Use PropertyGetterPatch<T> instead.")]
public static bool PropertyGetterPatch(MethodBase __originalMethod, ref object __result)
{
if (!GetterLookups.TryGetValue(__originalMethod, out var attribute))
@@ -438,4 +494,26 @@ public static class ModdedOptionsManager
__result = attribute.GetValue();
return false;
}
/// <summary>
/// Patches the getter of a property to return the value of the option.
/// </summary>
/// <typeparam name="T">The type of the option value.</typeparam>
/// <param name="__originalMethod">The original getter method.</param>
/// <param name="__result">The result of the property getter.</param>
/// <returns><see langword="false"/> so the original getter gets skipped.</returns>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")]
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")]
public static bool PropertyGetterPatch<T>(MethodBase __originalMethod, ref T __result)
{
if (!GetterLookups.TryGetValue(__originalMethod, out var attribute))
return true;
if (attribute is ITypedOption<T> typedAttribute)
__result = typedAttribute.GetValueUnboxed();
else
__result = (T)attribute.GetValue();
return false;
}
}
@@ -13,6 +13,7 @@ namespace MiraAPI.GameOptions.OptionTypes;
/// <summary>
/// An option for selecting an <see langword="enum"/> value.
/// </summary>
[Obsolete("Use ModdedEnum<T> instead.")]
public class ModdedEnumOption : ModdedOption<int>
{
/// <summary>