MotionInput.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using Ryujinx.Input.Motion;
  2. using System;
  3. using System.Numerics;
  4. namespace Ryujinx.Input
  5. {
  6. public class MotionInput
  7. {
  8. public ulong TimeStamp { get; set; }
  9. public Vector3 Accelerometer { get; set; }
  10. public Vector3 Gyroscrope { get; set; }
  11. public Vector3 Rotation { get; set; }
  12. private readonly MotionSensorFilter _filter;
  13. private int _calibrationFrame = 0;
  14. public MotionInput()
  15. {
  16. TimeStamp = 0;
  17. Accelerometer = new Vector3();
  18. Gyroscrope = new Vector3();
  19. Rotation = new Vector3();
  20. // TODO: RE the correct filter.
  21. _filter = new MotionSensorFilter(0f);
  22. }
  23. public void Update(Vector3 accel, Vector3 gyro, ulong timestamp, int sensitivity, float deadzone)
  24. {
  25. if (TimeStamp != 0)
  26. {
  27. if (gyro.Length() <= 1f && accel.Length() >= 0.8f && accel.Z >= 0.8f)
  28. {
  29. _calibrationFrame++;
  30. if (_calibrationFrame >= 90)
  31. {
  32. gyro = Vector3.Zero;
  33. Rotation = Vector3.Zero;
  34. _filter.Reset();
  35. _calibrationFrame = 0;
  36. }
  37. }
  38. else
  39. {
  40. _calibrationFrame = 0;
  41. }
  42. Accelerometer = -accel;
  43. if (gyro.Length() < deadzone)
  44. {
  45. gyro = Vector3.Zero;
  46. }
  47. gyro *= (sensitivity / 100f);
  48. Gyroscrope = gyro;
  49. float deltaTime = MathF.Abs((long)(timestamp - TimeStamp) / 1000000f);
  50. Vector3 deltaGyro = gyro * deltaTime;
  51. Rotation += deltaGyro;
  52. _filter.SamplePeriod = deltaTime;
  53. _filter.Update(accel, DegreeToRad(gyro));
  54. }
  55. TimeStamp = timestamp;
  56. }
  57. public Matrix4x4 GetOrientation()
  58. {
  59. return Matrix4x4.CreateFromQuaternion(_filter.Quaternion);
  60. }
  61. private static Vector3 DegreeToRad(Vector3 degree)
  62. {
  63. return degree * (MathF.PI / 180);
  64. }
  65. }
  66. }