AimHandler.cs 19 KB

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