Decompiled source of ReppoCompat v1.0.0

patchers/ReppoCompat.dll

Decompiled 31 minutes ago
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx.Logging;
using HarmonyLib;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ReppoCompat;

public static class Patcher
{
	private class Shim
	{
		public string Type;

		public string Method;

		public string[] OldParams;

		public Dictionary<string, object> Fill = new Dictionary<string, object>();
	}

	private const string B = "System.Boolean";

	private const string F = "System.Single";

	private const string I = "System.Int32";

	private const string S = "System.String";

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

	internal static readonly HashSet<string> ShimmedNames = new HashSet<string>();

	public static IEnumerable<string> TargetDLLs => new string[1] { "Assembly-CSharp.dll" };

	public static void Finish()
	{
		try
		{
			NameLookupFix.Install(ShimmedNames);
			Log.LogInfo((object)"Name-only Harmony lookups of the restored methods resolve to the game's own method.");
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Could not install the lookup fix: " + ex.Message));
		}
	}

	private static Shim Make(string type, string method, params string[] oldParams)
	{
		Shim shim = new Shim();
		shim.Type = type;
		shim.Method = method;
		shim.OldParams = oldParams;
		return shim;
	}

	public static void Patch(AssemblyDefinition assembly)
	{
		ModuleDefinition mainModule = assembly.MainModule;
		List<Shim> list = new List<Shim>();
		list.Add(Make("Sound", "PlayLoop", "System.Boolean", "System.Single", "System.Single", "System.Single"));
		list.Add(Make("PlayerHealth", "Hurt", "System.Int32", "System.Boolean", "System.Int32"));
		list.Add(Make("ChatManager", "PossessChat", "ChatManager/PossessChatID", "System.String", "System.Single", "UnityEngine.Color", "System.Single", "System.Boolean", "System.Int32", "UnityEngine.Events.UnityEvent"));
		list.Add(Make("ParticleScriptExplosion", "Spawn", "UnityEngine.Vector3", "System.Single", "System.Int32", "System.Int32", "System.Single", "System.Boolean", "System.Boolean", "System.Single"));
		list.Add(Make("PhysGrabObjectImpactDetector", "DestroyObject", "System.Boolean"));
		list.Add(Make("PlayerController", "OverrideSpeed", "System.Single", "System.Single"));
		list.Add(Make("PostProcessing", "ContrastOverride", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GameObject"));
		list.Add(Make("PostProcessing", "SaturationOverride", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GameObject"));
		string[] array = new string[9] { "UpgradeMapPlayerCount", "UpgradePlayerEnergy", "UpgradePlayerExtraJump", "UpgradePlayerGrabRange", "UpgradePlayerGrabStrength", "UpgradePlayerHealth", "UpgradePlayerSprintSpeed", "UpgradePlayerThrowStrength", "UpgradePlayerTumbleLaunch" };
		foreach (string method in array)
		{
			list.Add(Make("PunManager", method, "System.String"));
		}
		Shim shim = Make("PhysGrabber", "ReleaseObjectRPC", "System.Boolean", "System.Single");
		shim.Fill["_releaseObjectViewID"] = -1;
		list.Add(shim);
		int num = 0;
		foreach (Shim item in list)
		{
			try
			{
				if (AddShim(mainModule, item))
				{
					num++;
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)(item.Type + "." + item.Method + ": " + ex.Message));
			}
		}
		Log.LogInfo((object)("Compatibility overloads added: " + num + "/" + list.Count));
	}

	private static bool SameStart(MethodDefinition m, string[] types, bool exactCount)
	{
		if (exactCount && ((MethodReference)m).Parameters.Count != types.Length)
		{
			return false;
		}
		if (((MethodReference)m).Parameters.Count < types.Length)
		{
			return false;
		}
		for (int i = 0; i < types.Length; i++)
		{
			if (((MemberReference)((ParameterReference)((MethodReference)m).Parameters[i]).ParameterType).FullName != types[i])
			{
				return false;
			}
		}
		return true;
	}

	private static bool AddShim(ModuleDefinition module, Shim shim)
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0131: 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)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Expected O, but got Unknown
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0141: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_018c: Expected O, but got Unknown
		//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01db: Unknown result type (might be due to invalid IL or missing references)
		//IL_027f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0278: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: 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_02c5: Expected O, but got Unknown
		TypeDefinition type = module.GetType(shim.Type);
		if (type == null)
		{
			Log.LogWarning((object)("Type not found: " + shim.Type));
			return false;
		}
		MethodDefinition val = null;
		Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				MethodDefinition current = enumerator.Current;
				if (((MemberReference)current).Name != shim.Method)
				{
					continue;
				}
				if (SameStart(current, shim.OldParams, exactCount: true))
				{
					return false;
				}
				if (val != null || !SameStart(current, shim.OldParams, exactCount: false))
				{
					continue;
				}
				bool flag = true;
				for (int i = shim.OldParams.Length; i < ((MethodReference)current).Parameters.Count; i++)
				{
					ParameterDefinition val2 = ((MethodReference)current).Parameters[i];
					if (!val2.HasConstant && !val2.IsOptional && !shim.Fill.ContainsKey(((ParameterReference)val2).Name))
					{
						flag = false;
					}
				}
				if (flag)
				{
					val = current;
				}
			}
		}
		finally
		{
			((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
		}
		if (val == null)
		{
			Log.LogWarning((object)("No compatible target for " + shim.Type + "." + shim.Method));
			return false;
		}
		MethodAttributes val3 = (MethodAttributes)134;
		if (val.IsStatic)
		{
			val3 = (MethodAttributes)(ushort)(val3 | 0x10);
		}
		MethodDefinition val4 = new MethodDefinition(((MemberReference)val).Name, val3, ((MethodReference)val).ReturnType);
		for (int j = 0; j < shim.OldParams.Length; j++)
		{
			ParameterDefinition val5 = ((MethodReference)val).Parameters[j];
			((MethodReference)val4).Parameters.Add(new ParameterDefinition(((ParameterReference)val5).Name, (ParameterAttributes)0, ((ParameterReference)val5).ParameterType));
		}
		ILProcessor iLProcessor = val4.Body.GetILProcessor();
		if (!val.IsStatic)
		{
			iLProcessor.Emit(OpCodes.Ldarg_0);
		}
		Enumerator<ParameterDefinition> enumerator2 = ((MethodReference)val4).Parameters.GetEnumerator();
		try
		{
			while (enumerator2.MoveNext())
			{
				ParameterDefinition current2 = enumerator2.Current;
				iLProcessor.Emit(OpCodes.Ldarg, current2);
			}
		}
		finally
		{
			((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
		}
		for (int k = shim.OldParams.Length; k < ((MethodReference)val).Parameters.Count; k++)
		{
			ParameterDefinition val6 = ((MethodReference)val).Parameters[k];
			if (!shim.Fill.TryGetValue(((ParameterReference)val6).Name, out var value))
			{
				value = (val6.HasConstant ? val6.Constant : null);
			}
			EmitDefault(module, val4, iLProcessor, ((ParameterReference)val6).ParameterType, value);
		}
		iLProcessor.Emit(val.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, (MethodReference)(object)val);
		iLProcessor.Emit(OpCodes.Ret);
		MethodReference val7 = module.ImportReference((MethodBase)typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes));
		val4.CustomAttributes.Add(new CustomAttribute(val7));
		type.Methods.Add(val4);
		ShimmedNames.Add(shim.Type + "." + shim.Method);
		Log.LogDebug((object)("Added " + shim.Type + "." + shim.Method + "(" + string.Join(", ", shim.OldParams) + ")"));
		return true;
	}

	private static void EmitDefault(ModuleDefinition module, MethodDefinition method, ILProcessor il, TypeReference type, object value)
	{
		//IL_0204: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0188: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Unknown result type (might be due to invalid IL or missing references)
		//IL_023f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0245: Expected O, but got Unknown
		//IL_0263: Unknown result type (might be due to invalid IL or missing references)
		//IL_026f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0281: Unknown result type (might be due to invalid IL or missing references)
		switch (((MemberReference)type).FullName)
		{
		case "System.Boolean":
			il.Emit(OpCodes.Ldc_I4, (value != null && Convert.ToBoolean(value)) ? 1 : 0);
			return;
		case "System.Int32":
		case "System.Int16":
		case "System.SByte":
		case "System.Byte":
		case "System.UInt16":
		case "System.Char":
			il.Emit(OpCodes.Ldc_I4, (value != null) ? Convert.ToInt32(value) : 0);
			return;
		case "System.UInt32":
			il.Emit(OpCodes.Ldc_I4, (int)((value != null) ? Convert.ToUInt32(value) : 0));
			return;
		case "System.Int64":
		case "System.UInt64":
			il.Emit(OpCodes.Ldc_I8, (value == null) ? 0 : Convert.ToInt64(value));
			return;
		case "System.Single":
			il.Emit(OpCodes.Ldc_R4, (value == null) ? 0f : Convert.ToSingle(value));
			return;
		case "System.Double":
			il.Emit(OpCodes.Ldc_R8, (value == null) ? 0.0 : Convert.ToDouble(value));
			return;
		case "System.String":
			if (value == null)
			{
				il.Emit(OpCodes.Ldnull);
			}
			else
			{
				il.Emit(OpCodes.Ldstr, (string)value);
			}
			return;
		}
		TypeDefinition val = null;
		try
		{
			val = type.Resolve();
		}
		catch (Exception)
		{
		}
		if (val != null && val.IsEnum)
		{
			il.Emit(OpCodes.Ldc_I4, (value != null) ? Convert.ToInt32(value) : 0);
		}
		else if (type.IsValueType || (val != null && ((TypeReference)val).IsValueType))
		{
			VariableDefinition val2 = new VariableDefinition(module.ImportReference(type));
			method.Body.Variables.Add(val2);
			method.Body.InitLocals = true;
			il.Emit(OpCodes.Ldloca, val2);
			il.Emit(OpCodes.Initobj, module.ImportReference(type));
			il.Emit(OpCodes.Ldloc, val2);
		}
		else
		{
			il.Emit(OpCodes.Ldnull);
		}
	}
}
public static class NameLookupFix
{
	private const BindingFlags All = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

	private static HashSet<string> names = new HashSet<string>();

	public static void Install(IEnumerable<string> shimmedNames)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Expected O, but got Unknown
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Expected O, but got Unknown
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Expected O, but got Unknown
		names = new HashSet<string>(shimmedNames);
		if (names.Count != 0)
		{
			Harmony val = new Harmony("local.reppo.compat.lookupfix");
			Type[] types = new Type[4]
			{
				typeof(Type),
				typeof(string),
				typeof(Type[]),
				typeof(Type[])
			};
			MethodInfo method = typeof(AccessTools).GetMethod("DeclaredMethod", BindingFlags.Static | BindingFlags.Public, null, types, null);
			MethodInfo method2 = typeof(AccessTools).GetMethod("Method", BindingFlags.Static | BindingFlags.Public, null, types, null);
			HarmonyMethod val2 = new HarmonyMethod(typeof(NameLookupFix).GetMethod("DeclaredPrefix", BindingFlags.Static | BindingFlags.Public));
			HarmonyMethod val3 = new HarmonyMethod(typeof(NameLookupFix).GetMethod("MethodPrefix", BindingFlags.Static | BindingFlags.Public));
			if (method != null)
			{
				val.Patch((MethodBase)method, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (method2 != null)
			{
				val.Patch((MethodBase)method2, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}
	}

	public static bool DeclaredPrefix(Type type, string name, Type[] parameters, Type[] generics, ref MethodInfo __result)
	{
		MethodInfo methodInfo = Pick(type, name, parameters, generics, declaredOnly: true);
		if (methodInfo == null)
		{
			return true;
		}
		__result = methodInfo;
		return false;
	}

	public static bool MethodPrefix(Type type, string name, Type[] parameters, Type[] generics, ref MethodInfo __result)
	{
		MethodInfo methodInfo = Pick(type, name, parameters, generics, declaredOnly: false);
		if (methodInfo == null)
		{
			return true;
		}
		__result = methodInfo;
		return false;
	}

	public static MethodInfo Pick(Type type, string name, Type[] parameters, Type[] generics, bool declaredOnly)
	{
		if (parameters != null || generics != null || type == null || name == null)
		{
			return null;
		}
		Type type2 = type;
		while (type2 != null)
		{
			if (names.Contains(type2.FullName + "." + name))
			{
				MethodInfo methodInfo = null;
				MethodInfo[] methods = type2.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo2 in methods)
				{
					if (!(methodInfo2.Name != name) && !methodInfo2.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false))
					{
						if (methodInfo != null)
						{
							return null;
						}
						methodInfo = methodInfo2;
					}
				}
				return methodInfo;
			}
			type2 = (declaredOnly ? null : type2.BaseType);
		}
		return null;
	}
}