GLRenderer.cs 22 KB

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