WindowBase.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  133. Translator.IsReadyForTranslation.Set();
  134. while (_isActive)
  135. {
  136. if (_isStopped)
  137. {
  138. return;
  139. }
  140. _ticks += _chrono.ElapsedTicks;
  141. _chrono.Restart();
  142. if (Device.WaitFifo())
  143. {
  144. Device.Statistics.RecordFifoStart();
  145. Device.ProcessFrame();
  146. Device.Statistics.RecordFifoEnd();
  147. }
  148. while (Device.ConsumeFrameAvailable())
  149. {
  150. Device.PresentFrame(SwapBuffers);
  151. }
  152. if (_ticks >= _ticksPerFrame)
  153. {
  154. string dockedMode = Device.System.State.DockedMode ? "Docked" : "Handheld";
  155. float scale = Graphics.Gpu.GraphicsConfig.ResScale;
  156. if (scale != 1)
  157. {
  158. dockedMode += $" ({scale}x)";
  159. }
  160. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  161. Device.EnableDeviceVsync,
  162. dockedMode,
  163. Device.Configuration.AspectRatio.ToText(),
  164. $"Game: {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  165. $"FIFO: {Device.Statistics.GetFifoPercent():0.00} %",
  166. $"GPU: {_gpuVendorName}"));
  167. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  168. }
  169. }
  170. });
  171. FinalizeRenderer();
  172. }
  173. public void Exit()
  174. {
  175. TouchScreenManager?.Dispose();
  176. NpadManager?.Dispose();
  177. if (_isStopped)
  178. {
  179. return;
  180. }
  181. _gpuCancellationTokenSource.Cancel();
  182. _isStopped = true;
  183. _isActive = false;
  184. _exitEvent.WaitOne();
  185. _exitEvent.Dispose();
  186. }
  187. public void MainLoop()
  188. {
  189. while (_isActive)
  190. {
  191. UpdateFrame();
  192. SDL_PumpEvents();
  193. // Polling becomes expensive if it's not slept
  194. Thread.Sleep(1);
  195. }
  196. _exitEvent.Set();
  197. }
  198. private void NVStutterWorkaround()
  199. {
  200. while (_isActive)
  201. {
  202. // When NVIDIA Threaded Optimization is on, the driver will snapshot all threads in the system whenever the application creates any new ones.
  203. // The ThreadPool has something called a "GateThread" which terminates itself after some inactivity.
  204. // However, it immediately starts up again, since the rules regarding when to terminate and when to start differ.
  205. // This creates a new thread every second or so.
  206. // The main problem with this is that the thread snapshot can take 70ms, is on the OpenGL thread and will delay rendering any graphics.
  207. // This is a little over budget on a frame time of 16ms, so creates a large stutter.
  208. // The solution is to keep the ThreadPool active so that it never has a reason to terminate the GateThread.
  209. // TODO: This should be removed when the issue with the GateThread is resolved.
  210. ThreadPool.QueueUserWorkItem((state) => { });
  211. Thread.Sleep(300);
  212. }
  213. }
  214. private bool UpdateFrame()
  215. {
  216. if (!_isActive)
  217. {
  218. return true;
  219. }
  220. if (_isStopped)
  221. {
  222. return false;
  223. }
  224. NpadManager.Update();
  225. // Touchscreen
  226. bool hasTouch = false;
  227. // Get screen touch position
  228. if (!_enableMouse)
  229. {
  230. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as SDL2MouseDriver).IsButtonPressed(MouseButton.Button1), _aspectRatio.ToFloat());
  231. }
  232. if (!hasTouch)
  233. {
  234. TouchScreenManager.Update(false);
  235. }
  236. Device.Hid.DebugPad.Update();
  237. return true;
  238. }
  239. public void Execute()
  240. {
  241. _chrono.Restart();
  242. _isActive = true;
  243. InitializeWindow();
  244. Thread renderLoopThread = new Thread(Render)
  245. {
  246. Name = "GUI.RenderLoop"
  247. };
  248. renderLoopThread.Start();
  249. Thread nvStutterWorkaround = null;
  250. if (Renderer is Graphics.OpenGL.Renderer)
  251. {
  252. nvStutterWorkaround = new Thread(NVStutterWorkaround)
  253. {
  254. Name = "GUI.NVStutterWorkaround"
  255. };
  256. nvStutterWorkaround.Start();
  257. }
  258. MainLoop();
  259. renderLoopThread.Join();
  260. nvStutterWorkaround?.Join();
  261. Exit();
  262. }
  263. public bool DisplayInputDialog(SoftwareKeyboardUiArgs args, out string userText)
  264. {
  265. // SDL2 doesn't support input dialogs
  266. userText = "Ryujinx";
  267. return true;
  268. }
  269. public bool DisplayMessageDialog(string title, string message)
  270. {
  271. SDL_ShowSimpleMessageBox(SDL_MessageBoxFlags.SDL_MESSAGEBOX_INFORMATION, title, message, WindowHandle);
  272. return true;
  273. }
  274. public bool DisplayMessageDialog(ControllerAppletUiArgs args)
  275. {
  276. string playerCount = args.PlayerCountMin == args.PlayerCountMax ? $"exactly {args.PlayerCountMin}" : $"{args.PlayerCountMin}-{args.PlayerCountMax}";
  277. string message = $"Application requests {playerCount} player(s) with:\n\n"
  278. + $"TYPES: {args.SupportedStyles}\n\n"
  279. + $"PLAYERS: {string.Join(", ", args.SupportedPlayers)}\n\n"
  280. + (args.IsDocked ? "Docked mode set. Handheld is also invalid.\n\n" : "")
  281. + "Please reconfigure Input now and then press OK.";
  282. return DisplayMessageDialog("Controller Applet", message);
  283. }
  284. public IDynamicTextInputHandler CreateDynamicTextInputHandler()
  285. {
  286. return new HeadlessDynamicTextInputHandler();
  287. }
  288. public void ExecuteProgram(Switch device, ProgramSpecifyKind kind, ulong value)
  289. {
  290. device.Configuration.UserChannelPersistence.ExecuteProgram(kind, value);
  291. Exit();
  292. }
  293. public bool DisplayErrorAppletDialog(string title, string message, string[] buttonsText)
  294. {
  295. SDL_MessageBoxData data = new SDL_MessageBoxData
  296. {
  297. title = title,
  298. message = message,
  299. buttons = new SDL_MessageBoxButtonData[buttonsText.Length],
  300. numbuttons = buttonsText.Length,
  301. window = WindowHandle
  302. };
  303. for (int i = 0; i < buttonsText.Length; i++)
  304. {
  305. data.buttons[i] = new SDL_MessageBoxButtonData
  306. {
  307. buttonid = i,
  308. text = buttonsText[i]
  309. };
  310. }
  311. SDL_ShowMessageBox(ref data, out int _);
  312. return true;
  313. }
  314. public void Dispose()
  315. {
  316. Dispose(true);
  317. }
  318. protected virtual void Dispose(bool disposing)
  319. {
  320. if (disposing)
  321. {
  322. _isActive = false;
  323. TouchScreenManager?.Dispose();
  324. NpadManager.Dispose();
  325. SDL2Driver.Instance.UnregisterWindow(_windowId);
  326. SDL_DestroyWindow(WindowHandle);
  327. SDL2Driver.Instance.Dispose();
  328. }
  329. }
  330. }
  331. }