WindowBase.cs 15 KB

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