Decompiled source of RandyOrtonV81Fix v1.2.2

patchers/RandyOrtonV81Fix.Patcher.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Logging;
using Mono.Cecil;
using Mono.Cecil.Cil;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
public static class RandyOrtonV81FixPatcher
{
	private struct Fix
	{
		public string Type;

		public string Method;

		public int OldCount;
	}

	private static readonly ManualLogSource Log = Logger.CreateLogSource("RandyOrtonV81Fix.Patcher");

	private static readonly Fix[] Fixes = new Fix[2]
	{
		new Fix
		{
			Type = "GameNetcodeStuff.PlayerControllerB",
			Method = "HasLineOfSightToPosition",
			OldCount = 4
		},
		new Fix
		{
			Type = "EnemyAI",
			Method = "TargetClosestPlayer",
			OldCount = 3
		}
	};

	public static IEnumerable<string> TargetDLLs { get; } = new string[0];

	public static void Patch(AssemblyDefinition assembly)
	{
	}

	public static void Initialize()
	{
		Run(Paths.PluginPath, Paths.ManagedPath, Paths.BepInExAssemblyDirectory);
	}

	public static void Run(string pluginPath, string managedPath, string coreDir)
	{
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Expected O, but got Unknown
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Expected O, but got Unknown
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Unknown result type (might be due to invalid IL or missing references)
		//IL_030c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0302: Unknown result type (might be due to invalid IL or missing references)
		//IL_033c: Unknown result type (might be due to invalid IL or missing references)
		//IL_036e: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			string text = Directory.GetFiles(pluginPath, "FrenchPlatypus.RandyOrton.dll", SearchOption.AllDirectories).FirstOrDefault();
			if (text == null)
			{
				Log.LogInfo((object)"Randy Orton not installed, nothing to do.");
				return;
			}
			DefaultAssemblyResolver val = new DefaultAssemblyResolver();
			((BaseAssemblyResolver)val).AddSearchDirectory(managedPath);
			((BaseAssemblyResolver)val).AddSearchDirectory(coreDir);
			((BaseAssemblyResolver)val).AddSearchDirectory(Path.GetDirectoryName(text));
			string[] directories = Directory.GetDirectories(pluginPath, "*", SearchOption.AllDirectories);
			foreach (string text2 in directories)
			{
				((BaseAssemblyResolver)val).AddSearchDirectory(text2);
			}
			ReaderParameters val2 = new ReaderParameters();
			val2.AssemblyResolver = (IAssemblyResolver)(object)val;
			ReaderParameters val3 = val2;
			AssemblyDefinition val4 = AssemblyDefinition.ReadAssembly(Path.Combine(managedPath, "Assembly-CSharp.dll"), val3);
			int num = 0;
			AssemblyDefinition val5 = AssemblyDefinition.ReadAssembly((Stream)new MemoryStream(File.ReadAllBytes(text)), val3);
			byte[] bytes;
			try
			{
				bool flag = default(bool);
				int num4 = default(int);
				float num5 = default(float);
				foreach (TypeDefinition type in val5.MainModule.GetTypes())
				{
					foreach (MethodDefinition item in ((IEnumerable<MethodDefinition>)type.Methods).Where((MethodDefinition m) => m.HasBody))
					{
						ILProcessor iLProcessor = item.Body.GetILProcessor();
						foreach (Instruction item2 in ((IEnumerable<Instruction>)item.Body.Instructions).ToList())
						{
							object operand = item2.Operand;
							MethodReference val6 = (MethodReference)((operand is MethodReference) ? operand : null);
							if (val6 == null || (item2.OpCode != OpCodes.Call && item2.OpCode != OpCodes.Callvirt))
							{
								continue;
							}
							Fix[] fixes = Fixes;
							for (int num2 = 0; num2 < fixes.Length; num2++)
							{
								Fix fix = fixes[num2];
								if (((MemberReference)val6).Name != fix.Method || ((MemberReference)((MemberReference)val6).DeclaringType).FullName != fix.Type || val6.Parameters.Count != fix.OldCount)
								{
									continue;
								}
								MethodDefinition val7 = (from m in (IEnumerable<MethodDefinition>)val4.MainModule.GetType(fix.Type).Methods
									where ((MemberReference)m).Name == fix.Method && ((MethodReference)m).Parameters.Count > fix.OldCount
									orderby ((MethodReference)m).Parameters.Count
									select m).FirstOrDefault();
								if (val7 == null)
								{
									Log.LogWarning((object)$"{fix.Type}.{fix.Method}: v81 version not found.");
									continue;
								}
								List<Instruction> list = new List<Instruction>();
								for (int num3 = fix.OldCount; num3 < ((MethodReference)val7).Parameters.Count; num3++)
								{
									object constant = ((MethodReference)val7).Parameters[num3].Constant;
									object obj = ((constant is bool) ? constant : null);
									if (obj != null)
									{
										flag = (bool)constant;
									}
									if (obj != null)
									{
										list.Add(iLProcessor.Create((!flag) ? OpCodes.Ldc_I4_0 : OpCodes.Ldc_I4_1));
										continue;
									}
									object obj2 = ((constant is int) ? constant : null);
									if (obj2 != null)
									{
										num4 = (int)constant;
									}
									if (obj2 != null)
									{
										list.Add(iLProcessor.Create(OpCodes.Ldc_I4, num4));
										continue;
									}
									object obj3 = ((constant is float) ? constant : null);
									if (obj3 != null)
									{
										num5 = (float)constant;
									}
									if (obj3 != null)
									{
										list.Add(iLProcessor.Create(OpCodes.Ldc_R4, num5));
										continue;
									}
									list = null;
									break;
								}
								if (list == null)
								{
									Log.LogWarning((object)$"{fix.Type}.{fix.Method}: unsupported default value.");
									continue;
								}
								foreach (Instruction item3 in list)
								{
									iLProcessor.InsertBefore(item2, item3);
								}
								item2.Operand = val5.MainModule.ImportReference((MethodReference)(object)val7);
								num++;
							}
						}
					}
				}
				if (num == 0)
				{
					Log.LogInfo((object)"Randy Orton already up to date for v81, nothing to do.");
					return;
				}
				MemoryStream memoryStream = new MemoryStream();
				val5.Write((Stream)memoryStream);
				bytes = memoryStream.ToArray();
			}
			finally
			{
				((IDisposable)val5)?.Dispose();
			}
			string text3 = text + ".orig";
			if (!File.Exists(text3))
			{
				File.Copy(text, text3);
			}
			File.SetAttributes(text, File.GetAttributes(text) & ~FileAttributes.ReadOnly);
			File.WriteAllBytes(text, bytes);
			Log.LogInfo((object)$"Updated {num} call(s) in {Path.GetFileName(text)} to the v81 game methods (original saved as .orig).");
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Randy Orton v81 fix failed: " + ex));
		}
	}
}

