Chainloader.cs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using BepInEx.Logging;
  9. using UnityEngine;
  10. using UnityInjector.ConsoleUtil;
  11. using UnityLogWriter = BepInEx.Logging.UnityLogWriter;
  12. namespace BepInEx.Bootstrap
  13. {
  14. /// <summary>
  15. /// The manager and loader for all plugins, and the entry point for BepInEx plugin system.
  16. /// </summary>
  17. public class Chainloader
  18. {
  19. /// <summary>
  20. /// The loaded and initialized list of plugins.
  21. /// </summary>
  22. public static List<BaseUnityPlugin> Plugins { get; protected set; } = new List<BaseUnityPlugin>();
  23. /// <summary>
  24. /// The GameObject that all plugins are attached to as components.
  25. /// </summary>
  26. public static GameObject ManagerObject { get; protected set; } = new GameObject("BepInEx_Manager");
  27. private static bool _loaded = false;
  28. private static bool _initialized = false;
  29. /// <summary>
  30. /// Initializes BepInEx to be able to start the chainloader.
  31. /// </summary>
  32. public static void Initialize(string containerExePath, bool startConsole = true)
  33. {
  34. if (_initialized)
  35. return;
  36. //Set vitals
  37. Paths.SetExecutablePath(containerExePath);
  38. Paths.SetPluginPath(Config.GetEntry("chainloader-plugins-directory", "plugins", "BepInEx"));
  39. //Start logging
  40. if (startConsole)
  41. {
  42. ConsoleWindow.Attach();
  43. ConsoleEncoding.ConsoleCodePage = (uint)Encoding.UTF8.CodePage;
  44. Console.OutputEncoding = Encoding.UTF8;
  45. }
  46. UnityLogWriter unityLogWriter = new UnityLogWriter();
  47. if (Preloader.PreloaderLog != null)
  48. unityLogWriter.WriteToLog($"{Preloader.PreloaderLog}\r\n");
  49. Logger.SetLogger(unityLogWriter);
  50. _initialized = true;
  51. }
  52. /// <summary>
  53. /// The entrypoint for the BepInEx plugin system.
  54. /// </summary>
  55. public static void Start()
  56. {
  57. if (_loaded)
  58. return;
  59. if (!_initialized)
  60. throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
  61. if (!Directory.Exists(Paths.PluginPath))
  62. Directory.CreateDirectory(Paths.PluginPath);
  63. if (!Directory.Exists(Paths.PatcherPluginPath))
  64. Directory.CreateDirectory(Paths.PatcherPluginPath);
  65. try
  66. {
  67. if (bool.Parse(Config.GetEntry("chainloader-log-unity-messages", "false", "BepInEx")))
  68. UnityLogWriter.ListenUnityLogs();
  69. var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);
  70. if (productNameProp != null)
  71. ConsoleWindow.Title =
  72. $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {productNameProp.GetValue(null, null)}";
  73. Logger.Log(LogLevel.Message, "Chainloader started");
  74. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  75. string currentProcess = Process.GetCurrentProcess().ProcessName.ToLower();
  76. var pluginTypes = TypeLoader.LoadTypes<BaseUnityPlugin>(Paths.PluginPath)
  77. .Where(plugin =>
  78. {
  79. //Perform a filter for currently running process
  80. var filters = MetadataHelper.GetAttributes<BepInProcess>(plugin);
  81. if (!filters.Any())
  82. return true;
  83. return filters.Any(x => x.ProcessName.ToLower().Replace(".exe", "") == currentProcess);
  84. })
  85. .ToList();
  86. Logger.Log(LogLevel.Info, $"{pluginTypes.Count} plugins selected");
  87. Dictionary<Type, IEnumerable<Type>> dependencyDict = new Dictionary<Type, IEnumerable<Type>>();
  88. foreach (Type t in pluginTypes)
  89. {
  90. try
  91. {
  92. IEnumerable<Type> dependencies = MetadataHelper.GetDependencies(t, pluginTypes);
  93. dependencyDict[t] = dependencies;
  94. }
  95. catch (MissingDependencyException)
  96. {
  97. var metadata = MetadataHelper.GetMetadata(t);
  98. Logger.Log(LogLevel.Info, $"Cannot load [{metadata.Name}] due to missing dependencies.");
  99. }
  100. }
  101. pluginTypes = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict[x]).ToList();
  102. foreach (Type t in pluginTypes)
  103. {
  104. try
  105. {
  106. var metadata = MetadataHelper.GetMetadata(t);
  107. var plugin = (BaseUnityPlugin) ManagerObject.AddComponent(t);
  108. Plugins.Add(plugin);
  109. Logger.Log(LogLevel.Info, $"Loaded [{metadata.Name} {metadata.Version}]");
  110. }
  111. catch (Exception ex)
  112. {
  113. Logger.Log(LogLevel.Info, $"Error loading [{t.Name}] : {ex.Message}");
  114. }
  115. }
  116. }
  117. catch (Exception ex)
  118. {
  119. ConsoleWindow.Attach();
  120. Console.WriteLine("Error occurred starting the game");
  121. Console.WriteLine(ex.ToString());
  122. }
  123. _loaded = true;
  124. }
  125. }
  126. }