GLRenderer.cs 21 KB

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