AimHandler.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 o0._9Axis;
  8. using o0;
  9. /* 瞄准处理器 */
  10. public class AimHandler : MonoBehaviour
  11. {
  12. Transform controlObj {
  13. get {
  14. if (CameraToLook.ins) {
  15. return CameraToLook.ins.transform;
  16. }
  17. return null;
  18. }
  19. }
  20. [SerializeField] Button SetIdentityButton;
  21. [SerializeField] Button MagCalibrationButton;
  22. [SerializeField] Button GyrCalibrationButton;
  23. [SerializeField] Text MagScaleText;
  24. [SerializeField] Text GyrScaleText;
  25. //椭圆对象
  26. [SerializeField] Ellipse ellipseScript;
  27. [SerializeField] GameObject AccObj;
  28. [SerializeField] GameObject MagObj;
  29. [SerializeField] GameObject AccMesh;
  30. [SerializeField] GameObject GryMesh;
  31. [SerializeField] GameObject MagMesh;
  32. [SerializeField] GameObject AMesh;
  33. [SerializeField] Transform DebugTexts;
  34. [SerializeField] Transform DrawImage;
  35. long TimeGap = default;
  36. Vector3 Acc = default;
  37. Vector3 Gyr = default;
  38. Vector3 Mag = default;
  39. public o09Axis _9Axis = new o09Axis();
  40. Vector3 cMaxVector = new Vector3(0,0,0);
  41. Vector3 cMinVector = new Vector3(0, 0, 0);
  42. [o0.Serialize]
  43. public MagnetometerAutoCalibrater MagCalibrater;
  44. o0GyrCalibrater GyrCalibrater;
  45. //陀螺仪校准进度记录
  46. [NonSerialized] public int gyrCalibrateCompleteCount = 0;
  47. [NonSerialized] public int gyrCalibrateTotalCount = 2000;
  48. [NonSerialized] public long msOld = 0;
  49. public static AimHandler ins;
  50. void Start()
  51. {
  52. ins = this;
  53. BluetoothDispatcher.aim = OnDataReceived;
  54. //初始化
  55. _9Axis.LoadIdentity();
  56. _9Axis.AccMesh = AccMesh;
  57. _9Axis.GryMesh = GryMesh;
  58. _9Axis.MagMesh = MagMesh;
  59. for (var i = 0; i < 9; ++i)
  60. {
  61. _9Axis.Tester.Add(DrawImage.Find(i.ToString()).gameObject.AddComponent<o0UIRawImageTester>());
  62. }
  63. for (var i = 0; i < 15; ++i)
  64. {
  65. _9Axis.TextTester.Add(DebugTexts.transform.Find("Text" + i.ToString()).gameObject.GetComponent<Text>());
  66. }
  67. if (SetIdentityButton)
  68. {
  69. SetIdentityButton.onClick.AddListener(DoIdentity);
  70. }
  71. // try
  72. // {
  73. // string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  74. // MagCalibrater = JsonConvert.DeserializeObject<o0MagneticCalibraterEllipsoidFitting>(magDataStr);
  75. // }
  76. // catch(Exception)
  77. // {
  78. // MagCalibrater = null;
  79. // }
  80. if (MagCalibrater == null)
  81. {
  82. // MagCalibrater = new o0MagneticCalibraterEllipsoidFitting();
  83. MagCalibrater = new MagnetometerAutoCalibrater();
  84. try {
  85. Json.FromJson<MagnetometerAutoCalibrater>(PlayerPrefs.GetString("new_mag_record"), ref MagCalibrater);
  86. } catch (System.Exception) {}
  87. magComplete = MagCalibrater.Complete;
  88. }
  89. if (MagCalibrationButton)
  90. {
  91. MagCalibrationButton.onClick.AddListener(delegate {
  92. // CalibrateMag(!MagCalibrater.Calibration);
  93. });
  94. }
  95. try {
  96. string gyrDataStr = PlayerPrefs.GetString("o0GyrCalibrater");
  97. GyrCalibrater = JsonConvert.DeserializeObject<o0GyrCalibrater>(gyrDataStr);
  98. if (GyrCalibrater._Average != Vector3.zero) GyrScaleText.text = "已校准";
  99. } catch(Exception) {
  100. GyrCalibrater = null;
  101. }
  102. if (GyrCalibrater == null)
  103. {
  104. GyrCalibrater = new o0GyrCalibrater();
  105. }
  106. if (GyrCalibrationButton)
  107. {
  108. GyrCalibrationButton.onClick.AddListener(delegate() {
  109. CalibrateGyr(!GyrCalibrater.Calibration);
  110. });
  111. }
  112. }
  113. public void CalibrateGyr(bool calibration) {
  114. try {
  115. GyrCalibrater.Calibration = calibration;
  116. if (calibration)
  117. {
  118. GyrCalibrationButton.GetComponentInChildren<Text>().text = "停止陀螺仪校准";
  119. }
  120. else
  121. {
  122. GyrCalibrationButton.GetComponentInChildren<Text>().text = "开始陀螺仪校准";
  123. PlayerPrefs.SetString("o0GyrCalibrater", JsonConvert.SerializeObject(GyrCalibrater));
  124. }
  125. } catch (Exception e) { Debug.LogError(e.Message); }
  126. }
  127. [NonSerialized] public bool isCalibrateMagPerfect = false;
  128. public void CalibrateMag(bool calibration) {
  129. // try {
  130. // if (calibration)
  131. // {
  132. // PointCorrector.ins = new PointCorrector(this.ellipseScript, this.MagCalibrater);
  133. // MagCalibrater.Calibration = calibration;
  134. // MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  135. // this.cMaxVector = new Vector3(float.MinValue, float.MinValue, float.MinValue);
  136. // this.cMinVector = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
  137. // this.ellipseScript.ellipseTran.gameObject.SetActive(false);
  138. // }
  139. // else
  140. // {
  141. // PointCorrector.ins = null;
  142. // List<Vector3> list = MagCalibrater.getRecords();
  143. // //停止校准时候,看看数组值
  144. // float maxDistance = 0f,ratio = 1f;
  145. // Vector3 maxVector3 = new Vector3(0,0,0);
  146. // List<Vector3> endRecords = new List<Vector3>();
  147. // foreach (Vector3 i in list)
  148. // {
  149. // Vector3 v = i - MagCalibrater._Center;
  150. // if (Math.Abs(v.magnitude) > maxDistance)
  151. // {
  152. // maxVector3 = v;
  153. // maxDistance = Math.Abs(v.magnitude);
  154. // if(Math.Abs(v.magnitude) < Math.Abs(MagCalibrater._Radius.magnitude))
  155. // ratio = Math.Abs(v.magnitude) / Math.Abs(MagCalibrater._Radius.magnitude);
  156. // else
  157. // ratio = Math.Abs(MagCalibrater._Radius.magnitude) / Math.Abs(v.magnitude);
  158. // }
  159. // }
  160. // Debug.LogWarning(maxDistance + " == " + Math.Abs(MagCalibrater._Radius.magnitude) + " == " + MagCalibrater._Radius + " = " + maxVector3);
  161. // //如果比例效果不理想。可以设置为ratio=0.5f
  162. // foreach (Vector3 i in list)
  163. // {
  164. // //- MagCalibrater._Center
  165. // Vector3 v = i ;
  166. // v *= ratio;
  167. // if(endRecords.Count>3000)
  168. // {
  169. // endRecords.RemoveAt(0);
  170. // }
  171. // endRecords.Add(v);
  172. // }
  173. // this.ellipseScript.ClearAndUpdatePointArray();
  174. // // this.ellipseScript.DrawPointCloud(endRecords);
  175. // MagCalibrater.Calibration = calibration;
  176. // this.ellipseScript.ellipseTran.gameObject.SetActive(true);
  177. // //绘制椭圆形
  178. // if (MagCalibrater._Radius != this.ellipseScript.ellipseTran.localScale)
  179. // {
  180. // this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center * ratio);
  181. // //设置绘制图像相机的对应位置
  182. // this.ellipseScript.setCameraPos(MagCalibrater._Center * ratio);
  183. // this.ellipseScript.setCameraSize(MagCalibrater._Radius);
  184. // }
  185. // MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  186. // PlayerPrefs.SetString("o0MagneticCalibrater", JsonConvert.SerializeObject(MagCalibrater));
  187. // #region 看校准是否完美,求Records方差
  188. // if (list == null || list.Count == 0) isCalibrateMagPerfect = false;
  189. // else
  190. // {
  191. // double sumV = 0;
  192. // double[] listArray = new double[list.Count];
  193. // for (int i = 0; i < list.Count; i++)
  194. // {
  195. // listArray[i] = MagCalibrater.Update(list[i]).magnitude;
  196. // sumV += listArray[i];
  197. // }
  198. // double avarageV = sumV / listArray.Length;
  199. // double varianceV = 0;
  200. // foreach (double vvv in listArray)
  201. // {
  202. // varianceV += Math.Pow(vvv - avarageV, 2);
  203. // }
  204. // varianceV /= listArray.Length;
  205. // isCalibrateMagPerfect = varianceV < 0.001;
  206. // PopupMgr.ins.ShowTip(TextAutoLanguage2.GetTextByKey("tip_mag-calibrate-variance-equal") + varianceV);
  207. // }
  208. // #endregion
  209. // }
  210. // } catch (Exception e) { Debug.LogError(e.Message); }
  211. }
  212. //转换读取的数据,无符号->有符号
  213. float TwoByteToFloat(byte b1, byte b2)
  214. {
  215. ushort twoByte = (ushort) (b1 * 256 + b2);
  216. short shortNum = (short) twoByte;
  217. return (float) shortNum;
  218. }
  219. public void OnDataReceived(byte[] bytes)
  220. {
  221. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  222. if (bytes.Length != 27)
  223. {
  224. if (bytes.Length == 2) {
  225. if (bytes[0] == 0x66 && bytes[1] == 0x31) {
  226. if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) {
  227. //鼠标居中
  228. SB_EventSystem.ins.MakeMouseToScreenCenter();
  229. //视角回正
  230. DoIdentity();
  231. } else {
  232. AutoResetView.DoIdentity();
  233. }
  234. } else if (bytes[0] == 0x66 && bytes[1] == 0x32) {
  235. if (SB_EventSystem.ins) {
  236. // if (SB_EventSystem.ins && !CommonConfig.SpecialVersion1) {
  237. //唤起/隐藏虚拟鼠标
  238. SB_EventSystem.ins.AwakenSimulateMouse();
  239. }
  240. } else if (bytes[1] == 10) {
  241. //显示电量
  242. DeviceBatteryView.ins.RenderBattery(1, bytes[0]);
  243. }
  244. } else if (bytes[0] == 0x5b) {
  245. if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) {
  246. //点击鼠标
  247. SB_EventSystem.ins.ClickMouse();
  248. } else {
  249. //红外射击检测
  250. ShootCheck.ins.ShootByInfrared(bytes);
  251. }
  252. }
  253. return;
  254. }
  255. // if (DeviceBatteryView.ins) {
  256. // DeviceBatteryView.ins.labelTemperature.text = (TwoByteToFloat(bytes[5], bytes[6]) / 100).ToString("#0.00") + "℃";
  257. // }
  258. if (bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0 && bytes[10] == 0 && bytes[11] == 0 && bytes[12] == 0)
  259. return;
  260. if (bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0 && bytes[22] == 0 && bytes[23] == 0 && bytes[24] == 0)
  261. return;
  262. //if (ban9AxisCalculate) //如果箭射出后禁止九轴计算,就缓存最新几帧九轴数据
  263. //{
  264. //
  265. // if (cached9AxisFrames.Count < 2)
  266. // {
  267. // cached9AxisFrames.Enqueue(bytes);
  268. // }
  269. // else
  270. // {
  271. // cached9AxisFrames.Dequeue();
  272. // cached9AxisFrames.Enqueue(bytes);
  273. // }
  274. // return;
  275. //}
  276. float ax = TwoByteToFloat(bytes[7], bytes[8]);
  277. float ay = TwoByteToFloat(bytes[9], bytes[10]);
  278. float az = TwoByteToFloat(bytes[11], bytes[12]);
  279. float roll = TwoByteToFloat(bytes[13], bytes[14]);
  280. float pitch = TwoByteToFloat(bytes[15], bytes[16]);
  281. float yaw = TwoByteToFloat(bytes[17], bytes[18]);
  282. float x = TwoByteToFloat(bytes[19], bytes[20]);
  283. float y = TwoByteToFloat(bytes[21], bytes[22]);
  284. float z = TwoByteToFloat(bytes[23], bytes[24]);
  285. float mxr = TwoByteToFloat(bytes[20], bytes[19]);
  286. float myr = TwoByteToFloat(bytes[22], bytes[21]);
  287. float mzr = TwoByteToFloat(bytes[24], bytes[23]);
  288. if (CommonConfig.devicePlan == 0) {
  289. Acc = new Vector3(-az, ay, -ax) / 32768 * 16;
  290. Gyr = new Vector3(yaw, -pitch, roll) / 32768 * 2;
  291. Mag = new Vector3(-z, y, x) / 32768 * 256; //旧版
  292. } else if (CommonConfig.devicePlan == 1) {
  293. Acc = new Vector3(ax, ay, az) / 32768 * 16;
  294. Gyr = new Vector3(roll, pitch, yaw) / 32768 * 2;
  295. Mag = new Vector3(z, x, -y) / 32768 * 256;//第一个6+3硬件
  296. } else if (CommonConfig.devicePlan == 2) {
  297. Acc = new Vector3(-az, ax, -ay) / 32768 * 16;
  298. Gyr = new Vector3(-yaw, roll, -pitch) / 32768 * 2;
  299. Mag = new Vector3(mzr, mxr, -myr) / 32768 * 256;//第二个6+3硬件
  300. }
  301. AccObj.transform.GetChild(0).localPosition = Acc;
  302. Gyr = GyrCalibrater.Update(Gyr);
  303. if (GyrCalibrater.Calibration)
  304. {
  305. if (gyrCalibrateCompleteCount < gyrCalibrateTotalCount) {
  306. gyrCalibrateCompleteCount++;
  307. }
  308. }
  309. // if (GyrScaleText && GyrCalibrater.Calibration)
  310. // {
  311. // // _9Axis.getGyrOld(),states缓存列表没数据时,会报错
  312. // GyrScaleText.text = "" + (_9Axis.getGyrOld() * 1000000).ToString();
  313. // }
  314. // if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  315. // {
  316. // //绘制地磁计点
  317. // if (MagCalibrater.Calibration)
  318. // {
  319. // this.ellipseScript.AddAndUpdatePointArray(Mag);
  320. // if (Mag.x > cMaxVector.x) cMaxVector.x = Mag.x;
  321. // if (Mag.y > cMaxVector.y) cMaxVector.y = Mag.y;
  322. // if (Mag.z > cMaxVector.z) cMaxVector.z = Mag.z;
  323. // if (Mag.x < cMinVector.x) cMinVector.x = Mag.x;
  324. // if (Mag.y < cMinVector.y) cMinVector.y = Mag.y;
  325. // if (Mag.z < cMinVector.z) cMinVector.z = Mag.z;
  326. // Vector3 centerPoint = (this.cMaxVector + this.cMinVector) / 2;
  327. // //设置绘制图像相机的对应位置
  328. // this.ellipseScript.setCameraPos(centerPoint);
  329. // this.ellipseScript.setCameraSize(this.cMaxVector - this.cMinVector);
  330. // PointCorrector.ins?.Update(centerPoint);
  331. // }
  332. // Mag = MagCalibrater.Update(Mag);
  333. // if (MagScaleText)
  334. // {
  335. // MagScaleText.text = MagCalibrater._Radius.ToString();
  336. // }
  337. // }
  338. mag0o = UnityVectorTo0o(Mag);
  339. try {
  340. if (!MagCalibrater.Update(mag0o)) return;
  341. } catch(System.Exception) {
  342. MagCalibrater = new MagnetometerAutoCalibrater();
  343. return;
  344. }
  345. mag0o = MagCalibrater.EllipsoidFitting.Map(mag0o);
  346. Mag = o0VectorToUnity(mag0o);
  347. MagObj.transform.GetChild(0).localPosition = Mag;
  348. var ms = (((long)bytes[1]) *60 + bytes[2])*1000 + (long)TwoByteToFloat(bytes[3], bytes[4]);
  349. if(msOld == default)
  350. {
  351. msOld = ms;
  352. return;
  353. }
  354. TimeGap = ms - msOld;
  355. msOld = ms;
  356. GapMs = TimeGap;
  357. gyr0o = UnityVectorTo0o(Gyr);
  358. acc0o = UnityVectorTo0o(Acc);
  359. distanceToAxis.Update(gyr0o, acc0o, mag0o, GapMs);
  360. acc0o = distanceToAxis.AccCorrection(gyr0o, acc0o, GapMs);/**///轴心偏离矫正
  361. Acc = o0VectorToUnity(acc0o);
  362. var GyrOperator = new Quaternion();
  363. GyrOperator.eulerAngles = Gyr * TimeGap;
  364. GryMesh.transform.localRotation *= GyrOperator;
  365. AMesh.transform.localRotation = newRotation = _9Axis.update(Acc, Gyr, Mag, TimeGap);
  366. if (BowQuatDebug.ins) BowQuatDebug.ins.ShowModuleQuat(newRotation.eulerAngles);
  367. if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) {
  368. SB_EventSystem.ins.MoveSimulateMouse(newRotation);
  369. }
  370. }
  371. o0.Bow.DistanceToAxis distanceToAxis = new o0.Bow.DistanceToAxis();
  372. double GapMs;
  373. o0.Geometry.Vector<double> gyr0o;
  374. o0.Geometry.Vector<double> acc0o;
  375. o0.Geometry.Vector<double> mag0o;
  376. o0.Geometry.Vector<double> UnityVectorTo0o(Vector3 src) {
  377. return new o0.Geometry.Vector<double>(double.Parse(src.x.ToString()), double.Parse(src.y.ToString()), double.Parse(src.z.ToString()));
  378. }
  379. Vector3 o0VectorToUnity(o0.Geometry.Vector<double> src) {
  380. return new Vector3(float.Parse(src.x.ToString()), float.Parse(src.y.ToString()), float.Parse(src.z.ToString()));
  381. }
  382. [NonSerialized] public bool lerpForRotation = true;
  383. [NonSerialized] public float lerpTimeRate = 7;
  384. public void Update()
  385. {
  386. if (controlObj && !ban9AxisCalculate)
  387. {
  388. if (lerpForRotation)
  389. {
  390. controlObj.localRotation = Quaternion.Lerp(controlObj.localRotation, newRotation, Time.deltaTime * lerpTimeRate);
  391. }
  392. else
  393. {
  394. controlObj.localRotation = newRotation;
  395. }
  396. }
  397. if (!magComplete && MagCalibrater.Complete) {
  398. PlayerPrefs.SetString("new_mag_record", MagCalibrater.ToJson());
  399. PopupMgr.ins.ShowTipTop("地磁计校准成功");
  400. }
  401. magComplete = MagCalibrater.Complete;
  402. }
  403. bool magComplete;
  404. private bool ban9AxisCalculate = false;
  405. private Queue<byte[]> cached9AxisFrames = new Queue<byte[]>();
  406. public void Ban9AxisCalculate(bool ban) {
  407. ban9AxisCalculate = ban;
  408. if (!ban) {
  409. msOld = default;
  410. // try
  411. // {
  412. // if (StatesBackDebug.ins) _9Axis.DeleteStatesFromTail(StatesBackDebug.ins.val);
  413. // }
  414. // catch (Exception) { }
  415. //恢复九轴计算时,把缓存的最新几帧计算了
  416. // bool isFirstFrame = true;
  417. while (cached9AxisFrames.Count > 0)
  418. {
  419. try
  420. {
  421. OnDataReceived(cached9AxisFrames.Dequeue());
  422. //最初的一帧是用来顶掉msOld的,不会进state数组,因此不需要设置方差
  423. // if (!isFirstFrame) {
  424. // _9Axis.SetAccMagVariance(10000);
  425. // }
  426. // isFirstFrame = false;
  427. }
  428. catch (Exception) { }
  429. }
  430. //立马应用到控制物体中
  431. if (controlObj) controlObj.localRotation = newRotation;
  432. }
  433. }
  434. Quaternion newRotation = Quaternion.identity;
  435. public void DoIdentity()
  436. {
  437. _9Axis.SetIdentityAndSave();
  438. Quaternion qua = _9Axis.getLastState().Qua;
  439. newRotation = qua;
  440. if (controlObj) controlObj.localRotation = qua;
  441. }
  442. }