RendererWidgetBase.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. using ARMeilleure.Translation;
  2. using ARMeilleure.Translation.PTC;
  3. using Gdk;
  4. using Gtk;
  5. using Ryujinx.Common;
  6. using Ryujinx.Common.Configuration;
  7. using Ryujinx.Configuration;
  8. using Ryujinx.Graphics.GAL;
  9. using Ryujinx.HLE.HOS.Services.Hid;
  10. using Ryujinx.Input;
  11. using Ryujinx.Input.GTK3;
  12. using Ryujinx.Input.HLE;
  13. using Ryujinx.Ui.Widgets;
  14. using System;
  15. using System.Diagnostics;
  16. using System.Linq;
  17. using System.Threading;
  18. namespace Ryujinx.Ui
  19. {
  20. using Key = Input.Key;
  21. using Switch = HLE.Switch;
  22. public abstract class RendererWidgetBase : DrawingArea
  23. {
  24. private const int SwitchPanelWidth = 1280;
  25. private const int SwitchPanelHeight = 720;
  26. private const int TargetFps = 60;
  27. public ManualResetEvent WaitEvent { get; set; }
  28. public NpadManager NpadManager { get; }
  29. public TouchScreenManager TouchScreenManager { get; }
  30. public Switch Device { get; private set; }
  31. public IRenderer Renderer { get; private set; }
  32. public static event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  33. private bool _isActive;
  34. private bool _isStopped;
  35. private bool _toggleFullscreen;
  36. private bool _toggleDockedMode;
  37. private readonly long _ticksPerFrame;
  38. private long _ticks = 0;
  39. private readonly Stopwatch _chrono;
  40. private KeyboardHotkeyState _prevHotkeyState;
  41. private readonly ManualResetEvent _exitEvent;
  42. // Hide Cursor
  43. const int CursorHideIdleTime = 8; // seconds
  44. private static readonly Cursor _invisibleCursor = new Cursor(Display.Default, CursorType.BlankCursor);
  45. private long _lastCursorMoveTime;
  46. private bool _hideCursorOnIdle;
  47. private InputManager _inputManager;
  48. private IKeyboard _keyboardInterface;
  49. private GraphicsDebugLevel _glLogLevel;
  50. private string _gpuVendorName;
  51. private int _windowHeight;
  52. private int _windowWidth;
  53. private bool _isMouseInClient;
  54. public RendererWidgetBase(InputManager inputManager, GraphicsDebugLevel glLogLevel)
  55. {
  56. var mouseDriver = new GTK3MouseDriver(this);
  57. _inputManager = inputManager;
  58. _inputManager.SetMouseDriver(mouseDriver);
  59. NpadManager = _inputManager.CreateNpadManager();
  60. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  61. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  62. WaitEvent = new ManualResetEvent(false);
  63. _glLogLevel = glLogLevel;
  64. Destroyed += Renderer_Destroyed;
  65. _chrono = new Stopwatch();
  66. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  67. AddEvents((int)(EventMask.ButtonPressMask
  68. | EventMask.ButtonReleaseMask
  69. | EventMask.PointerMotionMask
  70. | EventMask.ScrollMask
  71. | EventMask.EnterNotifyMask
  72. | EventMask.LeaveNotifyMask
  73. | EventMask.KeyPressMask
  74. | EventMask.KeyReleaseMask));
  75. _exitEvent = new ManualResetEvent(false);
  76. _hideCursorOnIdle = ConfigurationState.Instance.HideCursorOnIdle;
  77. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  78. ConfigurationState.Instance.HideCursorOnIdle.Event += HideCursorStateChanged;
  79. }
  80. public abstract void InitializeRenderer();
  81. public abstract void SwapBuffers();
  82. public abstract string GetGpuVendorName();
  83. private void HideCursorStateChanged(object sender, ReactiveEventArgs<bool> state)
  84. {
  85. Gtk.Application.Invoke(delegate
  86. {
  87. _hideCursorOnIdle = state.NewValue;
  88. if (_hideCursorOnIdle)
  89. {
  90. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  91. }
  92. else
  93. {
  94. Window.Cursor = null;
  95. }
  96. });
  97. }
  98. private void Renderer_Destroyed(object sender, EventArgs e)
  99. {
  100. ConfigurationState.Instance.HideCursorOnIdle.Event -= HideCursorStateChanged;
  101. Window.Cursor = null;
  102. NpadManager.Dispose();
  103. Dispose();
  104. }
  105. protected override bool OnMotionNotifyEvent(EventMotion evnt)
  106. {
  107. if (_hideCursorOnIdle)
  108. {
  109. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  110. }
  111. if(ConfigurationState.Instance.Hid.EnableMouse)
  112. {
  113. Window.Cursor = _invisibleCursor;
  114. }
  115. _isMouseInClient = true;
  116. return false;
  117. }
  118. protected override bool OnEnterNotifyEvent(EventCrossing evnt)
  119. {
  120. Window.Cursor = ConfigurationState.Instance.Hid.EnableMouse ? _invisibleCursor : null;
  121. _isMouseInClient = true;
  122. return base.OnEnterNotifyEvent(evnt);
  123. }
  124. protected override bool OnLeaveNotifyEvent(EventCrossing evnt)
  125. {
  126. Window.Cursor = null;
  127. _isMouseInClient = false;
  128. return base.OnLeaveNotifyEvent(evnt);
  129. }
  130. protected override void OnGetPreferredHeight(out int minimumHeight, out int naturalHeight)
  131. {
  132. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  133. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  134. if (monitor.Geometry.Height >= 1080)
  135. {
  136. minimumHeight = SwitchPanelHeight;
  137. }
  138. // Otherwise, we default minimal size to 480p 16:9.
  139. else
  140. {
  141. minimumHeight = 480;
  142. }
  143. naturalHeight = minimumHeight;
  144. }
  145. protected override void OnGetPreferredWidth(out int minimumWidth, out int naturalWidth)
  146. {
  147. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  148. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  149. if (monitor.Geometry.Height >= 1080)
  150. {
  151. minimumWidth = SwitchPanelWidth;
  152. }
  153. // Otherwise, we default minimal size to 480p 16:9.
  154. else
  155. {
  156. minimumWidth = 854;
  157. }
  158. naturalWidth = minimumWidth;
  159. }
  160. protected override bool OnConfigureEvent(EventConfigure evnt)
  161. {
  162. bool result = base.OnConfigureEvent(evnt);
  163. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  164. _windowWidth = evnt.Width * monitor.ScaleFactor;
  165. _windowHeight = evnt.Height * monitor.ScaleFactor;
  166. Renderer?.Window.SetSize(_windowWidth, _windowHeight);
  167. return result;
  168. }
  169. private void HandleScreenState(KeyboardStateSnapshot keyboard)
  170. {
  171. bool toggleFullscreen = keyboard.IsPressed(Key.F11)
  172. || ((keyboard.IsPressed(Key.AltLeft)
  173. || keyboard.IsPressed(Key.AltRight))
  174. && keyboard.IsPressed(Key.Enter))
  175. || keyboard.IsPressed(Key.Escape);
  176. bool fullScreenToggled = ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen);
  177. if (toggleFullscreen != _toggleFullscreen)
  178. {
  179. if (toggleFullscreen)
  180. {
  181. if (fullScreenToggled)
  182. {
  183. ParentWindow.Unfullscreen();
  184. (Toplevel as MainWindow)?.ToggleExtraWidgets(true);
  185. }
  186. else
  187. {
  188. if (keyboard.IsPressed(Key.Escape))
  189. {
  190. if (!ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  191. {
  192. Exit();
  193. }
  194. }
  195. else
  196. {
  197. ParentWindow.Fullscreen();
  198. (Toplevel as MainWindow)?.ToggleExtraWidgets(false);
  199. }
  200. }
  201. }
  202. }
  203. _toggleFullscreen = toggleFullscreen;
  204. bool toggleDockedMode = keyboard.IsPressed(Key.F9);
  205. if (toggleDockedMode != _toggleDockedMode)
  206. {
  207. if (toggleDockedMode)
  208. {
  209. ConfigurationState.Instance.System.EnableDockedMode.Value =
  210. !ConfigurationState.Instance.System.EnableDockedMode.Value;
  211. }
  212. }
  213. _toggleDockedMode = toggleDockedMode;
  214. if (_hideCursorOnIdle && !ConfigurationState.Instance.Hid.EnableMouse)
  215. {
  216. long cursorMoveDelta = Stopwatch.GetTimestamp() - _lastCursorMoveTime;
  217. Window.Cursor = (cursorMoveDelta >= CursorHideIdleTime * Stopwatch.Frequency) ? _invisibleCursor : null;
  218. }
  219. if(ConfigurationState.Instance.Hid.EnableMouse && _isMouseInClient)
  220. {
  221. Window.Cursor = _invisibleCursor;
  222. }
  223. }
  224. public void Initialize(Switch device)
  225. {
  226. Device = device;
  227. Renderer = Device.Gpu.Renderer;
  228. Renderer?.Window.SetSize(_windowWidth, _windowHeight);
  229. NpadManager.Initialize(device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  230. TouchScreenManager.Initialize(device);
  231. }
  232. public void Render()
  233. {
  234. Gtk.Window parent = Toplevel as Gtk.Window;
  235. parent.Present();
  236. InitializeRenderer();
  237. Device.Gpu.Renderer.Initialize(_glLogLevel);
  238. _gpuVendorName = GetGpuVendorName();
  239. Device.Gpu.InitializeShaderCache();
  240. Translator.IsReadyForTranslation.Set();
  241. while (_isActive)
  242. {
  243. if (_isStopped)
  244. {
  245. return;
  246. }
  247. _ticks += _chrono.ElapsedTicks;
  248. _chrono.Restart();
  249. if (Device.WaitFifo())
  250. {
  251. Device.Statistics.RecordFifoStart();
  252. Device.ProcessFrame();
  253. Device.Statistics.RecordFifoEnd();
  254. }
  255. while (Device.ConsumeFrameAvailable())
  256. {
  257. Device.PresentFrame(SwapBuffers);
  258. }
  259. if (_ticks >= _ticksPerFrame)
  260. {
  261. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? "Docked" : "Handheld";
  262. float scale = Graphics.Gpu.GraphicsConfig.ResScale;
  263. if (scale != 1)
  264. {
  265. dockedMode += $" ({scale}x)";
  266. }
  267. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  268. Device.EnableDeviceVsync,
  269. dockedMode,
  270. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  271. $"Game: {Device.Statistics.GetGameFrameRate():00.00} FPS",
  272. $"FIFO: {Device.Statistics.GetFifoPercent():0.00} %",
  273. $"GPU: {_gpuVendorName}"));
  274. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  275. }
  276. }
  277. }
  278. public void Start()
  279. {
  280. _chrono.Restart();
  281. _isActive = true;
  282. Gtk.Window parent = Toplevel as Gtk.Window;
  283. Application.Invoke(delegate
  284. {
  285. parent.Present();
  286. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName) ? string.Empty
  287. : $" - {Device.Application.TitleName}";
  288. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion) ? string.Empty
  289. : $" v{Device.Application.DisplayVersion}";
  290. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText) ? string.Empty
  291. : $" ({Device.Application.TitleIdText.ToUpper()})";
  292. string titleArchSection = Device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  293. parent.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  294. });
  295. Thread renderLoopThread = new Thread(Render)
  296. {
  297. Name = "GUI.RenderLoop"
  298. };
  299. renderLoopThread.Start();
  300. Thread nvStutterWorkaround = new Thread(NVStutterWorkaround)
  301. {
  302. Name = "GUI.NVStutterWorkaround"
  303. };
  304. nvStutterWorkaround.Start();
  305. MainLoop();
  306. renderLoopThread.Join();
  307. nvStutterWorkaround.Join();
  308. Exit();
  309. }
  310. public void Exit()
  311. {
  312. TouchScreenManager?.Dispose();
  313. NpadManager?.Dispose();
  314. if (_isStopped)
  315. {
  316. return;
  317. }
  318. _isStopped = true;
  319. _isActive = false;
  320. _exitEvent.WaitOne();
  321. _exitEvent.Dispose();
  322. }
  323. private void NVStutterWorkaround()
  324. {
  325. while (_isActive)
  326. {
  327. // When NVIDIA Threaded Optimization is on, the driver will snapshot all threads in the system whenever the application creates any new ones.
  328. // The ThreadPool has something called a "GateThread" which terminates itself after some inactivity.
  329. // However, it immediately starts up again, since the rules regarding when to terminate and when to start differ.
  330. // This creates a new thread every second or so.
  331. // The main problem with this is that the thread snapshot can take 70ms, is on the OpenGL thread and will delay rendering any graphics.
  332. // This is a little over budget on a frame time of 16ms, so creates a large stutter.
  333. // The solution is to keep the ThreadPool active so that it never has a reason to terminate the GateThread.
  334. // TODO: This should be removed when the issue with the GateThread is resolved.
  335. ThreadPool.QueueUserWorkItem((state) => { });
  336. Thread.Sleep(300);
  337. }
  338. }
  339. public void MainLoop()
  340. {
  341. while (_isActive)
  342. {
  343. UpdateFrame();
  344. // Polling becomes expensive if it's not slept
  345. Thread.Sleep(1);
  346. }
  347. _exitEvent.Set();
  348. }
  349. private bool UpdateFrame()
  350. {
  351. if (!_isActive)
  352. {
  353. return true;
  354. }
  355. if (_isStopped)
  356. {
  357. return false;
  358. }
  359. if ((Toplevel as MainWindow).IsFocused)
  360. {
  361. Application.Invoke(delegate
  362. {
  363. KeyboardStateSnapshot keyboard = _keyboardInterface.GetKeyboardStateSnapshot();
  364. HandleScreenState(keyboard);
  365. if (keyboard.IsPressed(Key.Delete))
  366. {
  367. if (!ParentWindow.State.HasFlag(WindowState.Fullscreen))
  368. {
  369. Ptc.Continue();
  370. }
  371. }
  372. });
  373. }
  374. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  375. if ((Toplevel as MainWindow).IsFocused)
  376. {
  377. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  378. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync) &&
  379. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync))
  380. {
  381. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  382. }
  383. _prevHotkeyState = currentHotkeyState;
  384. }
  385. // Touchscreen
  386. bool hasTouch = false;
  387. // Get screen touch position
  388. if ((Toplevel as MainWindow).IsFocused && !ConfigurationState.Instance.Hid.EnableMouse)
  389. {
  390. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as GTK3MouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  391. }
  392. if (!hasTouch)
  393. {
  394. TouchScreenManager.Update(false);
  395. }
  396. Device.Hid.DebugPad.Update();
  397. return true;
  398. }
  399. [Flags]
  400. private enum KeyboardHotkeyState
  401. {
  402. None,
  403. ToggleVSync
  404. }
  405. private KeyboardHotkeyState GetHotkeyState()
  406. {
  407. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  408. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  409. {
  410. state |= KeyboardHotkeyState.ToggleVSync;
  411. }
  412. return state;
  413. }
  414. }
  415. }