WindowBase.cs 14 KB

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