Program.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. using ARMeilleure.Translation.PTC;
  2. using Avalonia;
  3. using Avalonia.OpenGL;
  4. using Avalonia.Rendering;
  5. using Avalonia.Threading;
  6. using Ryujinx.Ava.Ui.Backend;
  7. using Ryujinx.Ava.Ui.Controls;
  8. using Ryujinx.Ava.Ui.Windows;
  9. using Ryujinx.Common;
  10. using Ryujinx.Common.Configuration;
  11. using Ryujinx.Common.GraphicsDriver;
  12. using Ryujinx.Common.Logging;
  13. using Ryujinx.Common.System;
  14. using Ryujinx.Common.SystemInfo;
  15. using Ryujinx.Graphics.Vulkan;
  16. using Ryujinx.Modules;
  17. using Ryujinx.Ui.Common;
  18. using Ryujinx.Ui.Common.Configuration;
  19. using Silk.NET.Vulkan.Extensions.EXT;
  20. using Silk.NET.Vulkan.Extensions.KHR;
  21. using System;
  22. using System.Collections.Generic;
  23. using System.IO;
  24. using System.Runtime.InteropServices;
  25. using System.Threading.Tasks;
  26. namespace Ryujinx.Ava
  27. {
  28. internal class Program
  29. {
  30. public static double WindowScaleFactor { get; set; }
  31. public static double ActualScaleFactor { get; set; }
  32. public static string Version { get; private set; }
  33. public static string ConfigurationPath { get; private set; }
  34. public static string CommandLineProfile { get; set; }
  35. public static bool PreviewerDetached { get; private set; }
  36. public static RenderTimer RenderTimer { get; private set; }
  37. public static bool UseVulkan { get; private set; }
  38. [DllImport("user32.dll", SetLastError = true)]
  39. public static extern int MessageBoxA(IntPtr hWnd, string text, string caption, uint type);
  40. private const uint MB_ICONWARNING = 0x30;
  41. private const int BaseDpi = 96;
  42. public static void Main(string[] args)
  43. {
  44. Version = ReleaseInformations.GetVersion();
  45. if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134))
  46. {
  47. MessageBoxA(IntPtr.Zero, "You are running an outdated version of Windows.\n\nStarting on June 1st 2022, Ryujinx will only support Windows 10 1803 and newer.\n", $"Ryujinx {Version}", MB_ICONWARNING);
  48. }
  49. PreviewerDetached = true;
  50. Initialize(args);
  51. RenderTimer = new RenderTimer();
  52. BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
  53. RenderTimer.Dispose();
  54. }
  55. public static AppBuilder BuildAvaloniaApp()
  56. {
  57. return AppBuilder.Configure<App>()
  58. .UsePlatformDetect()
  59. .With(new X11PlatformOptions
  60. {
  61. EnableMultiTouch = true,
  62. EnableIme = true,
  63. UseEGL = false,
  64. UseGpu = !UseVulkan,
  65. GlProfiles = new List<GlVersion>()
  66. {
  67. new GlVersion(GlProfileType.OpenGL, 4, 3)
  68. }
  69. })
  70. .With(new Win32PlatformOptions
  71. {
  72. EnableMultitouch = true,
  73. UseWgl = !UseVulkan,
  74. WglProfiles = new List<GlVersion>()
  75. {
  76. new GlVersion(GlProfileType.OpenGL, 4, 3)
  77. },
  78. AllowEglInitialization = false,
  79. CompositionBackdropCornerRadius = 8f,
  80. })
  81. .UseSkia()
  82. .With(new Ui.Vulkan.VulkanOptions()
  83. {
  84. ApplicationName = "Ryujinx.Graphics.Vulkan",
  85. MaxQueueCount = 2,
  86. PreferDiscreteGpu = true,
  87. PreferredDevice = !PreviewerDetached ? "" : ConfigurationState.Instance.Graphics.PreferredGpu.Value,
  88. UseDebug = !PreviewerDetached ? false : ConfigurationState.Instance.Logger.GraphicsDebugLevel.Value != GraphicsDebugLevel.None,
  89. })
  90. .With(new SkiaOptions()
  91. {
  92. CustomGpuFactory = UseVulkan ? SkiaGpuFactory.CreateVulkanGpu : null
  93. })
  94. .AfterSetup(_ =>
  95. {
  96. AvaloniaLocator.CurrentMutable
  97. .Bind<IRenderTimer>().ToConstant(RenderTimer)
  98. .Bind<IRenderLoop>().ToConstant(new RenderLoop(RenderTimer, Dispatcher.UIThread));
  99. })
  100. .LogToTrace();
  101. }
  102. private static void Initialize(string[] args)
  103. {
  104. // Parse Arguments.
  105. string launchPathArg = null;
  106. string baseDirPathArg = null;
  107. bool startFullscreenArg = false;
  108. for (int i = 0; i < args.Length; ++i)
  109. {
  110. string arg = args[i];
  111. if (arg == "-r" || arg == "--root-data-dir")
  112. {
  113. if (i + 1 >= args.Length)
  114. {
  115. Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");
  116. continue;
  117. }
  118. baseDirPathArg = args[++i];
  119. }
  120. else if (arg == "-p" || arg == "--profile")
  121. {
  122. if (i + 1 >= args.Length)
  123. {
  124. Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");
  125. continue;
  126. }
  127. CommandLineProfile = args[++i];
  128. }
  129. else if (arg == "-f" || arg == "--fullscreen")
  130. {
  131. startFullscreenArg = true;
  132. }
  133. else
  134. {
  135. launchPathArg = arg;
  136. }
  137. }
  138. // Delete backup files after updating.
  139. Task.Run(Updater.CleanupUpdate);
  140. Console.Title = $"Ryujinx Console {Version}";
  141. // Hook unhandled exception and process exit events.
  142. AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
  143. AppDomain.CurrentDomain.ProcessExit += (object sender, EventArgs e) => Exit();
  144. // Setup base data directory.
  145. AppDataManager.Initialize(baseDirPathArg);
  146. // Initialize the configuration.
  147. ConfigurationState.Initialize();
  148. // Initialize the logger system.
  149. LoggerModule.Initialize();
  150. // Initialize Discord integration.
  151. DiscordIntegrationModule.Initialize();
  152. ReloadConfig();
  153. UseVulkan = PreviewerDetached ? ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.Vulkan : false;
  154. if (UseVulkan)
  155. {
  156. if (VulkanRenderer.GetPhysicalDevices().Length == 0)
  157. {
  158. UseVulkan = false;
  159. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.OpenGl;
  160. Logger.Warning?.PrintMsg(LogClass.Application, "A suitable Vulkan physical device is not available. Falling back to OpenGL");
  161. }
  162. }
  163. if (UseVulkan)
  164. {
  165. // With a custom gpu backend, avalonia doesn't enable dpi awareness, so the backend must handle it. This isn't so for the opengl backed,
  166. // as that uses avalonia's gpu backend and it's enabled there.
  167. ForceDpiAware.Windows();
  168. }
  169. WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();
  170. ActualScaleFactor = ForceDpiAware.GetActualScaleFactor() / BaseDpi;
  171. // Logging system information.
  172. PrintSystemInfo();
  173. // Enable OGL multithreading on the driver, when available.
  174. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  175. DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);
  176. // Check if keys exists.
  177. bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
  178. if (!hasSystemProdKeys)
  179. {
  180. if (!(AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"))))
  181. {
  182. MainWindow.ShowKeyErrorOnLoad = true;
  183. }
  184. }
  185. if (launchPathArg != null)
  186. {
  187. MainWindow.DeferLoadApplication(launchPathArg, startFullscreenArg);
  188. }
  189. }
  190. public static void ReloadConfig()
  191. {
  192. string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
  193. string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");
  194. // Now load the configuration as the other subsystems are now registered
  195. if (File.Exists(localConfigurationPath))
  196. {
  197. ConfigurationPath = localConfigurationPath;
  198. }
  199. else if (File.Exists(appDataConfigurationPath))
  200. {
  201. ConfigurationPath = appDataConfigurationPath;
  202. }
  203. if (ConfigurationPath == null)
  204. {
  205. // No configuration, we load the default values and save it to disk
  206. ConfigurationPath = appDataConfigurationPath;
  207. ConfigurationState.Instance.LoadDefault();
  208. ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
  209. }
  210. else
  211. {
  212. if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
  213. {
  214. ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
  215. }
  216. else
  217. {
  218. ConfigurationState.Instance.LoadDefault();
  219. Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location {ConfigurationPath}");
  220. }
  221. }
  222. }
  223. private static void PrintSystemInfo()
  224. {
  225. Logger.Notice.Print(LogClass.Application, $"Ryujinx Version: {Version}");
  226. SystemInfo.Gather().Print();
  227. var enabledLogs = Logger.GetEnabledLevels();
  228. Logger.Notice.Print(LogClass.Application, $"Logs Enabled: {(enabledLogs.Count == 0 ? "<None>" : string.Join(", ", enabledLogs))}");
  229. if (AppDataManager.Mode == AppDataManager.LaunchMode.Custom)
  230. {
  231. Logger.Notice.Print(LogClass.Application, $"Launch Mode: Custom Path {AppDataManager.BaseDirPath}");
  232. }
  233. else
  234. {
  235. Logger.Notice.Print(LogClass.Application, $"Launch Mode: {AppDataManager.Mode}");
  236. }
  237. }
  238. private static void ProcessUnhandledException(Exception ex, bool isTerminating)
  239. {
  240. Ptc.Close();
  241. PtcProfiler.Stop();
  242. string message = $"Unhandled exception caught: {ex}";
  243. Logger.Error?.PrintMsg(LogClass.Application, message);
  244. if (Logger.Error == null)
  245. {
  246. Logger.Notice.PrintMsg(LogClass.Application, message);
  247. }
  248. if (isTerminating)
  249. {
  250. Exit();
  251. }
  252. }
  253. public static void Exit()
  254. {
  255. DiscordIntegrationModule.Exit();
  256. Ptc.Dispose();
  257. PtcProfiler.Dispose();
  258. Logger.Shutdown();
  259. }
  260. }
  261. }