AppHost.cs 40 KB

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