GLRenderer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. using Gdk;
  2. using OpenTK;
  3. using OpenTK.Graphics;
  4. using OpenTK.Graphics.OpenGL;
  5. using OpenTK.Input;
  6. using OpenTK.Platform;
  7. using Ryujinx.Configuration;
  8. using Ryujinx.Graphics.OpenGL;
  9. using Ryujinx.HLE;
  10. using Ryujinx.HLE.Input;
  11. using Ryujinx.Ui;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Text;
  15. using System.Threading;
  16. namespace Ryujinx.Ui
  17. {
  18. public class GLRenderer : GLWidget
  19. {
  20. private const int SwitchPanelWidth = 1280;
  21. private const int SwitchPanelHeight = 720;
  22. private const int TargetFps = 60;
  23. public ManualResetEvent WaitEvent { get; set; }
  24. public static event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  25. public bool IsActive { get; set; }
  26. public bool IsStopped { get; set; }
  27. public bool IsFocused { get; set; }
  28. private double _mouseX;
  29. private double _mouseY;
  30. private bool _mousePressed;
  31. private bool _toggleFullscreen;
  32. private readonly long _ticksPerFrame;
  33. private long _ticks = 0;
  34. private System.Diagnostics.Stopwatch _chrono;
  35. private Switch _device;
  36. private Renderer _renderer;
  37. private HotkeyButtons _prevHotkeyButtons = 0;
  38. private Input.NpadController _primaryController;
  39. public GLRenderer(Switch device)
  40. : base (GetGraphicsMode(),
  41. 3, 3,
  42. GraphicsContextFlags.ForwardCompatible)
  43. {
  44. WaitEvent = new ManualResetEvent(false);
  45. _device = device;
  46. this.Initialized += GLRenderer_Initialized;
  47. this.Destroyed += GLRenderer_Destroyed;
  48. this.ShuttingDown += GLRenderer_ShuttingDown;
  49. Initialize();
  50. _chrono = new System.Diagnostics.Stopwatch();
  51. _ticksPerFrame = System.Diagnostics.Stopwatch.Frequency / TargetFps;
  52. _primaryController = new Input.NpadController(ConfigurationState.Instance.Hid.JoystickControls);
  53. AddEvents((int)(Gdk.EventMask.ButtonPressMask
  54. | Gdk.EventMask.ButtonReleaseMask
  55. | Gdk.EventMask.PointerMotionMask
  56. | Gdk.EventMask.KeyPressMask
  57. | Gdk.EventMask.KeyReleaseMask));
  58. this.Shown += Renderer_Shown;
  59. }
  60. private static GraphicsMode GetGraphicsMode()
  61. {
  62. if (Environment.OSVersion.Platform == PlatformID.Unix)
  63. {
  64. return new GraphicsMode(new ColorFormat(24));
  65. }
  66. return new GraphicsMode(new ColorFormat());
  67. }
  68. private void GLRenderer_ShuttingDown(object sender, EventArgs args)
  69. {
  70. _device.DisposeGpu();
  71. }
  72. private void Parent_FocusOutEvent(object o, Gtk.FocusOutEventArgs args)
  73. {
  74. IsFocused = false;
  75. }
  76. private void Parent_FocusInEvent(object o, Gtk.FocusInEventArgs args)
  77. {
  78. IsFocused = true;
  79. }
  80. private void GLRenderer_Destroyed(object sender, EventArgs e)
  81. {
  82. Dispose();
  83. }
  84. protected void Renderer_Shown(object sender, EventArgs e)
  85. {
  86. IsFocused = this.ParentWindow.State.HasFlag(Gdk.WindowState.Focused);
  87. }
  88. public void HandleScreenState(KeyboardState keyboard)
  89. {
  90. bool toggleFullscreen = keyboard.IsKeyDown(OpenTK.Input.Key.F11)
  91. || ((keyboard.IsKeyDown(OpenTK.Input.Key.AltLeft)
  92. || keyboard.IsKeyDown(OpenTK.Input.Key.AltRight))
  93. && keyboard.IsKeyDown(OpenTK.Input.Key.Enter))
  94. || keyboard.IsKeyDown(OpenTK.Input.Key.Escape);
  95. bool fullScreenToggled = ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen);
  96. if (toggleFullscreen != _toggleFullscreen)
  97. {
  98. if (toggleFullscreen)
  99. {
  100. if (fullScreenToggled)
  101. {
  102. ParentWindow.Unfullscreen();
  103. (Toplevel as MainWindow)?.ToggleExtraWidgets(true);
  104. }
  105. else
  106. {
  107. if (keyboard.IsKeyDown(OpenTK.Input.Key.Escape))
  108. {
  109. Exit();
  110. }
  111. else
  112. {
  113. ParentWindow.Fullscreen();
  114. (Toplevel as MainWindow)?.ToggleExtraWidgets(false);
  115. }
  116. }
  117. }
  118. }
  119. _toggleFullscreen = toggleFullscreen;
  120. }
  121. private void GLRenderer_Initialized(object sender, EventArgs e)
  122. {
  123. // Release the GL exclusivity that OpenTK gave us as we aren't going to use it in GTK Thread.
  124. GraphicsContext.MakeCurrent(null);
  125. WaitEvent.Set();
  126. }
  127. protected override bool OnConfigureEvent(EventConfigure evnt)
  128. {
  129. var result = base.OnConfigureEvent(evnt);
  130. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  131. _renderer.Window.SetSize(evnt.Width * monitor.ScaleFactor, evnt.Height * monitor.ScaleFactor);
  132. return result;
  133. }
  134. public void Start()
  135. {
  136. IsRenderHandler = true;
  137. _chrono.Restart();
  138. IsActive = true;
  139. Gtk.Window parent = this.Toplevel as Gtk.Window;
  140. parent.FocusInEvent += Parent_FocusInEvent;
  141. parent.FocusOutEvent += Parent_FocusOutEvent;
  142. Gtk.Application.Invoke(delegate
  143. {
  144. parent.Present();
  145. string titleNameSection = string.IsNullOrWhiteSpace(_device.System.TitleName) ? string.Empty
  146. : " | " + _device.System.TitleName;
  147. string titleIdSection = string.IsNullOrWhiteSpace(_device.System.TitleIdText) ? string.Empty
  148. : " | " + _device.System.TitleIdText.ToUpper();
  149. parent.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleIdSection}";
  150. });
  151. Thread renderLoopThread = new Thread(Render)
  152. {
  153. Name = "GUI.RenderLoop"
  154. };
  155. renderLoopThread.Start();
  156. MainLoop();
  157. renderLoopThread.Join();
  158. Exit();
  159. }
  160. protected override bool OnButtonPressEvent(EventButton evnt)
  161. {
  162. _mouseX = evnt.X;
  163. _mouseY = evnt.Y;
  164. if (evnt.Button == 1)
  165. {
  166. _mousePressed = true;
  167. }
  168. return false;
  169. }
  170. protected override bool OnButtonReleaseEvent(EventButton evnt)
  171. {
  172. if (evnt.Button == 1)
  173. {
  174. _mousePressed = false;
  175. }
  176. return false;
  177. }
  178. protected override bool OnMotionNotifyEvent(EventMotion evnt)
  179. {
  180. if (evnt.Device.InputSource == InputSource.Mouse)
  181. {
  182. _mouseX = evnt.X;
  183. _mouseY = evnt.Y;
  184. }
  185. return false;
  186. }
  187. protected override void OnGetPreferredHeight(out int minimumHeight, out int naturalHeight)
  188. {
  189. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  190. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  191. if (monitor.Geometry.Height >= 1080)
  192. {
  193. minimumHeight = SwitchPanelHeight;
  194. }
  195. // Otherwise, we default minimal size to 480p 16:9.
  196. else
  197. {
  198. minimumHeight = 480;
  199. }
  200. naturalHeight = minimumHeight;
  201. }
  202. protected override void OnGetPreferredWidth(out int minimumWidth, out int naturalWidth)
  203. {
  204. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  205. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  206. if (monitor.Geometry.Height >= 1080)
  207. {
  208. minimumWidth = SwitchPanelWidth;
  209. }
  210. // Otherwise, we default minimal size to 480p 16:9.
  211. else
  212. {
  213. minimumWidth = 854;
  214. }
  215. naturalWidth = minimumWidth;
  216. }
  217. public void Exit()
  218. {
  219. if (IsStopped)
  220. {
  221. return;
  222. }
  223. IsStopped = true;
  224. IsActive = false;
  225. }
  226. public void Initialize()
  227. {
  228. if (!(_device.Gpu.Renderer is Renderer))
  229. {
  230. throw new NotSupportedException($"GPU renderer must be an OpenGL renderer when using GLRenderer!");
  231. }
  232. _renderer = (Renderer)_device.Gpu.Renderer;
  233. }
  234. public void Render()
  235. {
  236. // First take exclusivity on the OpenGL context.
  237. GraphicsContext.MakeCurrent(WindowInfo);
  238. _renderer.Initialize();
  239. // Make sure the first frame is not transparent.
  240. GL.ClearColor(OpenTK.Color.Black);
  241. GL.Clear(ClearBufferMask.ColorBufferBit);
  242. SwapBuffers();
  243. while (IsActive)
  244. {
  245. if (IsStopped)
  246. {
  247. return;
  248. }
  249. _ticks += _chrono.ElapsedTicks;
  250. _chrono.Restart();
  251. if (_device.WaitFifo())
  252. {
  253. _device.ProcessFrame();
  254. }
  255. if (_ticks >= _ticksPerFrame)
  256. {
  257. _device.PresentFrame(SwapBuffers);
  258. _device.Statistics.RecordSystemFrameTime();
  259. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  260. _device.EnableDeviceVsync,
  261. $"Host: {_device.Statistics.GetSystemFrameRate():00.00} FPS",
  262. $"Game: {_device.Statistics.GetGameFrameRate():00.00} FPS",
  263. $"GPU: {_renderer.GpuVendor}"));
  264. _device.System.SignalVsync();
  265. _device.VsyncEvent.Set();
  266. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  267. }
  268. }
  269. }
  270. public void SwapBuffers()
  271. {
  272. OpenTK.Graphics.GraphicsContext.CurrentContext.SwapBuffers();
  273. }
  274. public void MainLoop()
  275. {
  276. while (IsActive)
  277. {
  278. UpdateFrame();
  279. // Polling becomes expensive if it's not slept
  280. Thread.Sleep(1);
  281. }
  282. }
  283. private bool UpdateFrame()
  284. {
  285. if (!IsActive)
  286. {
  287. return true;
  288. }
  289. if (IsStopped)
  290. {
  291. return false;
  292. }
  293. HotkeyButtons currentHotkeyButtons = 0;
  294. ControllerButtons currentButton = 0;
  295. JoystickPosition leftJoystick;
  296. JoystickPosition rightJoystick;
  297. HLE.Input.Keyboard? hidKeyboard = null;
  298. int leftJoystickDx = 0;
  299. int leftJoystickDy = 0;
  300. int rightJoystickDx = 0;
  301. int rightJoystickDy = 0;
  302. // OpenTK always captures keyboard events, even if out of focus, so check if window is focused.
  303. if (IsFocused)
  304. {
  305. KeyboardState keyboard = OpenTK.Input.Keyboard.GetState();
  306. Gtk.Application.Invoke(delegate
  307. {
  308. HandleScreenState(keyboard);
  309. });
  310. // Normal Input
  311. currentHotkeyButtons = KeyboardControls.GetHotkeyButtons(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  312. currentButton = KeyboardControls.GetButtons(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  313. if (ConfigurationState.Instance.Hid.EnableKeyboard)
  314. {
  315. hidKeyboard = KeyboardControls.GetKeysDown(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  316. }
  317. (leftJoystickDx, leftJoystickDy) = KeyboardControls.GetLeftStick(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  318. (rightJoystickDx, rightJoystickDy) = KeyboardControls.GetRightStick(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  319. }
  320. if (!hidKeyboard.HasValue)
  321. {
  322. hidKeyboard = new HLE.Input.Keyboard
  323. {
  324. Modifier = 0,
  325. Keys = new int[0x8]
  326. };
  327. }
  328. currentButton |= _primaryController.GetButtons();
  329. // Keyboard has priority stick-wise
  330. if (leftJoystickDx == 0 && leftJoystickDy == 0)
  331. {
  332. (leftJoystickDx, leftJoystickDy) = _primaryController.GetLeftStick();
  333. }
  334. if (rightJoystickDx == 0 && rightJoystickDy == 0)
  335. {
  336. (rightJoystickDx, rightJoystickDy) = _primaryController.GetRightStick();
  337. }
  338. leftJoystick = new JoystickPosition
  339. {
  340. Dx = leftJoystickDx,
  341. Dy = leftJoystickDy
  342. };
  343. rightJoystick = new JoystickPosition
  344. {
  345. Dx = rightJoystickDx,
  346. Dy = rightJoystickDy
  347. };
  348. currentButton |= _device.Hid.UpdateStickButtons(leftJoystick, rightJoystick);
  349. bool hasTouch = false;
  350. // Get screen touch position from left mouse click
  351. // OpenTK always captures mouse events, even if out of focus, so check if window is focused.
  352. if (IsFocused && _mousePressed)
  353. {
  354. int screenWidth = AllocatedWidth;
  355. int screenHeight = AllocatedHeight;
  356. if (AllocatedWidth > (AllocatedHeight * SwitchPanelWidth) / SwitchPanelHeight)
  357. {
  358. screenWidth = (AllocatedHeight * SwitchPanelWidth) / SwitchPanelHeight;
  359. }
  360. else
  361. {
  362. screenHeight = (AllocatedWidth * SwitchPanelHeight) / SwitchPanelWidth;
  363. }
  364. int startX = (AllocatedWidth - screenWidth) >> 1;
  365. int startY = (AllocatedHeight - screenHeight) >> 1;
  366. int endX = startX + screenWidth;
  367. int endY = startY + screenHeight;
  368. if (_mouseX >= startX &&
  369. _mouseY >= startY &&
  370. _mouseX < endX &&
  371. _mouseY < endY)
  372. {
  373. int screenMouseX = (int)_mouseX - startX;
  374. int screenMouseY = (int)_mouseY - startY;
  375. int mX = (screenMouseX * SwitchPanelWidth) / screenWidth;
  376. int mY = (screenMouseY * SwitchPanelHeight) / screenHeight;
  377. TouchPoint currentPoint = new TouchPoint
  378. {
  379. X = mX,
  380. Y = mY,
  381. // Placeholder values till more data is acquired
  382. DiameterX = 10,
  383. DiameterY = 10,
  384. Angle = 90
  385. };
  386. hasTouch = true;
  387. _device.Hid.SetTouchPoints(currentPoint);
  388. }
  389. }
  390. if (!hasTouch)
  391. {
  392. _device.Hid.SetTouchPoints();
  393. }
  394. if (ConfigurationState.Instance.Hid.EnableKeyboard && hidKeyboard.HasValue)
  395. {
  396. _device.Hid.WriteKeyboard(hidKeyboard.Value);
  397. }
  398. BaseController controller = _device.Hid.PrimaryController;
  399. controller.SendInput(currentButton, leftJoystick, rightJoystick);
  400. // Toggle vsync
  401. if (currentHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync) &&
  402. !_prevHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync))
  403. {
  404. _device.EnableDeviceVsync = !_device.EnableDeviceVsync;
  405. }
  406. _prevHotkeyButtons = currentHotkeyButtons;
  407. return true;
  408. }
  409. }
  410. }