GLRenderer.cs 18 KB

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