RendererWidgetBase.cs 17 KB

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