AppHost.cs 42 KB

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