motion_input.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <cmath>
  4. #include "common/math_util.h"
  5. #include "core/hid/motion_input.h"
  6. namespace Core::HID {
  7. MotionInput::MotionInput() {
  8. // Initialize PID constants with default values
  9. SetPID(0.3f, 0.005f, 0.0f);
  10. SetGyroThreshold(ThresholdStandard);
  11. ResetQuaternion();
  12. ResetRotations();
  13. }
  14. void MotionInput::SetPID(f32 new_kp, f32 new_ki, f32 new_kd) {
  15. kp = new_kp;
  16. ki = new_ki;
  17. kd = new_kd;
  18. }
  19. void MotionInput::SetAcceleration(const Common::Vec3f& acceleration) {
  20. accel = acceleration;
  21. accel.x = std::clamp(accel.x, -AccelMaxValue, AccelMaxValue);
  22. accel.y = std::clamp(accel.y, -AccelMaxValue, AccelMaxValue);
  23. accel.z = std::clamp(accel.z, -AccelMaxValue, AccelMaxValue);
  24. }
  25. void MotionInput::SetGyroscope(const Common::Vec3f& gyroscope) {
  26. gyro = gyroscope - gyro_bias;
  27. gyro.x = std::clamp(gyro.x, -GyroMaxValue, GyroMaxValue);
  28. gyro.y = std::clamp(gyro.y, -GyroMaxValue, GyroMaxValue);
  29. gyro.z = std::clamp(gyro.z, -GyroMaxValue, GyroMaxValue);
  30. // Auto adjust gyro_bias to minimize drift
  31. if (!IsMoving(IsAtRestRelaxed)) {
  32. gyro_bias = (gyro_bias * 0.9999f) + (gyroscope * 0.0001f);
  33. }
  34. // Adjust drift when calibration mode is enabled
  35. if (calibration_mode) {
  36. gyro_bias = (gyro_bias * 0.99f) + (gyroscope * 0.01f);
  37. StopCalibration();
  38. }
  39. if (gyro.Length() < gyro_threshold * user_gyro_threshold) {
  40. gyro = {};
  41. } else {
  42. only_accelerometer = false;
  43. }
  44. }
  45. void MotionInput::SetQuaternion(const Common::Quaternion<f32>& quaternion) {
  46. quat = quaternion;
  47. }
  48. void MotionInput::SetEulerAngles(const Common::Vec3f& euler_angles) {
  49. const float cr = std::cos(euler_angles.x * 0.5f);
  50. const float sr = std::sin(euler_angles.x * 0.5f);
  51. const float cp = std::cos(euler_angles.y * 0.5f);
  52. const float sp = std::sin(euler_angles.y * 0.5f);
  53. const float cy = std::cos(euler_angles.z * 0.5f);
  54. const float sy = std::sin(euler_angles.z * 0.5f);
  55. quat.w = cr * cp * cy + sr * sp * sy;
  56. quat.xyz.x = sr * cp * cy - cr * sp * sy;
  57. quat.xyz.y = cr * sp * cy + sr * cp * sy;
  58. quat.xyz.z = cr * cp * sy - sr * sp * cy;
  59. }
  60. void MotionInput::SetGyroBias(const Common::Vec3f& bias) {
  61. gyro_bias = bias;
  62. }
  63. void MotionInput::SetGyroThreshold(f32 threshold) {
  64. gyro_threshold = threshold;
  65. }
  66. void MotionInput::SetUserGyroThreshold(f32 threshold) {
  67. user_gyro_threshold = threshold / ThresholdStandard;
  68. }
  69. void MotionInput::EnableReset(bool reset) {
  70. reset_enabled = reset;
  71. }
  72. void MotionInput::ResetRotations() {
  73. rotations = {};
  74. }
  75. void MotionInput::ResetQuaternion() {
  76. quat = {{0.0f, 0.0f, -1.0f}, 0.0f};
  77. }
  78. bool MotionInput::IsMoving(f32 sensitivity) const {
  79. return gyro.Length() >= sensitivity || accel.Length() <= 0.9f || accel.Length() >= 1.1f;
  80. }
  81. bool MotionInput::IsCalibrated(f32 sensitivity) const {
  82. return real_error.Length() < sensitivity;
  83. }
  84. void MotionInput::UpdateRotation(u64 elapsed_time) {
  85. const auto sample_period = static_cast<f32>(elapsed_time) / 1000000.0f;
  86. if (sample_period > 0.1f) {
  87. return;
  88. }
  89. rotations += gyro * sample_period;
  90. }
  91. void MotionInput::Calibrate() {
  92. calibration_mode = true;
  93. calibration_counter = 0;
  94. }
  95. void MotionInput::StopCalibration() {
  96. if (calibration_counter++ > CalibrationSamples) {
  97. calibration_mode = false;
  98. ResetQuaternion();
  99. ResetRotations();
  100. }
  101. }
  102. // Based on Madgwick's implementation of Mayhony's AHRS algorithm.
  103. // https://github.com/xioTechnologies/Open-Source-AHRS-With-x-IMU/blob/master/x-IMU%20IMU%20and%20AHRS%20Algorithms/x-IMU%20IMU%20and%20AHRS%20Algorithms/AHRS/MahonyAHRS.cs
  104. void MotionInput::UpdateOrientation(u64 elapsed_time) {
  105. if (!IsCalibrated(0.1f)) {
  106. ResetOrientation();
  107. }
  108. // Short name local variable for readability
  109. f32 q1 = quat.w;
  110. f32 q2 = quat.xyz[0];
  111. f32 q3 = quat.xyz[1];
  112. f32 q4 = quat.xyz[2];
  113. const auto sample_period = static_cast<f32>(elapsed_time) / 1000000.0f;
  114. // Ignore invalid elapsed time
  115. if (sample_period > 0.1f) {
  116. return;
  117. }
  118. const auto normal_accel = accel.Normalized();
  119. auto rad_gyro = gyro * Common::PI * 2;
  120. const f32 swap = rad_gyro.x;
  121. rad_gyro.x = rad_gyro.y;
  122. rad_gyro.y = -swap;
  123. rad_gyro.z = -rad_gyro.z;
  124. // Clear gyro values if there is no gyro present
  125. if (only_accelerometer) {
  126. rad_gyro.x = 0;
  127. rad_gyro.y = 0;
  128. rad_gyro.z = 0;
  129. }
  130. // Ignore drift correction if acceleration is not reliable
  131. if (accel.Length() >= 0.75f && accel.Length() <= 1.25f) {
  132. const f32 ax = -normal_accel.x;
  133. const f32 ay = normal_accel.y;
  134. const f32 az = -normal_accel.z;
  135. // Estimated direction of gravity
  136. const f32 vx = 2.0f * (q2 * q4 - q1 * q3);
  137. const f32 vy = 2.0f * (q1 * q2 + q3 * q4);
  138. const f32 vz = q1 * q1 - q2 * q2 - q3 * q3 + q4 * q4;
  139. // Error is cross product between estimated direction and measured direction of gravity
  140. const Common::Vec3f new_real_error = {
  141. az * vx - ax * vz,
  142. ay * vz - az * vy,
  143. ax * vy - ay * vx,
  144. };
  145. derivative_error = new_real_error - real_error;
  146. real_error = new_real_error;
  147. // Prevent integral windup
  148. if (ki != 0.0f && !IsCalibrated(0.05f)) {
  149. integral_error += real_error;
  150. } else {
  151. integral_error = {};
  152. }
  153. // Apply feedback terms
  154. if (!only_accelerometer) {
  155. rad_gyro += kp * real_error;
  156. rad_gyro += ki * integral_error;
  157. rad_gyro += kd * derivative_error;
  158. } else {
  159. // Give more weight to accelerometer values to compensate for the lack of gyro
  160. rad_gyro += 35.0f * kp * real_error;
  161. rad_gyro += 10.0f * ki * integral_error;
  162. rad_gyro += 10.0f * kd * derivative_error;
  163. // Emulate gyro values for games that need them
  164. gyro.x = -rad_gyro.y;
  165. gyro.y = rad_gyro.x;
  166. gyro.z = -rad_gyro.z;
  167. UpdateRotation(elapsed_time);
  168. }
  169. }
  170. const f32 gx = rad_gyro.y;
  171. const f32 gy = rad_gyro.x;
  172. const f32 gz = rad_gyro.z;
  173. // Integrate rate of change of quaternion
  174. const f32 pa = q2;
  175. const f32 pb = q3;
  176. const f32 pc = q4;
  177. q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * sample_period);
  178. q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * sample_period);
  179. q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * sample_period);
  180. q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * sample_period);
  181. quat.w = q1;
  182. quat.xyz[0] = q2;
  183. quat.xyz[1] = q3;
  184. quat.xyz[2] = q4;
  185. quat = quat.Normalized();
  186. }
  187. std::array<Common::Vec3f, 3> MotionInput::GetOrientation() const {
  188. const Common::Quaternion<float> quad{
  189. .xyz = {-quat.xyz[1], -quat.xyz[0], -quat.w},
  190. .w = -quat.xyz[2],
  191. };
  192. const std::array<float, 16> matrix4x4 = quad.ToMatrix();
  193. return {Common::Vec3f(matrix4x4[0], matrix4x4[1], -matrix4x4[2]),
  194. Common::Vec3f(matrix4x4[4], matrix4x4[5], -matrix4x4[6]),
  195. Common::Vec3f(-matrix4x4[8], -matrix4x4[9], matrix4x4[10])};
  196. }
  197. Common::Vec3f MotionInput::GetAcceleration() const {
  198. return accel;
  199. }
  200. Common::Vec3f MotionInput::GetGyroscope() const {
  201. return gyro;
  202. }
  203. Common::Vec3f MotionInput::GetGyroBias() const {
  204. return gyro_bias;
  205. }
  206. Common::Quaternion<f32> MotionInput::GetQuaternion() const {
  207. return quat;
  208. }
  209. Common::Vec3f MotionInput::GetRotations() const {
  210. return rotations;
  211. }
  212. Common::Vec3f MotionInput::GetEulerAngles() const {
  213. // roll (x-axis rotation)
  214. const float sinr_cosp = 2 * (quat.w * quat.xyz.x + quat.xyz.y * quat.xyz.z);
  215. const float cosr_cosp = 1 - 2 * (quat.xyz.x * quat.xyz.x + quat.xyz.y * quat.xyz.y);
  216. // pitch (y-axis rotation)
  217. const float sinp = std::sqrt(1 + 2 * (quat.w * quat.xyz.y - quat.xyz.x * quat.xyz.z));
  218. const float cosp = std::sqrt(1 - 2 * (quat.w * quat.xyz.y - quat.xyz.x * quat.xyz.z));
  219. // yaw (z-axis rotation)
  220. const float siny_cosp = 2 * (quat.w * quat.xyz.z + quat.xyz.x * quat.xyz.y);
  221. const float cosy_cosp = 1 - 2 * (quat.xyz.y * quat.xyz.y + quat.xyz.z * quat.xyz.z);
  222. return {
  223. std::atan2(sinr_cosp, cosr_cosp),
  224. 2 * std::atan2(sinp, cosp) - Common::PI / 2,
  225. std::atan2(siny_cosp, cosy_cosp),
  226. };
  227. }
  228. void MotionInput::ResetOrientation() {
  229. if (!reset_enabled || only_accelerometer) {
  230. return;
  231. }
  232. if (!IsMoving(IsAtRestRelaxed) && accel.z <= -0.9f) {
  233. ++reset_counter;
  234. if (reset_counter > 900) {
  235. quat.w = 0;
  236. quat.xyz[0] = 0;
  237. quat.xyz[1] = 0;
  238. quat.xyz[2] = -1;
  239. SetOrientationFromAccelerometer();
  240. integral_error = {};
  241. reset_counter = 0;
  242. }
  243. } else {
  244. reset_counter = 0;
  245. }
  246. }
  247. void MotionInput::SetOrientationFromAccelerometer() {
  248. int iterations = 0;
  249. const f32 sample_period = 0.015f;
  250. const auto normal_accel = accel.Normalized();
  251. while (!IsCalibrated(0.01f) && ++iterations < 100) {
  252. // Short name local variable for readability
  253. f32 q1 = quat.w;
  254. f32 q2 = quat.xyz[0];
  255. f32 q3 = quat.xyz[1];
  256. f32 q4 = quat.xyz[2];
  257. Common::Vec3f rad_gyro;
  258. const f32 ax = -normal_accel.x;
  259. const f32 ay = normal_accel.y;
  260. const f32 az = -normal_accel.z;
  261. // Estimated direction of gravity
  262. const f32 vx = 2.0f * (q2 * q4 - q1 * q3);
  263. const f32 vy = 2.0f * (q1 * q2 + q3 * q4);
  264. const f32 vz = q1 * q1 - q2 * q2 - q3 * q3 + q4 * q4;
  265. // Error is cross product between estimated direction and measured direction of gravity
  266. const Common::Vec3f new_real_error = {
  267. az * vx - ax * vz,
  268. ay * vz - az * vy,
  269. ax * vy - ay * vx,
  270. };
  271. derivative_error = new_real_error - real_error;
  272. real_error = new_real_error;
  273. rad_gyro += 10.0f * kp * real_error;
  274. rad_gyro += 5.0f * ki * integral_error;
  275. rad_gyro += 10.0f * kd * derivative_error;
  276. const f32 gx = rad_gyro.y;
  277. const f32 gy = rad_gyro.x;
  278. const f32 gz = rad_gyro.z;
  279. // Integrate rate of change of quaternion
  280. const f32 pa = q2;
  281. const f32 pb = q3;
  282. const f32 pc = q4;
  283. q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * sample_period);
  284. q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * sample_period);
  285. q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * sample_period);
  286. q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * sample_period);
  287. quat.w = q1;
  288. quat.xyz[0] = q2;
  289. quat.xyz[1] = q3;
  290. quat.xyz[2] = q4;
  291. quat = quat.Normalized();
  292. }
  293. }
  294. } // namespace Core::HID