AppHost.cs 42 KB

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