1use std::ops::Mul;
12
13use crate::protocol::{ImuSample, Packet, SAMPLE_INTERVAL_US};
14
15#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct Quat {
18 pub w: f32,
19 pub x: f32,
20 pub y: f32,
21 pub z: f32,
22}
23
24impl Default for Quat {
25 fn default() -> Quat {
26 Quat::IDENTITY
27 }
28}
29
30impl Quat {
31 pub const IDENTITY: Quat = Quat {
32 w: 1.0,
33 x: 0.0,
34 y: 0.0,
35 z: 0.0,
36 };
37
38 pub fn from_axis_angle(axis: [f32; 3], angle: f32) -> Quat {
40 let (s, c) = (angle * 0.5).sin_cos();
41 Quat {
42 w: c,
43 x: axis[0] * s,
44 y: axis[1] * s,
45 z: axis[2] * s,
46 }
47 }
48
49 pub fn from_euler(e: Euler) -> Quat {
51 Quat::from_axis_angle([0.0, 0.0, 1.0], e.yaw)
52 * Quat::from_axis_angle([1.0, 0.0, 0.0], e.pitch)
53 * Quat::from_axis_angle([0.0, 1.0, 0.0], e.roll)
54 }
55
56 pub fn conjugate(self) -> Quat {
57 Quat {
58 w: self.w,
59 x: -self.x,
60 y: -self.y,
61 z: -self.z,
62 }
63 }
64
65 pub fn normalized(self) -> Quat {
66 let n = (self.w * self.w + self.x * self.x + self.y * self.y + self.z * self.z).sqrt();
67 if n > 0.0 {
68 Quat {
69 w: self.w / n,
70 x: self.x / n,
71 y: self.y / n,
72 z: self.z / n,
73 }
74 } else {
75 Quat::IDENTITY
76 }
77 }
78
79 pub fn to_matrix(self) -> [[f32; 3]; 3] {
82 let Quat { w, x, y, z } = self;
83 [
84 [
85 1.0 - 2.0 * (y * y + z * z),
86 2.0 * (x * y - w * z),
87 2.0 * (x * z + w * y),
88 ],
89 [
90 2.0 * (x * y + w * z),
91 1.0 - 2.0 * (x * x + z * z),
92 2.0 * (y * z - w * x),
93 ],
94 [
95 2.0 * (x * z - w * y),
96 2.0 * (y * z + w * x),
97 1.0 - 2.0 * (x * x + y * y),
98 ],
99 ]
100 }
101
102 pub fn rotate(self, v: [f32; 3]) -> [f32; 3] {
104 let m = self.to_matrix();
105 [
106 m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2],
107 m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2],
108 m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2],
109 ]
110 }
111
112 pub fn euler(self) -> Euler {
114 let m = self.to_matrix();
115 Euler {
116 yaw: (-m[0][1]).atan2(m[1][1]),
117 pitch: m[2][1].clamp(-1.0, 1.0).asin(),
118 roll: (-m[2][0]).atan2(m[2][2]),
119 }
120 }
121
122 pub fn angle_to(self, other: Quat) -> f32 {
124 let dot = self.w * other.w + self.x * other.x + self.y * other.y + self.z * other.z;
125 2.0 * dot.abs().min(1.0).acos()
126 }
127}
128
129impl Mul for Quat {
130 type Output = Quat;
131 fn mul(self, r: Quat) -> Quat {
133 Quat {
134 w: self.w * r.w - self.x * r.x - self.y * r.y - self.z * r.z,
135 x: self.w * r.x + self.x * r.w + self.y * r.z - self.z * r.y,
136 y: self.w * r.y - self.x * r.z + self.y * r.w + self.z * r.x,
137 z: self.w * r.z + self.x * r.y - self.y * r.x + self.z * r.w,
138 }
139 }
140}
141
142#[derive(Clone, Copy, Debug, Default, PartialEq)]
144pub struct Euler {
145 pub yaw: f32,
147 pub pitch: f32,
149 pub roll: f32,
151}
152
153#[derive(Clone, Debug)]
155pub struct Orientation {
156 q: Quat,
157 yaw_offset: f32,
158 last_timestamp: Option<u32>,
159 samples: u32,
160 gain: f32,
161}
162
163impl Default for Orientation {
164 fn default() -> Orientation {
165 Orientation::new()
166 }
167}
168
169impl Orientation {
170 pub const DEFAULT_GAIN: f32 = 0.06;
172 const SETTLE_GAIN: f32 = 2.5;
174 const SETTLE_SAMPLES: u32 = 150;
175 const MAX_GAP_US: u32 = 100_000;
177
178 pub fn new() -> Orientation {
179 Orientation {
180 q: Quat::IDENTITY,
181 yaw_offset: 0.0,
182 last_timestamp: None,
183 samples: 0,
184 gain: Orientation::DEFAULT_GAIN,
185 }
186 }
187
188 pub fn set_gain(&mut self, gain: f32) {
191 self.gain = gain;
192 }
193
194 pub fn update(&mut self, packet: &Packet) {
196 for sample in &packet.samples {
197 self.update_sample(sample);
198 }
199 }
200
201 pub fn update_sample(&mut self, sample: &ImuSample) {
203 let gap = match self.last_timestamp {
204 Some(last) => sample.timestamp_us.wrapping_sub(last),
205 None => SAMPLE_INTERVAL_US,
206 };
207 self.last_timestamp = Some(sample.timestamp_us);
208 let gap = if gap == 0 || gap > Orientation::MAX_GAP_US {
209 SAMPLE_INTERVAL_US
210 } else {
211 gap
212 };
213 self.step(sample.gyro, sample.accel, gap as f32 * 1e-6);
214 }
215
216 pub fn step(&mut self, gyro: [f32; 3], accel: [f32; 3], dt: f32) {
218 let Quat {
219 w: q0,
220 x: q1,
221 y: q2,
222 z: q3,
223 } = self.q;
224 let [gx, gy, gz] = gyro;
225
226 let mut rate = [
228 0.5 * (-q1 * gx - q2 * gy - q3 * gz),
229 0.5 * (q0 * gx + q2 * gz - q3 * gy),
230 0.5 * (q0 * gy - q1 * gz + q3 * gx),
231 0.5 * (q0 * gz + q1 * gy - q2 * gx),
232 ];
233
234 let norm = accel.iter().map(|v| v * v).sum::<f32>().sqrt();
235 if norm > 1e-6 {
236 let f = [
238 2.0 * (q1 * q3 - q0 * q2) - accel[0] / norm,
239 2.0 * (q0 * q1 + q2 * q3) - accel[1] / norm,
240 1.0 - 2.0 * (q1 * q1 + q2 * q2) - accel[2] / norm,
241 ];
242 let mut s = [
244 -2.0 * q2 * f[0] + 2.0 * q1 * f[1],
245 2.0 * q3 * f[0] + 2.0 * q0 * f[1] - 4.0 * q1 * f[2],
246 -2.0 * q0 * f[0] + 2.0 * q3 * f[1] - 4.0 * q2 * f[2],
247 2.0 * q1 * f[0] + 2.0 * q2 * f[1],
248 ];
249 let s_norm = s.iter().map(|v| v * v).sum::<f32>().sqrt();
250 if s_norm > 1e-9 {
251 let gain = if self.samples < Orientation::SETTLE_SAMPLES {
252 Orientation::SETTLE_GAIN.max(self.gain)
253 } else {
254 self.gain
255 };
256 for (r, s) in rate.iter_mut().zip(s.iter_mut()) {
257 *r -= gain * *s / s_norm;
258 }
259 }
260 }
261
262 self.q = Quat {
263 w: q0 + rate[0] * dt,
264 x: q1 + rate[1] * dt,
265 y: q2 + rate[2] * dt,
266 z: q3 + rate[3] * dt,
267 }
268 .normalized();
269 self.samples = self.samples.saturating_add(1);
270 }
271
272 pub fn quaternion(&self) -> Quat {
274 Quat::from_axis_angle([0.0, 0.0, 1.0], -self.yaw_offset) * self.q
275 }
276
277 pub fn euler(&self) -> Euler {
279 self.quaternion().euler()
280 }
281
282 pub fn recenter(&mut self) {
285 self.yaw_offset = self.q.euler().yaw;
286 }
287
288 pub fn reset(&mut self) {
290 *self = Orientation {
291 gain: self.gain,
292 ..Orientation::new()
293 };
294 }
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300 use std::f32::consts::FRAC_PI_2;
301
302 const G: f32 = 9.80665;
303 const DT: f32 = 0.00485;
304
305 fn close(a: f32, b: f32, tolerance: f32) -> bool {
306 (a - b).abs() <= tolerance
307 }
308
309 #[test]
310 fn euler_round_trips() {
311 let e = Euler {
312 yaw: 0.7,
313 pitch: -0.4,
314 roll: 1.1,
315 };
316 let back = Quat::from_euler(e).euler();
317 assert!(
318 close(back.yaw, e.yaw, 1e-5)
319 && close(back.pitch, e.pitch, 1e-5)
320 && close(back.roll, e.roll, 1e-5)
321 );
322 }
323
324 #[test]
325 fn euler_signs_match_the_docs() {
326 let left = Quat::from_euler(Euler {
327 yaw: 0.5,
328 ..Euler::default()
329 })
330 .rotate([0.0, 1.0, 0.0]);
331 assert!(
332 left[0] < 0.0,
333 "positive yaw swings the tip toward -x (left)"
334 );
335 let up = Quat::from_euler(Euler {
336 pitch: 0.5,
337 ..Euler::default()
338 })
339 .rotate([0.0, 1.0, 0.0]);
340 assert!(up[2] > 0.0, "positive pitch lifts the tip");
341 let roll = Quat::from_euler(Euler {
342 roll: 0.5,
343 ..Euler::default()
344 })
345 .rotate([1.0, 0.0, 0.0]);
346 assert!(roll[2] < 0.0, "positive roll dips the right edge");
347 }
348
349 #[test]
350 fn lying_flat_stays_level() {
351 let mut o = Orientation::new();
352 for _ in 0..500 {
353 o.step([0.0; 3], [0.0, 0.0, G], DT);
354 }
355 assert!(o.quaternion().angle_to(Quat::IDENTITY) < 1e-3);
356 }
357
358 #[test]
359 fn finds_up_from_the_accelerometer() {
360 let mut o = Orientation::new();
362 for _ in 0..600 {
363 o.step([0.0; 3], [0.0, G, 0.0], DT);
364 }
365 assert!(
366 close(o.euler().pitch, FRAC_PI_2, 0.03),
367 "pitch {}",
368 o.euler().pitch
369 );
370
371 let mut o = Orientation::new();
373 for _ in 0..600 {
374 o.step([0.0; 3], [-G, 0.0, 0.0], DT);
375 }
376 let e = o.euler();
377 assert!(
378 close(e.roll, FRAC_PI_2, 0.03) && close(e.pitch, 0.0, 0.03),
379 "{e:?}"
380 );
381 }
382
383 #[test]
384 fn integrates_the_gyroscope() {
385 let mut o = Orientation::new();
386 let steps = (1.0 / DT).round() as usize;
388 for _ in 0..steps {
389 o.step([0.0, 0.0, 0.5], [0.0, 0.0, G], DT);
390 }
391 let e = o.euler();
392 assert!(close(e.yaw, 0.5 * steps as f32 * DT, 1e-3), "{e:?}");
393 assert!(close(e.pitch, 0.0, 1e-3) && close(e.roll, 0.0, 1e-3));
394 }
395
396 #[test]
397 fn recenter_zeroes_only_the_heading() {
398 let mut o = Orientation::new();
399 for _ in 0..300 {
400 o.step([0.0, 0.0, 1.0], [0.0, G * 0.5, G * 0.866], DT);
401 }
402 let before = o.euler();
403 assert!(before.yaw.abs() > 0.5);
404 o.recenter();
405 let after = o.euler();
406 assert!(close(after.yaw, 0.0, 1e-4));
407 assert!(close(after.pitch, before.pitch, 1e-4) && close(after.roll, before.roll, 1e-4));
408 }
409
410 #[test]
411 fn uses_device_timestamps() {
412 let sample = |t: u32| ImuSample {
413 timestamp_us: t,
414 accel: [0.0, 0.0, G],
415 gyro: [0.0, 0.0, 1.0],
416 };
417
418 let mut o = Orientation::new();
420 let start = u32::MAX - 500_000;
421 for i in 0..=100u32 {
422 o.update_sample(&sample(start.wrapping_add(i * 10_000)));
423 }
424 let expected = 1.0 + SAMPLE_INTERVAL_US as f32 * 1e-6;
426 assert!(
427 close(o.euler().yaw, expected, 2e-3),
428 "yaw {}",
429 o.euler().yaw
430 );
431
432 let mut o = Orientation::new();
434 o.update_sample(&sample(0));
435 o.update_sample(&sample(5_000_000));
436 assert!(o.euler().yaw < 0.02);
437 }
438}