-
Notifications
You must be signed in to change notification settings - Fork 6
/
GamepadMotion.hpp
1312 lines (1128 loc) · 38.6 KB
/
GamepadMotion.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2020-2023 Julian "Jibb" Smart
// Released under the MIT license. See https://github.com/JibbSmart/GamepadMotionHelpers/blob/main/LICENSE for more info
// Version 9
#pragma once
#define _USE_MATH_DEFINES
#include <math.h>
#include <algorithm> // std::min, std::max and std::clamp
// You don't need to look at these. These will just be used internally by the GamepadMotion class declared below.
// You can ignore anything in namespace GamepadMotionHelpers.
class GamepadMotionSettings;
class GamepadMotion;
namespace GamepadMotionHelpers
{
struct GyroCalibration
{
float X;
float Y;
float Z;
float AccelMagnitude;
int NumSamples;
};
struct Quat
{
float w;
float x;
float y;
float z;
Quat();
Quat(float inW, float inX, float inY, float inZ);
void Set(float inW, float inX, float inY, float inZ);
Quat& operator*=(const Quat& rhs);
friend Quat operator*(Quat lhs, const Quat& rhs);
void Normalize();
Quat Normalized() const;
void Invert();
Quat Inverse() const;
};
struct Vec
{
float x;
float y;
float z;
Vec();
Vec(float inValue);
Vec(float inX, float inY, float inZ);
void Set(float inX, float inY, float inZ);
float Length() const;
float LengthSquared() const;
void Normalize();
Vec Normalized() const;
float Dot(const Vec& other) const;
Vec Cross(const Vec& other) const;
Vec Min(const Vec& other) const;
Vec Max(const Vec& other) const;
Vec Abs() const;
Vec Lerp(const Vec& other, float factor) const;
Vec Lerp(const Vec& other, const Vec& factor) const;
Vec& operator+=(const Vec& rhs);
friend Vec operator+(Vec lhs, const Vec& rhs);
Vec& operator-=(const Vec& rhs);
friend Vec operator-(Vec lhs, const Vec& rhs);
Vec& operator*=(const float rhs);
friend Vec operator*(Vec lhs, const float rhs);
Vec& operator/=(const float rhs);
friend Vec operator/(Vec lhs, const float rhs);
Vec& operator*=(const Quat& rhs);
friend Vec operator*(Vec lhs, const Quat& rhs);
Vec operator-() const;
};
struct SensorMinMaxWindow
{
Vec MinGyro;
Vec MaxGyro;
Vec MeanGyro;
Vec MinAccel;
Vec MaxAccel;
Vec MeanAccel;
Vec StartAccel;
int NumSamples = 0;
float TimeSampled = 0.f;
SensorMinMaxWindow();
void Reset(float remainder);
void AddSample(const Vec& inGyro, const Vec& inAccel, float deltaTime);
Vec GetMidGyro();
};
struct AutoCalibration
{
SensorMinMaxWindow MinMaxWindow;
Vec SmoothedAngularVelocityGyro;
Vec SmoothedAngularVelocityAccel;
Vec SmoothedPreviousAccel;
Vec PreviousAccel;
AutoCalibration();
void Reset();
bool AddSampleStillness(const Vec& inGyro, const Vec& inAccel, float deltaTime, bool doSensorFusion);
void NoSampleStillness();
bool AddSampleSensorFusion(const Vec& inGyro, const Vec& inAccel, float deltaTime);
void NoSampleSensorFusion();
void SetCalibrationData(GyroCalibration* calibrationData);
void SetSettings(GamepadMotionSettings* settings);
float Confidence = 0.f;
bool IsSteady() { return bIsSteady; }
private:
Vec MinDeltaGyro = Vec(1.f);
Vec MinDeltaAccel = Vec(0.25f);
float RecalibrateThreshold = 1.f;
float SensorFusionSkippedTime = 0.f;
float TimeSteadySensorFusion = 0.f;
float TimeSteadyStillness = 0.f;
bool bIsSteady = false;
GyroCalibration* CalibrationData;
GamepadMotionSettings* Settings;
};
struct Motion
{
Quat Quaternion;
Vec Accel;
Vec Grav;
Vec SmoothAccel = Vec();
float Shakiness = 0.f;
const float ShortSteadinessHalfTime = 0.25f;
const float LongSteadinessHalfTime = 1.f;
Motion();
void Reset();
void Update(float inGyroX, float inGyroY, float inGyroZ, float inAccelX, float inAccelY, float inAccelZ, float gravityLength, float deltaTime);
void SetSettings(GamepadMotionSettings* settings);
private:
GamepadMotionSettings* Settings;
};
enum CalibrationMode
{
Manual = 0,
Stillness = 1,
SensorFusion = 2,
};
// https://stackoverflow.com/a/1448478/1130520
inline CalibrationMode operator|(CalibrationMode a, CalibrationMode b)
{
return static_cast<CalibrationMode>(static_cast<int>(a) | static_cast<int>(b));
}
inline CalibrationMode operator&(CalibrationMode a, CalibrationMode b)
{
return static_cast<CalibrationMode>(static_cast<int>(a) & static_cast<int>(b));
}
inline CalibrationMode operator~(CalibrationMode a)
{
return static_cast<CalibrationMode>(~static_cast<int>(a));
}
// https://stackoverflow.com/a/23152590/1130520
inline CalibrationMode& operator|=(CalibrationMode& a, CalibrationMode b)
{
return (CalibrationMode&)((int&)(a) |= static_cast<int>(b));
}
inline CalibrationMode& operator&=(CalibrationMode& a, CalibrationMode b)
{
return (CalibrationMode&)((int&)(a) &= static_cast<int>(b));
}
}
// Note that I'm using a Y-up coordinate system. This is to follow the convention set by the motion sensors in
// PlayStation controllers, which was what I was using when writing in this. But for the record, Z-up is
// better for most games (XY ground-plane in 3D games simplifies using 2D vectors in navigation, for example).
// Gyro units should be degrees per second. Accelerometer should be g-force (approx. 9.8 m/s^2 = 1 g). If you're using
// radians per second, meters per second squared, etc, conversion should be simple.
class GamepadMotionSettings
{
public:
int MinStillnessSamples = 10;
float MinStillnessCollectionTime = 0.5f;
float MinStillnessCorrectionTime = 2.f;
float MaxStillnessError = 2.f;
float StillnessSampleDeteriorationRate = 0.2f;
float StillnessErrorClimbRate = 0.1f;
float StillnessErrorDropOnRecalibrate = 0.1f;
float StillnessCalibrationEaseInTime = 3.f;
float StillnessCalibrationHalfTime = 0.1f;
float StillnessConfidenceRate = 1.f;
float StillnessGyroDelta = -1.f;
float StillnessAccelDelta = -1.f;
float SensorFusionCalibrationSmoothingStrength = 2.f;
float SensorFusionAngularAccelerationThreshold = 20.f;
float SensorFusionCalibrationEaseInTime = 3.f;
float SensorFusionCalibrationHalfTime = 0.1f;
float SensorFusionConfidenceRate = 1.f;
float GravityCorrectionShakinessMaxThreshold = 0.4f;
float GravityCorrectionShakinessMinThreshold = 0.01f;
float GravityCorrectionStillSpeed = 1.f;
float GravityCorrectionShakySpeed = 0.1f;
float GravityCorrectionGyroFactor = 0.1f;
float GravityCorrectionGyroMinThreshold = 0.05f;
float GravityCorrectionGyroMaxThreshold = 0.25f;
float GravityCorrectionMinimumSpeed = 0.01f;
};
class GamepadMotion
{
public:
GamepadMotion();
void Reset();
void ProcessMotion(float gyroX, float gyroY, float gyroZ,
float accelX, float accelY, float accelZ, float deltaTime);
// reading the current state
void GetCalibratedGyro(float& x, float& y, float& z);
void GetGravity(float& x, float& y, float& z);
void GetProcessedAcceleration(float& x, float& y, float& z);
void GetOrientation(float& w, float& x, float& y, float& z);
void GetPlayerSpaceGyro(float& x, float& y, const float yawRelaxFactor = 1.41f);
static void CalculatePlayerSpaceGyro(float& x, float& y, const float gyroX, const float gyroY, const float gyroZ, const float gravX, const float gravY, const float gravZ, const float yawRelaxFactor = 1.41f);
void GetWorldSpaceGyro(float& x, float& y, const float sideReductionThreshold = 0.125f);
static void CalculateWorldSpaceGyro(float& x, float& y, const float gyroX, const float gyroY, const float gyroZ, const float gravX, const float gravY, const float gravZ, const float sideReductionThreshold = 0.125f);
// gyro calibration functions
void StartContinuousCalibration();
void PauseContinuousCalibration();
void ResetContinuousCalibration();
void GetCalibrationOffset(float& xOffset, float& yOffset, float& zOffset);
void SetCalibrationOffset(float xOffset, float yOffset, float zOffset, int weight);
float GetAutoCalibrationConfidence();
void SetAutoCalibrationConfidence(float newConfidence);
bool GetAutoCalibrationIsSteady();
GamepadMotionHelpers::CalibrationMode GetCalibrationMode();
void SetCalibrationMode(GamepadMotionHelpers::CalibrationMode calibrationMode);
void ResetMotion();
GamepadMotionSettings Settings;
private:
GamepadMotionHelpers::Vec Gyro;
GamepadMotionHelpers::Vec RawAccel;
GamepadMotionHelpers::Motion Motion;
GamepadMotionHelpers::GyroCalibration GyroCalibration;
GamepadMotionHelpers::AutoCalibration AutoCalibration;
GamepadMotionHelpers::CalibrationMode CurrentCalibrationMode;
bool IsCalibrating;
void PushSensorSamples(float gyroX, float gyroY, float gyroZ, float accelMagnitude);
void GetCalibratedSensor(float& gyroOffsetX, float& gyroOffsetY, float& gyroOffsetZ, float& accelMagnitude);
};
///////////// Everything below here are just implementation details /////////////
namespace GamepadMotionHelpers
{
inline Quat::Quat()
{
w = 1.0f;
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
inline Quat::Quat(float inW, float inX, float inY, float inZ)
{
w = inW;
x = inX;
y = inY;
z = inZ;
}
inline static Quat AngleAxis(float inAngle, float inX, float inY, float inZ)
{
const float sinHalfAngle = sinf(inAngle * 0.5f);
Vec inAxis = Vec(inX, inY, inZ);
inAxis.Normalize();
inAxis *= sinHalfAngle;
Quat result = Quat(cosf(inAngle * 0.5f), inAxis.x, inAxis.y, inAxis.z);
return result;
}
inline void Quat::Set(float inW, float inX, float inY, float inZ)
{
w = inW;
x = inX;
y = inY;
z = inZ;
}
inline Quat& Quat::operator*=(const Quat& rhs)
{
Set(w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z,
w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y,
w * rhs.y - x * rhs.z + y * rhs.w + z * rhs.x,
w * rhs.z + x * rhs.y - y * rhs.x + z * rhs.w);
return *this;
}
inline Quat operator*(Quat lhs, const Quat& rhs)
{
lhs *= rhs;
return lhs;
}
inline void Quat::Normalize()
{
const float length = sqrtf(w * w + x * x + y * y + z * z);
const float fixFactor = 1.0f / length;
w *= fixFactor;
x *= fixFactor;
y *= fixFactor;
z *= fixFactor;
return;
}
inline Quat Quat::Normalized() const
{
Quat result = *this;
result.Normalize();
return result;
}
inline void Quat::Invert()
{
x = -x;
y = -y;
z = -z;
return;
}
inline Quat Quat::Inverse() const
{
Quat result = *this;
result.Invert();
return result;
}
inline Vec::Vec()
{
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
inline Vec::Vec(float inValue)
{
x = inValue;
y = inValue;
z = inValue;
}
inline Vec::Vec(float inX, float inY, float inZ)
{
x = inX;
y = inY;
z = inZ;
}
inline void Vec::Set(float inX, float inY, float inZ)
{
x = inX;
y = inY;
z = inZ;
}
inline float Vec::Length() const
{
return sqrtf(x * x + y * y + z * z);
}
inline float Vec::LengthSquared() const
{
return x * x + y * y + z * z;
}
inline void Vec::Normalize()
{
const float length = Length();
if (length == 0.0)
{
return;
}
const float fixFactor = 1.0f / length;
x *= fixFactor;
y *= fixFactor;
z *= fixFactor;
return;
}
inline Vec Vec::Normalized() const
{
Vec result = *this;
result.Normalize();
return result;
}
inline Vec& Vec::operator+=(const Vec& rhs)
{
Set(x + rhs.x, y + rhs.y, z + rhs.z);
return *this;
}
inline Vec operator+(Vec lhs, const Vec& rhs)
{
lhs += rhs;
return lhs;
}
inline Vec& Vec::operator-=(const Vec& rhs)
{
Set(x - rhs.x, y - rhs.y, z - rhs.z);
return *this;
}
inline Vec operator-(Vec lhs, const Vec& rhs)
{
lhs -= rhs;
return lhs;
}
inline Vec& Vec::operator*=(const float rhs)
{
Set(x * rhs, y * rhs, z * rhs);
return *this;
}
inline Vec operator*(Vec lhs, const float rhs)
{
lhs *= rhs;
return lhs;
}
inline Vec& Vec::operator/=(const float rhs)
{
Set(x / rhs, y / rhs, z / rhs);
return *this;
}
inline Vec operator/(Vec lhs, const float rhs)
{
lhs /= rhs;
return lhs;
}
inline Vec& Vec::operator*=(const Quat& rhs)
{
Quat temp = rhs * Quat(0.0f, x, y, z) * rhs.Inverse();
Set(temp.x, temp.y, temp.z);
return *this;
}
inline Vec operator*(Vec lhs, const Quat& rhs)
{
lhs *= rhs;
return lhs;
}
inline Vec Vec::operator-() const
{
Vec result = Vec(-x, -y, -z);
return result;
}
inline float Vec::Dot(const Vec& other) const
{
return x * other.x + y * other.y + z * other.z;
}
inline Vec Vec::Cross(const Vec& other) const
{
return Vec(y * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x);
}
inline Vec Vec::Min(const Vec& other) const
{
return Vec(x < other.x ? x : other.x,
y < other.y ? y : other.y,
z < other.z ? z : other.z);
}
inline Vec Vec::Max(const Vec& other) const
{
return Vec(x > other.x ? x : other.x,
y > other.y ? y : other.y,
z > other.z ? z : other.z);
}
inline Vec Vec::Abs() const
{
return Vec(x > 0 ? x : -x,
y > 0 ? y : -y,
z > 0 ? z : -z);
}
inline Vec Vec::Lerp(const Vec& other, float factor) const
{
return *this + (other - *this) * factor;
}
inline Vec Vec::Lerp(const Vec& other, const Vec& factor) const
{
return Vec(this->x + (other.x - this->x) * factor.x,
this->y + (other.y - this->y) * factor.y,
this->z + (other.z - this->z) * factor.z);
}
inline Motion::Motion()
{
Reset();
}
inline void Motion::Reset()
{
Quaternion.Set(1.f, 0.f, 0.f, 0.f);
Accel.Set(0.f, 0.f, 0.f);
Grav.Set(0.f, 0.f, 0.f);
SmoothAccel.Set(0.f, 0.f, 0.f);
Shakiness = 0.f;
}
/// <summary>
/// The gyro inputs should be calibrated degrees per second but have no other processing. Acceleration is in G units (1 = approx. 9.8m/s^2)
/// </summary>
inline void Motion::Update(float inGyroX, float inGyroY, float inGyroZ, float inAccelX, float inAccelY, float inAccelZ, float gravityLength, float deltaTime)
{
if (!Settings)
{
return;
}
// get settings
const float gravityCorrectionShakinessMinThreshold = Settings->GravityCorrectionShakinessMinThreshold;
const float gravityCorrectionShakinessMaxThreshold = Settings->GravityCorrectionShakinessMaxThreshold;
const float gravityCorrectionStillSpeed = Settings->GravityCorrectionStillSpeed;
const float gravityCorrectionShakySpeed = Settings->GravityCorrectionShakySpeed;
const float gravityCorrectionGyroFactor = Settings->GravityCorrectionGyroFactor;
const float gravityCorrectionGyroMinThreshold = Settings->GravityCorrectionGyroMinThreshold;
const float gravityCorrectionGyroMaxThreshold = Settings->GravityCorrectionGyroMaxThreshold;
const float gravityCorrectionMinimumSpeed = Settings->GravityCorrectionMinimumSpeed;
const Vec axis = Vec(inGyroX, inGyroY, inGyroZ);
const Vec accel = Vec(inAccelX, inAccelY, inAccelZ);
const float angleSpeed = axis.Length() * (float)M_PI / 180.0f;
const float angle = angleSpeed * deltaTime;
// rotate
Quat rotation = AngleAxis(angle, axis.x, axis.y, axis.z);
Quaternion *= rotation; // do it this way because it's a local rotation, not global
//printf("Quat: %.4f %.4f %.4f %.4f\n",
// Quaternion.w, Quaternion.x, Quaternion.y, Quaternion.z);
float accelMagnitude = accel.Length();
if (accelMagnitude > 0.0f)
{
const Vec accelNorm = accel / accelMagnitude;
// account for rotation when tracking smoothed acceleration
SmoothAccel *= rotation.Inverse();
//printf("Absolute Accel: %.4f %.4f %.4f\n",
// absoluteAccel.x, absoluteAccel.y, absoluteAccel.z);
const float smoothFactor = ShortSteadinessHalfTime <= 0.f ? 0.f : exp2f(-deltaTime / ShortSteadinessHalfTime);
Shakiness *= smoothFactor;
Shakiness = std::max(Shakiness, (accel - SmoothAccel).Length());
SmoothAccel = accel.Lerp(SmoothAccel, smoothFactor);
//printf("Shakiness: %.4f\n", Shakiness);
// update grav by rotation
Grav *= rotation.Inverse();
// we want to close the gap between grav and raw acceleration. What's the difference
const Vec gravToAccel = (accelNorm * -gravityLength) - Grav;
const Vec gravToAccelDir = gravToAccel.Normalized();
// adjustment rate
float gravCorrectionSpeed;
if (gravityCorrectionShakinessMinThreshold < gravityCorrectionShakinessMaxThreshold)
{
gravCorrectionSpeed = gravityCorrectionStillSpeed + (gravityCorrectionShakySpeed - gravityCorrectionStillSpeed) * std::clamp((Shakiness - gravityCorrectionShakinessMinThreshold) / (gravityCorrectionShakinessMaxThreshold - gravityCorrectionShakinessMinThreshold), 0.f, 1.f);
}
else
{
gravCorrectionSpeed = Shakiness < gravityCorrectionShakinessMaxThreshold ? gravityCorrectionStillSpeed : gravityCorrectionShakySpeed;
}
// we also limit it to be no faster than a given proportion of the gyro rate, or the minimum gravity correction speed
const float gyroGravCorrectionLimit = std::max(angleSpeed * gravityCorrectionGyroFactor, gravityCorrectionMinimumSpeed);
if (gravCorrectionSpeed > gyroGravCorrectionLimit)
{
float closeEnoughFactor;
if (gravityCorrectionGyroMinThreshold < gravityCorrectionGyroMaxThreshold)
{
closeEnoughFactor = std::clamp((gravToAccel.Length() - gravityCorrectionGyroMinThreshold) / (gravityCorrectionGyroMaxThreshold - gravityCorrectionGyroMinThreshold), 0.f, 1.f);
}
else
{
closeEnoughFactor = gravToAccel.Length() < gravityCorrectionGyroMaxThreshold ? 0.f : 1.f;
}
gravCorrectionSpeed = gyroGravCorrectionLimit + (gravCorrectionSpeed - gyroGravCorrectionLimit) * closeEnoughFactor;
}
const Vec gravToAccelDelta = gravToAccelDir * gravCorrectionSpeed * deltaTime;
if (gravToAccelDelta.LengthSquared() < gravToAccel.LengthSquared())
{
Grav += gravToAccelDelta;
}
else
{
Grav = accelNorm * -gravityLength;
}
const Vec gravityDirection = Grav.Normalized() * Quaternion.Inverse(); // absolute gravity direction
const float errorAngle = acosf(std::clamp(Vec(0.0f, -1.0f, 0.0f).Dot(gravityDirection), -1.f, 1.f));
const Vec flattened = Vec(0.0f, -1.0f, 0.0f).Cross(gravityDirection);
Quat correctionQuat = AngleAxis(errorAngle, flattened.x, flattened.y, flattened.z);
Quaternion = Quaternion * correctionQuat;
Accel = accel + Grav;
}
else
{
Grav *= rotation.Inverse();
Accel = Grav;
}
Quaternion.Normalize();
}
inline void Motion::SetSettings(GamepadMotionSettings* settings)
{
Settings = settings;
}
inline SensorMinMaxWindow::SensorMinMaxWindow()
{
Reset(0.f);
}
inline void SensorMinMaxWindow::Reset(float remainder)
{
NumSamples = 0;
TimeSampled = remainder;
}
inline void SensorMinMaxWindow::AddSample(const Vec& inGyro, const Vec& inAccel, float deltaTime)
{
if (NumSamples == 0)
{
MaxGyro = inGyro;
MinGyro = inGyro;
MeanGyro = inGyro;
MaxAccel = inAccel;
MinAccel = inAccel;
MeanAccel = inAccel;
StartAccel = inAccel;
NumSamples = 1;
TimeSampled += deltaTime;
return;
}
MaxGyro = MaxGyro.Max(inGyro);
MinGyro = MinGyro.Min(inGyro);
MaxAccel = MaxAccel.Max(inAccel);
MinAccel = MinAccel.Min(inAccel);
NumSamples++;
TimeSampled += deltaTime;
Vec delta = inGyro - MeanGyro;
MeanGyro += delta * (1.f / NumSamples);
delta = inAccel - MeanAccel;
MeanAccel += delta * (1.f / NumSamples);
}
inline Vec SensorMinMaxWindow::GetMidGyro()
{
return MeanGyro;
}
inline AutoCalibration::AutoCalibration()
{
CalibrationData = nullptr;
Reset();
}
inline void AutoCalibration::Reset()
{
MinMaxWindow.Reset(0.f);
Confidence = 0.f;
bIsSteady = false;
MinDeltaGyro = Vec(1.f);
MinDeltaAccel = Vec(0.25f);
RecalibrateThreshold = 1.f;
SensorFusionSkippedTime = 0.f;
TimeSteadySensorFusion = 0.f;
TimeSteadyStillness = 0.f;
}
inline bool AutoCalibration::AddSampleStillness(const Vec& inGyro, const Vec& inAccel, float deltaTime, bool doSensorFusion)
{
if (inGyro.x == 0.f && inGyro.y == 0.f && inGyro.z == 0.f &&
inAccel.x == 0.f && inAccel.y == 0.f && inAccel.z == 0.f)
{
// zeroes are almost certainly not valid inputs
return false;
}
if (!Settings)
{
return false;
}
if (!CalibrationData)
{
return false;
}
// get settings
const int minStillnessSamples = Settings->MinStillnessSamples;
const float minStillnessCollectionTime = Settings->MinStillnessCollectionTime;
const float minStillnessCorrectionTime = Settings->MinStillnessCorrectionTime;
const float maxStillnessError = Settings->MaxStillnessError;
const float stillnessSampleDeteriorationRate = Settings->StillnessSampleDeteriorationRate;
const float stillnessErrorClimbRate = Settings->StillnessErrorClimbRate;
const float stillnessErrorDropOnRecalibrate = Settings->StillnessErrorDropOnRecalibrate;
const float stillnessCalibrationEaseInTime = Settings->StillnessCalibrationEaseInTime;
const float stillnessCalibrationHalfTime = Settings->StillnessCalibrationHalfTime * Confidence;
const float stillnessConfidenceRate = Settings->StillnessConfidenceRate;
const float stillnessGyroDelta = Settings->StillnessGyroDelta;
const float stillnessAccelDelta = Settings->StillnessAccelDelta;
MinMaxWindow.AddSample(inGyro, inAccel, deltaTime);
// get deltas
const Vec gyroDelta = MinMaxWindow.MaxGyro - MinMaxWindow.MinGyro;
const Vec accelDelta = MinMaxWindow.MaxAccel - MinMaxWindow.MinAccel;
bool calibrated = false;
bool isSteady = false;
const Vec climbThisTick = Vec(stillnessSampleDeteriorationRate * deltaTime);
if (stillnessGyroDelta < 0.f)
{
if (Confidence < 1.f)
{
MinDeltaGyro += climbThisTick;
}
}
else
{
MinDeltaGyro = Vec(stillnessGyroDelta);
}
if (stillnessAccelDelta < 0.f)
{
if (Confidence < 1.f)
{
MinDeltaAccel += climbThisTick;
}
}
else
{
MinDeltaAccel = Vec(stillnessAccelDelta);
}
//printf("Deltas: %.4f %.4f %.4f; %.4f %.4f %.4f\n",
// gyroDelta.x, gyroDelta.y, gyroDelta.z,
// accelDelta.x, accelDelta.y, accelDelta.z);
if (MinMaxWindow.NumSamples >= minStillnessSamples && MinMaxWindow.TimeSampled >= minStillnessCollectionTime)
{
MinDeltaGyro = MinDeltaGyro.Min(gyroDelta);
MinDeltaAccel = MinDeltaAccel.Min(accelDelta);
}
else
{
RecalibrateThreshold = std::min(RecalibrateThreshold + stillnessErrorClimbRate * deltaTime, maxStillnessError);
return false;
}
// check that all inputs are below appropriate thresholds to be considered "still"
if (gyroDelta.x <= MinDeltaGyro.x * RecalibrateThreshold &&
gyroDelta.y <= MinDeltaGyro.y * RecalibrateThreshold &&
gyroDelta.z <= MinDeltaGyro.z * RecalibrateThreshold &&
accelDelta.x <= MinDeltaAccel.x * RecalibrateThreshold &&
accelDelta.y <= MinDeltaAccel.y * RecalibrateThreshold &&
accelDelta.z <= MinDeltaAccel.z * RecalibrateThreshold)
{
if (MinMaxWindow.NumSamples >= minStillnessSamples && MinMaxWindow.TimeSampled >= minStillnessCorrectionTime)
{
/*if (TimeSteadyStillness == 0.f)
{
printf("Still!\n");
}/**/
TimeSteadyStillness = std::min(TimeSteadyStillness + deltaTime, stillnessCalibrationEaseInTime);
const float calibrationEaseIn = stillnessCalibrationEaseInTime <= 0.f ? 1.f : TimeSteadyStillness / stillnessCalibrationEaseInTime;
const Vec calibratedGyro = MinMaxWindow.GetMidGyro();
const Vec oldGyroBias = Vec(CalibrationData->X, CalibrationData->Y, CalibrationData->Z) / std::max((float)CalibrationData->NumSamples, 1.f);
const float stillnessLerpFactor = stillnessCalibrationHalfTime <= 0.f ? 0.f : exp2f(-calibrationEaseIn * deltaTime / stillnessCalibrationHalfTime);
Vec newGyroBias = calibratedGyro.Lerp(oldGyroBias, stillnessLerpFactor);
Confidence = std::min(Confidence + deltaTime * stillnessConfidenceRate, 1.f);
isSteady = true;
if (doSensorFusion)
{
const Vec previousNormal = MinMaxWindow.StartAccel.Normalized();
const Vec thisNormal = inAccel.Normalized();
Vec angularVelocity = thisNormal.Cross(previousNormal);
const float crossLength = angularVelocity.Length();
if (crossLength > 0.f)
{
const float thisDotPrev = std::clamp(thisNormal.Dot(previousNormal), -1.f, 1.f);
const float angleChange = acosf(thisDotPrev) * 180.0f / (float)M_PI;
const float anglePerSecond = angleChange / MinMaxWindow.TimeSampled;
angularVelocity *= anglePerSecond / crossLength;
}
Vec axisCalibrationStrength = thisNormal.Abs();
Vec sensorFusionBias = (calibratedGyro - angularVelocity).Lerp(oldGyroBias, stillnessLerpFactor);
if (axisCalibrationStrength.x <= 0.7f)
{
newGyroBias.x = sensorFusionBias.x;
}
if (axisCalibrationStrength.y <= 0.7f)
{
newGyroBias.y = sensorFusionBias.y;
}
if (axisCalibrationStrength.z <= 0.7f)
{
newGyroBias.z = sensorFusionBias.z;
}
}
CalibrationData->X = newGyroBias.x;
CalibrationData->Y = newGyroBias.y;
CalibrationData->Z = newGyroBias.z;
CalibrationData->AccelMagnitude = MinMaxWindow.MeanAccel.Length();
CalibrationData->NumSamples = 1;
calibrated = true;
}
else
{
RecalibrateThreshold = std::min(RecalibrateThreshold + stillnessErrorClimbRate * deltaTime, maxStillnessError);
}
}
else if (TimeSteadyStillness > 0.f)
{
//printf("Moved!\n");
RecalibrateThreshold -= stillnessErrorDropOnRecalibrate;
if (RecalibrateThreshold < 1.f) RecalibrateThreshold = 1.f;
TimeSteadyStillness = 0.f;
MinMaxWindow.Reset(0.f);
}
else
{
RecalibrateThreshold = std::min(RecalibrateThreshold + stillnessErrorClimbRate * deltaTime, maxStillnessError);
MinMaxWindow.Reset(0.f);
}
bIsSteady = isSteady;
return calibrated;
}
inline void AutoCalibration::NoSampleStillness()
{
MinMaxWindow.Reset(0.f);
}
inline bool AutoCalibration::AddSampleSensorFusion(const Vec& inGyro, const Vec& inAccel, float deltaTime)
{
if (deltaTime <= 0.f)
{
return false;
}
if (inGyro.x == 0.f && inGyro.y == 0.f && inGyro.z == 0.f &&
inAccel.x == 0.f && inAccel.y == 0.f && inAccel.z == 0.f)
{
// all zeroes are almost certainly not valid inputs
TimeSteadySensorFusion = 0.f;
SensorFusionSkippedTime = 0.f;
PreviousAccel = inAccel;
SmoothedPreviousAccel = inAccel;
SmoothedAngularVelocityGyro = GamepadMotionHelpers::Vec();
SmoothedAngularVelocityAccel = GamepadMotionHelpers::Vec();
return false;
}
if (PreviousAccel.x == 0.f && PreviousAccel.y == 0.f && PreviousAccel.z == 0.f)
{
TimeSteadySensorFusion = 0.f;
SensorFusionSkippedTime = 0.f;
PreviousAccel = inAccel;
SmoothedPreviousAccel = inAccel;
SmoothedAngularVelocityGyro = GamepadMotionHelpers::Vec();
SmoothedAngularVelocityAccel = GamepadMotionHelpers::Vec();
return false;
}
// in case the controller state hasn't updated between samples
if (inAccel.x == PreviousAccel.x && inAccel.y == PreviousAccel.y && inAccel.z == PreviousAccel.z)
{
SensorFusionSkippedTime += deltaTime;
return false;
}
if (!Settings)
{
return false;
}
// get settings
const float sensorFusionCalibrationSmoothingStrength = Settings->SensorFusionCalibrationSmoothingStrength;
const float sensorFusionAngularAccelerationThreshold = Settings->SensorFusionAngularAccelerationThreshold;
const float sensorFusionCalibrationEaseInTime = Settings->SensorFusionCalibrationEaseInTime;
const float sensorFusionCalibrationHalfTime = Settings->SensorFusionCalibrationHalfTime * Confidence;
const float sensorFusionConfidenceRate = Settings->SensorFusionConfidenceRate;
deltaTime += SensorFusionSkippedTime;
SensorFusionSkippedTime = 0.f;
bool calibrated = false;
bool isSteady = false;
// framerate independent lerp smoothing: https://www.gamasutra.com/blogs/ScottLembcke/20180404/316046/Improved_Lerp_Smoothing.php
const float smoothingLerpFactor = exp2f(-sensorFusionCalibrationSmoothingStrength * deltaTime);
// velocity from smoothed accel matches better if we also smooth gyro
const Vec previousGyro = SmoothedAngularVelocityGyro;
SmoothedAngularVelocityGyro = inGyro.Lerp(SmoothedAngularVelocityGyro, smoothingLerpFactor); // smooth what remains
const float gyroAccelerationMag = (SmoothedAngularVelocityGyro - previousGyro).Length() / deltaTime;
// get angle between old and new accel
const Vec previousNormal = SmoothedPreviousAccel.Normalized();
const Vec thisAccel = inAccel.Lerp(SmoothedPreviousAccel, smoothingLerpFactor);
const Vec thisNormal = thisAccel.Normalized();
Vec angularVelocity = thisNormal.Cross(previousNormal);
const float crossLength = angularVelocity.Length();
if (crossLength > 0.f)
{
const float thisDotPrev = std::clamp(thisNormal.Dot(previousNormal), -1.f, 1.f);
const float angleChange = acosf(thisDotPrev) * 180.0f / (float)M_PI;
const float anglePerSecond = angleChange / deltaTime;
angularVelocity *= anglePerSecond / crossLength;
}
SmoothedAngularVelocityAccel = angularVelocity;
// apply corrections
if (gyroAccelerationMag > sensorFusionAngularAccelerationThreshold || CalibrationData == nullptr)
{
/*if (TimeSteadySensorFusion > 0.f)
{
printf("Shaken!\n");
}/**/
TimeSteadySensorFusion = 0.f;
//printf("No calibration due to acceleration of %.4f\n", gyroAccelerationMag);
}
else
{
/*if (TimeSteadySensorFusion == 0.f)
{
printf("Steady!\n");
}/**/
TimeSteadySensorFusion = std::min(TimeSteadySensorFusion + deltaTime, sensorFusionCalibrationEaseInTime);
const float calibrationEaseIn = sensorFusionCalibrationEaseInTime <= 0.f ? 1.f : TimeSteadySensorFusion / sensorFusionCalibrationEaseInTime;
const Vec oldGyroBias = Vec(CalibrationData->X, CalibrationData->Y, CalibrationData->Z) / std::max((float)CalibrationData->NumSamples, 1.f);
// recalibrate over time proportional to the difference between the calculated bias and the current assumed bias
const float sensorFusionLerpFactor = sensorFusionCalibrationHalfTime <= 0.f ? 0.f : exp2f(-calibrationEaseIn * deltaTime / sensorFusionCalibrationHalfTime);
Vec newGyroBias = (SmoothedAngularVelocityGyro - SmoothedAngularVelocityAccel).Lerp(oldGyroBias, sensorFusionLerpFactor);
Confidence = std::min(Confidence + deltaTime * sensorFusionConfidenceRate, 1.f);
isSteady = true;
// don't change bias in axes that can't be affected by the gravity direction
Vec axisCalibrationStrength = thisNormal.Abs();
if (axisCalibrationStrength.x > 0.7f)