GLRenderer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 bool IsActive { get; set; }
  25. public bool IsStopped { get; set; }
  26. public bool IsFocused { get; set; }
  27. private double _mouseX;
  28. private double _mouseY;
  29. private bool _mousePressed;
  30. private bool _titleEvent;
  31. private bool _toggleFullscreen;
  32. private string _newTitle;
  33. private readonly long _ticksPerFrame;
  34. private long _ticks = 0;
  35. private System.Diagnostics.Stopwatch _chrono;
  36. private Switch _device;
  37. private Renderer _renderer;
  38. private HotkeyButtons _prevHotkeyButtons = 0;
  39. private Input.NpadController _primaryController;
  40. public GLRenderer(Switch device)
  41. : base (new GraphicsMode(new ColorFormat()),
  42. 3, 3,
  43. GraphicsContextFlags.ForwardCompatible)
  44. {
  45. WaitEvent = new ManualResetEvent(false);
  46. _device = device;
  47. this.Initialized += GLRenderer_Initialized;
  48. this.Destroyed += GLRenderer_Destroyed;
  49. this.ShuttingDown += GLRenderer_ShuttingDown;
  50. Initialize();
  51. _chrono = new System.Diagnostics.Stopwatch();
  52. _ticksPerFrame = System.Diagnostics.Stopwatch.Frequency / TargetFps;
  53. _primaryController = new Input.NpadController(ConfigurationState.Instance.Hid.JoystickControls);
  54. AddEvents((int)(Gdk.EventMask.ButtonPressMask
  55. | Gdk.EventMask.ButtonReleaseMask
  56. | Gdk.EventMask.PointerMotionMask
  57. | Gdk.EventMask.KeyPressMask
  58. | Gdk.EventMask.KeyReleaseMask));
  59. this.Shown += Renderer_Shown;
  60. }
  61. private void GLRenderer_ShuttingDown(object sender, EventArgs args)
  62. {
  63. _device.DisposeGpu();
  64. }
  65. private void Parent_FocusOutEvent(object o, Gtk.FocusOutEventArgs args)
  66. {
  67. IsFocused = false;
  68. }
  69. private void Parent_FocusInEvent(object o, Gtk.FocusInEventArgs args)
  70. {
  71. IsFocused = true;
  72. }
  73. private void GLRenderer_Destroyed(object sender, EventArgs e)
  74. {
  75. Dispose();
  76. }
  77. protected void Renderer_Shown(object sender, EventArgs e)
  78. {
  79. IsFocused = this.ParentWindow.State.HasFlag(Gdk.WindowState.Focused);
  80. }
  81. public void HandleScreenState(KeyboardState keyboard)
  82. {
  83. bool toggleFullscreen = keyboard.IsKeyDown(OpenTK.Input.Key.F11)
  84. || ((keyboard.IsKeyDown(OpenTK.Input.Key.AltLeft)
  85. || keyboard.IsKeyDown(OpenTK.Input.Key.AltRight))
  86. && keyboard.IsKeyDown(OpenTK.Input.Key.Enter))
  87. || keyboard.IsKeyDown(OpenTK.Input.Key.Escape);
  88. bool fullScreenToggled = ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen);
  89. if (toggleFullscreen != _toggleFullscreen)
  90. {
  91. if (toggleFullscreen)
  92. {
  93. if (fullScreenToggled)
  94. {
  95. ParentWindow.Unfullscreen();
  96. (Toplevel as MainWindow)?.ToggleExtraWidgets(true);
  97. }
  98. else
  99. {
  100. if (keyboard.IsKeyDown(OpenTK.Input.Key.Escape))
  101. {
  102. Exit();
  103. }
  104. else
  105. {
  106. ParentWindow.Fullscreen();
  107. (Toplevel as MainWindow)?.ToggleExtraWidgets(false);
  108. }
  109. }
  110. }
  111. }
  112. _toggleFullscreen = toggleFullscreen;
  113. }
  114. private void GLRenderer_Initialized(object sender, EventArgs e)
  115. {
  116. // Release the GL exclusivity that OpenTK gave us as we aren't going to use it in GTK Thread.
  117. GraphicsContext.MakeCurrent(null);
  118. WaitEvent.Set();
  119. }
  120. protected override bool OnConfigureEvent(EventConfigure evnt)
  121. {
  122. var result = base.OnConfigureEvent(evnt);
  123. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  124. _renderer.Window.SetSize(evnt.Width * monitor.ScaleFactor, evnt.Height * monitor.ScaleFactor);
  125. return result;
  126. }
  127. public void Start()
  128. {
  129. IsRenderHandler = true;
  130. _chrono.Restart();
  131. IsActive = true;
  132. Gtk.Window parent = this.Toplevel as Gtk.Window;
  133. parent.FocusInEvent += Parent_FocusInEvent;
  134. parent.FocusOutEvent += Parent_FocusOutEvent;
  135. Gtk.Application.Invoke(delegate
  136. {
  137. parent.Present();
  138. });
  139. Thread renderLoopThread = new Thread(Render)
  140. {
  141. Name = "GUI.RenderLoop"
  142. };
  143. renderLoopThread.Start();
  144. MainLoop();
  145. renderLoopThread.Join();
  146. Exit();
  147. }
  148. protected override bool OnButtonPressEvent(EventButton evnt)
  149. {
  150. _mouseX = evnt.X;
  151. _mouseY = evnt.Y;
  152. if (evnt.Button == 1)
  153. {
  154. _mousePressed = true;
  155. }
  156. return false;
  157. }
  158. protected override bool OnButtonReleaseEvent(EventButton evnt)
  159. {
  160. if (evnt.Button == 1)
  161. {
  162. _mousePressed = false;
  163. }
  164. return false;
  165. }
  166. protected override bool OnMotionNotifyEvent(EventMotion evnt)
  167. {
  168. if (evnt.Device.InputSource == InputSource.Mouse)
  169. {
  170. _mouseX = evnt.X;
  171. _mouseY = evnt.Y;
  172. }
  173. return false;
  174. }
  175. protected override void OnGetPreferredHeight(out int minimumHeight, out int naturalHeight)
  176. {
  177. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  178. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  179. if (monitor.Geometry.Height >= 1080)
  180. {
  181. minimumHeight = SwitchPanelHeight;
  182. }
  183. // Otherwise, we default minimal size to 480p 16:9.
  184. else
  185. {
  186. minimumHeight = 480;
  187. }
  188. naturalHeight = minimumHeight;
  189. }
  190. protected override void OnGetPreferredWidth(out int minimumWidth, out int naturalWidth)
  191. {
  192. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  193. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  194. if (monitor.Geometry.Height >= 1080)
  195. {
  196. minimumWidth = SwitchPanelWidth;
  197. }
  198. // Otherwise, we default minimal size to 480p 16:9.
  199. else
  200. {
  201. minimumWidth = 854;
  202. }
  203. naturalWidth = minimumWidth;
  204. }
  205. public void Exit()
  206. {
  207. if (IsStopped)
  208. {
  209. return;
  210. }
  211. IsStopped = true;
  212. IsActive = false;
  213. }
  214. public void Initialize()
  215. {
  216. if (!(_device.Gpu.Renderer is Renderer))
  217. {
  218. throw new NotSupportedException($"GPU renderer must be an OpenGL renderer when using GLRenderer!");
  219. }
  220. _renderer = (Renderer)_device.Gpu.Renderer;
  221. }
  222. public void Render()
  223. {
  224. // First take exclusivity on the OpenGL context.
  225. GraphicsContext.MakeCurrent(WindowInfo);
  226. _renderer.Initialize();
  227. // Make sure the first frame is not transparent.
  228. GL.ClearColor(OpenTK.Color.Black);
  229. GL.Clear(ClearBufferMask.ColorBufferBit);
  230. SwapBuffers();
  231. while (IsActive)
  232. {
  233. if (IsStopped)
  234. {
  235. return;
  236. }
  237. _ticks += _chrono.ElapsedTicks;
  238. _chrono.Restart();
  239. if (_device.WaitFifo())
  240. {
  241. _device.ProcessFrame();
  242. }
  243. if (_ticks >= _ticksPerFrame)
  244. {
  245. _device.PresentFrame(SwapBuffers);
  246. _device.Statistics.RecordSystemFrameTime();
  247. double hostFps = _device.Statistics.GetSystemFrameRate();
  248. double gameFps = _device.Statistics.GetGameFrameRate();
  249. string titleNameSection = string.IsNullOrWhiteSpace(_device.System.TitleName) ? string.Empty
  250. : " | " + _device.System.TitleName;
  251. string titleIdSection = string.IsNullOrWhiteSpace(_device.System.TitleIdText) ? string.Empty
  252. : " | " + _device.System.TitleIdText.ToUpper();
  253. _newTitle = $"Ryujinx {Program.Version}{titleNameSection}{titleIdSection} | Host FPS: {hostFps:0.0} | Game FPS: {gameFps:0.0} | " +
  254. $"Game Vsync: {(_device.EnableDeviceVsync ? "On" : "Off")}";
  255. _titleEvent = true;
  256. _device.System.SignalVsync();
  257. _device.VsyncEvent.Set();
  258. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  259. }
  260. }
  261. }
  262. public void SwapBuffers()
  263. {
  264. OpenTK.Graphics.GraphicsContext.CurrentContext.SwapBuffers();
  265. }
  266. public void MainLoop()
  267. {
  268. while (IsActive)
  269. {
  270. if (_titleEvent)
  271. {
  272. _titleEvent = false;
  273. Gtk.Application.Invoke(delegate
  274. {
  275. this.ParentWindow.Title = _newTitle;
  276. });
  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. }