use std::f64::consts::PI;
use std::time::Duration;
use crate::orientation::{Euler, Quat};
use crate::protocol::{
Buttons, ImuSample, Packet, Touch, PACKET_LEN, SAMPLE_INTERVAL_US, TOUCH_MAX,
};
const GRAVITY: f32 = 9.80665;
const FIELD: [f32; 3] = [0.0, 20.0, -44.0];
const CYCLE: f64 = 4.0 * PI;
#[derive(Clone, Debug, Default)]
pub struct Simulator {
sample_index: u64,
}
impl Simulator {
pub const PACKET_INTERVAL: Duration = Duration::from_micros(3 * SAMPLE_INTERVAL_US as u64);
pub const NAME: &'static str = "Simulated controller";
pub fn new() -> Simulator {
Simulator::default()
}
pub fn elapsed(&self) -> f64 {
time_of(self.sample_index)
}
pub fn pose_at(t: f64) -> Quat {
Quat::from_euler(angles(t).0)
}
pub fn next_bytes(&mut self) -> [u8; PACKET_LEN] {
let mut samples = [ImuSample::default(); 3];
for sample in &mut samples {
*sample = sample_at(self.sample_index);
self.sample_index += 1;
}
let t = time_of(self.sample_index - 1);
let (touch, buttons) = inputs(t % CYCLE);
let to_body = Simulator::pose_at(t).conjugate();
Packet {
samples,
mag: to_body.rotate(FIELD),
touch,
temperature: 25,
buttons,
}
.encode()
}
pub fn next_packet(&mut self) -> Packet {
Packet::parse(&self.next_bytes()).expect("simulated packets are full length")
}
}
fn time_of(sample_index: u64) -> f64 {
sample_index as f64 * SAMPLE_INTERVAL_US as f64 * 1e-6
}
fn angles(t: f64) -> (Euler, Euler) {
let angle = Euler {
yaw: (0.9 * (0.5 * t).sin()) as f32,
pitch: (0.5 * (0.8 * t).sin() + 0.15) as f32,
roll: (0.6 * (1.1 * t).sin()) as f32,
};
let rate = Euler {
yaw: (0.45 * (0.5 * t).cos()) as f32,
pitch: (0.4 * (0.8 * t).cos()) as f32,
roll: (0.66 * (1.1 * t).cos()) as f32,
};
(angle, rate)
}
fn sample_at(index: u64) -> ImuSample {
let t = time_of(index);
let (angle, rate) = angles(t);
let (sp, cp) = angle.pitch.sin_cos();
let (sr, cr) = angle.roll.sin_cos();
let gyro = [
-sr * cp * rate.yaw + cr * rate.pitch,
sp * rate.yaw + rate.roll,
cr * cp * rate.yaw + sr * rate.pitch,
];
let accel = Quat::from_euler(angle)
.conjugate()
.rotate([0.0, 0.0, GRAVITY]);
ImuSample {
timestamp_us: (1_000_000 + index * SAMPLE_INTERVAL_US as u64) as u32,
accel,
gyro,
}
}
fn inputs(c: f64) -> (Option<Touch>, Buttons) {
let touch = (2.0..6.0).contains(&c).then(|| {
let half = TOUCH_MAX as f64 / 2.0;
let a = (c - 2.0) * 1.8;
Touch {
x: (half + 110.0 * a.cos()).round() as u16,
y: (half + 110.0 * a.sin()).round() as u16,
}
});
let script = [
(0.0..0.3, Buttons::HOME),
(4.5..4.9, Buttons::TOUCHPAD),
(6.8..7.6, Buttons::TRIGGER),
(8.4..8.8, Buttons::BACK),
(9.6..10.0, Buttons::VOLUME_UP),
(10.6..11.0, Buttons::VOLUME_DOWN),
];
let buttons = script
.into_iter()
.filter(|(range, _)| range.contains(&c))
.fold(Buttons::NONE, |held, (_, button)| held | button);
(touch, buttons)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Orientation;
#[test]
fn packets_look_like_real_ones() {
let mut sim = Simulator::new();
let mut last = None;
for _ in 0..200 {
let p = sim.next_packet();
for s in &p.samples {
if let Some(last) = last {
assert_eq!(s.timestamp_us - last, SAMPLE_INTERVAL_US);
}
last = Some(s.timestamp_us);
let g = s.accel.iter().map(|v| v * v).sum::<f32>().sqrt() / GRAVITY;
assert!((g - 1.0).abs() < 0.01, "accelerometer reads {g} g");
}
assert_eq!(p.temperature, 25);
}
}
#[test]
fn the_filter_tracks_the_simulated_motion() {
let mut sim = Simulator::new();
let mut orientation = Orientation::new();
let mut worst = 0.0f32;
while sim.elapsed() < 25.0 {
orientation.update(&sim.next_packet());
if sim.elapsed() > 1.5 {
let truth = Simulator::pose_at(sim.elapsed() - time_of(1));
worst = worst.max(orientation.quaternion().angle_to(truth));
}
}
assert!(
worst.to_degrees() < 3.0,
"worst error {:.2}°",
worst.to_degrees()
);
}
#[test]
fn every_button_and_the_touchpad_are_exercised() {
let mut sim = Simulator::new();
let mut seen = Buttons::NONE;
let (mut touched, mut untouched) = (false, false);
let mut first = None;
while sim.elapsed() < CYCLE {
let p = sim.next_packet();
first.get_or_insert(p.buttons);
seen = seen | p.buttons;
match p.touch {
Some(t) => {
touched = true;
assert!(t.x <= TOUCH_MAX && t.y <= TOUCH_MAX);
}
None => untouched = true,
}
}
assert_eq!(seen.bits(), 0b11_1111);
assert!(touched && untouched);
assert_eq!(
first,
Some(Buttons::HOME),
"Home is pressed at the start, where yaw is 0"
);
}
}