use std::ops::Mul;
use crate::protocol::{ImuSample, Packet, SAMPLE_INTERVAL_US};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Quat {
pub w: f32,
pub x: f32,
pub y: f32,
pub z: f32,
}
impl Default for Quat {
fn default() -> Quat {
Quat::IDENTITY
}
}
impl Quat {
pub const IDENTITY: Quat = Quat {
w: 1.0,
x: 0.0,
y: 0.0,
z: 0.0,
};
pub fn from_axis_angle(axis: [f32; 3], angle: f32) -> Quat {
let (s, c) = (angle * 0.5).sin_cos();
Quat {
w: c,
x: axis[0] * s,
y: axis[1] * s,
z: axis[2] * s,
}
}
pub fn from_euler(e: Euler) -> Quat {
Quat::from_axis_angle([0.0, 0.0, 1.0], e.yaw)
* Quat::from_axis_angle([1.0, 0.0, 0.0], e.pitch)
* Quat::from_axis_angle([0.0, 1.0, 0.0], e.roll)
}
pub fn conjugate(self) -> Quat {
Quat {
w: self.w,
x: -self.x,
y: -self.y,
z: -self.z,
}
}
pub fn normalized(self) -> Quat {
let n = (self.w * self.w + self.x * self.x + self.y * self.y + self.z * self.z).sqrt();
if n > 0.0 {
Quat {
w: self.w / n,
x: self.x / n,
y: self.y / n,
z: self.z / n,
}
} else {
Quat::IDENTITY
}
}
pub fn to_matrix(self) -> [[f32; 3]; 3] {
let Quat { w, x, y, z } = self;
[
[
1.0 - 2.0 * (y * y + z * z),
2.0 * (x * y - w * z),
2.0 * (x * z + w * y),
],
[
2.0 * (x * y + w * z),
1.0 - 2.0 * (x * x + z * z),
2.0 * (y * z - w * x),
],
[
2.0 * (x * z - w * y),
2.0 * (y * z + w * x),
1.0 - 2.0 * (x * x + y * y),
],
]
}
pub fn rotate(self, v: [f32; 3]) -> [f32; 3] {
let m = self.to_matrix();
[
m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2],
m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2],
m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2],
]
}
pub fn euler(self) -> Euler {
let m = self.to_matrix();
Euler {
yaw: (-m[0][1]).atan2(m[1][1]),
pitch: m[2][1].clamp(-1.0, 1.0).asin(),
roll: (-m[2][0]).atan2(m[2][2]),
}
}
pub fn angle_to(self, other: Quat) -> f32 {
let dot = self.w * other.w + self.x * other.x + self.y * other.y + self.z * other.z;
2.0 * dot.abs().min(1.0).acos()
}
}
impl Mul for Quat {
type Output = Quat;
fn mul(self, r: Quat) -> Quat {
Quat {
w: self.w * r.w - self.x * r.x - self.y * r.y - self.z * r.z,
x: self.w * r.x + self.x * r.w + self.y * r.z - self.z * r.y,
y: self.w * r.y - self.x * r.z + self.y * r.w + self.z * r.x,
z: self.w * r.z + self.x * r.y - self.y * r.x + self.z * r.w,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Euler {
pub yaw: f32,
pub pitch: f32,
pub roll: f32,
}
#[derive(Clone, Debug)]
pub struct Orientation {
q: Quat,
yaw_offset: f32,
last_timestamp: Option<u32>,
samples: u32,
gain: f32,
}
impl Default for Orientation {
fn default() -> Orientation {
Orientation::new()
}
}
impl Orientation {
pub const DEFAULT_GAIN: f32 = 0.06;
const SETTLE_GAIN: f32 = 2.5;
const SETTLE_SAMPLES: u32 = 150;
const MAX_GAP_US: u32 = 100_000;
pub fn new() -> Orientation {
Orientation {
q: Quat::IDENTITY,
yaw_offset: 0.0,
last_timestamp: None,
samples: 0,
gain: Orientation::DEFAULT_GAIN,
}
}
pub fn set_gain(&mut self, gain: f32) {
self.gain = gain;
}
pub fn update(&mut self, packet: &Packet) {
for sample in &packet.samples {
self.update_sample(sample);
}
}
pub fn update_sample(&mut self, sample: &ImuSample) {
let gap = match self.last_timestamp {
Some(last) => sample.timestamp_us.wrapping_sub(last),
None => SAMPLE_INTERVAL_US,
};
self.last_timestamp = Some(sample.timestamp_us);
let gap = if gap == 0 || gap > Orientation::MAX_GAP_US {
SAMPLE_INTERVAL_US
} else {
gap
};
self.step(sample.gyro, sample.accel, gap as f32 * 1e-6);
}
pub fn step(&mut self, gyro: [f32; 3], accel: [f32; 3], dt: f32) {
let Quat {
w: q0,
x: q1,
y: q2,
z: q3,
} = self.q;
let [gx, gy, gz] = gyro;
let mut rate = [
0.5 * (-q1 * gx - q2 * gy - q3 * gz),
0.5 * (q0 * gx + q2 * gz - q3 * gy),
0.5 * (q0 * gy - q1 * gz + q3 * gx),
0.5 * (q0 * gz + q1 * gy - q2 * gx),
];
let norm = accel.iter().map(|v| v * v).sum::<f32>().sqrt();
if norm > 1e-6 {
let f = [
2.0 * (q1 * q3 - q0 * q2) - accel[0] / norm,
2.0 * (q0 * q1 + q2 * q3) - accel[1] / norm,
1.0 - 2.0 * (q1 * q1 + q2 * q2) - accel[2] / norm,
];
let mut s = [
-2.0 * q2 * f[0] + 2.0 * q1 * f[1],
2.0 * q3 * f[0] + 2.0 * q0 * f[1] - 4.0 * q1 * f[2],
-2.0 * q0 * f[0] + 2.0 * q3 * f[1] - 4.0 * q2 * f[2],
2.0 * q1 * f[0] + 2.0 * q2 * f[1],
];
let s_norm = s.iter().map(|v| v * v).sum::<f32>().sqrt();
if s_norm > 1e-9 {
let gain = if self.samples < Orientation::SETTLE_SAMPLES {
Orientation::SETTLE_GAIN.max(self.gain)
} else {
self.gain
};
for (r, s) in rate.iter_mut().zip(s.iter_mut()) {
*r -= gain * *s / s_norm;
}
}
}
self.q = Quat {
w: q0 + rate[0] * dt,
x: q1 + rate[1] * dt,
y: q2 + rate[2] * dt,
z: q3 + rate[3] * dt,
}
.normalized();
self.samples = self.samples.saturating_add(1);
}
pub fn quaternion(&self) -> Quat {
Quat::from_axis_angle([0.0, 0.0, 1.0], -self.yaw_offset) * self.q
}
pub fn euler(&self) -> Euler {
self.quaternion().euler()
}
pub fn recenter(&mut self) {
self.yaw_offset = self.q.euler().yaw;
}
pub fn reset(&mut self) {
*self = Orientation {
gain: self.gain,
..Orientation::new()
};
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::f32::consts::FRAC_PI_2;
const G: f32 = 9.80665;
const DT: f32 = 0.00485;
fn close(a: f32, b: f32, tolerance: f32) -> bool {
(a - b).abs() <= tolerance
}
#[test]
fn euler_round_trips() {
let e = Euler {
yaw: 0.7,
pitch: -0.4,
roll: 1.1,
};
let back = Quat::from_euler(e).euler();
assert!(
close(back.yaw, e.yaw, 1e-5)
&& close(back.pitch, e.pitch, 1e-5)
&& close(back.roll, e.roll, 1e-5)
);
}
#[test]
fn euler_signs_match_the_docs() {
let left = Quat::from_euler(Euler {
yaw: 0.5,
..Euler::default()
})
.rotate([0.0, 1.0, 0.0]);
assert!(
left[0] < 0.0,
"positive yaw swings the tip toward -x (left)"
);
let up = Quat::from_euler(Euler {
pitch: 0.5,
..Euler::default()
})
.rotate([0.0, 1.0, 0.0]);
assert!(up[2] > 0.0, "positive pitch lifts the tip");
let roll = Quat::from_euler(Euler {
roll: 0.5,
..Euler::default()
})
.rotate([1.0, 0.0, 0.0]);
assert!(roll[2] < 0.0, "positive roll dips the right edge");
}
#[test]
fn lying_flat_stays_level() {
let mut o = Orientation::new();
for _ in 0..500 {
o.step([0.0; 3], [0.0, 0.0, G], DT);
}
assert!(o.quaternion().angle_to(Quat::IDENTITY) < 1e-3);
}
#[test]
fn finds_up_from_the_accelerometer() {
let mut o = Orientation::new();
for _ in 0..600 {
o.step([0.0; 3], [0.0, G, 0.0], DT);
}
assert!(
close(o.euler().pitch, FRAC_PI_2, 0.03),
"pitch {}",
o.euler().pitch
);
let mut o = Orientation::new();
for _ in 0..600 {
o.step([0.0; 3], [-G, 0.0, 0.0], DT);
}
let e = o.euler();
assert!(
close(e.roll, FRAC_PI_2, 0.03) && close(e.pitch, 0.0, 0.03),
"{e:?}"
);
}
#[test]
fn integrates_the_gyroscope() {
let mut o = Orientation::new();
let steps = (1.0 / DT).round() as usize;
for _ in 0..steps {
o.step([0.0, 0.0, 0.5], [0.0, 0.0, G], DT);
}
let e = o.euler();
assert!(close(e.yaw, 0.5 * steps as f32 * DT, 1e-3), "{e:?}");
assert!(close(e.pitch, 0.0, 1e-3) && close(e.roll, 0.0, 1e-3));
}
#[test]
fn recenter_zeroes_only_the_heading() {
let mut o = Orientation::new();
for _ in 0..300 {
o.step([0.0, 0.0, 1.0], [0.0, G * 0.5, G * 0.866], DT);
}
let before = o.euler();
assert!(before.yaw.abs() > 0.5);
o.recenter();
let after = o.euler();
assert!(close(after.yaw, 0.0, 1e-4));
assert!(close(after.pitch, before.pitch, 1e-4) && close(after.roll, before.roll, 1e-4));
}
#[test]
fn uses_device_timestamps() {
let sample = |t: u32| ImuSample {
timestamp_us: t,
accel: [0.0, 0.0, G],
gyro: [0.0, 0.0, 1.0],
};
let mut o = Orientation::new();
let start = u32::MAX - 500_000;
for i in 0..=100u32 {
o.update_sample(&sample(start.wrapping_add(i * 10_000)));
}
let expected = 1.0 + SAMPLE_INTERVAL_US as f32 * 1e-6;
assert!(
close(o.euler().yaw, expected, 2e-3),
"yaw {}",
o.euler().yaw
);
let mut o = Orientation::new();
o.update_sample(&sample(0));
o.update_sample(&sample(5_000_000));
assert!(o.euler().yaw < 0.02);
}
}