AimHandler.cs 19 KB

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