Decompiled source of Diversity v81 Patch v81.0.1

BepInEx/patchers/DiversityV81Patch/DiversityV81Patch.dll

Decompiled 3 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DiversityV81Patch")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("81.0.0.0")]
[assembly: AssemblyInformationalVersion("81.0.0+1535ec287db3066d0c920f497c3c45667137b2d9")]
[assembly: AssemblyProduct("DiversityV81Patch")]
[assembly: AssemblyTitle("DiversityV81Patch")]
[assembly: AssemblyVersion("81.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 DiversityV81Patch
{
	public static class Patcher
	{
		internal static readonly ManualLogSource Log = Logger.CreateLogSource("Diversity v81 Patch");

		internal static string OriginalFolder;

		[ThreadStatic]
		private static bool busy;

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

		private static string CacheDir => Path.Combine(Paths.CachePath, "DiversityV81Patch");

		public static void Patch(AssemblyDefinition _)
		{
		}

		public static void Initialize()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			Harmony val = new Harmony("nine78.diversityv81patch");
			MethodInfo method = typeof(Assembly).GetMethod("LoadFile", new Type[1] { typeof(string) });
			MethodInfo method2 = typeof(Assembly).GetMethod("LoadFrom", new Type[1] { typeof(string) });
			val.Patch((MethodBase)method, new HarmonyMethod(typeof(Patcher), "Redirect", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)method2, new HarmonyMethod(typeof(Patcher), "Redirect", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Log.LogInfo((object)"Ready: will fix Diversity 3.1.0 for v81 when it loads.");
		}

		private static void Redirect(ref string __0)
		{
			if (busy || string.IsNullOrEmpty(__0))
			{
				return;
			}
			string fileName = Path.GetFileName(__0);
			try
			{
				busy = true;
				if (fileName.Equals("Diversity Remastered.dll", StringComparison.OrdinalIgnoreCase) && !__0.StartsWith(CacheDir, StringComparison.OrdinalIgnoreCase))
				{
					OriginalFolder = Path.GetDirectoryName(Path.GetFullPath(__0));
					__0 = PatchedCopy(__0);
				}
				else
				{
					if (!fileName.Equals("DiversityDungeonGen.dll", StringComparison.OrdinalIgnoreCase) || File.Exists(__0) || OriginalFolder == null)
					{
						return;
					}
					string[] array = new string[2]
					{
						OriginalFolder,
						Path.GetDirectoryName(OriginalFolder)
					};
					foreach (string text in array)
					{
						string text2 = Path.Combine(text, "DiversityDungeonGen.dll");
						if (File.Exists(text2))
						{
							__0 = text2;
							Log.LogInfo((object)("Found DiversityDungeonGen.dll for Diversity: " + Path.GetFileName(text)));
							break;
						}
					}
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Couldn't fix Diversity, loading it as it is: " + ex));
			}
			finally
			{
				busy = false;
			}
		}

		private static string PatchedCopy(string original)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Expected O, but got Unknown
			byte[] buffer = File.ReadAllBytes(original);
			string text;
			using (SHA256 sHA = SHA256.Create())
			{
				text = BitConverter.ToString(sHA.ComputeHash(buffer)).Replace("-", "").Substring(0, 16);
			}
			Directory.CreateDirectory(CacheDir);
			string text2 = Path.Combine(CacheDir, text, "Diversity Remastered.dll");
			if (File.Exists(text2))
			{
				Log.LogInfo((object)"Loading the fixed copy from cache.");
				return text2;
			}
			Directory.CreateDirectory(Path.GetDirectoryName(text2));
			DefaultAssemblyResolver val = new DefaultAssemblyResolver();
			((BaseAssemblyResolver)val).AddSearchDirectory(Paths.ManagedPath);
			((BaseAssemblyResolver)val).AddSearchDirectory(Paths.BepInExAssemblyDirectory);
			((BaseAssemblyResolver)val).AddSearchDirectory(Path.GetDirectoryName(original));
			((BaseAssemblyResolver)val).AddSearchDirectory(Path.GetDirectoryName(Path.GetDirectoryName(original)));
			string[] directories = Directory.GetDirectories(Paths.PluginPath, "*", SearchOption.AllDirectories);
			foreach (string text3 in directories)
			{
				((BaseAssemblyResolver)val).AddSearchDirectory(text3);
			}
			using MemoryStream memoryStream = new MemoryStream(buffer);
			AssemblyDefinition val2 = AssemblyDefinition.ReadAssembly((Stream)memoryStream, new ReaderParameters
			{
				AssemblyResolver = (IAssemblyResolver)(object)val
			});
			try
			{
				int num = Fixes.Apply(val2.MainModule, (IAssemblyResolver)(object)val, Log);
				val2.Write(text2);
				Log.LogInfo((object)$"Fixed Diversity for v81 ({num} changes); cached as {text}.");
				return text2;
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}
	}
	public static class Fixes
	{
		public static int Apply(ModuleDefinition mod, IAssemblyResolver resolver, ManualLogSource log)
		{
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			AssemblyNameReference val = ((IEnumerable<AssemblyNameReference>)mod.AssemblyReferences).First((AssemblyNameReference a) => a.Name == "Assembly-CSharp");
			ModuleDefinition mainModule = resolver.Resolve(val).MainModule;
			TypeDefinition type = mainModule.GetType("GameNetcodeStuff.PlayerControllerB");
			TypeDefinition type2 = mainModule.GetType("SpawnableEnemyWithRarity");
			MethodReference operand = mod.ImportReference((MethodReference)(object)((IEnumerable<MethodDefinition>)type2.Methods).First((MethodDefinition m) => m.IsConstructor && ((MethodReference)m).Parameters.Count == 2));
			MethodReference operand2 = mod.ImportReference((MethodReference)(object)((IEnumerable<MethodDefinition>)type.Methods).First((MethodDefinition m) => ((MemberReference)m).Name == "DropAllHeldItemsAndSyncNonexact"));
			MethodReference operand3 = mod.ImportReference((MethodReference)(object)((IEnumerable<MethodDefinition>)type.Methods).First((MethodDefinition m) => ((MemberReference)m).Name == "KillPlayer" && ((MethodReference)m).Parameters.Count == 6));
			MethodReference operand4 = mod.ImportReference((MethodReference)(object)((IEnumerable<MethodDefinition>)type.Methods).First((MethodDefinition m) => ((MemberReference)m).Name == "HasLineOfSightToPosition" && ((MethodReference)m).Parameters.Count == 5));
			int num = 0;
			foreach (TypeDefinition type3 in mod.GetTypes())
			{
				foreach (MethodDefinition item in ((IEnumerable<MethodDefinition>)type3.Methods).Where((MethodDefinition x) => x.HasBody))
				{
					ILProcessor iLProcessor = item.Body.GetILProcessor();
					foreach (Instruction item2 in ((IEnumerable<Instruction>)item.Body.Instructions).ToList())
					{
						if (item2.OpCode == OpCodes.Newobj)
						{
							object operand5 = item2.Operand;
							MethodReference val2 = (MethodReference)((operand5 is MethodReference) ? operand5 : null);
							if (val2 != null && ((MemberReference)((MemberReference)val2).DeclaringType).FullName == "SpawnableEnemyWithRarity" && val2.Parameters.Count == 0)
							{
								iLProcessor.InsertBefore(item2, iLProcessor.Create(OpCodes.Ldnull));
								iLProcessor.InsertBefore(item2, iLProcessor.Create(OpCodes.Ldc_I4_0));
								item2.Operand = operand;
								num++;
								continue;
							}
						}
						if (!(item2.OpCode == OpCodes.Call) && !(item2.OpCode == OpCodes.Callvirt))
						{
							continue;
						}
						object operand6 = item2.Operand;
						MethodReference val3 = (MethodReference)((operand6 is MethodReference) ? operand6 : null);
						if (val3 != null && ((MemberReference)((MemberReference)val3).DeclaringType).Name == "PlayerControllerB")
						{
							if (((MemberReference)val3).Name == "DropAllHeldItemsServerRpc")
							{
								item2.Operand = operand2;
								num++;
							}
							else if (((MemberReference)val3).Name == "KillPlayer" && val3.Parameters.Count == 5)
							{
								iLProcessor.InsertBefore(item2, iLProcessor.Create(OpCodes.Ldc_I4_0));
								item2.Operand = operand3;
								num++;
							}
							else if (((MemberReference)val3).Name == "HasLineOfSightToPosition" && val3.Parameters.Count == 4)
							{
								iLProcessor.InsertBefore(item2, iLProcessor.Create(OpCodes.Ldc_I4_M1));
								item2.Operand = operand4;
								num++;
							}
						}
					}
				}
			}
			return num;
		}
	}
}