WindowBase.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. using ARMeilleure.Translation;
  2. using Ryujinx.Common.Configuration;
  3. using Ryujinx.Common.Configuration.Hid;
  4. using Ryujinx.Common.Logging;
  5. using Ryujinx.Graphics.GAL;
  6. using Ryujinx.Graphics.GAL.Multithreading;
  7. using Ryujinx.HLE.HOS.Applets;
  8. using Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy.Types;
  9. using Ryujinx.HLE.Ui;
  10. using Ryujinx.Input;
  11. using Ryujinx.Input.HLE;
  12. using Ryujinx.SDL2.Common;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Diagnostics;
  16. using System.Threading;
  17. using static SDL2.SDL;
  18. using Switch = Ryujinx.HLE.Switch;
  19. namespace Ryujinx.Headless.SDL2
  20. {
  21. abstract class WindowBase : IHostUiHandler, IDisposable
  22. {
  23. protected const int DefaultWidth = 1280;
  24. protected const int DefaultHeight = 720;
  25. private const SDL_WindowFlags DefaultFlags = SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI | SDL_WindowFlags.SDL_WINDOW_RESIZABLE | SDL_WindowFlags.SDL_WINDOW_INPUT_FOCUS | SDL_WindowFlags.SDL_WINDOW_SHOWN;
  26. private const int TargetFps = 60;
  27. public NpadManager NpadManager { get; }
  28. public TouchScreenManager TouchScreenManager { get; }
  29. public Switch Device { get; private set; }
  30. public IRenderer Renderer { get; private set; }
  31. public event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  32. protected IntPtr WindowHandle { get; set; }
  33. public IHostUiTheme HostUiTheme { get; }
  34. public int Width { get; private set; }
  35. public int Height { get; private set; }
  36. protected SDL2MouseDriver MouseDriver;
  37. private InputManager _inputManager;
  38. private IKeyboard _keyboardInterface;
  39. private GraphicsDebugLevel _glLogLevel;
  40. private readonly Stopwatch _chrono;
  41. private readonly long _ticksPerFrame;
  42. private readonly CancellationTokenSource _gpuCancellationTokenSource;
  43. private readonly ManualResetEvent _exitEvent;
  44. private long _ticks;
  45. private bool _isActive;
  46. private bool _isStopped;
  47. private uint _windowId;
  48. private string _gpuVendorName;
  49. private AspectRatio _aspectRatio;
  50. private bool _enableMouse;
  51. public WindowBase(InputManager inputManager, GraphicsDebugLevel glLogLevel, AspectRatio aspectRatio, bool enableMouse)
  52. {
  53. MouseDriver = new SDL2MouseDriver();
  54. _inputManager = inputManager;
  55. _inputManager.SetMouseDriver(MouseDriver);
  56. NpadManager = _inputManager.CreateNpadManager();
  57. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  58. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  59. _glLogLevel = glLogLevel;
  60. _chrono = new Stopwatch();
  61. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  62. _gpuCancellationTokenSource = new CancellationTokenSource();
  63. _exitEvent = new ManualResetEvent(false);
  64. _aspectRatio = aspectRatio;
  65. _enableMouse = enableMouse;
  66. HostUiTheme = new HeadlessHostUiTheme();
  67. SDL2Driver.Instance.Initialize();
  68. }
  69. public void Initialize(Switch device, List<InputConfig> inputConfigs, bool enableKeyboard, bool enableMouse)
  70. {
  71. Device = device;
  72. IRenderer renderer = Device.Gpu.Renderer;
  73. if (renderer is ThreadedRenderer tr)
  74. {
  75. renderer = tr.BaseRenderer;
  76. }
  77. Renderer = renderer;
  78. NpadManager.Initialize(device, inputConfigs, enableKeyboard, enableMouse);
  79. TouchScreenManager.Initialize(device);
  80. }
  81. private void InitializeWindow()
  82. {
  83. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName) ? string.Empty
  84. : $" - {Device.Application.TitleName}";
  85. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion) ? string.Empty
  86. : $" v{Device.Application.DisplayVersion}";
  87. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText) ? string.Empty
  88. : $" ({Device.Application.TitleIdText.ToUpper()})";
  89. string titleArchSection = Device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  90. WindowHandle = SDL_CreateWindow($"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DefaultWidth, DefaultHeight, DefaultFlags | GetWindowFlags());
  91. if (WindowHandle == IntPtr.Zero)
  92. {
  93. string errorMessage = $"SDL_CreateWindow failed with error \"{SDL_GetError()}\"";
  94. Logger.Error?.Print(LogClass.Application, errorMessage);
  95. throw new Exception(errorMessage);
  96. }
  97. _windowId = SDL_GetWindowID(WindowHandle);
  98. SDL2Driver.Instance.RegisterWindow(_windowId, HandleWindowEvent);
  99. Width = DefaultWidth;
  100. Height = DefaultHeight;
  101. }
  102. private void HandleWindowEvent(SDL_Event evnt)
  103. {
  104. if (evnt.type == SDL_EventType.SDL_WINDOWEVENT)
  105. {
  106. switch (evnt.window.windowEvent)
  107. {
  108. case SDL_WindowEventID.SDL_WINDOWEVENT_SIZE_CHANGED:
  109. Width = evnt.window.data1;
  110. Height = evnt.window.data2;
  111. Renderer?.Window.SetSize(Width, Height);
  112. MouseDriver.SetClientSize(Width, Height);
  113. break;
  114. case SDL_WindowEventID.SDL_WINDOWEVENT_CLOSE:
  115. Exit();
  116. break;
  117. default:
  118. break;
  119. }
  120. }
  121. else
  122. {
  123. MouseDriver.Update(evnt);
  124. }
  125. }
  126. protected abstract void InitializeWindowRenderer();
  127. protected abstract void InitializeRenderer();
  128. protected abstract void FinalizeWindowRenderer();
  129. protected abstract void SwapBuffers();
  130. public abstract SDL_WindowFlags GetWindowFlags();
  131. private string GetGpuVendorName()
  132. {
  133. return Renderer.GetHardwareInfo().GpuVendor;
  134. }
  135. public void Render()
  136. {
  137. Device.Gpu.Renderer.RunLoop(() =>
  138. {
  139. Device.Gpu.SetGpuThread();
  140. Device.Gpu.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  141. Translator.IsReadyForTranslation.Set();
  142. while (_isActive)
  143. {
  144. if (_isStopped)
  145. {
  146. return;
  147. }
  148. _ticks += _chrono.ElapsedTicks;
  149. _chrono.Restart();
  150. if (Device.WaitFifo())
  151. {
  152. Device.Statistics.RecordFifoStart();
  153. Device.ProcessFrame();
  154. Device.Statistics.RecordFifoEnd();
  155. }
  156. while (Device.ConsumeFrameAvailable())
  157. {
  158. Device.PresentFrame(SwapBuffers);
  159. }
  160. if (_ticks >= _ticksPerFrame)
  161. {
  162. string dockedMode = Device.System.State.DockedMode ? "Docked" : "Handheld";
  163. float scale = Graphics.Gpu.GraphicsConfig.ResScale;
  164. if (scale != 1)
  165. {
  166. dockedMode += $" ({scale}x)";
  167. }
  168. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  169. Device.EnableDeviceVsync,
  170. dockedMode,
  171. Device.Configuration.AspectRatio.ToText(),
  172. $"Game: {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  173. $"FIFO: {Device.Statistics.GetFifoPercent():0.00} %",
  174. $"GPU: {_gpuVendorName}"));
  175. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  176. }
  177. }
  178. });
  179. FinalizeWindowRenderer();
  180. }
  181. public void Exit()
  182. {
  183. TouchScreenManager?.Dispose();
  184. NpadManager?.Dispose();
  185. if (_isStopped)
  186. {
  187. return;
  188. }
  189. _gpuCancellationTokenSource.Cancel();
  190. _isStopped = true;
  191. _isActive = false;
  192. _exitEvent.WaitOne();
  193. _exitEvent.Dispose();
  194. }
  195. public void MainLoop()
  196. {
  197. while (_isActive)
  198. {
  199. UpdateFrame();
  200. SDL_PumpEvents();
  201. // Polling becomes expensive if it's not slept
  202. Thread.Sleep(1);
  203. }
  204. _exitEvent.Set();
  205. }
  206. private void NVStutterWorkaround()
  207. {
  208. while (_isActive)
  209. {
  210. // When NVIDIA Threaded Optimization is on, the driver will snapshot all threads in the system whenever the application creates any new ones.
  211. // The ThreadPool has something called a "GateThread" which terminates itself after some inactivity.
  212. // However, it immediately starts up again, since the rules regarding when to terminate and when to start differ.
  213. // This creates a new thread every second or so.
  214. // The main problem with this is that the thread snapshot can take 70ms, is on the OpenGL thread and will delay rendering any graphics.
  215. // This is a little over budget on a frame time of 16ms, so creates a large stutter.
  216. // The solution is to keep the ThreadPool active so that it never has a reason to terminate the GateThread.
  217. // TODO: This should be removed when the issue with the GateThread is resolved.
  218. ThreadPool.QueueUserWorkItem((state) => { });
  219. Thread.Sleep(300);
  220. }
  221. }
  222. private bool UpdateFrame()
  223. {
  224. if (!_isActive)
  225. {
  226. return true;
  227. }
  228. if (_isStopped)
  229. {
  230. return false;
  231. }
  232. NpadManager.Update();
  233. // Touchscreen
  234. bool hasTouch = false;
  235. // Get screen touch position
  236. if (!_enableMouse)
  237. {
  238. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as SDL2MouseDriver).IsButtonPressed(MouseButton.Button1), _aspectRatio.ToFloat());
  239. }
  240. if (!hasTouch)
  241. {
  242. TouchScreenManager.Update(false);
  243. }
  244. Device.Hid.DebugPad.Update();
  245. return true;
  246. }
  247. public void Execute()
  248. {
  249. _chrono.Restart();
  250. _isActive = true;
  251. InitializeWindow();
  252. InitializeWindowRenderer();
  253. Device.Gpu.Renderer.Initialize(_glLogLevel);
  254. InitializeRenderer();
  255. _gpuVendorName = GetGpuVendorName();
  256. Thread renderLoopThread = new Thread(Render)
  257. {
  258. Name = "GUI.RenderLoop"
  259. };
  260. renderLoopThread.Start();
  261. Thread nvStutterWorkaround = null;
  262. if (Renderer is Graphics.OpenGL.OpenGLRenderer)
  263. {
  264. nvStutterWorkaround = new Thread(NVStutterWorkaround)
  265. {
  266. Name = "GUI.NVStutterWorkaround"
  267. };
  268. nvStutterWorkaround.Start();
  269. }
  270. MainLoop();
  271. renderLoopThread.Join();
  272. nvStutterWorkaround?.Join();
  273. Exit();
  274. }
  275. public bool DisplayInputDialog(SoftwareKeyboardUiArgs args, out string userText)
  276. {
  277. // SDL2 doesn't support input dialogs
  278. userText = "Ryujinx";
  279. return true;
  280. }
  281. public bool DisplayMessageDialog(string title, string message)
  282. {
  283. SDL_ShowSimpleMessageBox(SDL_MessageBoxFlags.SDL_MESSAGEBOX_INFORMATION, title, message, WindowHandle);
  284. return true;
  285. }
  286. public bool DisplayMessageDialog(ControllerAppletUiArgs args)
  287. {
  288. string playerCount = args.PlayerCountMin == args.PlayerCountMax ? $"exactly {args.PlayerCountMin}" : $"{args.PlayerCountMin}-{args.PlayerCountMax}";
  289. string message = $"Application requests {playerCount} player(s) with:\n\n"
  290. + $"TYPES: {args.SupportedStyles}\n\n"
  291. + $"PLAYERS: {string.Join(", ", args.SupportedPlayers)}\n\n"
  292. + (args.IsDocked ? "Docked mode set. Handheld is also invalid.\n\n" : "")
  293. + "Please reconfigure Input now and then press OK.";
  294. return DisplayMessageDialog("Controller Applet", message);
  295. }
  296. public IDynamicTextInputHandler CreateDynamicTextInputHandler()
  297. {
  298. return new HeadlessDynamicTextInputHandler();
  299. }
  300. public void ExecuteProgram(Switch device, ProgramSpecifyKind kind, ulong value)
  301. {
  302. device.Configuration.UserChannelPersistence.ExecuteProgram(kind, value);
  303. Exit();
  304. }
  305. public bool DisplayErrorAppletDialog(string title, string message, string[] buttonsText)
  306. {
  307. SDL_MessageBoxData data = new SDL_MessageBoxData
  308. {
  309. title = title,
  310. message = message,
  311. buttons = new SDL_MessageBoxButtonData[buttonsText.Length],
  312. numbuttons = buttonsText.Length,
  313. window = WindowHandle
  314. };
  315. for (int i = 0; i < buttonsText.Length; i++)
  316. {
  317. data.buttons[i] = new SDL_MessageBoxButtonData
  318. {
  319. buttonid = i,
  320. text = buttonsText[i]
  321. };
  322. }
  323. SDL_ShowMessageBox(ref data, out int _);
  324. return true;
  325. }
  326. public void Dispose()
  327. {
  328. Dispose(true);
  329. }
  330. protected virtual void Dispose(bool disposing)
  331. {
  332. if (disposing)
  333. {
  334. _isActive = false;
  335. TouchScreenManager?.Dispose();
  336. NpadManager.Dispose();
  337. SDL2Driver.Instance.UnregisterWindow(_windowId);
  338. SDL_DestroyWindow(WindowHandle);
  339. SDL2Driver.Instance.Dispose();
  340. }
  341. }
  342. }
  343. }