WindowBase.cs 14 KB

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