Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ULTRASILK v0.2.0
BepInEx/plugins/ExtraCrestSlots/ExtraCrestSlots.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading; using BepInEx; using HarmonyLib; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Shared.CollectionNS; using Shared.JsonNS; using Shared.LoggerNS; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: <00538e61-8bb8-43cf-97d7-0a318d02f534>IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: <00538e61-8bb8-43cf-97d7-0a318d02f534>IgnoresAccessChecksTo("TeamCherry.TK2D")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("Truinto")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © Truinto 2025")] [assembly: AssemblyFileVersion("1.1.0.1")] [assembly: AssemblyInformationalVersion("1.1.0.1+83a88c077cae4bbab383f75ebb87687f0a445a6d")] [assembly: AssemblyProduct("ExtraCrestSlots")] [assembly: AssemblyTitle("ExtraCrestSlots")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Truinto/")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.0.1")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Shared.JsonNS { public static class JsonTool { public class WritablePropertiesOnlyResolver : DefaultContractResolver { protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) IList<JsonProperty> list = ((DefaultContractResolver)this).CreateProperties(type, memberSerialization); for (int num = list.Count - 1; num >= 0; num--) { if (!list[num].Writable) { list.RemoveAt(num); } } return list; } } public static List<JsonConverter> DefaultConverters = new List<JsonConverter>(1) { (JsonConverter)new StringEnumConverter() }; public static JsonSerializerSettings JsonOptions = new JsonSerializerSettings { Formatting = (Formatting)1, NullValueHandling = (NullValueHandling)1, StringEscapeHandling = (StringEscapeHandling)0, Converters = DefaultConverters, ObjectCreationHandling = (ObjectCreationHandling)2, DefaultValueHandling = (DefaultValueHandling)0, TypeNameHandling = (TypeNameHandling)0, MetadataPropertyHandling = (MetadataPropertyHandling)2, ReferenceLoopHandling = (ReferenceLoopHandling)1, ContractResolver = (IContractResolver)(object)new WritablePropertiesOnlyResolver() }; public static JsonSerializerSettings JsonOptionsRef = new JsonSerializerSettings { PreserveReferencesHandling = (PreserveReferencesHandling)3, Formatting = (Formatting)1, NullValueHandling = (NullValueHandling)1, StringEscapeHandling = (StringEscapeHandling)0, Converters = DefaultConverters, ObjectCreationHandling = (ObjectCreationHandling)2, DefaultValueHandling = (DefaultValueHandling)0, TypeNameHandling = (TypeNameHandling)0, MetadataPropertyHandling = (MetadataPropertyHandling)2, ReferenceLoopHandling = (ReferenceLoopHandling)1, ContractResolver = (IContractResolver)(object)new WritablePropertiesOnlyResolver() }; public static JsonSerializerSettings JsonOptionsCompact = new JsonSerializerSettings { Formatting = (Formatting)0, NullValueHandling = (NullValueHandling)1, StringEscapeHandling = (StringEscapeHandling)0, Converters = DefaultConverters, ObjectCreationHandling = (ObjectCreationHandling)2, DefaultValueHandling = (DefaultValueHandling)0, TypeNameHandling = (TypeNameHandling)0, MetadataPropertyHandling = (MetadataPropertyHandling)2, ReferenceLoopHandling = (ReferenceLoopHandling)1, ContractResolver = (IContractResolver)(object)new WritablePropertiesOnlyResolver() }; public static JsonSerializerSettings JsonOptionsCompactRef = new JsonSerializerSettings { PreserveReferencesHandling = (PreserveReferencesHandling)3, Formatting = (Formatting)0, NullValueHandling = (NullValueHandling)1, StringEscapeHandling = (StringEscapeHandling)0, Converters = DefaultConverters, ObjectCreationHandling = (ObjectCreationHandling)2, DefaultValueHandling = (DefaultValueHandling)0, TypeNameHandling = (TypeNameHandling)0, MetadataPropertyHandling = (MetadataPropertyHandling)2, ReferenceLoopHandling = (ReferenceLoopHandling)1, ContractResolver = (IContractResolver)(object)new WritablePropertiesOnlyResolver() }; public static string Serialize<T>(T value, JsonSerializerSettings? options = null) { return JsonConvert.SerializeObject((object)value, typeof(T), options ?? JsonOptions); } public static bool Serialize<T>(T value, [<00538e61-8bb8-43cf-97d7-0a318d02f534>NotNullWhen(true)] out string? result, JsonSerializerSettings? options = null) { try { return (result = JsonConvert.SerializeObject((object)value, typeof(T), options ?? JsonOptions)) != null; } catch (Exception) { result = null; return false; } } public static T? Deserialize<T>(string json, JsonSerializerSettings? options = null) { return (T)JsonConvert.DeserializeObject(json, typeof(T), options ?? JsonOptions); } public static bool Deserialize<T>(string json, [<00538e61-8bb8-43cf-97d7-0a318d02f534>NotNullWhen(true)] out T? result, JsonSerializerSettings? options = null) { try { return (result = (T)JsonConvert.DeserializeObject(json, typeof(T), options ?? JsonOptions)) != null; } catch (Exception) { result = default(T); return false; } } public static bool SerializeFile<T>(string path, T value, JsonSerializerSettings? options = null) { try { string directoryName = Path.GetDirectoryName(path); if (directoryName != null) { Directory.CreateDirectory(directoryName); } using FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); using StreamWriter streamWriter = new StreamWriter(stream); JsonSerializer.Create(options ?? JsonOptions).Serialize((TextWriter)streamWriter, (object)value, typeof(T)); return true; } catch (Exception) { return false; } } public static T? DeserializeFile<T>(string path, JsonSerializerSettings? options = null) { if (!File.Exists(path)) { return default(T); } using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using StreamReader streamReader = new StreamReader(stream); return (T)JsonSerializer.Create(options ?? JsonOptions).Deserialize((TextReader)streamReader, typeof(T)); } public static bool DeserializeFile<T>(string path, [<00538e61-8bb8-43cf-97d7-0a318d02f534>NotNullWhen(true)] out T? result, JsonSerializerSettings? options = null) { try { return (result = DeserializeFile<T>(path, options)) != null; } catch (Exception) { result = default(T); return false; } } } } namespace Shared.AttributesNS { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public class MaybeNull : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public class NeverNull : Attribute { } } namespace ExtraCrestSlots { [BepInPlugin("Truinto.ExtraCrestSlots", "ExtraCrestSlots", "1.1.0.1")] public class Plugin : BaseUnityPlugin { private static bool OnceAddToolSlots; public void Awake() { Harmony.CreateAndPatchAll(typeof(Plugin), (string)null); ((BaseUnityPlugin)this).Logger.LogMessage((object)"Plugin loaded"); } [HarmonyPatch(typeof(ToolItemManager), "Awake")] [HarmonyPostfix] public static void AddToolSlots(ToolItemManager __instance) { //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) if (OnceAddToolSlots) { return; } OnceAddToolSlots = true; Debug.Log((object)"CRESTS:"); foreach (ToolCrest item in (NamedScriptableObjectList<ToolCrest>)(object)__instance.crestList) { if ((Object)(object)item == (Object)null || item.slots == null) { continue; } int num = item.slots.Length; if ((num > 9 || num == 0) ? true : false) { continue; } foreach (SettingCrest slot in Settings.State.Slots) { if (slot.CrestID == "ALL" || slot.CrestID == item.name) { addSlots(ref item.slots, slot); } } fixMapping(ref item.slots); Debug.Log((object)("\t" + item.name)); SlotInfo[] slots = item.Slots; foreach (SlotInfo val in slots) { Debug.Log((object)($"\t\tType={val.Type} attack={val.AttackBinding} IsLocked={val.IsLocked} Position={val.Position}" + $" l={val.NavLeftIndex} d={val.NavDownIndex} r={val.NavRightIndex} u={val.NavUpIndex}")); } } static void addSlots(ref SlotInfo[] reference, SettingCrest setting) { //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Invalid comparison between Unknown and I4 //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Unknown result type (might be due to invalid IL or missing references) //IL_02de: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_033e: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Invalid comparison between Unknown and I4 //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) int slotCount = setting.SlotCount; if ((slotCount <= 0 || slotCount > 50) ? true : false) { setting.SlotCount = 1; } int num2 = setting.OverrideSlot ?? (-1); if (num2 >= 0) { int num3 = 0; while (num3 < setting.SlotCount && num2 < reference.Length) { SlotInfo[] array = reference; int num4 = num2; _ = ref array[num4]; ToolItemType type = (ToolItemType)(setting.SlotType switch { SlotType.Auto => reference[num2].Type, SlotType.Blue => 1, SlotType.Yellow => 2, SlotType.RedUp => 0, SlotType.RedNeutral => 0, SlotType.RedDown => 0, SlotType.WhiteUp => 3, SlotType.WhiteNeutral => 3, SlotType.WhiteDown => 3, _ => 1, }); array[num4].Type = type; SlotInfo[] array2 = reference; int num5 = num2; _ = ref array2[num5]; AttackToolBinding attackBinding = (AttackToolBinding)(setting.SlotType switch { SlotType.Auto => reference[num2].AttackBinding, SlotType.RedUp => 1, SlotType.RedNeutral => 0, SlotType.WhiteUp => 1, SlotType.WhiteNeutral => 0, _ => 2, }); array2[num5].AttackBinding = attackBinding; if (setting.IsLocked.HasValue) { reference[num2].IsLocked = setting.IsLocked.Value; } num3++; num2++; } } else { int num6 = reference.Length; Array.Resize(ref reference, reference.Length + setting.SlotCount); bool flag = false; if (setting.SlotType == SlotType.Auto) { flag = true; for (int j = 0; j < num6; j++) { ToolItemType type = reference[j].Type; bool flag2 = (((int)type == 0 || (int)type == 3) ? true : false); if (flag2 && (int)reference[j].AttackBinding == 2) { flag = false; } } } float num7 = setting.PositionX; for (int k = num6; k < reference.Length; k++) { reference[k] = new SlotInfo { IsLocked = (setting.IsLocked == true), Position = new Vector2(num7, setting.PositionY), NavUpFallbackIndex = -1, NavDownFallbackIndex = -1, NavLeftFallbackIndex = -1, NavRightFallbackIndex = -1 }; SlotInfo[] array3 = reference; int num8 = k; _ = ref array3[num8]; ToolItemType type = (ToolItemType)(setting.SlotType switch { SlotType.Auto => !flag, SlotType.Blue => 1, SlotType.Yellow => 2, SlotType.RedUp => 0, SlotType.RedNeutral => 0, SlotType.RedDown => 0, SlotType.WhiteUp => 3, SlotType.WhiteNeutral => 3, SlotType.WhiteDown => 3, _ => 1, }); array3[num8].Type = type; SlotInfo[] array4 = reference; int num9 = k; _ = ref array4[num9]; AttackToolBinding attackBinding = (AttackToolBinding)(setting.SlotType switch { SlotType.RedUp => 1, SlotType.RedNeutral => 0, SlotType.WhiteUp => 1, SlotType.WhiteNeutral => 0, _ => 2, }); array4[num9].AttackBinding = attackBinding; flag = false; num7 += 1.5f; } } } static void fixMapping(ref SlotInfo[] reference) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) for (int j = 0; j < reference.Length; j++) { Vector2 position = reference[j].Position; for (int k = 1; k <= 4; k++) { float num2 = float.MaxValue; int num3 = -1; for (int l = 0; l < reference.Length; l++) { if (j != l) { Vector2 position2 = reference[l].Position; Direction directionTo = position.GetDirectionTo(position2); if (k == (int)directionTo) { float num4 = Vector2.Distance(position, position2); if (num4 < num2) { num2 = num4; num3 = l; } } } } switch ((Direction)k) { case Direction.Left: reference[j].NavLeftIndex = num3; break; case Direction.Right: reference[j].NavRightIndex = num3; break; case Direction.Up: reference[j].NavUpIndex = num3; break; case Direction.Down: reference[j].NavDownIndex = num3; break; } } } } } } public static class UtilDir { public static Direction GetDirectionTo(this Vector2 origin, Vector2 destination) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) Vector2 val = origin - destination; if (val.x > 0f && val.x >= Math.Abs(val.y)) { return Direction.Left; } if (val.x < 0f && 0f - val.x >= Math.Abs(val.y)) { return Direction.Right; } if (val.y > 0f && val.y >= Math.Abs(val.x)) { return Direction.Down; } if (val.y < 0f && 0f - val.y >= Math.Abs(val.x)) { return Direction.Up; } return Direction.None; } } public enum Direction { None, Left, Right, Up, Down } public class SettingCrest { public string? CrestID; public int SlotCount = 1; public float PositionX; public float PositionY; public SlotType SlotType; public bool? IsLocked; public int? OverrideSlot; } public enum SlotType { Auto, Blue, Yellow, RedUp, RedNeutral, RedDown, WhiteUp, WhiteNeutral, WhiteDown } public class Settings { [JsonIgnore] public string? FilePath; [JsonProperty] public int Version = 1; [JsonProperty] public List<SettingCrest> Slots = new List<SettingCrest> { new SettingCrest { CrestID = "ALL", SlotCount = 6, PositionX = -4.5f, PositionY = -3.5f } }; private static Settings? _state; public static Settings State => _state ?? Load(); public void Save() { JsonTool.SerializeFile(FilePath, this); } public static Settings Load() { string text = Path.Combine(Paths.ConfigPath, "ExtraCrestSlots.json"); if (JsonTool.DeserializeFile<Settings>(text, out _state)) { _state.FilePath = text; } else { _state = new Settings(); _state.FilePath = text; _state.Save(); } return _state; } } internal static class ModInfo { public const string MOD_GUID = "ExtraCrestSlots"; public const string MOD_NAME = "ExtraCrestSlots"; public const string MOD_AUTHORS = "Truinto"; public const string MOD_VERSION = "1.1.0.1"; public const string MOD_DESCRIPTION = ""; public const byte MOD_NICESSE = 10; } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class <00538e61-8bb8-43cf-97d7-0a318d02f534>NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public <00538e61-8bb8-43cf-97d7-0a318d02f534>NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class <00538e61-8bb8-43cf-97d7-0a318d02f534>IgnoresAccessChecksToAttribute : Attribute { public <00538e61-8bb8-43cf-97d7-0a318d02f534>IgnoresAccessChecksToAttribute(string assemblyName) { } } } namespace Shared { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public class LocalParameterAttribute : Attribute { public string Name; public Type Type; public int Index = -1; public int IndexByType; public LocalParameterAttribute(string name = null, Type type = null, int index = -1, int indexByType = 0) { Name = name; Type = type; Index = index; IndexByType = indexByType; } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public class OriginalParameterAttribute : Attribute { public string Name; public OriginalParameterAttribute(string name) { Name = name; } } public class PatchInfoAttribute : Attribute, IComparable<PatchInfoAttribute>, IEquatable<PatchInfoAttribute> { public Severity PatchType; public LocalizedStringCached DisplayClass; public LocalizedStringCached DisplayName; public LocalizedStringCached Description; public bool Homebrew; public Type Requirement; public int Priority; public string Class; public string Method; public int Hash; public bool Disabled; public bool DisabledAll; public bool IsWIP => (PatchType & Severity.WIP) != 0; public bool IsFaulty => (PatchType & Severity.Faulty) != 0; public bool IsDangerous => (PatchType & Severity.Create) != 0; public bool IsHarmony => (PatchType & Severity.Harmony) != 0; public bool IsEvent => (PatchType & Severity.Event) != 0; public bool IsHidden => (PatchType & Severity.Hidden) != 0; public bool IsDefaultOff => (PatchType & Severity.DefaultOff) != 0; public string FullName => Class + "." + Method; public string HomebrewStr => Homebrew ? ":house:" : ":book:"; public string StatusStr => IsFaulty ? ":x:" : (IsWIP ? ":construction:" : ":heavy_check_mark:"); public PatchInfoAttribute() { } public PatchInfoAttribute(Severity PatchType, string DisplayName = null, string Description = null, bool Homebrew = true, int Priority = 400, Type Requirement = null) { this.PatchType = PatchType; this.DisplayName = DisplayName; this.Description = Description; this.Homebrew = Homebrew; this.Requirement = Requirement; this.Priority = Priority; } public int CompareTo(PatchInfoAttribute other) { int num = 0; if (Class == "Patch") { num += 100; } if (other.Class == "Patch") { num -= 100; } if (num == 0) { num = Class.CompareTo(other.Class); } if (num == 0) { num = (other.PatchType & (Severity)255) - (PatchType & (Severity)255); } if (num == 0) { num = Method.CompareTo(other.Method); } return num; } public bool Equals(PatchInfoAttribute other) { return Method == other.Method && Class == other.Class; } public override int GetHashCode() { return Hash; } } [Flags] public enum Severity { None = 0, Event = 1, Harmony = 2, Fix = 4, Extend = 8, Create = 0x10, WIP = 0x100, Faulty = 0x200, Hidden = 0x400, DefaultOff = 0x800 } public class PatchInfoCollection : IEnumerable<PatchInfoAttribute>, IEnumerable { private List<PatchInfoAttribute> list = new List<PatchInfoAttribute>(); private ISettings state; public PatchInfoCollection(ISettings state) { this.state = state; } public void Add(PatchInfoAttribute attr, MemberInfo info) { attr.Class = info.DeclaringType?.Name ?? "Patch"; attr.DisplayClass = attr.Class; attr.Method = info.Name; attr.Hash = (attr.Class + "." + attr.Method).GetHashCode(); if (!list.Contains(attr)) { list.Add(attr); } } public void SetEnable(bool value, string category, bool force = false) { if (category.Last() == '*') { if (value) { state.Blacklist.Remove(category); } else { state.Blacklist.Add(category); } } else if (value) { state.Whitelist.Add(category); state.Blacklist.Remove(category); if (force) { state.Blacklist.Remove(TrySubstring(category, '.') + ".*"); } } else { state.Whitelist.Remove(category); state.Blacklist.Add(category); } Update(); } public void SetEnable(bool value, PatchInfoAttribute attr, bool force = false) { attr.Disabled = !value; string fullName = attr.FullName; if (value) { state.Blacklist.Remove(fullName); state.Whitelist.Add(fullName); if (force) { state.Blacklist.Remove(TrySubstring(fullName, '.') + ".*"); Update(); } } else { state.Whitelist.Remove(fullName); state.Blacklist.Add(fullName); } } public void Update() { string text = null; bool disabledAll = false; foreach (PatchInfoAttribute item in list) { if (item.Class != text) { text = item.Class; disabledAll = IsDisenabledCategory(text + ".*"); } item.DisabledAll = disabledAll; item.Disabled = IsDisenabledSingle(item.Class + "." + item.Method); } } private bool IsDisenabledCategory(string name) { if (state.Blacklist.Contains(name)) { return true; } return false; } private bool IsDisenabledSingle(string name) { if (state.Blacklist.Contains(name)) { return true; } if (state.Whitelist.Contains(name)) { return false; } int hash = name.GetHashCode(); PatchInfoAttribute? patchInfoAttribute = list.Find((PatchInfoAttribute f) => f.Hash == hash); if (patchInfoAttribute != null && patchInfoAttribute.IsDefaultOff) { return true; } return !state.NewFeatureDefaultOn; } public bool IsDisenabled(string name) { if (state.Blacklist.Contains(name)) { return true; } if (name.Last() == '*') { return false; } if (state.Blacklist.Contains(TrySubstring(name, '.') + ".*")) { return true; } if (state.Whitelist.Contains(name)) { return false; } int hash = name.GetHashCode(); PatchInfoAttribute? patchInfoAttribute = list.Find((PatchInfoAttribute f) => f.Hash == hash); if (patchInfoAttribute != null && patchInfoAttribute.IsDefaultOff) { return true; } return !state.NewFeatureDefaultOn; } public bool IsEnabled(string name) { return !IsDisenabled(name); } public IEnumerator<PatchInfoAttribute> GetEnumerator() { return list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } public void Sort() { list.Sort(); } public IEnumerable<string> GetCriticalPatches() { return from s in list where s.IsDangerous && !s.Disabled && !s.DisabledAll select s.FullName; } public List<string> IsEnabledAll(List<string> source) { for (int num = source.Count - 1; num >= 0; num--) { if (IsEnabled(source[num])) { source.RemoveAt(num); } } return source; } private static string TrySubstring(string str, char c, int start = 0, bool tail = false) { try { if (tail) { if (start < 0) { return str.Substring(str.LastIndexOf(c) + 1); } return str.Substring(str.IndexOf(c, start) + 1); } if (start < 0) { return str.Substring(0, str.LastIndexOf(c)); } return str.Substring(start, str.IndexOf(c, start)); } catch (Exception) { return null; } } } public class CacheData<T> where T : class { private readonly int Size; private int Pointer; private readonly T[] Cache; private readonly object[][] Arguments; private readonly Func<object[], T> Getter; public CacheData(Func<object[], T> getter, int size = 5) { Size = size; Cache = new T[size]; Arguments = new object[size][]; Getter = getter; } public T Get(params object[] args) { for (int i = 0; i < Size; i++) { object[] obj = Arguments[i]; if (obj != null && obj.SequenceEqual(args)) { return Cache[i]; } } if (Pointer >= Size) { Pointer = 0; } Arguments[Pointer] = args; return Cache[Pointer++] = Getter(args); } } public class ExceptionMissingReturn : Exception { public ExceptionMissingReturn() { } public ExceptionMissingReturn(string message) : base(message) { } } public class ExceptionInvalidReturn : Exception { public ExceptionInvalidReturn() { } public ExceptionInvalidReturn(string message) : base(message) { } } public class ExceptionMissingInstance : Exception { public ExceptionMissingInstance() { } public ExceptionMissingInstance(string message) : base(message) { } } public class ExceptionMissingParameter : Exception { public ExceptionMissingParameter() { } public ExceptionMissingParameter(string message) : base(message) { } } public class ExceptionInvalidParameter : Exception { public ExceptionInvalidParameter() { } public ExceptionInvalidParameter(string message) : base(message) { } } public class ExceptionMissingResult : Exception { public ExceptionMissingResult() { } public ExceptionMissingResult(string message) : base(message) { } } public class ExceptionInvalidResult : Exception { public ExceptionInvalidResult() { } public ExceptionInvalidResult(string message) : base(message) { } } public class ExceptionInvalidInstance : Exception { public ExceptionInvalidInstance() { } public ExceptionInvalidInstance(string message) : base(message) { } } public class ExceptionInvalidParameterOrder : Exception { public ExceptionInvalidParameterOrder() { } public ExceptionInvalidParameterOrder(string message) : base(message) { } } public class ExceptionMissingRef : Exception { public ExceptionMissingRef() { } public ExceptionMissingRef(string message) : base(message) { } } public struct LocalizedStringCached { private string? cache; public readonly string Default; public static Func<LocalizedStringCached, string>? Resolver; public LocalizedStringCached(string value) { cache = null; Default = value; } public void Clear() { cache = null; } public override string ToString() { if (Resolver == null) { return Default; } string text = cache; if (text == null) { string obj = Resolver(this) ?? Default; string text2 = obj; cache = obj; text = text2; } return text; } public static implicit operator string(LocalizedStringCached lsc) { return lsc.ToString(); } public static implicit operator LocalizedStringCached(string str) { return new LocalizedStringCached(str); } } public abstract class BaseSettings<T> : ISettings where T : BaseSettings<T>, new() { [JsonIgnore] public string? FilePath; [JsonIgnore] public JsonSerializerSettings JSettings = new JsonSerializerSettings { Formatting = (Formatting)1, NullValueHandling = (NullValueHandling)1, ObjectCreationHandling = (ObjectCreationHandling)2, DefaultValueHandling = (DefaultValueHandling)0, TypeNameHandling = (TypeNameHandling)4, MetadataPropertyHandling = (MetadataPropertyHandling)2, PreserveReferencesHandling = (PreserveReferencesHandling)0 }; [JsonProperty] public int Version { get; set; } [JsonProperty] public bool NewFeatureDefaultOn { get; set; } [JsonProperty] public HashSet<string> Blacklist { get; protected set; } = new HashSet<string>(); [JsonProperty] public HashSet<string> Whitelist { get; protected set; } = new HashSet<string>(); protected virtual bool OnUpdate() { return true; } public virtual void TrySave() { if (FilePath == null) { return; } try { Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); using StreamWriter streamWriter = new StreamWriter(FilePath, append: false); streamWriter.WriteLine(JsonConvert.SerializeObject((object)this, typeof(T), JSettings)); streamWriter.Close(); } catch (Exception exception) { Logger.PrintException(exception); } } public static T TryLoad(string path, string file = "settings.json") { string text = Path.Combine(path, file); try { using StreamReader streamReader = new StreamReader(text); T val = JsonConvert.DeserializeObject<T>(streamReader.ReadToEnd()); streamReader.Close(); val.FilePath = text; T val2 = new T(); if (val.Version != val2.Version && val.OnUpdate()) { val.Version = val2.Version; val.TrySave(); } return val; } catch (Exception) { Logger.Print("Could not load setting, creating new."); T val3 = new T { FilePath = text }; val3.TrySave(); return val3; } } } public interface ISettings { int Version { get; } bool NewFeatureDefaultOn { get; } HashSet<string> Blacklist { get; } HashSet<string> Whitelist { get; } } [Serializable] public readonly struct StringHash : IEquatable<StringHash>, IEquatable<string>, IComparable<StringHash>, IComparable<string>, IComparable { public readonly string Value; [NonSerialized] public readonly int Hash; public StringHash(string value) { Value = value; Hash = value.GetHashCode(); } public override int GetHashCode() { return Hash; } public override string ToString() { return Value; } public override bool Equals(object obj) { if (obj is StringHash stringHash) { return Hash == stringHash.Hash; } if (obj is string text) { return Value == text; } return false; } public bool Equals(StringHash other) { return Hash == other.Hash; } public bool Equals(string other) { return Value == other; } public int CompareTo(StringHash other) { return Hash - other.Hash; } public int CompareTo(string other) { return Hash - other.GetHashCode(); } public int CompareTo(object obj) { return (Hash - obj?.GetHashCode()).GetValueOrDefault(); } public static implicit operator StringHash(string text) { return new StringHash(text); } public static implicit operator string(StringHash hash) { return hash.Value; } } internal class StringHashConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(StringHash); } public override object? ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 JToken val = JToken.Load(reader); JTokenType type = val.Type; JTokenType val2 = type; if ((int)val2 != 1) { if ((int)val2 == 8) { return ((object)val).ToString(); } return null; } return ((object)val[(object)"Value"])?.ToString(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); return; } if (value is StringHash stringHash) { writer.WriteValue(stringHash.ToString()); return; } writer.WriteStartObject(); writer.WritePropertyName("$type"); writer.WriteValue((object)value.GetType()); writer.WritePropertyName("Value"); writer.WriteValue(value.ToString()); writer.WriteEndObject(); } } public class TranspilerTool : IList<CodeInstruction>, ICollection<CodeInstruction>, IEnumerable<CodeInstruction>, IEnumerable { public const BindingFlags BindingAll = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; public const BindingFlags BindingInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; public const BindingFlags BindingStatic = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; public int Index; public readonly IList<CodeInstruction> Code; public readonly ILGenerator Generator; public readonly MethodInfo Original; public readonly IList<LocalVariableInfo> Locals; public readonly List<LocalInfo> LocalsExtended; public readonly List<LabelInfo> LabelsExtended; public static OpCode[] OpCode_Ldc_i = new OpCode[13] { OpCodes.Ldc_I4_M1, OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8, OpCodes.Ldc_I4, OpCodes.Ldc_I4_S, OpCodes.Ldc_I8 }; public static OpCode[] OpCode_Ldc_r = new OpCode[2] { OpCodes.Ldc_R4, OpCodes.Ldc_R8 }; public static OpCode[] OpCode_Member = new OpCode[6] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldsfld, OpCodes.Ldsflda, OpCodes.Ldfld, OpCodes.Ldflda }; protected static readonly CacheData<MemberInfo> _memberCache = new CacheData<MemberInfo>((object[] a) => GetMemberInfo((Type)a[0], (string)a[1], (Type[])a[2], (Type[])a[3])); public CodeInstruction Current => Code[Index]; public CodeInstruction? Next => (!IsLast) ? Code[Index + 1] : null; public CodeInstruction? Previous => (!IsFirst) ? Code[Index - 1] : null; public bool IsStatic => Original.IsStatic; public bool IsFirst => Index <= 0; public bool IsLast => Index >= Code.Count - 1; public int Count => Code.Count; public bool IsReadOnly => Code.IsReadOnly; public CodeInstruction this[int index] { get { return Code[index]; } set { Code[index] = value; } } public TranspilerTool(IEnumerable<CodeInstruction> code, ILGenerator generator, MethodBase original) { if (code is TranspilerTool transpilerTool) { Code = transpilerTool.Code; Generator = transpilerTool.Generator; Original = transpilerTool.Original; Locals = transpilerTool.Locals; LocalsExtended = transpilerTool.LocalsExtended; LabelsExtended = transpilerTool.LabelsExtended; return; } Code = (code as IList<CodeInstruction>) ?? code.ToList(); Index = 0; Generator = generator ?? throw new ArgumentNullException(); Original = ((MethodInfo)original) ?? throw new ArgumentNullException(); Locals = original.GetMethodBody().LocalVariables; LocalsExtended = new List<LocalInfo>(); LabelsExtended = new List<LabelInfo>(); foreach (LocalVariableInfo local in Locals) { LocalsExtended.Add(new LocalInfo(local, "V_" + local.LocalIndex)); } foreach (CodeInstruction item in code) { LabelsExtended.AddUnique(item.labels, (Label a) => new LabelInfo(a)); } } public TranspilerTool First() { Index = 0; return this; } public TranspilerTool Last() { Index = Code.Count - 1; return this; } public TranspilerTool Offset(int offset) { Index += offset; if (Index < 0) { Index = 0; } if (Index >= Code.Count) { Index = Code.Count - 1; } return this; } public TranspilerTool Seek(Func<TranspilerTool, bool> pred) { do { if (IsLast) { throw new IndexOutOfRangeException("IsLast"); } Index++; } while (!pred(this)); return this; } public TranspilerTool Rewind(Func<TranspilerTool, bool> pred) { do { if (IsFirst) { throw new IndexOutOfRangeException("IsFirst"); } Index--; } while (!pred(this)); return this; } public TranspilerTool Seek(Type type, string name, Type[]? parameters = null, Type[]? generics = null) { do { if (IsLast) { throw new IndexOutOfRangeException("IsLast"); } Index++; } while (!Calls(type, name, parameters, generics)); return this; } public TranspilerTool Rewind(Type type, string name, Type[]? parameters = null, Type[]? generics = null) { do { if (IsFirst) { throw new IndexOutOfRangeException("IsFirst"); } Index--; } while (!Calls(type, name, parameters, generics)); return this; } public TranspilerTool SeekSetter(Type type, string name) { MethodInfo memberinfo = AccessTools.PropertyGetter(type, name); do { if (IsLast) { throw new IndexOutOfRangeException("IsLast"); } Index++; } while (!Calls(memberinfo)); return this; } public TranspilerTool RewindSetter(Type type, string name) { MethodInfo memberinfo = AccessTools.PropertyGetter(type, name); do { if (IsFirst) { throw new IndexOutOfRangeException("IsFirst"); } Index--; } while (!Calls(memberinfo)); return this; } public TranspilerTool Seek(MemberInfo memberInfo) { do { if (IsLast) { throw new IndexOutOfRangeException("IsLast"); } Index++; } while (!Calls(memberInfo)); return this; } public TranspilerTool Rewind(MemberInfo memberInfo) { do { if (IsFirst) { throw new IndexOutOfRangeException("IsFirst"); } Index--; } while (!Calls(memberInfo)); return this; } public TranspilerTool Seek(OpCode op, object? operand = null) { do { if (IsLast) { throw new IndexOutOfRangeException("IsLast"); } Index++; } while (!(Current.opcode == op) || (operand != null && !object.Equals(Current.operand, operand))); return this; } public TranspilerTool Rewind(OpCode op, object? operand = null) { do { if (IsFirst) { throw new IndexOutOfRangeException("IsFirst"); } Index--; } while (!(Current.opcode == op) || (operand != null && Current.operand != operand)); return this; } public TranspilerTool Seek(LocalInfo local, bool loadIsTrue_storeIsFalse) { do { if (IsLast) { throw new IndexOutOfRangeException("IsLast"); } Index++; } while (!(loadIsTrue_storeIsFalse ? IsLdloc(local) : IsStloc(local))); return this; } public TranspilerTool Rewind(LocalInfo local, bool loadIsTrue_storeIsFalse) { do { if (IsFirst) { throw new IndexOutOfRangeException("IsFirst"); } Index--; } while (!(loadIsTrue_storeIsFalse ? IsLdloc(local) : IsStloc(local))); return this; } public TranspilerTool Seek(bool onStart, params Func<TranspilerTool, bool>[] pred) { bool flag = true; while (true) { Seek(pred[0]); int index = Index; int num = 1; while (true) { if (num < pred.Length) { if (IsLast) { throw new IndexOutOfRangeException("IsLast"); } Index++; if (!pred[num](this)) { break; } num++; continue; } if (onStart) { Index = index; } return this; } Index = index; } } public bool Is(OpCode op) { return Current.opcode == op; } public bool Is(OpCode op, object operand) { return Current.opcode == op && object.Equals(Current.operand, operand); } public bool Calls(Type type, string name, Type[]? parameters = null, Type[]? generics = null) { return OpCode_Member.Contains(Current.opcode) && _memberCache.Get(type, name, parameters, generics).Equals(Current.operand); } public bool Calls(MemberInfo memberinfo) { return OpCode_Member.Contains(Current.opcode) && memberinfo.Equals(Current.operand); } public bool IsBranch() { FlowControl flowControl = Current.opcode.FlowControl; if (flowControl == FlowControl.Branch || flowControl == FlowControl.Cond_Branch) { return true; } return false; } public bool IsStloc(int localIndex) { return CodeInstructionExtensions.IsStloc(Current, (LocalBuilder)null) && localIndex == GetLocalIndex(); } public bool IsStloc(string localName) { return CodeInstructionExtensions.IsStloc(Current, (LocalBuilder)null) && GetLocal(localName).Equals(Current.operand); } public bool IsStloc(Type type) { return CodeInstructionExtensions.IsStloc(Current, (LocalBuilder)null) && GetLocal().Type == type; } public bool IsLdloc(int localIndex) { return CodeInstructionExtensions.IsLdloc(Current, (LocalBuilder)null) && localIndex == GetLocalIndex(); } public bool IsLdloc(string localName) { return CodeInstructionExtensions.IsLdloc(Current, (LocalBuilder)null) && GetLocal(localName).Equals(Current.operand); } public bool IsLdloc(Type type) { return CodeInstructionExtensions.IsLdloc(Current, (LocalBuilder)null) && GetLocal().Type == type; } public bool IsLoadConstant(long number) { return CodeInstructionExtensions.LoadsConstant(Current, number); } public bool IsLoadConstant(Enum e) { return CodeInstructionExtensions.LoadsConstant(Current, e); } public bool IsLoadConstant(double number) { return CodeInstructionExtensions.LoadsConstant(Current, number); } public void Set(OpCode opCode, object? operand = null) { Current.opcode = opCode; Current.operand = operand; } public void InsertCall(Delegate func, bool before) { //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Expected O, but got Unknown MethodInfo methodInfo = func.GetMethodInfo(); ParameterInfo[] parameters = methodInfo.GetParameters(); bool flag = methodInfo.ReturnType != typeof(void); if (!methodInfo.IsStatic) { throw new ArgumentException("Delegate must be static"); } if (flag && (parameters.Length == 0 || parameters[0].ParameterType != methodInfo.ReturnType)) { throw new ExceptionInvalidReturn("Delegate return value must equal it's first argument (unless it returns void)!"); } for (int i = (flag ? 1 : 0); i < parameters.Length; i++) { ParameterInfo parameterInfo = parameters[i]; if (!InsertPushOriginal(before, parameterInfo) && !InsertPushLocal(before, parameterInfo)) { throw new ArgumentException("Delegate unknown parameter name '" + parameterInfo.Name + "'!"); } } Code.Insert(before ? Index++ : (++Index), new CodeInstruction(OpCodes.Call, (object)methodInfo)); } protected bool InsertPushLocal(bool before, ParameterInfo parameterFunc) { //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Expected O, but got Unknown Type targetType = ((!parameterFunc.ParameterType.IsByRef) ? parameterFunc.ParameterType : parameterFunc.ParameterType.GetElementType()); int counter = 0; LocalParameterAttribute targetLocal = parameterFunc.GetCustomAttribute<LocalParameterAttribute>(); LocalInfo localInfo; if (targetLocal == null) { localInfo = GetLocal(parameterFunc.Name, null, canMake: false); if (localInfo.IsEmpty) { return false; } } else if (targetLocal.Name == null) { localInfo = ((targetLocal.Index >= 0) ? LocalsExtended.Find((LocalInfo f) => f.Index == targetLocal.Index) : ((targetLocal.IndexByType < 0) ? LocalsExtended.Find((LocalInfo a) => a.Index == GetLocalIndex()) : LocalsExtended.Find((LocalInfo a) => a.Type == targetType && counter++ >= targetLocal.IndexByType))); } else { string name = targetLocal.Name; LocalParameterAttribute localParameterAttribute = targetLocal; localInfo = GetLocal(name, localParameterAttribute.Type ?? (localParameterAttribute.Type = targetType)); } if (localInfo.IsEmpty) { throw new ExceptionInvalidParameter("no matching local for " + parameterFunc.Name); } bool flag = ThrowParameterIncompatible(parameterFunc, localInfo.Type); Code.Insert(before ? Index++ : (++Index), new CodeInstruction(flag ? OpCodes.Ldloca : OpCodes.Ldloc, (object)localInfo.Index)); return true; } protected bool InsertPushOriginal(bool before, ParameterInfo parameterFunc) { //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Expected O, but got Unknown OriginalParameterAttribute customAttribute = parameterFunc.GetCustomAttribute<OriginalParameterAttribute>(); string name = customAttribute?.Name ?? parameterFunc.Name; int num; Type right; if (name == "__instance") { if (IsStatic) { throw new ExceptionInvalidInstance("Delegate can not define __instance for a static method!"); } num = -1; right = Original.DeclaringType; } else { ParameterInfo[] parameters = Original.GetParameters(); num = parameters.GetIndex((ParameterInfo f) => f.Name == name); if (num < 0) { if (customAttribute == null) { return false; } throw new ExceptionInvalidParameter("no matching original for " + parameterFunc.Name + "=" + name); } right = parameters[num].ParameterType; } bool flag = ThrowParameterIncompatible(parameterFunc, right); Code.Insert(before ? Index++ : (++Index), new CodeInstruction(flag ? OpCodes.Ldarga : OpCodes.Ldarg, (object)(IsStatic ? num : (num + 1)))); return true; } public void InsertBefore(OpCode opcode, object? operand = null) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown if (operand is LabelInfo labelInfo) { operand = (Label)labelInfo; } Code.Insert(Index++, new CodeInstruction(opcode, operand)); } public void InsertAfter(OpCode opcode, object? operand = null) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown if (operand is LabelInfo labelInfo) { operand = (Label)labelInfo; } Code.Insert(++Index, new CodeInstruction(opcode, operand)); } public void InsertBefore(Delegate func) { InsertCall(func, before: true); } public void InsertAfter(Delegate func) { InsertCall(func, before: false); } public int InsertAfterAll(Type type, string name, Delegate func, Type[]? parameters = null, Type[]? generics = null) { MemberInfo original = _memberCache.Get(type, name, parameters, generics); return InsertAfterAll(original, func); } public int InsertAfterAll(MemberInfo original, Delegate func) { int num = 0; int index = Index; First(); while (!IsLast) { if (Calls(original)) { InsertAfter(func); num++; } Index++; } Index = index; return num; } public void InsertReturn(Delegate func, bool before = true) { //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Expected O, but got Unknown //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Expected O, but got Unknown //IL_02f3: Unknown result type (might be due to invalid IL or missing references) //IL_02fd: Expected O, but got Unknown //IL_0397: Unknown result type (might be due to invalid IL or missing references) //IL_03a1: Expected O, but got Unknown //IL_0353: Unknown result type (might be due to invalid IL or missing references) //IL_035d: Expected O, but got Unknown MethodInfo methodInfo = func.GetMethodInfo(); ParameterInfo[] parameters = methodInfo.GetParameters(); bool flag = false; LocalInfo localInfo = default(LocalInfo); Type returnType = Original.ReturnType; Label item = default(Label); if (!methodInfo.IsStatic) { throw new ArgumentException("Delegate must be static"); } if (methodInfo.ReturnType == typeof(bool)) { flag = true; } else if (methodInfo.ReturnType != typeof(void)) { throw new ExceptionInvalidReturn("Delegate can only return void or bool!"); } if (returnType != typeof(void) && !parameters.Any((ParameterInfo a) => a.Name == "__result")) { throw new ExceptionMissingResult("Original has a return value; Delegate must have __result!"); } if (returnType == typeof(void) && parameters.Any((ParameterInfo a) => a.Name == "__result")) { throw new ExceptionInvalidResult("Original has no return value; Delegate must not have __result!"); } foreach (ParameterInfo parameterInfo in parameters) { if (parameterInfo.Name == "__result") { if (!parameterInfo.ParameterType.IsByRef) { throw new ExceptionMissingRef("Delegate __result must be by ref!"); } Type elementType = parameterInfo.ParameterType.GetElementType(); if (!returnType.IsTypeCompatible(elementType)) { throw new InvalidCastException($"Delegate parameter {parameterInfo.Name} mismatch type '{returnType}' - '{elementType}'!"); } localInfo = GetLocal("__result", returnType); Code.Insert(before ? Index++ : (++Index), new CodeInstruction(OpCodes.Ldloca, (object)localInfo.Local)); } else if (!InsertPushOriginal(before, parameterInfo) && !InsertPushLocal(before, parameterInfo)) { throw new ArgumentException("Delegate unknown parameter name '" + parameterInfo.Name + "'!"); } } Code.Insert(before ? Index++ : (++Index), new CodeInstruction(OpCodes.Call, (object)methodInfo)); if (flag) { Code.Insert(before ? Index++ : (++Index), new CodeInstruction(OpCodes.Brtrue, (object)(item = GetLabel()))); } if (returnType != typeof(void)) { Code.Insert(before ? Index++ : (++Index), new CodeInstruction(OpCodes.Ldloc, (object)localInfo.Local)); } Code.Insert(before ? Index++ : (++Index), new CodeInstruction(OpCodes.Ret, (object)null)); if (flag) { ((CodeInstruction)(before ? ((object)Current) : ((object)(Next ?? throw new Exception("Cannot insert condition here"))))).labels.Add(item); } } public void InsertJump(Delegate func, LabelInfo label, bool before = false) { //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Expected O, but got Unknown MethodInfo methodInfo = func.GetMethodInfo(); ParameterInfo[] parameters = methodInfo.GetParameters(); if (!methodInfo.IsStatic) { throw new ArgumentException("Delegate must be static"); } if (methodInfo.ReturnType != typeof(bool)) { throw new ArgumentException("Delegate must return bool"); } if (label.IsEmpty) { throw new ArgumentException("LabelInfo must not be empty"); } foreach (ParameterInfo parameterInfo in parameters) { if (!InsertPushOriginal(before, parameterInfo) && !InsertPushLocal(before, parameterInfo)) { throw new ArgumentException("Delegate unknown parameter name '" + parameterInfo.Name + "'!"); } } Code.Insert(before ? Index++ : (++Index), new CodeInstruction(OpCodes.Call, (object)methodInfo)); Code.Insert(before ? Index++ : (++Index), new CodeInstruction(OpCodes.Brtrue, (object)(Label)label)); } public void ReplaceCall(Delegate func) { MemberInfo memberInfo = Current.operand as MemberInfo; MethodInfo methodInfo = func.GetMethodInfo(); ParameterInfo[] parameters = methodInfo.GetParameters(); if (!methodInfo.IsStatic) { throw new ArgumentException("Delegate must be static"); } ParameterInfo[] array; bool flag; if (memberInfo is MethodInfo methodInfo2) { array = methodInfo2.GetParameters(); flag = methodInfo2.IsStatic; if (!methodInfo2.ReturnType.IsTypeCompatible(methodInfo.ReturnType)) { throw new ExceptionMissingReturn("Delegate must return identical type!"); } } else if (memberInfo is FieldInfo fieldInfo) { array = Array.Empty<ParameterInfo>(); flag = Current.opcode != OpCodes.Ldfld; if (!fieldInfo.FieldType.IsTypeCompatible(methodInfo.ReturnType)) { throw new ExceptionMissingReturn("Delegate must return identical type!"); } } else if (Current.opcode == OpCodes.Ldc_I8) { array = Array.Empty<ParameterInfo>(); flag = true; if (!typeof(long).IsTypeCompatible(methodInfo.ReturnType)) { throw new ExceptionMissingReturn("Delegate must return identical type!"); } } else if (OpCode_Ldc_i.Contains(Current.opcode)) { array = Array.Empty<ParameterInfo>(); flag = true; if (!typeof(int).IsTypeCompatible(methodInfo.ReturnType)) { throw new ExceptionMissingReturn("Delegate must return identical type!"); } } else if (Current.opcode == OpCodes.Ldc_R8) { array = Array.Empty<ParameterInfo>(); flag = true; if (typeof(double) != methodInfo.ReturnType) { throw new ExceptionMissingReturn("Delegate must return identical type!"); } } else if (Current.opcode == OpCodes.Ldc_R4) { array = Array.Empty<ParameterInfo>(); flag = true; if (typeof(float) != methodInfo.ReturnType) { throw new ExceptionMissingReturn("Delegate must return identical type!"); } } else { LocalInfo local; LocalInfo localInfo = (local = GetLocal()); if (localInfo.IsEmpty) { throw new InvalidOperationException("Current must call a member"); } array = Array.Empty<ParameterInfo>(); flag = true; if (!local.Type.IsTypeCompatible(methodInfo.ReturnType)) { throw new ExceptionMissingReturn("Delegate must return identical type!"); } } if (!flag && (parameters.Length == 0 || parameters[0].Name == array.AtIndex(0)?.Name)) { throw new ExceptionMissingInstance("Delegate is missing instance!"); } if (parameters.Length < array.Length + ((!flag) ? 1 : 0)) { throw new ExceptionMissingParameter("Delegate has less parameters than replaced method!"); } int num = 0; int num2 = 0; while (num < parameters.Length) { ParameterInfo parameterInfo = parameters[num]; if (num == 0 && !flag) { if (!parameterInfo.ParameterType.IsTypeCompatible(memberInfo?.DeclaringType)) { throw new InvalidCastException($"Delegate parameter {parameterInfo.Name} mismatch type '{parameterInfo.ParameterType}' - '{memberInfo?.DeclaringType}'!"); } num2--; } else { ParameterInfo parameterInfo2 = array.AtIndex(num2); if (parameterInfo2 != null) { if (parameterInfo.Name != parameterInfo2.Name) { throw new ExceptionInvalidParameterOrder("Delegate must implement all replacement parameters in the same order and the same name '" + parameterInfo.Name + "' - '" + parameterInfo2.Name + "'!"); } if (!parameterInfo.ParameterType.IsTypeCompatible(parameterInfo2.ParameterType)) { throw new InvalidCastException($"Delegate parameter {parameterInfo.Name} mismatch type '{parameterInfo.ParameterType}' - '{parameterInfo2.ParameterType}'!"); } } else if (!InsertPushOriginal(before: true, parameterInfo) && !InsertPushLocal(before: true, parameterInfo)) { throw new ArgumentException("Delegate unknown parameter name '" + parameterInfo.Name + "'!"); } } num++; num2++; } Current.opcode = OpCodes.Call; Current.operand = methodInfo; } public int ReplaceAllCalls(Type type, string name, Delegate func, Type[]? parameters = null, Type[]? generics = null) { MemberInfo original = _memberCache.Get(type, name, parameters, generics); return ReplaceAllCalls(original, func); } public int ReplaceAllCalls(MemberInfo original, Delegate func) { int num = 0; int index = Index; First(); while (!IsLast) { if (Calls(original)) { ReplaceCall(func); num++; } Index++; } Index = index; return num; } public void ReplaceConstant(Enum newValue) { if (!OpCode_Ldc_i.Contains(Current.opcode)) { throw new InvalidOperationException("IL must load constant"); } if (Current.opcode.OperandType == OperandType.InlineNone) { Current.opcode = OpCodes.Ldc_I4; } if (Current.opcode.OperandType == OperandType.InlineI8) { Current.operand = Convert.ToInt64(newValue); } else { Current.operand = Convert.ToInt32(newValue); } } public void ReplaceConstant(long newValue) { if (!OpCode_Ldc_i.Contains(Current.opcode)) { throw new InvalidOperationException("IL must load constant"); } if (Current.opcode.OperandType == OperandType.InlineNone) { Current.opcode = OpCodes.Ldc_I4; } if (Current.opcode.OperandType == OperandType.InlineI8) { Current.operand = newValue; } else { Current.operand = (int)newValue; } } public void ReplaceConstant(double newValue) { if (!OpCode_Ldc_r.Contains(Current.opcode)) { throw new InvalidOperationException("IL must load constant"); } if (Current.opcode.OperandType == OperandType.ShortInlineR) { Current.operand = (float)newValue; } else { Current.operand = newValue; } } public int ReplaceAllConstant(Enum oldValue, Enum newValue, int start = 0, int end = -1) { int num = 0; int index = Index; if (end < 0 || end > Count) { end = Count; } for (Index = start; Index < end; Index++) { if (CodeInstructionExtensions.LoadsConstant(Current, oldValue)) { ReplaceConstant(newValue); num++; } } Index = index; return num; } public int ReplaceAllConstant(long oldValue, long newValue, int start = 0, int end = -1) { int num = 0; int index = Index; if (end < 0 || end > Count) { end = Count; } for (Index = start; Index < end; Index++) { if (CodeInstructionExtensions.LoadsConstant(Current, oldValue)) { ReplaceConstant(newValue); num++; } } Index = index; return num; } public int ReplaceAllConstant(double oldValue, double newValue, int start = 0, int end = -1) { int num = 0; int index = Index; if (end < 0 || end > Count) { end = Count; } for (Index = start; Index < end; Index++) { if (CodeInstructionExtensions.LoadsConstant(Current, oldValue)) { ReplaceConstant(newValue); num++; } } Index = index; return num; } public void ReplaceNOP() { Current.opcode = OpCodes.Nop; Current.operand = null; } public void NextJumpAlways() { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Expected O, but got Unknown while (Index < Code.Count) { CodeInstruction current = Current; if (current.opcode.FlowControl == FlowControl.Branch) { throw new InvalidOperationException("unexpected branch"); } if (current.opcode == OpCodes.Switch) { throw new InvalidOperationException("unexpected switch"); } if (current.opcode.FlowControl == FlowControl.Cond_Branch) { if (current.opcode.OperandType == OperandType.InlineBrTarget) { Code.Insert(++Index, new CodeInstruction(OpCodes.Br, current.operand)); return; } if (current.opcode.OperandType == OperandType.ShortInlineBrTarget) { Code.Insert(++Index, new CodeInstruction(OpCodes.Br_S, current.operand)); return; } throw new Exception($"Did not expect this OpCode {current.opcode}"); } Index++; } throw new IndexOutOfRangeException("IsLast"); } public void NextJumpNever() { while (Index < Code.Count) { CodeInstruction current = Current; if (current.opcode.FlowControl == FlowControl.Branch) { throw new InvalidOperationException("unexpected branch"); } if (current.opcode == OpCodes.Switch) { throw new InvalidOperationException("unexpected switch"); } if (current.opcode.FlowControl == FlowControl.Cond_Branch) { current.operand = (Label)GetLabel(Next ?? throw new Exception("Cannot get label to end of code")); return; } Index++; } throw new IndexOutOfRangeException("IsLast"); } public LabelInfo GetLabel(CodeInstruction line, string? name = null, bool canMake = true) { LabelInfo labelInfo; if (name != null) { labelInfo = LabelsExtended.Find((LabelInfo f) => f.Name == name); if (!labelInfo.IsEmpty) { if (!line.labels.Contains(labelInfo)) { throw new Exception("Label not attached to correct CodeInstruction: " + name); } return labelInfo; } } if (line.labels.Count == 0) { if (!canMake) { throw new Exception("CodeInstruction has no label and canMake is false"); } line.labels.Add(labelInfo = GetLabel(name)); return labelInfo; } labelInfo = LabelsExtended.Find((LabelInfo f) => f.Equals(line.labels.First())); if (labelInfo.IsEmpty) { throw new Exception($"Missing label in LabelsExtended: {labelInfo}"); } return labelInfo; } public LabelInfo GetLabel(string? name = null, bool canMake = true) { LabelInfo info = ((name == null) ? default(LabelInfo) : LabelsExtended.Find((LabelInfo f) => f.Name == name)); if (info.IsEmpty && canMake) { info = new LabelInfo(Generator.DefineLabel(), name); if (LabelsExtended.Any((LabelInfo a) => a.Equals(info))) { throw new Exception($"Label with the same index/name already exists! {info}"); } LabelsExtended.Add(info); } return info; } public LabelInfo GetLabel(int number) { return LabelsExtended.Find((LabelInfo f) => f.Index == number); } public void NameLabel(int labelIndex, string name) { if (LabelsExtended.Any((LabelInfo a) => a.Name == name)) { throw new Exception("Label with the same index/name already exists! " + name); } int num = LabelsExtended.FindIndex((LabelInfo f) => f.Index == labelIndex); if (num < 0) { throw new Exception($"Label with index {labelIndex} doesn't exists! {name}"); } LabelsExtended[num] = new LabelInfo(LabelsExtended[num].Label, name); } public void NameLabel(Label label, string name) { if (LabelsExtended.Any((LabelInfo a) => a.Name == name)) { throw new Exception("Label with the same index/name already exists! " + name); } int num = LabelsExtended.FindIndex((LabelInfo f) => f.Label == label); if (num < 0) { throw new Exception($"Label with index {label} doesn't exists! {name}"); } LabelsExtended[num] = new LabelInfo(label, name); } public LabelInfo GetCurrentLabel(bool canMake = true) { return GetLabel(Current, null, canMake); } public LabelInfo GetTargetLabel() { if (!IsBranch()) { return default(LabelInfo); } object operand = Current.operand; if (operand is Label) { Label label = (Label)operand; if (true) { return LabelsExtended.Find((LabelInfo a) => a.Index == label.GetHashCode()); } } operand = Current.operand; if (operand is int) { int integer = (int)operand; if (true) { return LabelsExtended.Find((LabelInfo a) => a.Index == integer); } } return default(LabelInfo); } public LocalInfo GetLocal(Type type, string? name = null, int occurrence = 0) { for (int i = 0; i < LocalsExtended.Count; i++) { if (LocalsExtended[i].Type == type && occurrence-- <= 0) { if (name != null && LocalsExtended[i].Name != name && LocalsExtended[i].Name.StartsWith("V_")) { NameLocal(LocalsExtended[i], name); } return LocalsExtended[i]; } } throw new InvalidCastException("unable to find matching local type"); } public LocalInfo GetLocal(string? name = null, Type? type = null, bool canMake = true) { LocalInfo info = ((name == null) ? default(LocalInfo) : LocalsExtended.Find((LocalInfo f) => f.Name == name)); if (info.IsEmpty && type != null && canMake) { info = new LocalInfo(Generator.DeclareLocal(type), name); if (LocalsExtended.Any((LocalInfo a) => a.Index == info.Index)) { throw new Exception($"Label with the same index already exists! {info.Index}"); } LocalsExtended.Add(info); } if (type != null && !info.IsEmpty && !info.Type.IsTypeCompatible(type)) { throw new InvalidCastException("local type incompatible"); } return info; } public LocalInfo GetLocal(int index, Type? type = null) { LocalInfo result = LocalsExtended.Find((LocalInfo f) => f.Index == index); if (type != null && !result.IsEmpty && !result.Type.IsTypeCompatible(type)) { throw new InvalidCastException("local type incompatible"); } return result; } public void NameLocal(string name) { LocalInfo local = GetLocal(); if (local.IsEmpty) { throw new Exception("CodeInstruction does not point to local"); } NameLocal(local, name); } public void NameLocal(int localIndex, string name) { if (LocalsExtended.Any((LocalInfo a) => a.Name == name)) { throw new Exception("Label with the same index/name already exists! " + name); } int num = LocalsExtended.FindIndex((LocalInfo f) => f.Equals(localIndex)); if (num < 0) { throw new Exception($"Local with index {localIndex} doesn't exists! {name}"); } LocalsExtended[num] = new LocalInfo(LocalsExtended[num].Local, name); } public void NameLocal(LocalVariableInfo local, string name) { if (LocalsExtended.Any((LocalInfo a) => a.Name == name)) { throw new Exception("Label with the same index/name already exists! " + name); } int num = LocalsExtended.FindIndex((LocalInfo f) => f.Equals(local)); if (num < 0) { throw new Exception($"Local with index {local.LocalIndex} doesn't exists! {name}"); } LocalsExtended[num] = new LocalInfo(local, name); } public void NameLocal(LocalInfo local, string name) { if (LocalsExtended.Any((LocalInfo a) => a.Name == name)) { throw new Exception("Label with the same index/name already exists! " + name); } int num = LocalsExtended.FindIndex((LocalInfo f) => f.Equals(local)); if (num < 0) { throw new Exception($"Local with index {local.Local.LocalIndex} doesn't exists! {name}"); } LocalsExtended[num] = new LocalInfo(local, name); } public LocalInfo GetLocal() { int index = GetLocalIndex(); if (index < 0) { return default(LocalInfo); } return LocalsExtended.Find((LocalInfo a) => a.Index == index); } public int GetLocalIndex() { if (!CodeInstructionExtensions.IsLdloc(Current, (LocalBuilder)null) && !CodeInstructionExtensions.IsStloc(Current, (LocalBuilder)null)) { return -1; } if (Current.opcode == OpCodes.Ldloc_0 || Current.opcode == OpCodes.Stloc_0) { return 0; } if (Current.opcode == OpCodes.Ldloc_1 || Current.opcode == OpCodes.Stloc_1) { return 1; } if (Current.opcode == OpCodes.Ldloc_2 || Current.opcode == OpCodes.Stloc_2) { return 2; } if (Current.opcode == OpCodes.Ldloc_3 || Current.opcode == OpCodes.Stloc_3) { return 3; } if (!(Current.operand is LocalVariableInfo { LocalIndex: var localIndex })) { if (Current.operand is int result) { return result; } return -1; } return localIndex; } public int IndexOf(CodeInstruction item) { return Code.IndexOf(item); } public void Insert(int index, CodeInstruction item) { if (item.operand is LabelInfo labelInfo) { item.operand = (Label)labelInfo; } Code.Insert(index, item); } public void RemoveAt(int index) { Code.RemoveAt(index); } public void Add(CodeInstruction item) { if (item.operand is LabelInfo labelInfo) { item.operand = (Label)labelInfo; } Code.Add(item); } public void Clear() { Code.Clear(); } public bool Contains(CodeInstruction item) { return Code.Contains(item); } public void CopyTo(CodeInstruction[] array, int arrayIndex) { Code.CopyTo(array, arrayIndex); } public bool Remove(CodeInstruction item) { return Code.Remove(item); } public IEnumerator<CodeInstruction> GetEnumerator() { return Code.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)Code).GetEnumerator(); } public static TranspilerTool operator ++(TranspilerTool a) { a.Index++; return a; } public static TranspilerTool operator --(TranspilerTool a) { a.Index--; return a; } public static MemberInfo GetMemberInfo(Type type, string name, Type[]? parameters = null, Type[]? generics = null) { return (MemberInfo)(AccessTools.Method(type, name, parameters, generics) ?? ((object)AccessTools.PropertyGetter(type, name)) ?? ((object)(AccessTools.Field(type, name) ?? throw new ArgumentException(string.Format("could not find anything for type={0} name={1} parameters={2} generics={3}", type, name, GeneralExtensions.Join<Type>((IEnumerable<Type>)parameters, (Func<Type, string>)null, ", "), GeneralExtensions.Join<Type>((IEnumerable<Type>)generics, (Func<Type, string>)null, ", ")))))); } public static int GetStackChange(StackBehaviour stack) { switch (stack) { case StackBehaviour.Pop0: case StackBehaviour.Push0: return 0; case StackBehaviour.Pop1: case StackBehaviour.Popi: case StackBehaviour.Popref: case StackBehaviour.Varpop: return -1; case StackBehaviour.Push1: case StackBehaviour.Pushi: case StackBehaviour.Pushi8: case StackBehaviour.Pushr4: case StackBehaviour.Pushr8: case StackBehaviour.Pushref: case StackBehaviour.Varpush: return 1; case StackBehaviour.Pop1_pop1: case StackBehaviour.Popi_pop1: case StackBehaviour.Popi_popi: case StackBehaviour.Popi_popi8: case StackBehaviour.Popi_popr4: case StackBehaviour.Popi_popr8: case StackBehaviour.Popref_pop1: case StackBehaviour.Popref_popi: return -2; case StackBehaviour.Push1_push1: return 2; case StackBehaviour.Popi_popi_popi: case StackBehaviour.Popref_popi_popi: case StackBehaviour.Popref_popi_popi8: case StackBehaviour.Popref_popi_popr4: case StackBehaviour.Popref_popi_popr8: case StackBehaviour.Popref_popi_popref: case StackBehaviour.Popref_popi_pop1: return -3; default: throw new ArgumentOutOfRangeException(); } } public static bool ThrowParameterIncompatible(ParameterInfo? parameter, Type? right) { return ThrowParameterIncompatible(parameter?.ParameterType, right); } public static bool ThrowParameterIncompatible(Type? left, Type? right) { if (left == null) { throw new ArgumentNullException("left is null"); } if (right == null) { throw new ArgumentNullException("right is null"); } if (!left.IsByRef && right.IsByRef) { throw new ExceptionMissingRef($"parameter must be by ref, if type is by ref '{left}' - '{right}'"); } if (left == right) { return false; } if (left.IsByRef) { if (left.GetElementType() == right) { return true; } throw new InvalidCastException($"by ref parameters must match type exactly '{left}' - '{right}'"); } if (left.IsValueType || right.IsValueType) { throw new InvalidCastException($"value-type parameters must match type exactly '{left}' - '{right}'"); } if (!left.IsAssignableFrom(right)) { throw new InvalidCastException($"cannot cast '{left}' - '{right}'"); } return false; } public static bool HasMethodCall(MethodInfo parentMethod, MethodInfo lookingforMethod) { foreach (KeyValuePair<OpCode, object> item in PatchProcessor.ReadMethodBody((MethodBase)parentMethod)) { if (lookingforMethod.Equals(item.Value)) { return true; } } return false; } public static IEnumerable<MethodInfo> GetCallers(MethodInfo lookingforMethod, string[]? includeAssemblies = null, string[]? excludeAssemblies = null) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { string name = assembly.FullName; if ((includeAssemblies != null && !includeAssemblies.Any(name.StartsWith)) || (excludeAssemblies?.Any(name.StartsWith) ?? false)) { continue; } Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(assembly); foreach (Type @class in typesFromAssembly) { MethodInfo[] methods = @class.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo parentMethod in methods) { if (HasMethodCall(parentMethod, lookingforMethod)) { yield return parentMethod; } } } } } public static IEnumerable<MethodInfo> GetCallersR(MethodInfo parentMethod, MethodInfo lookingforMethod, bool onlyParent = false) { bool didReturn = false; MethodInfo lambda = default(MethodInfo); foreach (KeyValuePair<OpCode, object> line in PatchProcessor.ReadMethodBody((MethodBase)parentMethod)) { if (!didReturn && lookingforMethod.Equals(line.Value)) { didReturn = true; yield return parentMethod; } int num; if (line.Key == OpCodes.Ldftn) { object value = line.Value; lambda = value as MethodInfo; if ((object)lambda != null && (!onlyParent || lambda.DeclaringType == parentMethod.DeclaringType || lambda.DeclaringType?.DeclaringType == parentMethod.DeclaringType)) { num = (HasMethodCall(lambda, lookingforMethod) ? 1 : 0); goto IL_0161; } } num = 0; goto IL_0161; IL_0161: if (num != 0) { yield return lambda; } lambda = null; } } public static MethodInfo? GetLambda(MethodInfo parentMethod, Type returnType, Type[] parameters, int occurrence = 0) { if ((object)returnType == null) { returnType = typeof(void); } if (parameters == null) { parameters = Array.Empty<Type>(); } List<CodeInstruction> originalInstructions = PatchProcessor.GetOriginalInstructions((MethodBase)parentMethod, (ILGenerator)null); foreach (CodeInstruction item in originalInstructions) { if (item.opcode == OpCodes.Ldftn && item.operand is MethodInfo methodInfo && (returnType == null || methodInfo.ReturnType == returnType) && GeneralExtensions.Types(methodInfo.GetParameters()).SequenceEqual(parameters) && occurrence-- <= 0) { return methodInfo; } } return null; } public static List<MethodInfo> GetLambdas(MethodInfo parentMethod) { List<MethodInfo> list = new List<MethodInfo>(); List<CodeInstruction> originalInstructions = PatchProcessor.GetOriginalInstructions((MethodBase)parentMethod, (ILGenerator)null); foreach (CodeInstruction item2 in originalInstructions) { if (item2.opcode == OpCodes.Ldftn && item2.operand is MethodInfo item) { list.Add(item); } } return list; } public static TranspilerTool Load(MethodInfo original) { ILGenerator generator = default(ILGenerator); return new TranspilerTool(PatchProcessor.GetOriginalInstructions((MethodBase)original, ref generator), generator, original); } } public readonly struct LabelInfo { public readonly Label Label; public readonly string? Name; public int Index => (!IsEmpty) ? Label.GetHashCode() : (-1); public bool IsEmpty => Name == null; internal LabelInfo(Label label, string? name = null) { Label = label; Name = name ?? ("L_" + label.GetHashCode()); } internal LabelInfo(int label, string name) { if (label < 0) { throw new IndexOutOfRangeException(); } Label = (Label)typeof(Label).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0].Invoke(new object[1] { label }); Name = name ?? throw new ArgumentNullException(); } public override string ToString() { return $"[Label:{Index}:{Name}]"; } public override bool Equals(object obj) { if (obj is LabelInfo labelInfo) { return Index == labelInfo.Index || Name == labelInfo.Name; } if (obj is int num) { return Index == num; } if (obj is Label label) { return Index == label.GetHashCode(); } if (obj is string text) { return Name == text; } return false; } public override int GetHashCode() { return Index; } public static implicit operator Label(LabelInfo info) { return info.Label; } public static implicit operator int(LabelInfo info) { return info.Index; } } public readonly struct LocalInfo { public readonly LocalVariableInfo Local; public readonly string Name; public int Index => Local?.LocalIndex ?? (-1); public Type? Type => Local?.LocalType; public bool IsEmpty => Local == null; internal LocalInfo(LocalVariableInfo local, string? name) { Name = null; Local = local ?? throw new ArgumentNullException(); Name = name ?? $"V_{Index}"; } public override string ToString() { return $"[Local:{Index}:{Name}:{Type?.Name}]"; } public override bool Equals(object obj) { if (obj is LocalInfo localInfo) { return Index == localInfo.Index || Name == localInfo.Name; } if (obj is int num) { return Index == num; } if (obj is LocalVariableInfo localVariableInfo) { return Index == localVariableInfo.LocalIndex; } if (obj is string text) { return Name == text; } return false; } public override int GetHashCode() { return Index; } public static implicit operator LocalVariableInfo(LocalInfo info) { return info.Local; } public static implicit operator int(LocalInfo info) { return info.Index; } } internal static class ModInfo { public const string MOD_GUID = "UnityMod-net472"; public const string MOD_NAME = "UnityMod-net472"; public const string MOD_AUTHORS = "Truinto"; public const string MOD_VERSION = "1.1.2.0"; public const string MOD_DESCRIPTION = ""; public const byte MOD_NICESSE = 10; } } namespace Shared.CollectionNS { public static class CollectionTool { public static readonly byte[] Buffer = new byte[2048]; private static readonly List<object> _list = new List<object>(); public static int Count(this IEnumerable enumerable) { if (!(enumerable is ICollection { Count: var count })) { int num = 0; foreach (object item in enumerable) { num++; } return num; } return count; } public static T? Get<T>(this IEnumerable enumerable) { if (enumerable == null) { return default(T); } foreach (object item in enumerable) { if (item is T result) { return result; } } return default(T); } public static IEnumerable<T> GetAll<T>(this IEnumerable enumerable) { if (enumerable == null) { yield break; } T t = default(T); foreach (object item in enumerable) { int num; if (item is T) { t = (T)item; num = 1; } else { num = 0; } if (num != 0) { yield return t; } t = default(T); } } public static T? GetFirst<T>(this IList<T> list) { if (list.Count <= 0) { return default(T); } return list[0]; } public static T? GetLast<T>(this IList<T> list) { if (list.Count <= 0) { return default(T); } return list[list.Count - 1]; } public static bool IsTypeCompatible(this Type? left, Type? right) { if (left == null || right == null) { return false; } if (left == right) { return true; } if (left.IsValueType || right.IsValueType) { return false; } return left.IsAssignableFrom(right); } public static int GetIndex<T>(this IEnumerable enumerable, Func<T, bool> pred) { int num = 0; foreach (T item in enumerable) { if (pred(item)) { return num; } num++; } return -1; } public static int GetIndex<T>(this IEnumerable<T> enumerable, Func<T, bool> pred) { int num = 0; foreach (T item in enumerable) { if (pred(item)) { return num; } num++; } return -1; } public static int GetIndex<T>(this IEnumerable<T> enumerable, T element) { int num = 0; foreach (T item in enumerable) { if (object.Equals(item, element)) { return num; } num++; } return -1; } public static int GetIndex<T>(this IEnumerable<T> enumerable, T element, int notFound) { int num = 0; foreach (T item in enumerable) { if (object.Equals(item, element)) { return num; } num++; } return notFound; } public static T? AtIndex<T>(this IEnumerable enumerable, int index) { int num = 0; foreach (object item in enumerable) { if (num == index) { return (T)item; } } return default(T); } public static T? AtIndex<T>(this IEnumerable<T> enumerable, int index) { return enumerable.ElementAtOrDefault(index); } public static bool ContainsReference(this IEnumerable enumerable, object? element) { if (element == null) { return false; } foreach (object item in enumerable) { if (item == element) { return true; } } return false; } public static bool Contains(this IEnumerable enumerable, object? element) { if (element == null) { return false; } foreach (object item in enumerable) { if (object.Equals(item, element)) { return true; } } return false; } public static bool ContainsMany(this IEnumerable enumerable, object? element, int depth = 50) { if (element == null || depth < 0) { return false; } foreach (object item in enumerable) { if (object.Equals(item, element)) { return true; } if (item is IEnumerable enumerable2 && enumerable2.ContainsMany(element, depth - 1)) { return true; } } return false; } public static bool Contains<T>(this IEnumerable<IEnumerable<T>> enumerable, T element) { foreach (IEnumerable<T> item in enumerable) { if (item.Contains(element)) { return true; } } return false; } public static bool ContainsSequence(this IList array, IList search, int offsetArray = 0, int offsetSearch = 0, int lengthArray = -1, int lengthSearch = -1) { if (lengthArray < 0) { lengthArray = array.Count; } if (lengthSearch < 0) { lengthSearch = search.Count; } else if (lengthSearch == 0) { return true; } int num = offsetArray; int num2 = offsetSearch; do { if (array.Count >= num || search.Count >= num2) { return false; } if (num - offsetArray >= lengthArray) { return false; } if (!object.Equals(array[num++], search[num2++])) { num2 = offsetSearch; } } while (num2 - offsetSearch < lengthSearch); return true; } public static bool ContainsSequence(this byte[] array, byte[] search, int offsetArray = 0, int offsetSearch = 0, int lengthArray = -1, int lengthSearch = -1) { if (lengthArray < 0) { lengthArray = array.Length; } if (lengthSearch < 0) { lengthSearch = search.Length; } else if (lengthSearch == 0) { return true; } int num = offsetArray; int num2 = offsetSearch; do { if (array.Length <= num || search.Length <= num2) { return false; } if (num - offsetArray >= lengthArray) { return false; } if (array[num++] != search[num2++]) { num2 = offsetSearch; } } while (num2 - offsetSearch < lengthSearch); return true; } public static bool StartsWith(this FileInfo filePath, string text, bool throwOnError = false) { try { using FileStream fileStream = new FileStream(filePath.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); fileStream.Position = 0L; int num = fileStream.Read(Buffer, 0, Math.Min(Buffer.Length, text.Length * 2 + 2)); bool flag = false; int num2 = 0; if (num >= 2) { if (Buffer[0] == byte.MaxValue && Buffer[1] == 254) { flag = true; num2 = 2; } else if (Buffer[1] == byte.MaxValue && Buffer[0] == 254) { flag = true; num2 = 3; } } int num3 = 0; while (num3 < text.Length) { if (num2 >= num) { return false; } if (text[num3++] != Buffer[num2++]) { return false; } if (flag) { num2++; } } return true; } catch (Exception) { if (!throwOnError) { return false; } throw; } } public static IEnumerable<TResult> SelectWhere<T, TResult>(this IEnumerable<T> enumerable, Func<T, bool> predicate, Func<T, TResult> selector) { return enumerable.Where(predicate).Select(selector); } public static IEnumerable<TResult> SelectNotNull<T, TResult>(this IEnumerable<T> enumerable, Func<T, TResult?> selector) where TResult : class { foreach (T item in enumerable) { if (item != null) { TResult item2 = selector(item); if (item2 != null) { yield return item2; } } } } public static void AddUnique<T>(this IList<T> list, IEnumerable<T> values) { foreach (T value in values) { if (value == null) { continue; } foreach (T item in list) { if (!value.Equals(item)) { continue; } goto IL_0072; } list.Add(value); IL_0072:; } } public static void AddUnique<T1, T2>(this IList<T1> list, IEnumerable<T2> values, Func<T2, T1> converter) { foreach (T2 value in values) { if (value == null) { continue; } foreach (T1 item in list) { if (item == null || !item.Equals(value)) { continue; } goto IL_0083; } list.Add(converter(value)); IL_0083:; } } public static void AddUnique2<T1, T2>(this IList<T1> list, IEnumerable<T2> values, Func<T2, T1> converter) { foreach (T2 value in values) { if (value == null) { continue; } foreach (T1 item in list) { if (!value.Equals(item)) { continue; } goto IL_0078; } list.Add(converter(value)); IL_0078:; } } public static List<T> AddUnique<T>(this List<T> list, T item) { if (!list.Contains(item)) { list.Add(item); } return list; } public static List<T> AddUnique<T>(this List<T> list, Func<T, bool> pred, Func<T> getter) { if (!list.Any(pred)) { list.Add(getter()); } return list; } public static T[] AsArray<T>(this IEnumerable<T> values) { return (values as T[]) ?? values.ToArray(); } public static List<T> AsList<T>(this IEnumerable<T> values) { return (values as List<T>) ?? values.ToList(); } public static IEnumerable<T> Concat<T>(this IEnumerable<T> enumerable, T value) { foreach (T item in enumerable) { yield return item; } yield return value; } public static IEnumerable<T> Concat<T>(this T value, IEnumerable<T> enumerable) { yield return value; foreach (T item in enumerable) { yield return item; } } public static IEnumerable<T> InjectBefore<T>(this IEnumerable<T> enumerable, Func<T, bool> pred, Func<T, T> value) { foreach (T item in enumerable) { if (pred(item)) { yield return value(item); } yield return item; } } public static IEnumerable<T> InjectAfter<T>(this IEnumerable<T> enumerable, Func<T, bool> pred, Func<T, T> value) { foreach (T item in enumerable) { yield return item; if (pred(item)) { yield return value(item); } } } public static TList Add<T, TList>(this TList destination, IEnumerable<T> source) where TList : ICollection<T> { if (destination == null) { throw new ArgumentNullException("destination"); } if (source == null) { throw new ArgumentNullException("source"); } if (destination is List<T> list) { list.AddRange(source); return destination; } foreach (T item in source) { destination.Add(item); } return destination; } public static IEnumerable<T> AddBefore<T>(this IEnumerable<T> collection, T element) { yield return element; foreach (T item in collection) { yield return item; } } public static IEnumerable<T> AddAfter<T>(this IEnumerable<T> collection, T element) { foreach (T item in collection) { yield return item; } yield return element; } public static T[] Append<T>(this T[] orig, params T[] objs) { if (orig == null) { orig = Array.Empty<T>(); } if (objs == null) { objs = Array.Empty<T>(); } T[] array = new T[orig.Length + objs.Length]; int i; for (i = 0; i < orig.Length; i++) { array[i] = orig[i]; } int num = 0; for (; i < array.Length; i++) { array[i] = objs[num++]; } return array; } public static List<T> Append<T>(this IList<T> orig, IList<T> objs) { List<T> list = new List<T>(orig); list.AddRange(objs); return list; } public static void AppendAndReplace<T>(ref T[] orig, params T[] objs) { AppendAndReplace(ref orig, (IEnumerable<T>)objs); } public static void AppendAndReplace<T>(ref T[] orig, IEnumerable<T> objs) { if (orig == null) { orig = Array.Empty<T>(); } T[] array = new T[orig.Length + objs.Count()]; int i; for (i = 0; i < orig.Length; i++) { array[i] = orig[i]; } foreach (T obj in objs) { array[i++] = obj; } orig = array; } public static void RemoveAll<T>(ref T[] orig, Func<T, bool> predicate) { orig = orig.Where((T w) => !predicate(w)).ToArray(); } public static void InsertAt<T>(ref T[] orig, T obj, int index = -1) { if (orig == null) { orig = Array.Empty<T>(); } if (index < 0 || index > orig.Length) { index = orig.Length; } T[] array = new T[orig.Length + 1]; int i = 0; int num = 0; for (; i < array.Length; i++) { if (i == index) { array[i] = obj; } else { array[i] = orig[num++]; } } orig = array; } public static void RemoveAt<T>(ref T[] orig, int index) { if (orig == null) { orig = Array.Empty<T>(); } if (index < 0 || index >= orig.Length) { return; } T[] array = new T[orig.Length - 1]; int i = 0; int num = 0; for (; i < array.Length; i++) { if (i != index) { array[i] = orig[num++]; } } orig = array; } public static void RemoveGet<T>(this List<T> list, List<T> result, Func<T, bool> predicate) { for (int num = list.Count - 1; num >= 0; num--) { if (predicate(list[num])) { result.Add(list[num]); list.RemoveAt(num); break; } } } public static void RemoveGet<T1, T2>(this List<T1> list, List<T2> result, Func<T1, bool> predicate, Func<T1, T2> select) { for (int num = list.Count - 1; num >= 0; num--) { if (predicate(list[num])) { result.Add(select(list[num])); list.RemoveAt(num); break; } } } public static bool Ensure<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, out TValue value) where TKey : notnull where TValue : new() { if (dic.TryGetValue(key, out value)) { return false; } dic[key] = (value = new TValue()); return true; } public static bool Ensure<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, out TValue value, Func<TValue> getter) where TKey : notnull { if (dic.TryGetValue(key, out value)) { return false; } dic[key] = (value = getter()); return true; } public static void QuickSort<T>(IList<T> list, int leftBound, int rightBound) where T : IComparable<T> { if (rightBound <= leftBound) { return; } int i = leftBound; int num = rightBound; T other = list[leftBound]; while (i <= num) { for (; list[i].CompareTo(other) < 0; i++) { } while (list[num].CompareTo(other) > 0) { num--; } if (i <= num) { T value = list[i]; list[i++] = list[num]; list[num--] = value; } } if (leftBound < num) { QuickSort(list, leftBound, num); } if (i < rightBound) { QuickSort(list, i, rightBound); } } public static void QuickSort<T1, T2>(IList<T1> list, Func<T1, T2> keySelector, int leftBound, int rightBound) where T2 : IComparable<T2> { int i = leftBound; int num = rightBound; T2 other = keySelector(list[leftBound]); while (i <= num) { for (; keySelector(list[i]).CompareTo(other) < 0; i++) { } while (keySelector(list[num]).CompareTo(other) > 0) { num--; } if (i <= num) { T1 value = list[i]; list[i++] = list[num]; list[num--] = value; } } if (leftBound