AppHost.cs 39 KB

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