GLRenderer.cs 21 KB

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