using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using MathNet.Numerics.LinearAlgebra; using UnityEngine.UI; using MathNet.Numerics; using System.Runtime.InteropServices; public class o0Vector3Filter { Vector3 state = default; float Variance = 1; public Vector3 Update(Vector3 v) { if (state == default) return state = v; Variance += 10; float mVariance = 1; state = Vector3.Lerp(state, v, mVariance/ (Variance + mVariance)); Variance = Variance * mVariance / (Variance + mVariance); return state; } } public class o0MagneticCalibraterEllipsoidFitting//默认在无磁干扰环境下,有磁干扰则无法保证效果 { [JsonIgnore] public Vector3 _Center = Vector3.zero; [JsonIgnore] Matrix _CorrectMatrix = null; public float[] Center { get { return new float[]{_Center.x, _Center.y, _Center.z}; } set { _Center = new Vector3(value[0], value[1], value[2]); } } public double[] CorrectMatrix { get { if (_CorrectMatrix == null) return default; var m = new double[9]; for (var i = 0; i < 3; ++i) for (var j = 0; j < 3; ++j) m[j + i * 3] = _CorrectMatrix[i,j]; return m; } set { if (value == default) { _CorrectMatrix = null; return; } _CorrectMatrix = CreateMatrix.Dense(3,3); for (var i = 0; i < 3; ++i) for (var j = 0; j < 3; ++j) _CorrectMatrix[i, j] = value[j + i * 3]; } } public o0MagneticCalibraterEllipsoidFitting() { //Calibration = true; } // public o0MagneticCalibraterEllipsoidFitting(o0Project.Vector3f Center, double[] CorrectMatrix) public o0MagneticCalibraterEllipsoidFitting(float[] Center, double[] CorrectMatrix) { this.Center = Center; this.CorrectMatrix = CorrectMatrix; } [JsonIgnore] public List records = null; [JsonIgnore] public Vector3 _Radius = default; public float[] Radius { get { return new float[]{_Radius.x, _Radius.y, _Radius.z}; } set { _Radius = new Vector3(value[0], value[1], value[2]); } } public List getRecords() { //Debug.LogWarning(records); return records; } [JsonIgnore] List BadRecords = null; [JsonIgnore] public bool Calibration { get { return records != null; } set { if (value == true) { records = new List(); } else { try { int mag_data_counter = records.Count; //mag数据数量 double mag_x, mag_y, mag_z; var mat_D = CreateMatrix.Dense(mag_data_counter, 9); //读取mag for (int i = 0; i < mag_data_counter; i++) { //mag_x_y_z赋值 mag_x = records[i].x; mag_y = records[i].y; mag_z = records[i].z; mat_D[i, 0] = mag_x * mag_x; mat_D[i, 1] = mag_y * mag_y; mat_D[i, 2] = mag_z * mag_z; mat_D[i, 3] = 2 * mag_x * mag_y; mat_D[i, 4] = 2 * mag_x * mag_z; mat_D[i, 5] = 2 * mag_y * mag_z; mat_D[i, 6] = 2 * mag_x; mat_D[i, 7] = 2 * mag_y; mat_D[i, 8] = 2 * mag_z; } var mat_DT = mat_D.Transpose(); var mat_Ones = CreateMatrix.Dense(mag_data_counter, 1, 1.0); var mat_Result = (mat_DT * mat_D).Inverse() * (mat_DT * mat_Ones); var mat_A_4x4 = CreateMatrix.Dense(4, 4); mat_A_4x4[0, 0] = mat_Result[0, 0]; mat_A_4x4[0, 1] = mat_Result[3, 0]; mat_A_4x4[0, 2] = mat_Result[4, 0]; mat_A_4x4[0, 3] = mat_Result[6, 0]; mat_A_4x4[1, 0] = mat_Result[3, 0]; mat_A_4x4[1, 1] = mat_Result[1, 0]; mat_A_4x4[1, 2] = mat_Result[5, 0]; mat_A_4x4[1, 3] = mat_Result[7, 0]; mat_A_4x4[2, 0] = mat_Result[4, 0]; mat_A_4x4[2, 1] = mat_Result[5, 0]; mat_A_4x4[2, 2] = mat_Result[2, 0]; mat_A_4x4[2, 3] = mat_Result[8, 0]; mat_A_4x4[3, 0] = mat_Result[6, 0]; mat_A_4x4[3, 1] = mat_Result[7, 0]; mat_A_4x4[3, 2] = mat_Result[8, 0]; mat_A_4x4[3, 3] = -1.0; var mat_Center = -((mat_A_4x4.SubMatrix(0, 3, 0, 3)).Inverse() * mat_Result.SubMatrix(6, 3, 0, 1)); //椭球圆心 //分块,从0,0开始的3*3的矩阵 var mat_T_4x4 = CreateMatrix.DenseIdentity(4, 4); mat_T_4x4.SetSubMatrix(3, 1, 0, 3, mat_Center.Transpose()); var mat_R = mat_T_4x4 * mat_A_4x4 * mat_T_4x4.Transpose(); var evd = mat_R.SubMatrix(0, 3, 0, 3) / -mat_R[3, 3]; var eig = evd.Evd(); var mat_Eigval = CreateVector.Dense(3); var mat_Evecs = eig.EigenVectors; mat_Eigval[0] = eig.EigenValues[0].Real; //特征值的实部 mat_Eigval[1] = eig.EigenValues[1].Real; mat_Eigval[2] = eig.EigenValues[2].Real; var mat_Radii = mat_Eigval.Map(delegate (double x) { return 1.0 / Math.Sqrt(Math.Abs(x)); }); //椭球半径,特征值倒数后开方 var mat_Scale = CreateMatrix.DenseIdentity(3, 3); mat_Scale[0, 0] = mat_Radii[0]; mat_Scale[1, 1] = mat_Radii[1]; mat_Scale[2, 2] = mat_Radii[2]; //double min_Radii = mat_Radii.Minimum(); //返回最小的元素 mat_Scale = mat_Scale.Inverse();// * min_Radii; var mat_Correct = mat_Evecs * mat_Scale * mat_Evecs.Transpose(); //_Center = new Vector3((float)mat_Center[0], (float)mat_Center[1], (float)mat_Center[2]); Debug.Log("The Ellipsoid center is:" + mat_Center.ToString()); Debug.Log("The Ellipsoid radii is:" + mat_Radii.ToString()); Debug.Log("The scale matrix is:" + mat_Scale.ToString()); Debug.Log("The correct matrix is:" + mat_Correct.ToString()); _Center = new Vector3((float)mat_Center[0, 0], (float)mat_Center[1, 0], (float)mat_Center[2, 0]); _Radius = new Vector3((float)mat_Radii[0], (float)mat_Radii[1], (float)mat_Radii[2]); this._CorrectMatrix = mat_Correct; { BadRecords = new List(); var AverageDistance = 0f; foreach (var i in records) { var v = i - new Vector3((float)mat_Center[0, 0], (float)mat_Center[1, 0], (float)mat_Center[2, 0]); var MathNetV = CreateVector.Dense(3); MathNetV[0] = v.x; MathNetV[1] = v.y; MathNetV[2] = v.z; //MathNetV = (MathNetV * mat_Scale) * mat_Correct; MathNetV = (MathNetV) * mat_Correct; v = new Vector3((float)MathNetV[0], (float)MathNetV[1], (float)MathNetV[2]); AverageDistance += v.magnitude; } AverageDistance /= records.Count; foreach (var i in records) { var v = i - new Vector3((float)mat_Center[0, 0], (float)mat_Center[1, 0], (float)mat_Center[2, 0]); var MathNetV = CreateVector.Dense(3); MathNetV[0] = v.x; MathNetV[1] = v.y; MathNetV[2] = v.z; //MathNetV = (MathNetV * mat_Scale) * mat_Correct; MathNetV = (MathNetV) * mat_Correct; v = new Vector3((float)MathNetV[0], (float)MathNetV[1], (float)MathNetV[2]); if (Math.Abs(v.magnitude - AverageDistance) > 0.1 * AverageDistance) { BadRecords.Add(i); } } Debug.Log("BadRecords: "+ BadRecords.Count); } } catch(NonConvergenceException) { Debug.Log("数据错误无法拟合"); } records = null; } } } public Vector3 Update(Vector3 v) { // if (v.magnitude > 30) // Debug.Log(v); if (Calibration) { records.Add(v); return v; } if(_CorrectMatrix != null) { v -= _Center; var MathNetV = CreateVector.Dense(3); MathNetV[0] = v.x; MathNetV[1] = v.y; MathNetV[2] = v.z; //MathNetV = (MathNetV * mat_Scale) * mat_Correct; MathNetV = (MathNetV) * _CorrectMatrix; v = new Vector3((float)MathNetV[0], (float)MathNetV[1], (float)MathNetV[2]); //Debug.Log(v.magnitude); return v; } return v; } public float CalibratCompletionPercentage() { return 0; } } public class o0MagneticCalibraterSimple//默认在无磁干扰环境下,有磁干扰则无法保证效果 { [JsonIgnore] public Vector3 _Center = Vector3.zero; //Vector3 Center = new Vector3(0,0,0); [JsonIgnore] public Vector3 _Radius = new Vector3(2, 2, 2); public o0Project.Vector3f Center { get { return new o0Project.Vector3f(_Center.x, _Center.y, _Center.z); } set { _Center = new Vector3(value.x, value.y, value.z); } } public o0Project.Vector3f Radius { get { return new o0Project.Vector3f(_Radius.x, _Radius.y, _Radius.z); } set { _Radius = new Vector3(value.x, value.y, value.z); } } public o0MagneticCalibraterSimple() { //Calibration = true; } public o0MagneticCalibraterSimple(o0Project.Vector3f Center, o0Project.Vector3f Radius) { this.Center = Center; this.Radius = Radius; } [JsonIgnore] Vector3 Min = new Vector3(float.MinValue, float.MinValue, float.MinValue); [JsonIgnore] Vector3 Max = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); [JsonIgnore] public bool Calibration { get { return !(Min == new Vector3(float.MinValue, float.MinValue, float.MinValue) && Max == new Vector3(float.MaxValue, float.MaxValue, float.MaxValue)); } set { if (value == true) { Min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); Max = new Vector3(float.MinValue, float.MinValue, float.MinValue); } else { Min = new Vector3(float.MinValue, float.MinValue, float.MinValue); Max = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); } } } public Vector3 Update(Vector3 v) { if (v.magnitude > 30) Debug.Log(v); if (Calibration) { if (Min.x > v.x) Min.x = v.x; if (Min.y > v.y) Min.y = v.y; if (Min.z > v.z) Min.z = v.z; if (Max.x < v.x) Max.x = v.x; if (Max.y < v.y) Max.y = v.y; if (Max.z < v.z) Max.z = v.z; _Center = (Max + Min) / 2; _Radius = (Max - Min) / 2; return v; } v -= _Center; v = new Vector3(v.x / _Radius.x, v.y / _Radius.y, v.z / _Radius.z); return v; } public float CalibratCompletionPercentage() { return 0; } } public class o0MagneticCalibrater//默认在无磁干扰环境下,有磁干扰则无法保证效果 { [JsonIgnore] public Vector3 _Center = Vector3.zero; //Vector3 Center = new Vector3(0,0,0); [JsonIgnore] public Vector3 _Radius = new Vector3(2, 2, 2); public o0Project.Vector3f Center { get { return new o0Project.Vector3f(_Center.x, _Center.y, _Center.z); } set { _Center = new Vector3(value.x, value.y, value.z); } } public o0Project.Vector3f Radius { get { return new o0Project.Vector3f(_Radius.x, _Radius.y, _Radius.z); } set { _Radius = new Vector3(value.x, value.y, value.z); } } public o0MagneticCalibrater() { //Calibration = true; } public o0MagneticCalibrater(o0Project.Vector3f Center, o0Project.Vector3f Radius) { this.Center = Center; this.Radius = Radius; } [JsonIgnore] HashSet Point = default; [JsonIgnore] int PointMaxCount = 50; [JsonIgnore] Dictionary<(Vector3, Vector3), float> Distance = default; public void AddPoint(Vector3 v) { if (Point.Contains(v)) return; foreach (var i in Point) Distance.Add((i, v), Vector3.Distance(v, i)); Point.Add(v); } public void RemovePoint(Vector3 v) { Point.Remove(v); foreach (var i in Point) { Distance.Remove((v, i)); Distance.Remove((i, v)); } } public float TotalDistance(Vector3 v) { float t = 0; foreach (var i in Point) { if (Distance.ContainsKey((i, v))) { t += Distance[(i, v)]; continue; } else if (Distance.ContainsKey((v, i))) { t += Distance[(v, i)]; continue; } } return t; } public Vector3 MinDistancePoint() { Vector3 minV = default; float minD = float.MaxValue; foreach (var i in Point) { float d = TotalDistance(i); if (minV == default || minD > d) { minD = d; minV = i; } } return minV; } public Vector3 RadiusScale() { Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue); foreach (var i in Point) { if (min.x > i.x) min.x = i.x; if (min.y > i.y) min.y = i.y; if (min.z > i.z) min.z = i.z; if (max.x < i.x) max.x = i.x; if (max.y < i.y) max.y = i.y; if (max.z < i.z) max.z = i.z; } return (max - min) / 2; } [JsonIgnore] public bool Calibration { get { return Distance != null; } set { if (value == true) { Point = new HashSet(); Distance = new Dictionary<(Vector3, Vector3), float>(); } else { Distance = null; } } } [JsonIgnore] public System.Random r = new System.Random(); public Vector3 Update(Vector3 v) { if (v.magnitude > 30) Debug.Log(v); if (Calibration) { AddPoint(v); if (Point.Count > PointMaxCount) { RemovePoint(MinDistancePoint()); _Radius = RadiusScale(); } Vector3 randomV = Point.ElementAt(r.Next(Point.Count)); var scaledCenter = new Vector3(_Center.x / _Radius.x, _Center.y / _Radius.y, _Center.z / _Radius.z); var scaledV = new Vector3(randomV.x / _Radius.x, randomV.y / _Radius.y, randomV.z / _Radius.z); float diff = Vector3.Distance(scaledCenter, scaledV) - 1; scaledCenter += (scaledV - scaledCenter).normalized * diff * 0.1f; _Center = new Vector3(scaledCenter.x * _Radius.x, scaledCenter.y * _Radius.y, scaledCenter.z * _Radius.z); } /* if (diff > 0) { Center -= v * diff; } else { }/**/ //Point.Add(v); //Debug.Log(v.magnitude); v -= _Center; v = new Vector3(v.x / _Radius.x, v.y / _Radius.y, v.z / _Radius.z); return v; } public float CalibratCompletionPercentage() { if (Point == null) return 0; List ScaleDistance = new List(); foreach (var i in Point) { var v = i - _Center; ScaleDistance.Add(new Vector3(v.x / _Radius.x, v.y / _Radius.y, v.z / _Radius.z).magnitude); } while (ScaleDistance.Count < PointMaxCount) ScaleDistance.Add(0); float average = 0; foreach (var i in ScaleDistance) average += i; average /= ScaleDistance.Count; float variance = 0; foreach (var i in ScaleDistance) variance += Mathf.Pow(average - i, 2); variance /= ScaleDistance.Count; return Mathf.Pow((1 - variance / average), 10) * 100; //return variance; } } public class o0GyrCalibrater { [JsonIgnore] public Vector3 _Average = Vector3.zero; [JsonIgnore] public long Count = -1; [JsonIgnore] public bool Calibration { get { return Count != -1; } set { if (value) Count = 0; else Count = -1; } } public float[] Average { get { return new float[]{_Average.x, _Average.y, _Average.z}; } set { _Average = new Vector3(value[0], value[1], value[2]); } } public o0GyrCalibrater() { } //[JsonConstructor, o0.BinarySerialization.Constructor] // public o0GyrCalibrater(o0Project.Vector3f Average) public o0GyrCalibrater(float[] Average) { this.Average = Average; } public Vector3 Update(Vector3 v) { if (Calibration) _Average += (v - _Average) / ++Count; v -= _Average; if (v.magnitude < 0.0003) return Vector3.zero; return v; } } public class o09Axis { public List Tester = new List(); public List TextTester = new List(); public GameObject AccMesh; public GameObject GryMesh; public GameObject MagMesh; public struct State { public Int32 TimeGap; public Vector3 Acc; public Vector3 AccSmooth; public float AccVariance; public Vector3 Gyr; public Vector3 Mag; public Vector3 MagSmooth; public Quaternion Qua; public Quaternion QuaSmooth; public float Variance; } public void SetIdentityAndSave() { setIdentity(); TextTester[0].text = "AccIdentity:" + getAccIdentity(); AccMesh.transform.localRotation = default; MagMesh.transform.localRotation = default; GryMesh.transform.localRotation = default; SaveIdentity(); } public void LoadIdentity() { try { string magIdentityStr = PlayerPrefs.GetString("MagIdentity", ""); if (magIdentityStr.Length > 0) { float[] arr = JsonConvert.DeserializeObject(magIdentityStr); setMagIdentity(new Vector3(arr[0], arr[1], arr[2])); } string accIdentityStr = PlayerPrefs.GetString("AccIdentity", ""); if (accIdentityStr.Length > 0) { float[] arr = JsonConvert.DeserializeObject(accIdentityStr); setAccIdentity(new Vector3(arr[0], arr[1], arr[2])); } } catch (System.Exception e) { Debug.LogError(e.Message); } } private void SaveIdentity() { Vector3 m = getMagIdentity(); Vector3 a = getAccIdentity(); PlayerPrefs.SetString("MagIdentity",JsonConvert.SerializeObject(new float[]{ m.x, m.y, m.z })); PlayerPrefs.SetString("AccIdentity", JsonConvert.SerializeObject(new float[]{ a.x, a.y, a.z })); } int platformID = -1; void SetPlatformID() { if (Application.platform == RuntimePlatform.WindowsEditor) platformID = 1; else platformID = 2; } bool IsWindows() { if (platformID == -1) SetPlatformID(); return platformID == 1; } public o09AxisCSBridge axisCSBridge = new o09AxisCSBridge(); public Quaternion update(Vector3 AccOld, Vector3 GyrOld, Vector3 MagOld, long TimeGapOld) { if (axisCSBridge != null) { return axisCSBridge.Update_f(AccOld, GyrOld, MagOld, TimeGapOld); } if (IsWindows()) return Update_f(AccOld, GyrOld, MagOld, TimeGapOld); else return SO_Update_f(AccOld, GyrOld, MagOld, TimeGapOld); } private void setIdentity() { if (axisCSBridge != null) { axisCSBridge.SetIdentity(); return; } if (IsWindows()) SetIdentity(); else SO_SetIdentity(); } public Vector3 getGyrOld() { if (axisCSBridge != null) { return axisCSBridge.GetGyrOld_f(); } if (IsWindows()) return GetGyrOld_f(); else return SO_GetGyrOld_f(); } public State getLastState() { if (axisCSBridge != null) { return axisCSBridge.GetLastState_f(); } if (IsWindows()) return GetLastState_f(); else return SO_GetLastState_f(); } private Vector3 getAccIdentity() { if (axisCSBridge != null) { return axisCSBridge.GetAccIdentity_f(); } if (IsWindows()) return GetAccIdentity_f(); else return SO_GetAccIdentity_f(); } private Vector3 getMagIdentity() { if (axisCSBridge != null) { return axisCSBridge.GetMagIdentity_f(); } if (IsWindows()) return GetMagIdentity_f(); else return SO_GetMagIdentity_f(); } private void setAccIdentity(Vector3 value) { if (axisCSBridge != null) { axisCSBridge.SetAccIdentity(new Vector3D(value)); return; } if (IsWindows()) SetAccIdentity(new Vector3D(value)); else SO_SetAccIdentity(new Vector3D(value)); } private void setMagIdentity(Vector3 value) { if (axisCSBridge != null) { axisCSBridge.SetMagIdentity(new Vector3D(value)); return; } if (IsWindows()) SetMagIdentity(new Vector3D(value)); else SO_SetMagIdentity(new Vector3D(value)); } [DllImport("o09Axis")] extern static Quaternion Update_f(Vector3 AccOld, Vector3 GyrOld, Vector3 MagOld, long TimeGapOld); [DllImport("o09Axis")] extern static void SetIdentity(); [DllImport("o09Axis")] extern static Vector3 GetGyrOld_f(); [DllImport("o09Axis")] extern static State GetLastState_f(); [DllImport("o09Axis")] extern static Vector3 GetAccIdentity_f(); [DllImport("o09Axis")] extern static Vector3 GetMagIdentity_f(); [DllImport("o09Axis")] extern static void SetAccIdentity(Vector3D value); [DllImport("o09Axis")] extern static void SetMagIdentity(Vector3D value); [DllImport("libSharedObjectAxis")] extern static Quaternion SO_Update_f(Vector3 AccOld, Vector3 GyrOld, Vector3 MagOld, long TimeGapOld); [DllImport("libSharedObjectAxis")] extern static void SO_SetIdentity(); [DllImport("libSharedObjectAxis")] extern static Vector3 SO_GetGyrOld_f(); [DllImport("libSharedObjectAxis")] extern static State SO_GetLastState_f(); [DllImport("libSharedObjectAxis")] extern static Vector3 SO_GetAccIdentity_f(); [DllImport("libSharedObjectAxis")] extern static Vector3 SO_GetMagIdentity_f(); [DllImport("libSharedObjectAxis")] extern static void SO_SetAccIdentity(Vector3D value); [DllImport("libSharedObjectAxis")] extern static void SO_SetMagIdentity(Vector3D value); public struct Vector3D { public double x; public double y; public double z; public Vector3D(Vector3 v) { this.x = v.x; this.y = v.y; this.z = v.z; } } }