Chainloader.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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.Configuration;
  9. using BepInEx.Logging;
  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 (startConsole)
  42. {
  43. ConsoleWindow.Attach();
  44. ConsoleEncoding.ConsoleCodePage = (uint)Encoding.UTF8.CodePage;
  45. Console.OutputEncoding = Encoding.UTF8;
  46. Logger.Listeners.Add(new ConsoleLogListener());
  47. }
  48. //Fix for standard output getting overwritten by UnityLogger
  49. if (ConsoleWindow.StandardOut != null)
  50. Console.SetOut(ConsoleWindow.StandardOut);
  51. Logger.Listeners.Add(new UnityLogListener());
  52. if (!TraceLogSource.IsListening)
  53. Logger.Sources.Add(TraceLogSource.CreateSource());
  54. if (ConfigUnityLogging.Value)
  55. Logger.Sources.Add(new UnityLogSource());
  56. Logger.LogMessage("Chainloader ready");
  57. _initialized = true;
  58. }
  59. /// <summary>
  60. /// The entrypoint for the BepInEx plugin system.
  61. /// </summary>
  62. public static void Start()
  63. {
  64. if (_loaded)
  65. return;
  66. if (!_initialized)
  67. throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
  68. if (!Directory.Exists(Paths.PluginPath))
  69. Directory.CreateDirectory(Paths.PluginPath);
  70. if (!Directory.Exists(Paths.PatcherPluginPath))
  71. Directory.CreateDirectory(Paths.PatcherPluginPath);
  72. try
  73. {
  74. var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);
  75. if (productNameProp != null)
  76. ConsoleWindow.Title =
  77. $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {productNameProp.GetValue(null, null)}";
  78. Logger.LogMessage("Chainloader started");
  79. ManagerObject = new GameObject("BepInEx_Manager");
  80. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  81. string currentProcess = Process.GetCurrentProcess().ProcessName.ToLower();
  82. var globalPluginTypes = TypeLoader.LoadTypes<BaseUnityPlugin>(Paths.PluginPath).ToList();
  83. var selectedPluginTypes = globalPluginTypes
  84. .Where(plugin =>
  85. {
  86. //Ensure metadata exists
  87. var metadata = MetadataHelper.GetMetadata(plugin);
  88. if (metadata == null)
  89. {
  90. Logger.LogWarning($"Skipping over type [{plugin.Name}] as no metadata attribute is specified");
  91. return false;
  92. }
  93. //Perform a filter for currently running process
  94. var filters = MetadataHelper.GetAttributes<BepInProcess>(plugin);
  95. if (filters.Length == 0) //no filters means it loads everywhere
  96. return true;
  97. var result = filters.Any(x => x.ProcessName.ToLower().Replace(".exe", "") == currentProcess);
  98. if (!result)
  99. Logger.LogInfo($"Skipping over plugin [{metadata.GUID}] due to process filter");
  100. return result;
  101. })
  102. .ToList();
  103. Logger.LogInfo($"{selectedPluginTypes.Count} / {globalPluginTypes.Count} plugins to load");
  104. Dictionary<Type, IEnumerable<Type>> dependencyDict = new Dictionary<Type, IEnumerable<Type>>();
  105. foreach (Type t in selectedPluginTypes)
  106. {
  107. try
  108. {
  109. IEnumerable<Type> dependencies = MetadataHelper.GetDependencies(t, selectedPluginTypes);
  110. dependencyDict[t] = dependencies;
  111. }
  112. catch (MissingDependencyException)
  113. {
  114. var metadata = MetadataHelper.GetMetadata(t);
  115. Logger.LogWarning($"Cannot load [{metadata.Name}] due to missing dependencies.");
  116. }
  117. }
  118. var sortedTypes = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict[x]).ToList();
  119. foreach (Type t in sortedTypes)
  120. {
  121. try
  122. {
  123. var metadata = MetadataHelper.GetMetadata(t);
  124. Logger.LogInfo($"Loading [{metadata.Name} {metadata.Version}]");
  125. var plugin = (BaseUnityPlugin)ManagerObject.AddComponent(t);
  126. Plugins.Add(plugin);
  127. }
  128. catch (Exception ex)
  129. {
  130. Logger.LogError($"Error loading [{t.Name}] : {ex.Message}");
  131. Logger.LogDebug(ex);
  132. }
  133. }
  134. }
  135. catch (Exception ex)
  136. {
  137. ConsoleWindow.Attach();
  138. Console.WriteLine("Error occurred starting the game");
  139. Console.WriteLine(ex.ToString());
  140. }
  141. Logger.LogMessage("Chainloader startup complete");
  142. _loaded = true;
  143. }
  144. #region Config
  145. private static readonly ConfigWrapper<string> ConfigPluginsDirectory = ConfigFile.CoreConfig.Wrap(
  146. "Paths",
  147. "PluginsDirectory",
  148. "The relative directory to the BepInEx folder where plugins are loaded.",
  149. "plugins");
  150. private static readonly ConfigWrapper<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Wrap(
  151. "Logging",
  152. "UnityLogListening",
  153. "Enables showing unity log messages in the BepInEx logging system.",
  154. true);
  155. #endregion
  156. }
  157. }