AppHost.cs 41 KB

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