Chainloader.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using BepInEx.Configuration;
  2. using BepInEx.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. using UnityEngine;
  11. using UnityInjector.ConsoleUtil;
  12. using Logger = BepInEx.Logging.Logger;
  13. namespace BepInEx.Bootstrap
  14. {
  15. /// <summary>
  16. /// The manager and loader for all plugins, and the entry point for BepInEx plugin system.
  17. /// </summary>
  18. public static class Chainloader
  19. {
  20. /// <summary>
  21. /// The loaded and initialized list of plugins.
  22. /// </summary>
  23. public static List<BaseUnityPlugin> Plugins { get; private set; } = new List<BaseUnityPlugin>();
  24. /// <summary>
  25. /// The GameObject that all plugins are attached to as components.
  26. /// </summary>
  27. public static GameObject ManagerObject { get; private set; }
  28. private static bool _loaded = false;
  29. private static bool _initialized = false;
  30. /// <summary>
  31. /// Initializes BepInEx to be able to start the chainloader.
  32. /// </summary>
  33. public static void Initialize(string containerExePath, bool startConsole = true)
  34. {
  35. if (_initialized)
  36. return;
  37. //Set vitals
  38. Paths.SetExecutablePath(containerExePath);
  39. Paths.SetPluginPath(ConfigPluginsDirectory.Value);
  40. //Start logging
  41. if (ConsoleWindow.ConfigConsoleEnabled.Value && startConsole)
  42. {
  43. ConsoleWindow.Attach();
  44. Logger.Listeners.Add(new ConsoleLogListener());
  45. }
  46. //Fix for standard output getting overwritten by UnityLogger
  47. if (ConsoleWindow.StandardOut != null)
  48. {
  49. Console.SetOut(ConsoleWindow.StandardOut);
  50. var encoding = ConsoleWindow.ConfigConsoleShiftJis.Value ? 932 : (uint)Encoding.UTF8.CodePage;
  51. ConsoleEncoding.ConsoleCodePage = encoding;
  52. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  53. }
  54. Logger.Listeners.Add(new UnityLogListener());
  55. Logger.Listeners.Add(new DiskLogListener());
  56. if (!TraceLogSource.IsListening)
  57. Logger.Sources.Add(TraceLogSource.CreateSource());
  58. if (ConfigUnityLogging.Value)
  59. Logger.Sources.Add(new UnityLogSource());
  60. Logger.LogMessage("Chainloader ready");
  61. _initialized = true;
  62. }
  63. /// <summary>
  64. /// The entrypoint for the BepInEx plugin system.
  65. /// </summary>
  66. public static void Start()
  67. {
  68. if (_loaded)
  69. return;
  70. if (!_initialized)
  71. throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
  72. if (!Directory.Exists(Paths.PluginPath))
  73. Directory.CreateDirectory(Paths.PluginPath);
  74. if (!Directory.Exists(Paths.PatcherPluginPath))
  75. Directory.CreateDirectory(Paths.PatcherPluginPath);
  76. try
  77. {
  78. var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);
  79. if (productNameProp != null)
  80. ConsoleWindow.Title =
  81. $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {productNameProp.GetValue(null, null)}";
  82. Logger.LogMessage("Chainloader started");
  83. ManagerObject = new GameObject("BepInEx_Manager");
  84. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  85. string currentProcess = Process.GetCurrentProcess().ProcessName.ToLower();
  86. var globalPluginTypes = TypeLoader.LoadTypes<BaseUnityPlugin>(Paths.PluginPath).ToList();
  87. var selectedPluginTypes = globalPluginTypes
  88. .Where(plugin =>
  89. {
  90. //Ensure metadata exists
  91. var metadata = MetadataHelper.GetMetadata(plugin);
  92. if (metadata == null)
  93. {
  94. Logger.LogWarning($"Skipping over type [{plugin.Name}] as no metadata attribute is specified");
  95. return false;
  96. }
  97. //Perform a filter for currently running process
  98. var filters = MetadataHelper.GetAttributes<BepInProcess>(plugin);
  99. if (filters.Length == 0) //no filters means it loads everywhere
  100. return true;
  101. var result = filters.Any(x => x.ProcessName.ToLower().Replace(".exe", "") == currentProcess);
  102. if (!result)
  103. Logger.LogInfo($"Skipping over plugin [{metadata.GUID}] due to process filter");
  104. return result;
  105. })
  106. .ToList();
  107. Logger.LogInfo($"{selectedPluginTypes.Count} / {globalPluginTypes.Count} plugins to load");
  108. var dependencyDict = new Dictionary<string, IEnumerable<string>>();
  109. var pluginsByGUID = new Dictionary<string, Type>();
  110. foreach (Type t in selectedPluginTypes)
  111. {
  112. var dependencies = MetadataHelper.GetDependencies(t, selectedPluginTypes);
  113. var metadata = MetadataHelper.GetMetadata(t);
  114. if (metadata.GUID == null)
  115. {
  116. Logger.LogWarning($"Skipping [{metadata.Name}] because it does not have a valid GUID.");
  117. continue;
  118. }
  119. if (dependencyDict.ContainsKey(metadata.GUID))
  120. {
  121. Logger.LogWarning($"Skipping [{metadata.Name}] because its GUID ({metadata.GUID}) is already used by another plugin.");
  122. continue;
  123. }
  124. dependencyDict[metadata.GUID] = dependencies.Select(d => d.DependencyGUID);
  125. pluginsByGUID[metadata.GUID] = t;
  126. }
  127. var emptyDependencies = new string[0];
  128. // Sort plugins by their dependencies.
  129. // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
  130. var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();
  131. var invalidPlugins = new HashSet<string>();
  132. var processedPlugins = new HashSet<string>();
  133. foreach (var pluginGUID in sortedPlugins)
  134. {
  135. // If the plugin is missing, don't process it
  136. if (!pluginsByGUID.TryGetValue(pluginGUID, out var pluginType))
  137. continue;
  138. var metadata = MetadataHelper.GetMetadata(pluginType);
  139. var dependencies = MetadataHelper.GetDependencies(pluginType, selectedPluginTypes);
  140. var dependsOnInvalidPlugin = false;
  141. var missingDependencies = new List<string>();
  142. foreach (var dependency in dependencies)
  143. {
  144. // If the depenency wasn't already processed, it's missing altogether
  145. if (!processedPlugins.Contains(dependency.DependencyGUID))
  146. {
  147. // If the dependency is hard, collect it into a list to show
  148. if ((dependency.Flags & BepInDependency.DependencyFlags.HardDependency) != 0)
  149. missingDependencies.Add(dependency.DependencyGUID);
  150. continue;
  151. }
  152. // If the dependency is invalid (e.g. has missing depedencies), report that to the user
  153. if (invalidPlugins.Contains(dependency.DependencyGUID))
  154. {
  155. dependsOnInvalidPlugin = true;
  156. break;
  157. }
  158. }
  159. processedPlugins.Add(pluginGUID);
  160. if (dependsOnInvalidPlugin)
  161. {
  162. Logger.LogWarning($"Skipping [{metadata.Name}] because it has a dependency that was not loaded. See above errors for details.");
  163. continue;
  164. }
  165. if (missingDependencies.Count != 0)
  166. {
  167. Logger.LogError($@"Missing the following dependencies for [{metadata.Name}]: {"\r\n"}{
  168. string.Join("\r\n", missingDependencies.Select(s => $"- {s}").ToArray())
  169. }{"\r\n"}Loading will be skipped; expect further errors and unstabilities.");
  170. invalidPlugins.Add(pluginGUID);
  171. continue;
  172. }
  173. try
  174. {
  175. Logger.LogInfo($"Loading [{metadata.Name} {metadata.Version}]");
  176. Plugins.Add((BaseUnityPlugin)ManagerObject.AddComponent(pluginType));
  177. }
  178. catch (Exception ex)
  179. {
  180. invalidPlugins.Add(pluginGUID);
  181. Logger.LogError($"Error loading [{metadata.Name}] : {ex.Message}");
  182. Logger.LogDebug(ex);
  183. }
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. ConsoleWindow.Attach();
  189. Console.WriteLine("Error occurred starting the game");
  190. Console.WriteLine(ex.ToString());
  191. }
  192. Logger.LogMessage("Chainloader startup complete");
  193. _loaded = true;
  194. }
  195. #region Config
  196. private static readonly ConfigWrapper<string> ConfigPluginsDirectory = ConfigFile.CoreConfig.Wrap(
  197. "Paths",
  198. "PluginsDirectory",
  199. "The relative directory to the BepInEx folder where plugins are loaded.",
  200. "plugins");
  201. private static readonly ConfigWrapper<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Wrap(
  202. "Logging",
  203. "UnityLogListening",
  204. "Enables showing unity log messages in the BepInEx logging system.",
  205. true);
  206. #endregion
  207. }
  208. }