plugins/RandyOrtonV81Fix.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[BepInPlugin("community.RandyOrtonV81Fix", "RandyOrtonV81Fix", "1.2.2")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class RandyOrtonV81FixPlugin : BaseUnityPlugin
{
	internal static ManualLogSource Log;

	private static FieldInfo tableField;

	private static Type handlerType;

	private const string TargetTypeName = "CustomEnnemies.RandyOrtonAI";

	private static readonly MethodInfo StopCoroutineMethod = AccessTools.Method(typeof(MonoBehaviour), "StopCoroutine", new Type[1] { typeof(Coroutine) }, (Type[])null);

	private static readonly MethodInfo SafeStopMethod = AccessTools.Method(typeof(RandyOrtonV81FixPlugin), "SafeStopCoroutine", (Type[])null, (Type[])null);

	private static readonly MethodInfo StopEnumeratorMethod = AccessTools.Method(typeof(MonoBehaviour), "StopCoroutine", new Type[1] { typeof(IEnumerator) }, (Type[])null);

	private static readonly MethodInfo SafeStopEnumeratorMethod = AccessTools.Method(typeof(RandyOrtonV81FixPlugin), "SafeStopEnumerator", (Type[])null, (Type[])null);

	private void Awake()
	{
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Expected O, but got Unknown
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Expected O, but got Unknown
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		tableField = AccessTools.Field(typeof(NetworkBehaviour), "__rpc_func_table");
		handlerType = typeof(NetworkBehaviour).GetNestedType("RpcReceiveHandler", BindingFlags.Public | BindingFlags.NonPublic);
		MethodInfo methodInfo = AccessTools.Method(typeof(EnemyAI), "__initializeRpcs", (Type[])null, (Type[])null);
		if (tableField == null || handlerType == null || methodInfo == null)
		{
			Log.LogError((object)"Netcode internals not found, fix not applied.");
			return;
		}
		Harmony val = new Harmony("community.RandyOrtonV81Fix");
		MethodInfo methodInfo2 = methodInfo;
		HarmonyMethod val2 = new HarmonyMethod(typeof(RandyOrtonV81FixPlugin).GetMethod("InitializeRpcsPostfix", BindingFlags.Static | BindingFlags.NonPublic));
		val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		Log.LogInfo((object)"Ready to register Randy Orton RPC handlers.");
		Type type = AccessTools.TypeByName("CustomEnnemies.RandyOrtonAI");
		MethodInfo methodInfo3 = ((!(type == null)) ? AccessTools.Method(type, "HitEnemy", (Type[])null, (Type[])null) : null);
		if (methodInfo3 != null)
		{
			methodInfo2 = methodInfo3;
			val2 = new HarmonyMethod(typeof(RandyOrtonV81FixPlugin).GetMethod("SafeStopTranspiler", BindingFlags.Static | BindingFlags.NonPublic));
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null);
			Log.LogInfo((object)"Patched RandyOrtonAI.HitEnemy to ignore stopping a coroutine that was never started.");
		}
		else
		{
			Log.LogWarning((object)"RandyOrtonAI.HitEnemy not found, hit fix not applied.");
		}
	}

	private static void SafeStopEnumerator(MonoBehaviour behaviour, IEnumerator routine)
	{
		if (routine != null)
		{
			behaviour.StopCoroutine(routine);
		}
	}

	private static void SafeStopCoroutine(MonoBehaviour behaviour, Coroutine routine)
	{
		if (routine != null)
		{
			behaviour.StopCoroutine(routine);
		}
	}

	private static IEnumerable<CodeInstruction> SafeStopTranspiler(IEnumerable<CodeInstruction> instructions)
	{
		foreach (CodeInstruction ins in instructions)
		{
			if (ins.opcode == OpCodes.Call || ins.opcode == OpCodes.Callvirt)
			{
				MethodInfo methodInfo = ins.operand as MethodInfo;
				if (methodInfo == StopCoroutineMethod)
				{
					ins.opcode = OpCodes.Call;
					ins.operand = SafeStopMethod;
				}
				else if (methodInfo == StopEnumeratorMethod)
				{
					ins.opcode = OpCodes.Call;
					ins.operand = SafeStopEnumeratorMethod;
				}
			}
			yield return ins;
		}
	}

	private static void InitializeRpcsPostfix(EnemyAI __instance)
	{
		try
		{
			Type type = ((object)__instance).GetType();
			if (type.FullName != "CustomEnnemies.RandyOrtonAI" || !(tableField.GetValue(null) is IDictionary dictionary) || !dictionary.Contains(type) || !(dictionary[type] is IDictionary dictionary2))
			{
				return;
			}
			int num = 0;
			MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.Name.StartsWith("__rpc_handler_") && uint.TryParse(methodInfo.Name.Substring("__rpc_handler_".Length), out var result) && !dictionary2.Contains(result))
				{
					dictionary2[result] = Delegate.CreateDelegate(handlerType, methodInfo);
					num++;
				}
			}
			if (num > 0)
			{
				Log.LogInfo((object)$"Registered {num} Randy Orton RPC handlers.");
			}
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Failed to register Randy Orton RPC handlers: " + ex));
		}
	}
}