AimHandler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. using System;
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine.UI;
  6. using Newtonsoft.Json;
  7. public class AimHandler : MonoBehaviour
  8. {
  9. Transform controlObj {
  10. get {
  11. if (CameraToLook.ins) {
  12. return CameraToLook.ins.transform;
  13. }
  14. return null;
  15. }
  16. }
  17. [SerializeField] Button SetIdentityButton;
  18. [SerializeField] Button MagCalibrationButton;
  19. [SerializeField] Button GyrCalibrationButton;
  20. [SerializeField] Text MagScaleText;
  21. [SerializeField] Text GyrScaleText;
  22. //椭圆对象
  23. [SerializeField] Ellipse ellipseScript;
  24. [SerializeField] GameObject AccObj;
  25. [SerializeField] GameObject MagObj;
  26. [SerializeField] GameObject AMesh;
  27. [SerializeField] Transform DebugTexts;
  28. [SerializeField] Transform DrawImage;
  29. long TimeGap = default;
  30. Vector3 Acc = default;
  31. Vector3 Gyr = default;
  32. Vector3 Mag = default;
  33. o09Axis _9Axis = new o09Axis();
  34. Vector3 cMaxVector = new Vector3(0,0,0);
  35. Vector3 cMinVector = new Vector3(0, 0, 0);
  36. o0MagneticCalibraterEllipsoidFitting MagCalibrater;
  37. o0GyrCalibrater GyrCalibrater;
  38. //陀螺仪校准进度记录
  39. public int gyrCalibrateCompleteCount = 0;
  40. public int gyrCalibrateTotalCount = 300;
  41. long msOld = 0;
  42. public static AimHandler ins;
  43. void Start()
  44. {
  45. ins = this;
  46. BluetoothDispatcher.aim = OnDataReceived;
  47. //初始化
  48. _9Axis.LoadIdentity();
  49. for (var i = 0; i < 9; ++i)
  50. {
  51. _9Axis.Tester.Add(DrawImage.Find(i.ToString()).gameObject.AddComponent<o0UIRawImageTester>());
  52. }
  53. for (var i = 0; i < 15; ++i)
  54. {
  55. _9Axis.TextTester.Add(DebugTexts.transform.Find("Text" + i.ToString()).gameObject.GetComponent<Text>());
  56. }
  57. if (SetIdentityButton)
  58. {
  59. SetIdentityButton.onClick.AddListener(DoIdentity);
  60. }
  61. try
  62. {
  63. string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  64. MagCalibrater = JsonConvert.DeserializeObject<o0MagneticCalibraterEllipsoidFitting>(magDataStr);
  65. }
  66. catch(Exception)
  67. {
  68. MagCalibrater = null;
  69. }
  70. if (MagCalibrater == null)
  71. {
  72. MagCalibrater = new o0MagneticCalibraterEllipsoidFitting();
  73. }
  74. if (MagCalibrationButton)
  75. {
  76. MagCalibrationButton.onClick.AddListener(delegate {
  77. CalibrateMag(!MagCalibrater.Calibration);
  78. });
  79. }
  80. try {
  81. string gyrDataStr = PlayerPrefs.GetString("o0GyrCalibrater");
  82. GyrCalibrater = JsonConvert.DeserializeObject<o0GyrCalibrater>(gyrDataStr);
  83. if (GyrCalibrater._Average != Vector3.zero) GyrScaleText.text = "已校准";
  84. } catch(Exception) {
  85. GyrCalibrater = null;
  86. }
  87. if (GyrCalibrater == null)
  88. {
  89. GyrCalibrater = new o0GyrCalibrater();
  90. }
  91. if (GyrCalibrationButton)
  92. {
  93. GyrCalibrationButton.onClick.AddListener(delegate() {
  94. CalibrateGyr(!GyrCalibrater.Calibration);
  95. });
  96. }
  97. }
  98. public void CalibrateGyr(bool calibration) {
  99. try {
  100. GyrCalibrater.Calibration = calibration;
  101. if (calibration)
  102. {
  103. GyrCalibrationButton.GetComponentInChildren<Text>().text = "停止陀螺仪校准";
  104. }
  105. else
  106. {
  107. GyrCalibrationButton.GetComponentInChildren<Text>().text = "开始陀螺仪校准";
  108. PlayerPrefs.SetString("o0GyrCalibrater", JsonConvert.SerializeObject(GyrCalibrater));
  109. }
  110. } catch (Exception e) { Debug.LogError(e.Message); }
  111. }
  112. public void CalibrateMag(bool calibration) {
  113. try {
  114. if (calibration)
  115. {
  116. MagCalibrater.Calibration = calibration;
  117. MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  118. this.cMaxVector = new Vector3(0, 0, 0);
  119. this.cMinVector = new Vector3(0, 0, 0);
  120. this.ellipseScript.ellipseTran.gameObject.SetActive(false);
  121. }
  122. else
  123. {
  124. List<Vector3> list = MagCalibrater.getRecords();
  125. //停止校准时候,看看数组值
  126. float maxDistance = 0f,ratio = 1f;
  127. Vector3 maxVector3 = new Vector3(0,0,0);
  128. List<Vector3> endRecords = new List<Vector3>();
  129. foreach (Vector3 i in list)
  130. {
  131. Vector3 v = i - MagCalibrater._Center;
  132. if (Math.Abs(v.magnitude) > maxDistance)
  133. {
  134. maxVector3 = v;
  135. maxDistance = Math.Abs(v.magnitude);
  136. if(Math.Abs(v.magnitude) < Math.Abs(MagCalibrater._Radius.magnitude))
  137. ratio = Math.Abs(v.magnitude) / Math.Abs(MagCalibrater._Radius.magnitude);
  138. else
  139. ratio = Math.Abs(MagCalibrater._Radius.magnitude) / Math.Abs(v.magnitude);
  140. }
  141. }
  142. Debug.LogWarning(maxDistance + " == " + Math.Abs(MagCalibrater._Radius.magnitude) + " == " + MagCalibrater._Radius + " = " + maxVector3);
  143. //如果比例效果不理想。可以设置为ratio=0.5f
  144. foreach (Vector3 i in list)
  145. {
  146. //- MagCalibrater._Center
  147. Vector3 v = i ;
  148. v *= ratio;
  149. if(endRecords.Count>3000)
  150. {
  151. endRecords.RemoveAt(0);
  152. }
  153. endRecords.Add(v);
  154. }
  155. this.ellipseScript.ClearAndUpdatePointArray();
  156. this.ellipseScript.DrawPointCloud(endRecords);
  157. this.ellipseScript.ellipseTran.gameObject.SetActive(true);
  158. //绘制椭圆形
  159. if (MagCalibrater._Radius != this.ellipseScript.ellipseTran.localScale)
  160. {
  161. this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center* ratio);
  162. //设置绘制图像相机的对应位置
  163. this.ellipseScript.setCameraPos(MagCalibrater._Center * 0.5f);
  164. }
  165. MagCalibrater.Calibration = calibration;
  166. MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  167. PlayerPrefs.SetString("o0MagneticCalibrater", JsonConvert.SerializeObject(MagCalibrater));
  168. }
  169. } catch (Exception e) { Debug.LogError(e.Message); }
  170. }
  171. //转换读取的数据,无符号->有符号
  172. float TwoByteToFloat(byte b1, byte b2)
  173. {
  174. ushort twoByte = (ushort) (b1 * 256 + b2);
  175. short shortNum = (short) twoByte;
  176. return (float) shortNum;
  177. }
  178. public void OnDataReceived(byte[] bytes)
  179. {
  180. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  181. if (bytes.Length != 27)
  182. {
  183. if (bytes.Length == 2)
  184. {
  185. DeviceBatteryView.ins.RenderBattery(1, bytes[0]);
  186. return;
  187. }
  188. if (bytes.Length > 3 && bytes[3] == 125)
  189. {
  190. DoIdentity();
  191. }
  192. return;
  193. }
  194. if (bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0 && bytes[10] == 0 && bytes[11] == 0 && bytes[12] == 0)
  195. return;
  196. if (bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0 && bytes[22] == 0 && bytes[23] == 0 && bytes[24] == 0)
  197. return;
  198. float ax = -TwoByteToFloat(bytes[7], bytes[8]);
  199. float ay = TwoByteToFloat(bytes[9], bytes[10]);
  200. float az = -TwoByteToFloat(bytes[11], bytes[12]);
  201. ax = ax / 32768 * 16;
  202. ay = ay / 32768 * 16;
  203. az = az / 32768 * 16;
  204. Acc = new Vector3(ax, ay, az);
  205. AccObj.transform.GetChild(0).localPosition = Acc;
  206. float roll = TwoByteToFloat(bytes[13], bytes[14]);
  207. float pitch = TwoByteToFloat(bytes[15], bytes[16]);
  208. float yaw = TwoByteToFloat(bytes[17], bytes[18]);
  209. roll = -roll / 32768 * 2000;
  210. pitch = pitch / 32768 * 2000;
  211. yaw = -yaw / 32768 * 2000;
  212. Gyr = new Vector3(roll, pitch, yaw) / 1000;
  213. Gyr = GyrCalibrater.Update(Gyr);
  214. if (GyrCalibrater.Calibration)
  215. {
  216. if (gyrCalibrateCompleteCount < gyrCalibrateTotalCount) {
  217. gyrCalibrateCompleteCount++;
  218. }
  219. }
  220. if (GyrScaleText && GyrCalibrater.Calibration)
  221. {
  222. // GyrScaleText.text = GyrCalibrater._Average.x + "\n" + GyrCalibrater._Average.y + "\n" + GyrCalibrater._Average.z;
  223. // GyrScaleText.text = "Gyr*1000,000:" + (_9Axis.GyrOld * 1000000).ToString();
  224. GyrScaleText.text = "" + (_9Axis.GyrOld * 1000000).ToString();
  225. }
  226. float x = TwoByteToFloat(bytes[19], bytes[20]);
  227. float y = TwoByteToFloat(bytes[21], bytes[22]);
  228. float z = -TwoByteToFloat(bytes[23], bytes[24]);
  229. var mag = new Vector3(x, y, z);
  230. Mag = mag / 32768 * 256;
  231. if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  232. {
  233. //绘制地磁计点
  234. if (MagCalibrater.Calibration)
  235. {
  236. this.ellipseScript.AddAndUpdatePointArray(Mag);
  237. if (Mag.magnitude > this.cMaxVector.magnitude)
  238. {
  239. this.cMaxVector = Mag;
  240. }
  241. else if (Mag.magnitude < this.cMinVector.magnitude) {
  242. this.cMinVector = Mag;
  243. }
  244. Vector3 _center = this.cMaxVector - this.cMinVector;
  245. Debug.LogWarning(_center + " == "+ _center.magnitude);
  246. //设置绘制图像相机的对应位置
  247. this.ellipseScript.setCameraPos(_center/2);
  248. }
  249. Mag = MagCalibrater.Update(Mag);
  250. if (MagScaleText)
  251. {
  252. MagScaleText.text = MagCalibrater._Radius.ToString();
  253. }
  254. }
  255. MagObj.transform.GetChild(0).localPosition = Mag;
  256. var ms = (((long)bytes[1]) *60 + bytes[2])*1000 + (long)TwoByteToFloat(bytes[3], bytes[4]);
  257. if(msOld == default)
  258. {
  259. msOld = ms;
  260. return;
  261. }
  262. TimeGap = ms - msOld;
  263. msOld = ms;
  264. AMesh.transform.localRotation = newRotation = _9Axis.Update(Acc * 10, Gyr, Mag, TimeGap);
  265. // 记录一些旋转角---start
  266. if (ArmBow.ins) {
  267. for (int i = ArmBow.ins.recordRotations.Length - 1; i > 0 ; i--)
  268. {
  269. ArmBow.ins.recordRotations[i] = ArmBow.ins.recordRotations[i - 1];
  270. }
  271. ArmBow.ins.recordRotations[0] = newRotation;
  272. ArmBow.ins.recordCount++;
  273. }
  274. // 记录一些旋转角---end
  275. }
  276. public bool lerpForRotation = true;
  277. public void Update()
  278. {
  279. if (controlObj)
  280. {
  281. if (lerpForRotation)
  282. {
  283. controlObj.localRotation = Quaternion.Lerp(controlObj.localRotation, newRotation, Time.deltaTime * 8);
  284. }
  285. else
  286. {
  287. controlObj.localRotation = newRotation;
  288. }
  289. }
  290. }
  291. Quaternion newRotation = Quaternion.identity;
  292. public void DoIdentity()
  293. {
  294. _9Axis.SetIdentity();
  295. if (controlObj) controlObj.localRotation = _9Axis.States.Last().Qua;
  296. }
  297. }