AppHost.cs 44 KB

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