AppHost.cs 41 KB

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