AppHost.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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"],
  336. firmwareVersion.VersionString);
  337. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  338. LocaleManager.Instance["DialogFirmwareNoFirmwareInstalledMessage"], message,
  339. LocaleManager.Instance["InputDialogYes"], LocaleManager.Instance["InputDialogNo"], "");
  340. if (result != UserResult.Yes)
  341. {
  342. Dispatcher.UIThread.Post(async () => await
  343. UserErrorDialog.ShowUserErrorDialog(userError, _parent));
  344. Device.Dispose();
  345. return false;
  346. }
  347. }
  348. if (!SetupValidator.TryFixStartApplication(ContentManager, ApplicationPath, userError, out _))
  349. {
  350. Dispatcher.UIThread.Post(async () => await
  351. UserErrorDialog.ShowUserErrorDialog(userError, _parent));
  352. Device.Dispose();
  353. return false;
  354. }
  355. // Tell the user that we installed a firmware for them.
  356. if (userError == UserError.NoFirmware)
  357. {
  358. firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  359. _parent.RefreshFirmwareStatus();
  360. string message = string.Format(LocaleManager.Instance["DialogFirmwareInstallEmbeddedSuccessMessage"], firmwareVersion.VersionString);
  361. await ContentDialogHelper.CreateInfoDialog(
  362. string.Format(LocaleManager.Instance["DialogFirmwareInstalledMessage"], firmwareVersion.VersionString),
  363. message,
  364. LocaleManager.Instance["InputDialogOk"],
  365. "",
  366. LocaleManager.Instance["RyujinxInfo"]);
  367. }
  368. }
  369. else
  370. {
  371. Dispatcher.UIThread.Post(async () => await
  372. UserErrorDialog.ShowUserErrorDialog(userError, _parent));
  373. Device.Dispose();
  374. return false;
  375. }
  376. }
  377. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  378. if (_isFirmwareTitle)
  379. {
  380. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  381. Device.LoadNca(ApplicationPath);
  382. }
  383. else if (Directory.Exists(ApplicationPath))
  384. {
  385. string[] romFsFiles = Directory.GetFiles(ApplicationPath, "*.istorage");
  386. if (romFsFiles.Length == 0)
  387. {
  388. romFsFiles = Directory.GetFiles(ApplicationPath, "*.romfs");
  389. }
  390. if (romFsFiles.Length > 0)
  391. {
  392. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  393. Device.LoadCart(ApplicationPath, romFsFiles[0]);
  394. }
  395. else
  396. {
  397. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  398. Device.LoadCart(ApplicationPath);
  399. }
  400. }
  401. else if (File.Exists(ApplicationPath))
  402. {
  403. switch (System.IO.Path.GetExtension(ApplicationPath).ToLowerInvariant())
  404. {
  405. case ".xci":
  406. {
  407. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  408. Device.LoadXci(ApplicationPath);
  409. break;
  410. }
  411. case ".nca":
  412. {
  413. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  414. Device.LoadNca(ApplicationPath);
  415. break;
  416. }
  417. case ".nsp":
  418. case ".pfs0":
  419. {
  420. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  421. Device.LoadNsp(ApplicationPath);
  422. break;
  423. }
  424. default:
  425. {
  426. Logger.Info?.Print(LogClass.Application, "Loading as homebrew.");
  427. try
  428. {
  429. Device.LoadProgram(ApplicationPath);
  430. }
  431. catch (ArgumentOutOfRangeException)
  432. {
  433. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  434. Dispose();
  435. return false;
  436. }
  437. break;
  438. }
  439. }
  440. }
  441. else
  442. {
  443. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  444. Dispose();
  445. return false;
  446. }
  447. DiscordIntegrationModule.SwitchToPlayingState(Device.Application.TitleIdText, Device.Application.TitleName);
  448. _parent.ApplicationLibrary.LoadAndSaveMetaData(Device.Application.TitleIdText, appMetadata =>
  449. {
  450. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  451. });
  452. return true;
  453. }
  454. internal void Resume()
  455. {
  456. Device?.System.TogglePauseEmulation(false);
  457. _parent.ViewModel.IsPaused = false;
  458. }
  459. internal void Pause()
  460. {
  461. Device?.System.TogglePauseEmulation(true);
  462. _parent.ViewModel.IsPaused = true;
  463. }
  464. private void InitializeSwitchInstance()
  465. {
  466. VirtualFileSystem.ReloadKeySet();
  467. IRenderer renderer = new Renderer();
  468. IHardwareDeviceDriver deviceDriver = new DummyHardwareDeviceDriver();
  469. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  470. var isGALthreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  471. if (isGALthreaded)
  472. {
  473. renderer = new ThreadedRenderer(renderer);
  474. }
  475. Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALthreaded}");
  476. if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SDL2)
  477. {
  478. if (SDL2HardwareDeviceDriver.IsSupported)
  479. {
  480. deviceDriver = new SDL2HardwareDeviceDriver();
  481. }
  482. else
  483. {
  484. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");
  485. if (OpenALHardwareDeviceDriver.IsSupported)
  486. {
  487. Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");
  488. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
  489. MainWindow.SaveConfig();
  490. deviceDriver = new OpenALHardwareDeviceDriver();
  491. }
  492. else
  493. {
  494. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SoundIO.");
  495. if (SoundIoHardwareDeviceDriver.IsSupported)
  496. {
  497. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  498. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  499. MainWindow.SaveConfig();
  500. deviceDriver = new SoundIoHardwareDeviceDriver();
  501. }
  502. else
  503. {
  504. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  505. }
  506. }
  507. }
  508. }
  509. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SoundIo)
  510. {
  511. if (SoundIoHardwareDeviceDriver.IsSupported)
  512. {
  513. deviceDriver = new SoundIoHardwareDeviceDriver();
  514. }
  515. else
  516. {
  517. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, trying to fall back to SDL2.");
  518. if (SDL2HardwareDeviceDriver.IsSupported)
  519. {
  520. Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");
  521. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
  522. MainWindow.SaveConfig();
  523. deviceDriver = new SDL2HardwareDeviceDriver();
  524. }
  525. else
  526. {
  527. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");
  528. if (OpenALHardwareDeviceDriver.IsSupported)
  529. {
  530. Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");
  531. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
  532. MainWindow.SaveConfig();
  533. deviceDriver = new OpenALHardwareDeviceDriver();
  534. }
  535. else
  536. {
  537. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, falling back to dummy audio out.");
  538. }
  539. }
  540. }
  541. }
  542. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.OpenAl)
  543. {
  544. if (OpenALHardwareDeviceDriver.IsSupported)
  545. {
  546. deviceDriver = new OpenALHardwareDeviceDriver();
  547. }
  548. else
  549. {
  550. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SDL2.");
  551. if (SDL2HardwareDeviceDriver.IsSupported)
  552. {
  553. Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");
  554. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
  555. MainWindow.SaveConfig();
  556. deviceDriver = new SDL2HardwareDeviceDriver();
  557. }
  558. else
  559. {
  560. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to SoundIO.");
  561. if (SoundIoHardwareDeviceDriver.IsSupported)
  562. {
  563. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  564. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  565. MainWindow.SaveConfig();
  566. deviceDriver = new SoundIoHardwareDeviceDriver();
  567. }
  568. else
  569. {
  570. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  571. }
  572. }
  573. }
  574. }
  575. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value ? HLE.MemoryConfiguration.MemoryConfiguration6GB : HLE.MemoryConfiguration.MemoryConfiguration4GB;
  576. IntegrityCheckLevel fsIntegrityCheckLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None;
  577. HLE.HLEConfiguration configuration = new HLE.HLEConfiguration(VirtualFileSystem,
  578. _parent.LibHacHorizonManager,
  579. ContentManager,
  580. _accountManager,
  581. _userChannelPersistence,
  582. renderer,
  583. deviceDriver,
  584. memoryConfiguration,
  585. _parent.UiHandler,
  586. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  587. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  588. ConfigurationState.Instance.Graphics.EnableVsync,
  589. ConfigurationState.Instance.System.EnableDockedMode,
  590. ConfigurationState.Instance.System.EnablePtc,
  591. ConfigurationState.Instance.System.EnableInternetAccess,
  592. fsIntegrityCheckLevel,
  593. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  594. ConfigurationState.Instance.System.SystemTimeOffset,
  595. ConfigurationState.Instance.System.TimeZone,
  596. ConfigurationState.Instance.System.MemoryManagerMode,
  597. ConfigurationState.Instance.System.IgnoreMissingServices,
  598. ConfigurationState.Instance.Graphics.AspectRatio,
  599. ConfigurationState.Instance.System.AudioVolume);
  600. Device = new Switch(configuration);
  601. }
  602. private void Window_SizeChanged(object sender, Size e)
  603. {
  604. Width = (int)e.Width;
  605. Height = (int)e.Height;
  606. SetRendererWindowSize(e);
  607. }
  608. private void MainLoop()
  609. {
  610. while (_isActive)
  611. {
  612. UpdateFrame();
  613. // Polling becomes expensive if it's not slept
  614. Thread.Sleep(1);
  615. }
  616. }
  617. private unsafe void RenderLoop()
  618. {
  619. Dispatcher.UIThread.InvokeAsync(() =>
  620. {
  621. if (_parent.ViewModel.StartGamesInFullscreen)
  622. {
  623. _parent.WindowState = WindowState.FullScreen;
  624. }
  625. if (_parent.WindowState == WindowState.FullScreen)
  626. {
  627. _parent.ViewModel.ShowMenuAndStatusBar = false;
  628. }
  629. });
  630. IRenderer renderer = Device.Gpu.Renderer;
  631. if (renderer is ThreadedRenderer tr)
  632. {
  633. renderer = tr.BaseRenderer;
  634. }
  635. _renderer = renderer;
  636. _renderer.ScreenCaptured += Renderer_ScreenCaptured;
  637. (_renderer as Renderer).InitializeBackgroundContext(SPBOpenGLContext.CreateBackgroundContext(Renderer.GameContext));
  638. Renderer.MakeCurrent();
  639. Device.Gpu.Renderer.Initialize(_glLogLevel);
  640. Width = (int)Renderer.Bounds.Width;
  641. Height = (int)Renderer.Bounds.Height;
  642. _renderer.Window.SetSize((int)(Width * _parent.PlatformImpl.RenderScaling), (int)(Height * _parent.PlatformImpl.RenderScaling));
  643. Device.Gpu.Renderer.RunLoop(() =>
  644. {
  645. Device.Gpu.SetGpuThread();
  646. Device.Gpu.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  647. Translator.IsReadyForTranslation.Set();
  648. Renderer.Start();
  649. Renderer.QueueRender();
  650. while (_isActive)
  651. {
  652. if (Device.WaitFifo())
  653. {
  654. Device.Statistics.RecordFifoStart();
  655. Device.ProcessFrame();
  656. Device.Statistics.RecordFifoEnd();
  657. }
  658. while (Device.ConsumeFrameAvailable())
  659. {
  660. if (!_renderingStarted)
  661. {
  662. _renderingStarted = true;
  663. _parent.SwitchToGameControl();
  664. }
  665. Device.PresentFrame(Present);
  666. }
  667. }
  668. Renderer.Stop();
  669. });
  670. Renderer?.MakeCurrent(null);
  671. Renderer.SizeChanged -= Window_SizeChanged;
  672. }
  673. private void Present(object image)
  674. {
  675. // 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
  676. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? LocaleManager.Instance["Docked"] : LocaleManager.Instance["Handheld"];
  677. float scale = GraphicsConfig.ResScale;
  678. if (scale != 1)
  679. {
  680. dockedMode += $" ({scale}x)";
  681. }
  682. string vendor = _renderer is Renderer renderer ? renderer.GpuVendor : "";
  683. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  684. Device.EnableDeviceVsync,
  685. Device.GetVolume(),
  686. dockedMode,
  687. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  688. LocaleManager.Instance["Game"] + $": {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  689. $"FIFO: {Device.Statistics.GetFifoPercent():00.00} %",
  690. $"GPU: {vendor}"));
  691. Renderer.Present(image);
  692. }
  693. public async Task ShowExitPrompt()
  694. {
  695. bool shouldExit = !ConfigurationState.Instance.ShowConfirmExit;
  696. if (!shouldExit)
  697. {
  698. if (_dialogShown)
  699. {
  700. return;
  701. }
  702. _dialogShown = true;
  703. shouldExit = await ContentDialogHelper.CreateStopEmulationDialog();
  704. _dialogShown = false;
  705. }
  706. if (shouldExit)
  707. {
  708. Stop();
  709. }
  710. }
  711. private void HandleScreenState()
  712. {
  713. if (ConfigurationState.Instance.Hid.EnableMouse)
  714. {
  715. Dispatcher.UIThread.Post(() =>
  716. {
  717. _parent.Cursor = _isMouseInRenderer ? InvisibleCursor : Cursor.Default;
  718. });
  719. }
  720. else
  721. {
  722. if (_hideCursorOnIdle)
  723. {
  724. long cursorMoveDelta = Stopwatch.GetTimestamp() - _lastCursorMoveTime;
  725. Dispatcher.UIThread.Post(() =>
  726. {
  727. _parent.Cursor = cursorMoveDelta >= CursorHideIdleTime * Stopwatch.Frequency ? InvisibleCursor : Cursor.Default;
  728. });
  729. }
  730. }
  731. }
  732. private bool UpdateFrame()
  733. {
  734. if (!_isActive)
  735. {
  736. return false;
  737. }
  738. if (_parent.IsActive)
  739. {
  740. Dispatcher.UIThread.Post(() =>
  741. {
  742. HandleScreenState();
  743. if (_keyboardInterface.GetKeyboardStateSnapshot().IsPressed(Key.Delete) && _parent.WindowState != WindowState.FullScreen)
  744. {
  745. Ptc.Continue();
  746. }
  747. });
  748. }
  749. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  750. if (_parent.IsActive)
  751. {
  752. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  753. if (currentHotkeyState != _prevHotkeyState)
  754. {
  755. switch (currentHotkeyState)
  756. {
  757. case KeyboardHotkeyState.ToggleVSync:
  758. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  759. break;
  760. case KeyboardHotkeyState.Screenshot:
  761. ScreenshotRequested = true;
  762. break;
  763. case KeyboardHotkeyState.ShowUi:
  764. _parent.ViewModel.ShowMenuAndStatusBar = true;
  765. break;
  766. case KeyboardHotkeyState.Pause:
  767. if (_parent.ViewModel.IsPaused)
  768. {
  769. Resume();
  770. }
  771. else
  772. {
  773. Pause();
  774. }
  775. break;
  776. case KeyboardHotkeyState.ToggleMute:
  777. if (Device.IsAudioMuted())
  778. {
  779. Device.SetVolume(ConfigurationState.Instance.System.AudioVolume);
  780. }
  781. else
  782. {
  783. Device.SetVolume(0);
  784. }
  785. _parent.ViewModel.Volume = Device.GetVolume();
  786. break;
  787. case KeyboardHotkeyState.None:
  788. (_keyboardInterface as AvaloniaKeyboard).Clear();
  789. break;
  790. }
  791. }
  792. _prevHotkeyState = currentHotkeyState;
  793. if (ScreenshotRequested)
  794. {
  795. ScreenshotRequested = false;
  796. _renderer.Screenshot();
  797. }
  798. }
  799. // Touchscreen
  800. bool hasTouch = false;
  801. if (_parent.IsActive && !ConfigurationState.Instance.Hid.EnableMouse)
  802. {
  803. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as AvaloniaMouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  804. }
  805. if (!hasTouch)
  806. {
  807. Device.Hid.Touchscreen.Update();
  808. }
  809. Device.Hid.DebugPad.Update();
  810. return true;
  811. }
  812. private KeyboardHotkeyState GetHotkeyState()
  813. {
  814. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  815. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  816. {
  817. state = KeyboardHotkeyState.ToggleVSync;
  818. }
  819. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot))
  820. {
  821. state = KeyboardHotkeyState.Screenshot;
  822. }
  823. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi))
  824. {
  825. state = KeyboardHotkeyState.ShowUi;
  826. }
  827. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause))
  828. {
  829. state = KeyboardHotkeyState.Pause;
  830. }
  831. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleMute))
  832. {
  833. state = KeyboardHotkeyState.ToggleMute;
  834. }
  835. return state;
  836. }
  837. }
  838. }