Skip to content

Commit

Permalink
Proper checking for custom enums
Browse files Browse the repository at this point in the history
  • Loading branch information
LeeTwentyThree committed Jul 11, 2023
1 parent bfbf4f7 commit 51e7daa
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions Nautilus/Patchers/NewtonsoftJsonPatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
using System.Reflection.Emit;
using Nautilus.Handlers;
using System.Linq;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System;
using System.Reflection;

namespace Nautilus.Patchers;

Expand All @@ -27,6 +28,8 @@ private static IEnumerable<CodeInstruction> InitializeValuesAndNamesTranspiler(I
{
// load the text variable to the eval stack
yield return new CodeInstruction(OpCodes.Ldloc_S, (byte)6);
// load the type local variable (type of enum) to the eval stack
yield return new CodeInstruction(OpCodes.Ldloc_0, (byte) 6);
// call the IsEnumValueModded method
var func = AccessTools.Method(typeof(NewtonsoftJsonPatcher), nameof(NewtonsoftJsonPatcher.IsEnumValueModded));
yield return Transpilers.EmitDelegate(IsEnumValueModded);
Expand All @@ -41,11 +44,22 @@ private static IEnumerable<CodeInstruction> InitializeValuesAndNamesTranspiler(I
InternalLogger.Log("NewtonsoftJsonPatcher.InitializeValuesAndNamesTranspiler succeeded: " + found);
}

private static bool IsEnumValueModded(string text)
private static bool IsEnumValueModded(string text, Type enumType)
{
InternalLogger.Warn(text);
bool isCustom = EnumBuilder<TechType>.CacheManager.ContainsKey(text);
InternalLogger.Log("Custom: " + isCustom);
if (!_cachedCacheManagerContainsKeyMethods.TryGetValue(enumType, out var containsKeyMethod))
{
var enumBuilderType = typeof(EnumBuilder<>).MakeGenericType(enumType);
var cacheManager = enumBuilderType.GetProperty("CacheManager", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
containsKeyMethod = AccessTools.Method(cacheManager.GetType(), "ContainsKey", new Type[] { typeof(string) });
_cachedCacheManagers.Add(enumType, cacheManager);
_cachedCacheManagerContainsKeyMethods.Add(enumType, containsKeyMethod);
}
bool isCustom = (bool)containsKeyMethod.Invoke(_cachedCacheManagers[enumType], new object[] { text });
return isCustom;
}

// key: enum type, value: cache manager instances
private static Dictionary<Type, object> _cachedCacheManagers = new();
// key: enum type, value: methodinfo of the cache manager containskey method
private static Dictionary<Type, MethodInfo> _cachedCacheManagerContainsKeyMethods = new();
}

0 comments on commit 51e7daa

Please sign in to comment.