AppHost.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. using ARMeilleure.Translation;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.ApplicationLifetimes;
  4. using Avalonia.Input;
  5. using Avalonia.Threading;
  6. using LibHac.Tools.FsSystem;
  7. using Ryujinx.Audio.Backends.Dummy;
  8. using Ryujinx.Audio.Backends.OpenAL;
  9. using Ryujinx.Audio.Backends.SDL2;
  10. using Ryujinx.Audio.Backends.SoundIo;
  11. using Ryujinx.Audio.Integration;
  12. using Ryujinx.Ava.Common;
  13. using Ryujinx.Ava.Common.Locale;
  14. using Ryujinx.Ava.Input;
  15. using Ryujinx.Ava.UI.Helpers;
  16. using Ryujinx.Ava.UI.Models;
  17. using Ryujinx.Ava.UI.Renderer;
  18. using Ryujinx.Ava.UI.ViewModels;
  19. using Ryujinx.Ava.UI.Windows;
  20. using Ryujinx.Common;
  21. using Ryujinx.Common.Configuration;
  22. using Ryujinx.Common.Logging;
  23. using Ryujinx.Common.SystemInterop;
  24. using Ryujinx.Graphics.GAL;
  25. using Ryujinx.Graphics.GAL.Multithreading;
  26. using Ryujinx.Graphics.Gpu;
  27. using Ryujinx.Graphics.OpenGL;
  28. using Ryujinx.Graphics.Vulkan;
  29. using Ryujinx.HLE.FileSystem;
  30. using Ryujinx.HLE.HOS;
  31. using Ryujinx.HLE.HOS.Services.Account.Acc;
  32. using Ryujinx.HLE.HOS.SystemState;
  33. using Ryujinx.Input;
  34. using Ryujinx.Input.HLE;
  35. using Ryujinx.Ui.Common;
  36. using Ryujinx.Ui.Common.Configuration;
  37. using Ryujinx.Ui.Common.Helper;
  38. using Silk.NET.Vulkan;
  39. using SixLabors.ImageSharp;
  40. using SixLabors.ImageSharp.Formats.Png;
  41. using SixLabors.ImageSharp.PixelFormats;
  42. using SixLabors.ImageSharp.Processing;
  43. using SPB.Graphics.Vulkan;
  44. using System;
  45. using System.Collections.Generic;
  46. using System.Diagnostics;
  47. using System.IO;
  48. using System.Threading;
  49. using System.Threading.Tasks;
  50. using static Ryujinx.Ava.UI.Helpers.Win32NativeInterop;
  51. using Image = SixLabors.ImageSharp.Image;
  52. using InputManager = Ryujinx.Input.HLE.InputManager;
  53. using Key = Ryujinx.Input.Key;
  54. using MouseButton = Ryujinx.Input.MouseButton;
  55. using Size = Avalonia.Size;
  56. using Switch = Ryujinx.HLE.Switch;
  57. namespace Ryujinx.Ava
  58. {
  59. internal class AppHost
  60. {
  61. private const int CursorHideIdleTime = 5; // Hide Cursor seconds.
  62. private const float MaxResolutionScale = 4.0f; // Max resolution hotkeys can scale to before wrapping.
  63. private const int TargetFps = 60;
  64. private const float VolumeDelta = 0.05f;
  65. private static readonly Cursor InvisibleCursor = new(StandardCursorType.None);
  66. private readonly IntPtr InvisibleCursorWin;
  67. private readonly IntPtr DefaultCursorWin;
  68. private readonly long _ticksPerFrame;
  69. private readonly Stopwatch _chrono;
  70. private long _ticks;
  71. private readonly AccountManager _accountManager;
  72. private readonly UserChannelPersistence _userChannelPersistence;
  73. private readonly InputManager _inputManager;
  74. private readonly MainWindowViewModel _viewModel;
  75. private readonly IKeyboard _keyboardInterface;
  76. private readonly TopLevel _topLevel;
  77. public RendererHost _rendererHost;
  78. private readonly GraphicsDebugLevel _glLogLevel;
  79. private float _newVolume;
  80. private KeyboardHotkeyState _prevHotkeyState;
  81. private long _lastCursorMoveTime;
  82. private bool _isCursorInRenderer;
  83. private bool _isStopped;
  84. private bool _isActive;
  85. private bool _renderingStarted;
  86. private IRenderer _renderer;
  87. private readonly Thread _renderingThread;
  88. private readonly CancellationTokenSource _gpuCancellationTokenSource;
  89. private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  90. private bool _dialogShown;
  91. private readonly bool _isFirmwareTitle;
  92. private readonly object _lockObject = new();
  93. public event EventHandler AppExit;
  94. public event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  95. public VirtualFileSystem VirtualFileSystem { get; }
  96. public ContentManager ContentManager { get; }
  97. public NpadManager NpadManager { get; }
  98. public TouchScreenManager TouchScreenManager { get; }
  99. public Switch Device { get; set; }
  100. public int Width { get; private set; }
  101. public int Height { get; private set; }
  102. public string ApplicationPath { get; private set; }
  103. public bool ScreenshotRequested { get; set; }
  104. public AppHost(
  105. RendererHost renderer,
  106. InputManager inputManager,
  107. string applicationPath,
  108. VirtualFileSystem virtualFileSystem,
  109. ContentManager contentManager,
  110. AccountManager accountManager,
  111. UserChannelPersistence userChannelPersistence,
  112. MainWindowViewModel viewmodel,
  113. TopLevel topLevel)
  114. {
  115. _viewModel = viewmodel;
  116. _inputManager = inputManager;
  117. _accountManager = accountManager;
  118. _userChannelPersistence = userChannelPersistence;
  119. _renderingThread = new Thread(RenderLoop, 1 * 1024 * 1024) { Name = "GUI.RenderThread" };
  120. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  121. _glLogLevel = ConfigurationState.Instance.Logger.GraphicsDebugLevel;
  122. _topLevel = topLevel;
  123. _inputManager.SetMouseDriver(new AvaloniaMouseDriver(_topLevel, renderer));
  124. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  125. NpadManager = _inputManager.CreateNpadManager();
  126. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  127. ApplicationPath = applicationPath;
  128. VirtualFileSystem = virtualFileSystem;
  129. ContentManager = contentManager;
  130. _rendererHost = renderer;
  131. _chrono = new Stopwatch();
  132. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  133. if (ApplicationPath.StartsWith("@SystemContent"))
  134. {
  135. ApplicationPath = _viewModel.VirtualFileSystem.SwitchPathToSystemPath(ApplicationPath);
  136. _isFirmwareTitle = true;
  137. }
  138. ConfigurationState.Instance.HideCursor.Event += HideCursorState_Changed;
  139. _topLevel.PointerMoved += TopLevel_PointerMoved;
  140. if (OperatingSystem.IsWindows())
  141. {
  142. InvisibleCursorWin = CreateEmptyCursor();
  143. DefaultCursorWin = CreateArrowCursor();
  144. }
  145. ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
  146. ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
  147. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  148. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  149. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  150. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  151. ConfigurationState.Instance.Graphics.AntiAliasing.Event += UpdateAntiAliasing;
  152. ConfigurationState.Instance.Graphics.ScalingFilter.Event += UpdateScalingFilter;
  153. ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event += UpdateScalingFilterLevel;
  154. ConfigurationState.Instance.Multiplayer.LanInterfaceId.Event += UpdateLanInterfaceIdState;
  155. _gpuCancellationTokenSource = new CancellationTokenSource();
  156. }
  157. private void TopLevel_PointerMoved(object sender, PointerEventArgs e)
  158. {
  159. if (sender is MainWindow window)
  160. {
  161. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  162. if (_rendererHost.EmbeddedWindow.TransformedBounds != null)
  163. {
  164. var point = e.GetCurrentPoint(window).Position;
  165. var bounds = _rendererHost.EmbeddedWindow.TransformedBounds.Value.Clip;
  166. _isCursorInRenderer = point.X >= bounds.X &&
  167. point.X <= bounds.Width + bounds.X &&
  168. point.Y >= bounds.Y &&
  169. point.Y <= bounds.Height + bounds.Y;
  170. }
  171. }
  172. }
  173. private void UpdateScalingFilterLevel(object sender, ReactiveEventArgs<int> e)
  174. {
  175. _renderer.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value);
  176. _renderer.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value);
  177. }
  178. private void UpdateScalingFilter(object sender, ReactiveEventArgs<Ryujinx.Common.Configuration.ScalingFilter> e)
  179. {
  180. _renderer.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value);
  181. _renderer.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value);
  182. }
  183. private void ShowCursor()
  184. {
  185. Dispatcher.UIThread.Post(() =>
  186. {
  187. _viewModel.Cursor = Cursor.Default;
  188. if (OperatingSystem.IsWindows())
  189. {
  190. SetCursor(DefaultCursorWin);
  191. }
  192. });
  193. }
  194. private void HideCursor()
  195. {
  196. Dispatcher.UIThread.Post(() =>
  197. {
  198. _viewModel.Cursor = InvisibleCursor;
  199. if (OperatingSystem.IsWindows())
  200. {
  201. SetCursor(InvisibleCursorWin);
  202. }
  203. });
  204. }
  205. private void SetRendererWindowSize(Size size)
  206. {
  207. if (_renderer != null)
  208. {
  209. double scale = _topLevel.PlatformImpl.RenderScaling;
  210. _renderer.Window?.SetSize((int)(size.Width * scale), (int)(size.Height * scale));
  211. }
  212. }
  213. private void Renderer_ScreenCaptured(object sender, ScreenCaptureImageInfo e)
  214. {
  215. if (e.Data.Length > 0 && e.Height > 0 && e.Width > 0)
  216. {
  217. Task.Run(() =>
  218. {
  219. lock (_lockObject)
  220. {
  221. DateTime currentTime = DateTime.Now;
  222. string filename = $"ryujinx_capture_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png";
  223. string directory = AppDataManager.Mode switch
  224. {
  225. AppDataManager.LaunchMode.Portable => Path.Combine(AppDataManager.BaseDirPath, "screenshots"),
  226. _ => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx")
  227. };
  228. string path = Path.Combine(directory, filename);
  229. try
  230. {
  231. Directory.CreateDirectory(directory);
  232. }
  233. catch (Exception ex)
  234. {
  235. Logger.Error?.Print(LogClass.Application, $"Failed to create directory at path {directory}. Error : {ex.GetType().Name}", "Screenshot");
  236. return;
  237. }
  238. Image image = e.IsBgra ? Image.LoadPixelData<Bgra32>(e.Data, e.Width, e.Height)
  239. : Image.LoadPixelData<Rgba32>(e.Data, e.Width, e.Height);
  240. if (e.FlipX)
  241. {
  242. image.Mutate(x => x.Flip(FlipMode.Horizontal));
  243. }
  244. if (e.FlipY)
  245. {
  246. image.Mutate(x => x.Flip(FlipMode.Vertical));
  247. }
  248. image.SaveAsPng(path, new PngEncoder()
  249. {
  250. ColorType = PngColorType.Rgb
  251. });
  252. image.Dispose();
  253. Logger.Notice.Print(LogClass.Application, $"Screenshot saved to {path}", "Screenshot");
  254. }
  255. });
  256. }
  257. else
  258. {
  259. Logger.Error?.Print(LogClass.Application, $"Screenshot is empty. Size : {e.Data.Length} bytes. Resolution : {e.Width}x{e.Height}", "Screenshot");
  260. }
  261. }
  262. public void Start()
  263. {
  264. if (OperatingSystem.IsWindows())
  265. {
  266. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  267. }
  268. DisplaySleep.Prevent();
  269. NpadManager.Initialize(Device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  270. TouchScreenManager.Initialize(Device);
  271. _viewModel.IsGameRunning = true;
  272. var activeProcess = Device.Processes.ActiveApplication;
  273. string titleNameSection = string.IsNullOrWhiteSpace(activeProcess.Name) ? string.Empty : $" {activeProcess.Name}";
  274. string titleVersionSection = string.IsNullOrWhiteSpace(activeProcess.DisplayVersion) ? string.Empty : $" v{activeProcess.DisplayVersion}";
  275. string titleIdSection = $" ({activeProcess.ProgramIdText.ToUpper()})";
  276. string titleArchSection = activeProcess.Is64Bit ? " (64-bit)" : " (32-bit)";
  277. Dispatcher.UIThread.InvokeAsync(() =>
  278. {
  279. _viewModel.Title = $"Ryujinx {Program.Version} -{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  280. });
  281. _viewModel.SetUIProgressHandlers(Device);
  282. _rendererHost.SizeChanged += Window_SizeChanged;
  283. _isActive = true;
  284. _renderingThread.Start();
  285. _viewModel.Volume = ConfigurationState.Instance.System.AudioVolume.Value;
  286. MainLoop();
  287. Exit();
  288. }
  289. private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
  290. {
  291. if (Device != null)
  292. {
  293. Device.Configuration.IgnoreMissingServices = args.NewValue;
  294. }
  295. }
  296. private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
  297. {
  298. if (Device != null)
  299. {
  300. Device.Configuration.AspectRatio = args.NewValue;
  301. }
  302. }
  303. private void UpdateAntiAliasing(object sender, ReactiveEventArgs<Ryujinx.Common.Configuration.AntiAliasing> e)
  304. {
  305. _renderer?.Window?.SetAntiAliasing((Graphics.GAL.AntiAliasing)e.NewValue);
  306. }
  307. private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
  308. {
  309. Device?.System.ChangeDockedModeState(e.NewValue);
  310. }
  311. private void UpdateAudioVolumeState(object sender, ReactiveEventArgs<float> e)
  312. {
  313. Device?.SetVolume(e.NewValue);
  314. Dispatcher.UIThread.Post(() =>
  315. {
  316. _viewModel.Volume = e.NewValue;
  317. });
  318. }
  319. private void UpdateLanInterfaceIdState(object sender, ReactiveEventArgs<string> e)
  320. {
  321. Device.Configuration.MultiplayerLanInterfaceId = e.NewValue;
  322. }
  323. public void Stop()
  324. {
  325. _isActive = false;
  326. }
  327. private void Exit()
  328. {
  329. (_keyboardInterface as AvaloniaKeyboard)?.Clear();
  330. if (_isStopped)
  331. {
  332. return;
  333. }
  334. _isStopped = true;
  335. _isActive = false;
  336. }
  337. public void DisposeContext()
  338. {
  339. Dispose();
  340. _isActive = false;
  341. if (_renderingThread.IsAlive)
  342. {
  343. _renderingThread.Join();
  344. }
  345. DisplaySleep.Restore();
  346. NpadManager.Dispose();
  347. TouchScreenManager.Dispose();
  348. Device.Dispose();
  349. DisposeGpu();
  350. AppExit?.Invoke(this, EventArgs.Empty);
  351. }
  352. private void Dispose()
  353. {
  354. if (Device.Processes != null)
  355. {
  356. _viewModel.UpdateGameMetadata(Device.Processes.ActiveApplication.ProgramIdText);
  357. }
  358. ConfigurationState.Instance.System.IgnoreMissingServices.Event -= UpdateIgnoreMissingServicesState;
  359. ConfigurationState.Instance.Graphics.AspectRatio.Event -= UpdateAspectRatioState;
  360. ConfigurationState.Instance.System.EnableDockedMode.Event -= UpdateDockedModeState;
  361. ConfigurationState.Instance.System.AudioVolume.Event -= UpdateAudioVolumeState;
  362. ConfigurationState.Instance.Graphics.ScalingFilter.Event -= UpdateScalingFilter;
  363. ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event -= UpdateScalingFilterLevel;
  364. ConfigurationState.Instance.Graphics.AntiAliasing.Event -= UpdateAntiAliasing;
  365. _topLevel.PointerMoved -= TopLevel_PointerMoved;
  366. _gpuCancellationTokenSource.Cancel();
  367. _gpuCancellationTokenSource.Dispose();
  368. _chrono.Stop();
  369. }
  370. public void DisposeGpu()
  371. {
  372. if (OperatingSystem.IsWindows())
  373. {
  374. _windowsMultimediaTimerResolution?.Dispose();
  375. _windowsMultimediaTimerResolution = null;
  376. }
  377. (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent();
  378. Device.DisposeGpu();
  379. (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent(null);
  380. }
  381. private void HideCursorState_Changed(object sender, ReactiveEventArgs<HideCursorMode> state)
  382. {
  383. if (state.NewValue == HideCursorMode.OnIdle)
  384. {
  385. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  386. }
  387. }
  388. public async Task<bool> LoadGuestApplication()
  389. {
  390. InitializeSwitchInstance();
  391. MainWindow.UpdateGraphicsConfig();
  392. SystemVersion firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  393. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  394. {
  395. if (!SetupValidator.CanStartApplication(ContentManager, ApplicationPath, out UserError userError))
  396. {
  397. {
  398. if (SetupValidator.CanFixStartApplication(ContentManager, ApplicationPath, userError, out firmwareVersion))
  399. {
  400. if (userError == UserError.NoFirmware)
  401. {
  402. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  403. LocaleManager.Instance[LocaleKeys.DialogFirmwareNoFirmwareInstalledMessage],
  404. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallEmbeddedMessage, firmwareVersion.VersionString),
  405. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  406. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  407. "");
  408. if (result != UserResult.Yes)
  409. {
  410. await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow));
  411. Device.Dispose();
  412. return false;
  413. }
  414. }
  415. if (!SetupValidator.TryFixStartApplication(ContentManager, ApplicationPath, userError, out _))
  416. {
  417. await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow));
  418. Device.Dispose();
  419. return false;
  420. }
  421. // Tell the user that we installed a firmware for them.
  422. if (userError == UserError.NoFirmware)
  423. {
  424. firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  425. _viewModel.RefreshFirmwareStatus();
  426. await ContentDialogHelper.CreateInfoDialog(
  427. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstalledMessage, firmwareVersion.VersionString),
  428. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallEmbeddedSuccessMessage, firmwareVersion.VersionString),
  429. LocaleManager.Instance[LocaleKeys.InputDialogOk],
  430. "",
  431. LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  432. }
  433. }
  434. else
  435. {
  436. await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow));
  437. Device.Dispose();
  438. return false;
  439. }
  440. }
  441. }
  442. }
  443. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  444. if (_isFirmwareTitle)
  445. {
  446. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  447. if (!Device.LoadNca(ApplicationPath))
  448. {
  449. Device.Dispose();
  450. return false;
  451. }
  452. }
  453. else if (Directory.Exists(ApplicationPath))
  454. {
  455. string[] romFsFiles = Directory.GetFiles(ApplicationPath, "*.istorage");
  456. if (romFsFiles.Length == 0)
  457. {
  458. romFsFiles = Directory.GetFiles(ApplicationPath, "*.romfs");
  459. }
  460. if (romFsFiles.Length > 0)
  461. {
  462. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  463. if (!Device.LoadCart(ApplicationPath, romFsFiles[0]))
  464. {
  465. Device.Dispose();
  466. return false;
  467. }
  468. }
  469. else
  470. {
  471. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  472. if (!Device.LoadCart(ApplicationPath))
  473. {
  474. Device.Dispose();
  475. return false;
  476. }
  477. }
  478. }
  479. else if (File.Exists(ApplicationPath))
  480. {
  481. switch (Path.GetExtension(ApplicationPath).ToLowerInvariant())
  482. {
  483. case ".xci":
  484. {
  485. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  486. if (!Device.LoadXci(ApplicationPath))
  487. {
  488. Device.Dispose();
  489. return false;
  490. }
  491. break;
  492. }
  493. case ".nca":
  494. {
  495. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  496. if (!Device.LoadNca(ApplicationPath))
  497. {
  498. Device.Dispose();
  499. return false;
  500. }
  501. break;
  502. }
  503. case ".nsp":
  504. case ".pfs0":
  505. {
  506. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  507. if (!Device.LoadNsp(ApplicationPath))
  508. {
  509. Device.Dispose();
  510. return false;
  511. }
  512. break;
  513. }
  514. default:
  515. {
  516. Logger.Info?.Print(LogClass.Application, "Loading as homebrew.");
  517. try
  518. {
  519. if (!Device.LoadProgram(ApplicationPath))
  520. {
  521. Device.Dispose();
  522. return false;
  523. }
  524. }
  525. catch (ArgumentOutOfRangeException)
  526. {
  527. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  528. Device.Dispose();
  529. return false;
  530. }
  531. break;
  532. }
  533. }
  534. }
  535. else
  536. {
  537. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  538. Device.Dispose();
  539. return false;
  540. }
  541. DiscordIntegrationModule.SwitchToPlayingState(Device.Processes.ActiveApplication.ProgramIdText, Device.Processes.ActiveApplication.Name);
  542. _viewModel.ApplicationLibrary.LoadAndSaveMetaData(Device.Processes.ActiveApplication.ProgramIdText, appMetadata =>
  543. {
  544. appMetadata.LastPlayed = DateTime.UtcNow;
  545. });
  546. return true;
  547. }
  548. internal void Resume()
  549. {
  550. Device?.System.TogglePauseEmulation(false);
  551. _viewModel.IsPaused = false;
  552. }
  553. internal void Pause()
  554. {
  555. Device?.System.TogglePauseEmulation(true);
  556. _viewModel.IsPaused = true;
  557. }
  558. private void InitializeSwitchInstance()
  559. {
  560. // Initialize KeySet.
  561. VirtualFileSystem.ReloadKeySet();
  562. // Initialize Renderer.
  563. IRenderer renderer;
  564. if (ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.Vulkan)
  565. {
  566. renderer = new VulkanRenderer(
  567. Vk.GetApi(),
  568. (_rendererHost.EmbeddedWindow as EmbeddedWindowVulkan).CreateSurface,
  569. VulkanHelper.GetRequiredInstanceExtensions,
  570. ConfigurationState.Instance.Graphics.PreferredGpu.Value);
  571. }
  572. else
  573. {
  574. renderer = new OpenGLRenderer();
  575. }
  576. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  577. var isGALthreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  578. if (isGALthreaded)
  579. {
  580. renderer = new ThreadedRenderer(renderer);
  581. }
  582. Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALthreaded}");
  583. // Initialize Configuration.
  584. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value ? HLE.MemoryConfiguration.MemoryConfiguration6GiB : HLE.MemoryConfiguration.MemoryConfiguration4GiB;
  585. HLE.HLEConfiguration configuration = new(VirtualFileSystem,
  586. _viewModel.LibHacHorizonManager,
  587. ContentManager,
  588. _accountManager,
  589. _userChannelPersistence,
  590. renderer,
  591. InitializeAudio(),
  592. memoryConfiguration,
  593. _viewModel.UiHandler,
  594. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  595. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  596. ConfigurationState.Instance.Graphics.EnableVsync,
  597. ConfigurationState.Instance.System.EnableDockedMode,
  598. ConfigurationState.Instance.System.EnablePtc,
  599. ConfigurationState.Instance.System.EnableInternetAccess,
  600. ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None,
  601. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  602. ConfigurationState.Instance.System.SystemTimeOffset,
  603. ConfigurationState.Instance.System.TimeZone,
  604. ConfigurationState.Instance.System.MemoryManagerMode,
  605. ConfigurationState.Instance.System.IgnoreMissingServices,
  606. ConfigurationState.Instance.Graphics.AspectRatio,
  607. ConfigurationState.Instance.System.AudioVolume,
  608. ConfigurationState.Instance.System.UseHypervisor,
  609. ConfigurationState.Instance.Multiplayer.LanInterfaceId.Value);
  610. Device = new Switch(configuration);
  611. }
  612. private static IHardwareDeviceDriver InitializeAudio()
  613. {
  614. var availableBackends = new List<AudioBackend>()
  615. {
  616. AudioBackend.SDL2,
  617. AudioBackend.SoundIo,
  618. AudioBackend.OpenAl,
  619. AudioBackend.Dummy
  620. };
  621. AudioBackend preferredBackend = ConfigurationState.Instance.System.AudioBackend.Value;
  622. for (int i = 0; i < availableBackends.Count; i++)
  623. {
  624. if (availableBackends[i] == preferredBackend)
  625. {
  626. availableBackends.RemoveAt(i);
  627. availableBackends.Insert(0, preferredBackend);
  628. break;
  629. }
  630. }
  631. static IHardwareDeviceDriver InitializeAudioBackend<T>(AudioBackend backend, AudioBackend nextBackend) where T : IHardwareDeviceDriver, new()
  632. {
  633. if (T.IsSupported)
  634. {
  635. return new T();
  636. }
  637. else
  638. {
  639. Logger.Warning?.Print(LogClass.Audio, $"{backend} is not supported, falling back to {nextBackend}.");
  640. return null;
  641. }
  642. }
  643. IHardwareDeviceDriver deviceDriver = null;
  644. for (int i = 0; i < availableBackends.Count; i++)
  645. {
  646. AudioBackend currentBackend = availableBackends[i];
  647. AudioBackend nextBackend = i + 1 < availableBackends.Count ? availableBackends[i + 1] : AudioBackend.Dummy;
  648. deviceDriver = currentBackend switch
  649. {
  650. AudioBackend.SDL2 => InitializeAudioBackend<SDL2HardwareDeviceDriver>(AudioBackend.SDL2, nextBackend),
  651. AudioBackend.SoundIo => InitializeAudioBackend<SoundIoHardwareDeviceDriver>(AudioBackend.SoundIo, nextBackend),
  652. AudioBackend.OpenAl => InitializeAudioBackend<OpenALHardwareDeviceDriver>(AudioBackend.OpenAl, nextBackend),
  653. _ => new DummyHardwareDeviceDriver()
  654. };
  655. if (deviceDriver != null)
  656. {
  657. ConfigurationState.Instance.System.AudioBackend.Value = currentBackend;
  658. break;
  659. }
  660. }
  661. MainWindowViewModel.SaveConfig();
  662. return deviceDriver;
  663. }
  664. private void Window_SizeChanged(object sender, Size e)
  665. {
  666. Width = (int)e.Width;
  667. Height = (int)e.Height;
  668. SetRendererWindowSize(e);
  669. }
  670. private void MainLoop()
  671. {
  672. while (_isActive)
  673. {
  674. UpdateFrame();
  675. // Polling becomes expensive if it's not slept.
  676. Thread.Sleep(1);
  677. }
  678. }
  679. private void RenderLoop()
  680. {
  681. Dispatcher.UIThread.InvokeAsync(() =>
  682. {
  683. if (_viewModel.StartGamesInFullscreen)
  684. {
  685. _viewModel.WindowState = WindowState.FullScreen;
  686. }
  687. if (_viewModel.WindowState == WindowState.FullScreen)
  688. {
  689. _viewModel.ShowMenuAndStatusBar = false;
  690. }
  691. });
  692. _renderer = Device.Gpu.Renderer is ThreadedRenderer tr ? tr.BaseRenderer : Device.Gpu.Renderer;
  693. _renderer.ScreenCaptured += Renderer_ScreenCaptured;
  694. (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.InitializeBackgroundContext(_renderer);
  695. Device.Gpu.Renderer.Initialize(_glLogLevel);
  696. _renderer?.Window?.SetAntiAliasing((Graphics.GAL.AntiAliasing)ConfigurationState.Instance.Graphics.AntiAliasing.Value);
  697. _renderer?.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value);
  698. _renderer?.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value);
  699. Width = (int)_rendererHost.Bounds.Width;
  700. Height = (int)_rendererHost.Bounds.Height;
  701. _renderer.Window.SetSize((int)(Width * _topLevel.PlatformImpl.RenderScaling), (int)(Height * _topLevel.PlatformImpl.RenderScaling));
  702. _chrono.Start();
  703. Device.Gpu.Renderer.RunLoop(() =>
  704. {
  705. Device.Gpu.SetGpuThread();
  706. Device.Gpu.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  707. Translator.IsReadyForTranslation.Set();
  708. _renderer.Window.ChangeVSyncMode(Device.EnableDeviceVsync);
  709. while (_isActive)
  710. {
  711. _ticks += _chrono.ElapsedTicks;
  712. _chrono.Restart();
  713. if (Device.WaitFifo())
  714. {
  715. Device.Statistics.RecordFifoStart();
  716. Device.ProcessFrame();
  717. Device.Statistics.RecordFifoEnd();
  718. }
  719. while (Device.ConsumeFrameAvailable())
  720. {
  721. if (!_renderingStarted)
  722. {
  723. _renderingStarted = true;
  724. _viewModel.SwitchToRenderer(false);
  725. }
  726. Device.PresentFrame(() => (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.SwapBuffers());
  727. }
  728. if (_ticks >= _ticksPerFrame)
  729. {
  730. UpdateStatus();
  731. }
  732. }
  733. });
  734. (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent(null);
  735. }
  736. public void UpdateStatus()
  737. {
  738. // Run a status update only when a frame is to be drawn. This prevents from updating the ui and wasting a render when no frame is queued.
  739. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? LocaleManager.Instance[LocaleKeys.Docked] : LocaleManager.Instance[LocaleKeys.Handheld];
  740. if (GraphicsConfig.ResScale != 1)
  741. {
  742. dockedMode += $" ({GraphicsConfig.ResScale}x)";
  743. }
  744. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  745. Device.EnableDeviceVsync,
  746. LocaleManager.Instance[LocaleKeys.VolumeShort] + $": {(int)(Device.GetVolume() * 100)}%",
  747. ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.Vulkan ? "Vulkan" : "OpenGL",
  748. dockedMode,
  749. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  750. LocaleManager.Instance[LocaleKeys.Game] + $": {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  751. $"FIFO: {Device.Statistics.GetFifoPercent():00.00} %",
  752. $"GPU: {_renderer.GetHardwareInfo().GpuVendor}"));
  753. }
  754. public async Task ShowExitPrompt()
  755. {
  756. bool shouldExit = !ConfigurationState.Instance.ShowConfirmExit;
  757. if (!shouldExit)
  758. {
  759. if (_dialogShown)
  760. {
  761. return;
  762. }
  763. _dialogShown = true;
  764. shouldExit = await ContentDialogHelper.CreateStopEmulationDialog();
  765. _dialogShown = false;
  766. }
  767. if (shouldExit)
  768. {
  769. Stop();
  770. }
  771. }
  772. private bool UpdateFrame()
  773. {
  774. if (!_isActive)
  775. {
  776. return false;
  777. }
  778. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  779. if (_viewModel.IsActive)
  780. {
  781. if (_isCursorInRenderer)
  782. {
  783. if (ConfigurationState.Instance.Hid.EnableMouse)
  784. {
  785. HideCursor();
  786. }
  787. else
  788. {
  789. switch (ConfigurationState.Instance.HideCursor.Value)
  790. {
  791. case HideCursorMode.Never:
  792. ShowCursor();
  793. break;
  794. case HideCursorMode.OnIdle:
  795. if (Stopwatch.GetTimestamp() - _lastCursorMoveTime >= CursorHideIdleTime * Stopwatch.Frequency)
  796. {
  797. HideCursor();
  798. }
  799. else
  800. {
  801. ShowCursor();
  802. }
  803. break;
  804. case HideCursorMode.Always:
  805. HideCursor();
  806. break;
  807. }
  808. }
  809. }
  810. else
  811. {
  812. ShowCursor();
  813. }
  814. Dispatcher.UIThread.Post(() =>
  815. {
  816. if (_keyboardInterface.GetKeyboardStateSnapshot().IsPressed(Key.Delete) && _viewModel.WindowState != WindowState.FullScreen)
  817. {
  818. Device.Processes.ActiveApplication.DiskCacheLoadState?.Cancel();
  819. }
  820. });
  821. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  822. if (currentHotkeyState != _prevHotkeyState)
  823. {
  824. switch (currentHotkeyState)
  825. {
  826. case KeyboardHotkeyState.ToggleVSync:
  827. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  828. break;
  829. case KeyboardHotkeyState.Screenshot:
  830. ScreenshotRequested = true;
  831. break;
  832. case KeyboardHotkeyState.ShowUi:
  833. _viewModel.ShowMenuAndStatusBar = true;
  834. break;
  835. case KeyboardHotkeyState.Pause:
  836. if (_viewModel.IsPaused)
  837. {
  838. Resume();
  839. }
  840. else
  841. {
  842. Pause();
  843. }
  844. break;
  845. case KeyboardHotkeyState.ToggleMute:
  846. if (Device.IsAudioMuted())
  847. {
  848. Device.SetVolume(ConfigurationState.Instance.System.AudioVolume);
  849. }
  850. else
  851. {
  852. Device.SetVolume(0);
  853. }
  854. _viewModel.Volume = Device.GetVolume();
  855. break;
  856. case KeyboardHotkeyState.ResScaleUp:
  857. GraphicsConfig.ResScale = GraphicsConfig.ResScale % MaxResolutionScale + 1;
  858. break;
  859. case KeyboardHotkeyState.ResScaleDown:
  860. GraphicsConfig.ResScale =
  861. (MaxResolutionScale + GraphicsConfig.ResScale - 2) % MaxResolutionScale + 1;
  862. break;
  863. case KeyboardHotkeyState.VolumeUp:
  864. _newVolume = MathF.Round((Device.GetVolume() + VolumeDelta), 2);
  865. Device.SetVolume(_newVolume);
  866. _viewModel.Volume = Device.GetVolume();
  867. break;
  868. case KeyboardHotkeyState.VolumeDown:
  869. _newVolume = MathF.Round((Device.GetVolume() - VolumeDelta), 2);
  870. Device.SetVolume(_newVolume);
  871. _viewModel.Volume = Device.GetVolume();
  872. break;
  873. case KeyboardHotkeyState.None:
  874. (_keyboardInterface as AvaloniaKeyboard).Clear();
  875. break;
  876. }
  877. }
  878. _prevHotkeyState = currentHotkeyState;
  879. if (ScreenshotRequested)
  880. {
  881. ScreenshotRequested = false;
  882. _renderer.Screenshot();
  883. }
  884. }
  885. // Touchscreen.
  886. bool hasTouch = false;
  887. if (_viewModel.IsActive && !ConfigurationState.Instance.Hid.EnableMouse)
  888. {
  889. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as AvaloniaMouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  890. }
  891. if (!hasTouch)
  892. {
  893. Device.Hid.Touchscreen.Update();
  894. }
  895. Device.Hid.DebugPad.Update();
  896. return true;
  897. }
  898. private KeyboardHotkeyState GetHotkeyState()
  899. {
  900. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  901. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  902. {
  903. state = KeyboardHotkeyState.ToggleVSync;
  904. }
  905. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot))
  906. {
  907. state = KeyboardHotkeyState.Screenshot;
  908. }
  909. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi))
  910. {
  911. state = KeyboardHotkeyState.ShowUi;
  912. }
  913. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause))
  914. {
  915. state = KeyboardHotkeyState.Pause;
  916. }
  917. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleMute))
  918. {
  919. state = KeyboardHotkeyState.ToggleMute;
  920. }
  921. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleUp))
  922. {
  923. state = KeyboardHotkeyState.ResScaleUp;
  924. }
  925. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleDown))
  926. {
  927. state = KeyboardHotkeyState.ResScaleDown;
  928. }
  929. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeUp))
  930. {
  931. state = KeyboardHotkeyState.VolumeUp;
  932. }
  933. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeDown))
  934. {
  935. state = KeyboardHotkeyState.VolumeDown;
  936. }
  937. return state;
  938. }
  939. }
  940. }