GLRenderer.cs 25 KB

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