GLRenderer.cs 21 KB

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