Axis9Handler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using System;
  2. using UnityEngine;
  3. using System.Collections;
  4. using Newtonsoft.Json;
  5. using System.Reflection;
  6. public class Axis9Handler : AxisBaseHandler
  7. {
  8. private o0.Bow.o09AxisAfterXiaMenFromDll _9Axis;
  9. private AttitudeJson attitudeJson = new AttitudeJson();
  10. /*
  11. public o0.Geometry.Vector<int> GyrByteIndex = new o0.Geometry.Vector<int>(3, -2, 1);
  12. public o0.Geometry.Vector<int> AccByteIndex = new o0.Geometry.Vector<int>(3, -2, 1);
  13. public o0.Geometry.Vector<int> MagByteIndex = new o0.Geometry.Vector<int>(-3, 2, 1);/**///9轴 usb向上 pcb向左 电池向右
  14. public o0.Geometry.Vector<int> GyrByteIndex = new o0.Geometry.Vector<int>(-3, -2, -1);
  15. public o0.Geometry.Vector<int> AccByteIndex = new o0.Geometry.Vector<int>(-3, -2, -1);
  16. public o0.Geometry.Vector<int> MagByteIndex = new o0.Geometry.Vector<int>(3, 2, -1);/**///9轴 usb向上 pcb向右 电池向左
  17. public Axis9Handler(AimHandler aimHandler) : base(aimHandler) {}
  18. public override void Init()
  19. {
  20. CommonConfig.devicePlan = 3;
  21. _9Axis = new o0.Bow.o09AxisAfterXiaMenFromDll(GyrByteIndex, AccByteIndex, MagByteIndex);
  22. _9Axis.Attitude = new o0.IMU._9AxisPreProcessor(GyrByteIndex, AccByteIndex, MagByteIndex);
  23. LoadIdentity();
  24. Debug.Log("9轴启动成功(首次初始化)");
  25. PrintAxisInfo();
  26. }
  27. public override void Update(byte[] bytes)
  28. {
  29. if (_9Axis.Attitude.GyrCalibrate)
  30. {
  31. if (m_aimHandler.gyrCalibrateCompleteCount < m_aimHandler.gyrCalibrateTotalCount)
  32. {
  33. m_aimHandler.gyrCalibrateCompleteCount++;
  34. }
  35. }
  36. o0.Geometry.Quaternion Qua = o0.Geometry.Quaternion.Identity;
  37. try
  38. {
  39. lock (_9Axis)
  40. Qua = _9Axis.Update(new byte[] { bytes[13], bytes[14], bytes[15], bytes[16], bytes[17], bytes[18] },
  41. new byte[] { bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12] },
  42. new byte[] { bytes[19], bytes[20], bytes[21], bytes[22], bytes[23], bytes[24] },
  43. bytes[1], bytes[2], bytes[3], bytes[4]);/**///9轴
  44. }
  45. catch (Exception e) {
  46. Debug.LogError(e.Message);
  47. Debug.LogError(e.StackTrace);
  48. }
  49. m_aimHandler.SetNewRotation(Qua);
  50. }
  51. public override void DoIdentity()
  52. {
  53. if (_9Axis.States.Count == 0) return; //没数据时触发视角归位会产生NAN,从而导致算法崩坏
  54. SetIdentityAndSave();
  55. m_aimHandler.SetNewRotation(_9Axis.getLastState().Qua);
  56. }
  57. public override void NotifyAxisOnShot()
  58. {
  59. _9Axis.OnShot(100, 100, 100000);
  60. }
  61. public override void CalibrateGyr(bool calibration) {
  62. try {
  63. _9Axis.Attitude.GyrCalibrate = calibration;
  64. } catch (Exception) {}
  65. }
  66. public override void ResetGyr() {
  67. _9Axis.Attitude.GyrCalibrate = true;
  68. _9Axis.Attitude.GyrCalibrate = false;
  69. Debug.Log("陀螺仪校准结果主动重置!");
  70. }
  71. public override void ResetMag() {
  72. _SaveOldMag();
  73. _9Axis.Attitude.MagCalibrater = new o0.IMU.MagnetometerAutoCalibrater(0.001d);
  74. Debug.Log("地磁计校准结果主动重置!");
  75. }
  76. private string _oldEllipsoidFitting = "{\"Center\":[-3.0443925790756605,-3.6882526269162423,-0.9424965068421579],\"CorrectMatrixArray\":[[0.2584454016577151,0.00410177628600846,0.005727574526798527],[0.00410177628600846,0.2639115667519193,-0.03866026824619133],[0.005727574526798523,-0.03866026824619133,0.23912157876854007]],\"Radius\":[4.764270274783962,3.854047926765827,3.4233050788114037]}";
  77. private double _oldVariance = 0.000362;
  78. private void _SaveOldMag()
  79. {
  80. if (!_9Axis.Attitude.MagCalibrater.Complete) return;
  81. _oldVariance = _9Axis.Attitude.MagCalibrater.Variance;
  82. _oldEllipsoidFitting = attitudeJson.Stringify(_9Axis.Attitude.MagCalibrater.EllipsoidFitting);
  83. }
  84. //应用不精准地磁数据,为让客户不地磁校准成功也能动
  85. public override void ApplyImpreciseMag()
  86. {
  87. if (_9Axis.Attitude.MagCalibrater.Complete) return;
  88. // _9Axis.Attitude.MagCalibrater.Lock = true;
  89. // _9Axis.Attitude.MagCalibrater.Init();
  90. // _9Axis.Attitude.MagCalibrater.EllipsoidFitting = attitudeJson.Parse<o0.IMU.EllipsoidFitting>(_oldEllipsoidFitting);
  91. // _9Axis.Attitude.MagCalibrater.Variance = _oldVariance;
  92. //2023-3-27 改为拉取服务器数据
  93. UserComp.Instance.saveMac();
  94. }
  95. public override bool IsGyrCompleted() {
  96. return _9Axis.Attitude.GyrCalibrater.Count > 0;
  97. }
  98. public override bool IsMagCompleted() {
  99. return _9Axis.Attitude.MagCalibrater.Complete;
  100. }
  101. public override IEnumerator SaveGyr() {
  102. yield return null;
  103. SaveCalibrateRecord();
  104. }
  105. public override IEnumerator SaveMag() {
  106. yield return null;
  107. SaveCalibrateRecord();
  108. }
  109. private void SaveCalibrateRecord()
  110. {
  111. try
  112. {
  113. SideTipView.ShowTip("开始序列化九轴数据", Color.white);
  114. string record = attitudeJson.Stringify(_9Axis.Attitude);
  115. if (!string.IsNullOrEmpty(record))
  116. {
  117. SideTipView.ShowTip($"九轴数据序列化完成(长度{record.Length})\nGyrMeanLen:{_9Axis.Attitude.GyrCalibrater.Mean.Length}\nMagVariance:{_9Axis.Attitude.MagCalibrater.Variance}", Color.white);
  118. Debug.Log("9轴数据序列化成功");
  119. if (!IsGyrCompleted()) {
  120. SideTipView.ShowTip("陀螺仪未校准,因校准数据不完整无法上传!", Color.yellow);
  121. return;
  122. }
  123. if (!IsMagCompleted()) {
  124. SideTipView.ShowTip("地磁计未校准,因校准数据不完整无法上传!", Color.yellow);
  125. return;
  126. }
  127. UserComp.Instance.saveCalibrateRecord(record);
  128. SideTipView.ShowTip("正在上传九轴数据", Color.white);
  129. }
  130. }
  131. catch (Exception e)
  132. {
  133. Debug.LogError(e.Message);
  134. Debug.LogError(e.StackTrace);
  135. }
  136. }
  137. public override void ResumeCalibrateRecord(string record)
  138. {
  139. try
  140. {
  141. SideTipView.ShowTip($"成功加载服务端的九轴数据(长度{record.Length})", Color.white);
  142. _9Axis.Attitude = attitudeJson.Parse<o0.IMU._9AxisPreProcessor>(record);
  143. Debug.Log("9轴反序列化完成");
  144. SideTipView.ShowTip($"九轴数据恢复成功\nGyrMeanLen:{_9Axis.Attitude.GyrCalibrater.Mean.Length}\nMagVariance:{_9Axis.Attitude.MagCalibrater.Variance}", Color.white);
  145. PrintAxisInfo();
  146. if (!IsAxisRight())
  147. {
  148. _9Axis.Attitude = new o0.IMU._9AxisPreProcessor(GyrByteIndex, AccByteIndex, MagByteIndex);
  149. Debug.Log("跟保存的轴向不相同,重置校准记录!");
  150. SideTipView.ShowTip("跟保存的轴向不相同,重置校准记录!", Color.yellow);
  151. PrintAxisInfo();
  152. }
  153. Debug.Log("9轴数据恢复结果: " + _9Axis.Attitude.MagCalibrater.Complete);
  154. }
  155. catch (Exception e)
  156. {
  157. Debug.LogError(e.Message);
  158. Debug.LogError(e.StackTrace);
  159. }
  160. m_aimHandler.CorrectMagCompleted(_9Axis.Attitude.MagCalibrater.Complete);
  161. }
  162. //判断轴向是否正确
  163. private bool IsAxisRight()
  164. {
  165. object o = _9Axis.Attitude;
  166. Type t = o.GetType();
  167. var _gyr = t.GetField("GyrByteIndex", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(o);
  168. var _acc = t.GetField("AccByteIndex", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(o);
  169. var _mag = t.GetField("MagByteIndex", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(o);
  170. bool gyrEqual = GyrByteIndex.Equals(_gyr);
  171. bool accEqual = AccByteIndex.Equals(_acc);
  172. bool magEqual = MagByteIndex.Equals(_mag);
  173. return gyrEqual && accEqual && magEqual;
  174. }
  175. //打印当前轴向
  176. public void PrintAxisInfo()
  177. {
  178. object o = _9Axis.Attitude;
  179. Type t = o.GetType();
  180. var _gyr = t.GetField("GyrByteIndex", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(o);
  181. var _acc = t.GetField("AccByteIndex", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(o);
  182. var _mag = t.GetField("MagByteIndex", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(o);
  183. Debug.Log($"当前轴向:gyr:{_gyr.ToString()} acc:{_acc.ToString()} mag:{_mag.ToString()}");
  184. Debug.Log("当前轴向是否正确:" + IsAxisRight());
  185. }
  186. #region 视角归位-恢复和保存
  187. private void LoadIdentity()
  188. {
  189. try {
  190. string accStr = PlayerPrefs.GetString("AccIdentity0", "");
  191. if (accStr.Length > 0) {
  192. double[] arr = JsonConvert.DeserializeObject<double[]>(accStr);
  193. var v = new o0.Geometry.Vector<double>(arr);
  194. if (!double.IsNaN(v.x) && !double.IsInfinity(v.x)
  195. && !double.IsNaN(v.y) && !double.IsInfinity(v.y)
  196. && !double.IsNaN(v.z) && !double.IsInfinity(v.z)
  197. ) {
  198. o0.Bow.o09AxisAfterXiaMenFromDll.AccIdentity = v;
  199. }
  200. }
  201. string magStr = PlayerPrefs.GetString("MagIdentity0", "");
  202. if (magStr.Length > 0) {
  203. double[] arr = JsonConvert.DeserializeObject<double[]>(magStr);
  204. var v = new o0.Geometry.Vector<double>(arr);
  205. if (!double.IsNaN(v.x) && !double.IsInfinity(v.x)
  206. && !double.IsNaN(v.y) && !double.IsInfinity(v.y)
  207. && !double.IsNaN(v.z) && !double.IsInfinity(v.z)
  208. ) {
  209. o0.Bow.o09AxisAfterXiaMenFromDll.MagIdentity = v;
  210. }
  211. }
  212. } catch (System.Exception e) {
  213. Debug.LogError(e.Message);
  214. Debug.LogError(e.StackTrace);
  215. }
  216. }
  217. private void SetIdentityAndSave()
  218. {
  219. _9Axis.SetIdentity();
  220. //save
  221. var a = o0.Bow.o09AxisAfterXiaMenFromDll.AccIdentity;
  222. var m = o0.Bow.o09AxisAfterXiaMenFromDll.MagIdentity;
  223. PlayerPrefs.SetString("AccIdentity0", JsonConvert.SerializeObject(new double[]{
  224. a.x, a.y, a.z
  225. }));
  226. PlayerPrefs.SetString("MagIdentity0",JsonConvert.SerializeObject(new double[]{
  227. m.x, m.y, m.z
  228. }));
  229. }
  230. #endregion
  231. }