WindowBase.cs 17 KB

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