RendererWidgetBase.cs 19 KB

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