AimHandler.cs 12 KB

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