AimHandler.cs 19 KB

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