WindowBase.cs 14 KB

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