Program.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using BepInEx.Common;
  2. using Mono.Cecil;
  3. using Mono.Cecil.Cil;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. namespace BepInEx.Patcher
  11. {
  12. class Program
  13. {
  14. static void Error(string message)
  15. {
  16. Console.WriteLine($"Error: {message}");
  17. Console.WriteLine("Press any key to continue...");
  18. Console.ReadKey();
  19. Environment.Exit(1);
  20. }
  21. static void Main(string[] args)
  22. {
  23. string unityOutputDLL = Path.GetFullPath(@"KoikatuTrial_Data\Managed\UnityEngine.dll");
  24. if (!File.Exists(unityOutputDLL))
  25. Error("\"UnityEngine.dll\" not found.");
  26. string unityOriginalDLL = Path.GetFullPath(@"KoikatuTrial_Data\Managed\UnityEngine.dll.bak");
  27. if (!File.Exists(unityOriginalDLL))
  28. File.Copy(unityOutputDLL, unityOriginalDLL);
  29. string injectedDLL = Path.GetFullPath(@"KoikatuTrial_Data\Managed\BepInEx.dll");
  30. if (!File.Exists(unityOutputDLL))
  31. Error("\"BepInEx.dll\" not found.");
  32. string referenceDir = Path.GetFullPath(@"KoikatuTrial_Data\Managed");
  33. var defaultResolver = new DefaultAssemblyResolver();
  34. defaultResolver.AddSearchDirectory(referenceDir);
  35. AssemblyDefinition unity = AssemblyDefinition.ReadAssembly(unityOriginalDLL, new ReaderParameters
  36. {
  37. AssemblyResolver = defaultResolver
  38. });
  39. AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(injectedDLL, new ReaderParameters
  40. {
  41. AssemblyResolver = defaultResolver
  42. });
  43. InjectAssembly(unity, injected);
  44. unity.Write(unityOutputDLL);
  45. }
  46. static void InjectAssembly(AssemblyDefinition unity, AssemblyDefinition injected)
  47. {
  48. //Entry point
  49. var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods.First(x => x.Name == "Initialize");
  50. var injectMethod = unity.MainModule.Import(originalInjectMethod);
  51. var sceneManager = unity.MainModule.Types.First(x => x.Name == "SceneManager");
  52. ILProcessor IL;
  53. foreach (var loadScene in sceneManager.Methods.Where(x => x.Name == "LoadScene"))
  54. {
  55. IL = loadScene.Body.GetILProcessor();
  56. IL.InsertBefore(loadScene.Body.Instructions[0], IL.Create(OpCodes.Call, injectMethod));
  57. }
  58. }
  59. }
  60. }