Chainloader.cs 5.7 KB

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