AimHandler.cs 13 KB

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