AppHost.cs 41 KB

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