AppHost.cs 41 KB

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