AimHandler.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. }
  88. if (MagCalibrationButton)
  89. {
  90. MagCalibrationButton.onClick.AddListener(delegate {
  91. // CalibrateMag(!MagCalibrater.Calibration);
  92. });
  93. }
  94. try {
  95. string gyrDataStr = PlayerPrefs.GetString("o0GyrCalibrater");
  96. GyrCalibrater = JsonConvert.DeserializeObject<o0GyrCalibrater>(gyrDataStr);
  97. if (GyrCalibrater._Average != Vector3.zero) GyrScaleText.text = "已校准";
  98. } catch(Exception) {
  99. GyrCalibrater = null;
  100. }
  101. if (GyrCalibrater == null)
  102. {
  103. GyrCalibrater = new o0GyrCalibrater();
  104. }
  105. if (GyrCalibrationButton)
  106. {
  107. GyrCalibrationButton.onClick.AddListener(delegate() {
  108. CalibrateGyr(!GyrCalibrater.Calibration);
  109. });
  110. }
  111. }
  112. void OnDestroy() {
  113. if (MagCalibrater.Complete) PlayerPrefs.SetString("new_mag_record", MagCalibrater.ToJson());
  114. }
  115. public void CalibrateGyr(bool calibration) {
  116. try {
  117. GyrCalibrater.Calibration = calibration;
  118. if (calibration)
  119. {
  120. GyrCalibrationButton.GetComponentInChildren<Text>().text = "停止陀螺仪校准";
  121. }
  122. else
  123. {
  124. GyrCalibrationButton.GetComponentInChildren<Text>().text = "开始陀螺仪校准";
  125. PlayerPrefs.SetString("o0GyrCalibrater", JsonConvert.SerializeObject(GyrCalibrater));
  126. }
  127. } catch (Exception e) { Debug.LogError(e.Message); }
  128. }
  129. [NonSerialized] public bool isCalibrateMagPerfect = false;
  130. public void CalibrateMag(bool calibration) {
  131. // try {
  132. // if (calibration)
  133. // {
  134. // PointCorrector.ins = new PointCorrector(this.ellipseScript, this.MagCalibrater);
  135. // MagCalibrater.Calibration = calibration;
  136. // MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  137. // this.cMaxVector = new Vector3(float.MinValue, float.MinValue, float.MinValue);
  138. // this.cMinVector = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
  139. // this.ellipseScript.ellipseTran.gameObject.SetActive(false);
  140. // }
  141. // else
  142. // {
  143. // PointCorrector.ins = null;
  144. // List<Vector3> list = MagCalibrater.getRecords();
  145. // //停止校准时候,看看数组值
  146. // float maxDistance = 0f,ratio = 1f;
  147. // Vector3 maxVector3 = new Vector3(0,0,0);
  148. // List<Vector3> endRecords = new List<Vector3>();
  149. // foreach (Vector3 i in list)
  150. // {
  151. // Vector3 v = i - MagCalibrater._Center;
  152. // if (Math.Abs(v.magnitude) > maxDistance)
  153. // {
  154. // maxVector3 = v;
  155. // maxDistance = Math.Abs(v.magnitude);
  156. // if(Math.Abs(v.magnitude) < Math.Abs(MagCalibrater._Radius.magnitude))
  157. // ratio = Math.Abs(v.magnitude) / Math.Abs(MagCalibrater._Radius.magnitude);
  158. // else
  159. // ratio = Math.Abs(MagCalibrater._Radius.magnitude) / Math.Abs(v.magnitude);
  160. // }
  161. // }
  162. // Debug.LogWarning(maxDistance + " == " + Math.Abs(MagCalibrater._Radius.magnitude) + " == " + MagCalibrater._Radius + " = " + maxVector3);
  163. // //如果比例效果不理想。可以设置为ratio=0.5f
  164. // foreach (Vector3 i in list)
  165. // {
  166. // //- MagCalibrater._Center
  167. // Vector3 v = i ;
  168. // v *= ratio;
  169. // if(endRecords.Count>3000)
  170. // {
  171. // endRecords.RemoveAt(0);
  172. // }
  173. // endRecords.Add(v);
  174. // }
  175. // this.ellipseScript.ClearAndUpdatePointArray();
  176. // // this.ellipseScript.DrawPointCloud(endRecords);
  177. // MagCalibrater.Calibration = calibration;
  178. // this.ellipseScript.ellipseTran.gameObject.SetActive(true);
  179. // //绘制椭圆形
  180. // if (MagCalibrater._Radius != this.ellipseScript.ellipseTran.localScale)
  181. // {
  182. // this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center * ratio);
  183. // //设置绘制图像相机的对应位置
  184. // this.ellipseScript.setCameraPos(MagCalibrater._Center * ratio);
  185. // this.ellipseScript.setCameraSize(MagCalibrater._Radius);
  186. // }
  187. // MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  188. // PlayerPrefs.SetString("o0MagneticCalibrater", JsonConvert.SerializeObject(MagCalibrater));
  189. // #region 看校准是否完美,求Records方差
  190. // if (list == null || list.Count == 0) isCalibrateMagPerfect = false;
  191. // else
  192. // {
  193. // double sumV = 0;
  194. // double[] listArray = new double[list.Count];
  195. // for (int i = 0; i < list.Count; i++)
  196. // {
  197. // listArray[i] = MagCalibrater.Update(list[i]).magnitude;
  198. // sumV += listArray[i];
  199. // }
  200. // double avarageV = sumV / listArray.Length;
  201. // double varianceV = 0;
  202. // foreach (double vvv in listArray)
  203. // {
  204. // varianceV += Math.Pow(vvv - avarageV, 2);
  205. // }
  206. // varianceV /= listArray.Length;
  207. // isCalibrateMagPerfect = varianceV < 0.001;
  208. // PopupMgr.ins.ShowTip(TextAutoLanguage2.GetTextByKey("tip_mag-calibrate-variance-equal") + varianceV);
  209. // }
  210. // #endregion
  211. // }
  212. // } catch (Exception e) { Debug.LogError(e.Message); }
  213. }
  214. //转换读取的数据,无符号->有符号
  215. float TwoByteToFloat(byte b1, byte b2)
  216. {
  217. ushort twoByte = (ushort) (b1 * 256 + b2);
  218. short shortNum = (short) twoByte;
  219. return (float) shortNum;
  220. }
  221. public void OnDataReceived(byte[] bytes)
  222. {
  223. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  224. if (bytes.Length != 27)
  225. {
  226. if (bytes.Length == 2) {
  227. if (bytes[0] == 0x66 && bytes[1] == 0x31) {
  228. if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) {
  229. //鼠标居中
  230. SB_EventSystem.ins.MakeMouseToScreenCenter();
  231. //视角回正
  232. DoIdentity();
  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. if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) {
  248. //点击鼠标
  249. SB_EventSystem.ins.ClickMouse();
  250. } else {
  251. //红外射击检测
  252. ShootCheck.ins.ShootByInfrared(bytes);
  253. }
  254. }
  255. return;
  256. }
  257. // if (DeviceBatteryView.ins) {
  258. // DeviceBatteryView.ins.labelTemperature.text = (TwoByteToFloat(bytes[5], bytes[6]) / 100).ToString("#0.00") + "℃";
  259. // }
  260. if (bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0 && bytes[10] == 0 && bytes[11] == 0 && bytes[12] == 0)
  261. return;
  262. if (bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0 && bytes[22] == 0 && bytes[23] == 0 && bytes[24] == 0)
  263. return;
  264. //if (ban9AxisCalculate) //如果箭射出后禁止九轴计算,就缓存最新几帧九轴数据
  265. //{
  266. //
  267. // if (cached9AxisFrames.Count < 2)
  268. // {
  269. // cached9AxisFrames.Enqueue(bytes);
  270. // }
  271. // else
  272. // {
  273. // cached9AxisFrames.Dequeue();
  274. // cached9AxisFrames.Enqueue(bytes);
  275. // }
  276. // return;
  277. //}
  278. float ax = TwoByteToFloat(bytes[7], bytes[8]);
  279. float ay = TwoByteToFloat(bytes[9], bytes[10]);
  280. float az = TwoByteToFloat(bytes[11], bytes[12]);
  281. float roll = TwoByteToFloat(bytes[13], bytes[14]);
  282. float pitch = TwoByteToFloat(bytes[15], bytes[16]);
  283. float yaw = TwoByteToFloat(bytes[17], bytes[18]);
  284. float x = TwoByteToFloat(bytes[19], bytes[20]);
  285. float y = TwoByteToFloat(bytes[21], bytes[22]);
  286. float z = TwoByteToFloat(bytes[23], bytes[24]);
  287. float mxr = TwoByteToFloat(bytes[20], bytes[19]);
  288. float myr = TwoByteToFloat(bytes[22], bytes[21]);
  289. float mzr = TwoByteToFloat(bytes[24], bytes[23]);
  290. if (CommonConfig.devicePlan == 0) {
  291. Acc = new Vector3(-az, ay, -ax) / 32768 * 16;
  292. Gyr = new Vector3(yaw, -pitch, roll) / 32768 * 2;
  293. Mag = new Vector3(-z, y, x) / 32768 * 256; //旧版
  294. mag0o = UnityVectorTo0o(Mag);
  295. if (!MagCalibrater.Update(mag0o)) {
  296. isCalibrateMagPerfect = false;
  297. return;
  298. }
  299. isCalibrateMagPerfect = true;
  300. mag0o = MagCalibrater.EllipsoidFitting.Map(mag0o);
  301. Mag = o0VectorToUnity(mag0o);
  302. } else if (CommonConfig.devicePlan == 1) {
  303. Acc = new Vector3(ax, ay, az) / 32768 * 16;
  304. Gyr = new Vector3(roll, pitch, yaw) / 32768 * 2;
  305. Mag = new Vector3(z, x, -y) / 32768 * 256;//第一个6+3硬件
  306. } else if (CommonConfig.devicePlan == 2) {
  307. Acc = new Vector3(-az, ax, -ay) / 32768 * 16;
  308. Gyr = new Vector3(-yaw, roll, -pitch) / 32768 * 2;
  309. Mag = new Vector3(mzr, mxr, -myr) / 32768 * 256;//第二个6+3硬件
  310. }
  311. AccObj.transform.GetChild(0).localPosition = Acc;
  312. Gyr = GyrCalibrater.Update(Gyr);
  313. if (GyrCalibrater.Calibration)
  314. {
  315. if (gyrCalibrateCompleteCount < gyrCalibrateTotalCount) {
  316. gyrCalibrateCompleteCount++;
  317. }
  318. }
  319. if (GyrScaleText && GyrCalibrater.Calibration)
  320. {
  321. GyrScaleText.text = "" + (_9Axis.getGyrOld() * 1000000).ToString();
  322. }
  323. // if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  324. // {
  325. // //绘制地磁计点
  326. // if (MagCalibrater.Calibration)
  327. // {
  328. // this.ellipseScript.AddAndUpdatePointArray(Mag);
  329. // if (Mag.x > cMaxVector.x) cMaxVector.x = Mag.x;
  330. // if (Mag.y > cMaxVector.y) cMaxVector.y = Mag.y;
  331. // if (Mag.z > cMaxVector.z) cMaxVector.z = Mag.z;
  332. // if (Mag.x < cMinVector.x) cMinVector.x = Mag.x;
  333. // if (Mag.y < cMinVector.y) cMinVector.y = Mag.y;
  334. // if (Mag.z < cMinVector.z) cMinVector.z = Mag.z;
  335. // Vector3 centerPoint = (this.cMaxVector + this.cMinVector) / 2;
  336. // //设置绘制图像相机的对应位置
  337. // this.ellipseScript.setCameraPos(centerPoint);
  338. // this.ellipseScript.setCameraSize(this.cMaxVector - this.cMinVector);
  339. // PointCorrector.ins?.Update(centerPoint);
  340. // }
  341. // Mag = MagCalibrater.Update(Mag);
  342. // if (MagScaleText)
  343. // {
  344. // MagScaleText.text = MagCalibrater._Radius.ToString();
  345. // }
  346. // }
  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. }
  398. private bool ban9AxisCalculate = false;
  399. private Queue<byte[]> cached9AxisFrames = new Queue<byte[]>();
  400. public void Ban9AxisCalculate(bool ban) {
  401. ban9AxisCalculate = ban;
  402. if (!ban) {
  403. msOld = default;
  404. // try
  405. // {
  406. // if (StatesBackDebug.ins) _9Axis.DeleteStatesFromTail(StatesBackDebug.ins.val);
  407. // }
  408. // catch (Exception) { }
  409. //恢复九轴计算时,把缓存的最新几帧计算了
  410. // bool isFirstFrame = true;
  411. while (cached9AxisFrames.Count > 0)
  412. {
  413. try
  414. {
  415. OnDataReceived(cached9AxisFrames.Dequeue());
  416. //最初的一帧是用来顶掉msOld的,不会进state数组,因此不需要设置方差
  417. // if (!isFirstFrame) {
  418. // _9Axis.SetAccMagVariance(10000);
  419. // }
  420. // isFirstFrame = false;
  421. }
  422. catch (Exception) { }
  423. }
  424. //立马应用到控制物体中
  425. if (controlObj) controlObj.localRotation = newRotation;
  426. }
  427. }
  428. Quaternion newRotation = Quaternion.identity;
  429. public void DoIdentity()
  430. {
  431. _9Axis.SetIdentityAndSave();
  432. Quaternion qua = _9Axis.getLastState().Qua;
  433. newRotation = qua;
  434. if (controlObj) controlObj.localRotation = qua;
  435. }
  436. }