gearvr-controller 0.1.2

Read the Samsung Gear VR Controller (ET-YO324) over Bluetooth LE: packet decoding, orientation tracking and a btleplug transport
Documentation
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
//! Orientation tracking from the gyroscope and accelerometer.
//!
//! [`Orientation`] runs a Madgwick filter: the gyroscope is integrated for fast response and
//! the accelerometer's sense of "up" corrects the drift in pitch and roll. Nothing corrects
//! the heading, so yaw drifts slowly; call [`Orientation::recenter`] to zero it. The
//! magnetometer is not used because its readings are uncalibrated.
//!
//! The world frame has **z** up. After [`Orientation::recenter`], world **y** is the direction
//! the controller pointed at that moment.

use std::ops::Mul;

use crate::protocol::{ImuSample, Packet, SAMPLE_INTERVAL_US};

/// A rotation as a unit quaternion.
#[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,
    };

    /// A right-handed rotation of `angle` radians about `axis` (which must be unit length).
    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,
        }
    }

    /// Builds the rotation with the given heading, pitch and roll (see [`Euler`]).
    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
        }
    }

    /// The rotation as a matrix, indexed `[row][column]`. Column `k` is where the
    /// controller's axis `k` points in the world.
    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),
            ],
        ]
    }

    /// Rotates a vector from the controller's frame into the world frame.
    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],
        ]
    }

    /// Heading, pitch and roll of this rotation.
    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]),
        }
    }

    /// The angle in radians of the rotation that takes `self` to `other`.
    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;
    /// `a * b` applies `b` first, then `a`.
    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,
        }
    }
}

/// An orientation as three angles in radians.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Euler {
    /// Heading: positive when the tip swings to the left.
    pub yaw: f32,
    /// Positive when the tip points up.
    pub pitch: f32,
    /// Twist about the pointing direction: positive when the right edge dips.
    pub roll: f32,
}

/// Tracks the controller's orientation from its motion samples.
#[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 {
    /// How strongly the accelerometer corrects the gyroscope once the filter has settled.
    pub const DEFAULT_GAIN: f32 = 0.06;
    /// Gain used for the first [`Self::SETTLE_SAMPLES`] samples so the filter finds "up" quickly.
    const SETTLE_GAIN: f32 = 2.5;
    const SETTLE_SAMPLES: u32 = 150;
    /// Gaps longer than this (in µs) mean packets were lost; the nominal interval is used instead.
    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,
        }
    }

    /// Sets how strongly the accelerometer corrects the gyroscope. Higher values remove drift
    /// faster but let hand movement disturb pitch and roll more.
    pub fn set_gain(&mut self, gain: f32) {
        self.gain = gain;
    }

    /// Feeds all three samples of a packet.
    pub fn update(&mut self, packet: &Packet) {
        for sample in &packet.samples {
            self.update_sample(sample);
        }
    }

    /// Feeds one sample. Samples must arrive in order.
    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);
    }

    /// Advances the filter by `dt` seconds with one gyroscope (rad/s) and accelerometer reading.
    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;

        // Rate of change from the gyroscope: q' = q * (0, gyro) / 2.
        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 {
            // Difference between where the estimate says "up" is and where the accelerometer says.
            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,
            ];
            // Gradient of |f|² / 2 with respect to the quaternion.
            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);
    }

    /// The current orientation: the rotation from the controller's frame to the world frame.
    pub fn quaternion(&self) -> Quat {
        Quat::from_axis_angle([0.0, 0.0, 1.0], -self.yaw_offset) * self.q
    }

    /// The current orientation as heading, pitch and roll.
    pub fn euler(&self) -> Euler {
        self.quaternion().euler()
    }

    /// Makes the direction the controller points now the new "straight ahead" (yaw 0).
    /// Pitch and roll are untouched because gravity already anchors them.
    pub fn recenter(&mut self) {
        self.yaw_offset = self.q.euler().yaw;
    }

    /// Forgets everything, as if no sample had been seen.
    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() {
        // Tip straight up: gravity's reaction is along the controller's +y axis.
        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
        );

        // Rolled 90° so the right edge points down: the reaction is along -x.
        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();
        // 0.5 rad/s about the up axis for one second.
        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],
        };

        // 100 samples 10 ms apart, crossing the u32 wrap-around.
        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)));
        }
        // The first sample has no predecessor and counts as one nominal interval.
        let expected = 1.0 + SAMPLE_INTERVAL_US as f32 * 1e-6;
        assert!(
            close(o.euler().yaw, expected, 2e-3),
            "yaw {}",
            o.euler().yaw
        );

        // A long gap (lost packets) must not be integrated as if the rate held throughout.
        let mut o = Orientation::new();
        o.update_sample(&sample(0));
        o.update_sample(&sample(5_000_000));
        assert!(o.euler().yaw < 0.02);
    }
}