AimHandler.cs 13 KB

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