1use std::f64::consts::PI;
8use std::time::Duration;
9
10use crate::orientation::{Euler, Quat};
11use crate::protocol::{
12 Buttons, ImuSample, Packet, Touch, PACKET_LEN, SAMPLE_INTERVAL_US, TOUCH_MAX,
13};
14
15const GRAVITY: f32 = 9.80665;
16const FIELD: [f32; 3] = [0.0, 20.0, -44.0];
18const CYCLE: f64 = 4.0 * PI;
21
22#[derive(Clone, Debug, Default)]
24pub struct Simulator {
25 sample_index: u64,
26}
27
28impl Simulator {
29 pub const PACKET_INTERVAL: Duration = Duration::from_micros(3 * SAMPLE_INTERVAL_US as u64);
31 pub const NAME: &'static str = "Simulated controller";
33
34 pub fn new() -> Simulator {
35 Simulator::default()
36 }
37
38 pub fn elapsed(&self) -> f64 {
40 time_of(self.sample_index)
41 }
42
43 pub fn pose_at(t: f64) -> Quat {
45 Quat::from_euler(angles(t).0)
46 }
47
48 pub fn next_bytes(&mut self) -> [u8; PACKET_LEN] {
50 let mut samples = [ImuSample::default(); 3];
51 for sample in &mut samples {
52 *sample = sample_at(self.sample_index);
53 self.sample_index += 1;
54 }
55 let t = time_of(self.sample_index - 1);
56 let (touch, buttons) = inputs(t % CYCLE);
57 let to_body = Simulator::pose_at(t).conjugate();
58 Packet {
59 samples,
60 mag: to_body.rotate(FIELD),
61 touch,
62 temperature: 25,
63 buttons,
64 }
65 .encode()
66 }
67
68 pub fn next_packet(&mut self) -> Packet {
70 Packet::parse(&self.next_bytes()).expect("simulated packets are full length")
71 }
72}
73
74fn time_of(sample_index: u64) -> f64 {
75 sample_index as f64 * SAMPLE_INTERVAL_US as f64 * 1e-6
76}
77
78fn angles(t: f64) -> (Euler, Euler) {
80 let angle = Euler {
81 yaw: (0.9 * (0.5 * t).sin()) as f32,
82 pitch: (0.5 * (0.8 * t).sin() + 0.15) as f32,
83 roll: (0.6 * (1.1 * t).sin()) as f32,
84 };
85 let rate = Euler {
86 yaw: (0.45 * (0.5 * t).cos()) as f32,
87 pitch: (0.4 * (0.8 * t).cos()) as f32,
88 roll: (0.66 * (1.1 * t).cos()) as f32,
89 };
90 (angle, rate)
91}
92
93fn sample_at(index: u64) -> ImuSample {
94 let t = time_of(index);
95 let (angle, rate) = angles(t);
96 let (sp, cp) = angle.pitch.sin_cos();
97 let (sr, cr) = angle.roll.sin_cos();
98 let gyro = [
100 -sr * cp * rate.yaw + cr * rate.pitch,
101 sp * rate.yaw + rate.roll,
102 cr * cp * rate.yaw + sr * rate.pitch,
103 ];
104 let accel = Quat::from_euler(angle)
105 .conjugate()
106 .rotate([0.0, 0.0, GRAVITY]);
107 ImuSample {
108 timestamp_us: (1_000_000 + index * SAMPLE_INTERVAL_US as u64) as u32,
110 accel,
111 gyro,
112 }
113}
114
115fn inputs(c: f64) -> (Option<Touch>, Buttons) {
117 let touch = (2.0..6.0).contains(&c).then(|| {
118 let half = TOUCH_MAX as f64 / 2.0;
119 let a = (c - 2.0) * 1.8;
120 Touch {
121 x: (half + 110.0 * a.cos()).round() as u16,
122 y: (half + 110.0 * a.sin()).round() as u16,
123 }
124 });
125 let script = [
126 (0.0..0.3, Buttons::HOME),
127 (4.5..4.9, Buttons::TOUCHPAD),
128 (6.8..7.6, Buttons::TRIGGER),
129 (8.4..8.8, Buttons::BACK),
130 (9.6..10.0, Buttons::VOLUME_UP),
131 (10.6..11.0, Buttons::VOLUME_DOWN),
132 ];
133 let buttons = script
134 .into_iter()
135 .filter(|(range, _)| range.contains(&c))
136 .fold(Buttons::NONE, |held, (_, button)| held | button);
137 (touch, buttons)
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143 use crate::Orientation;
144
145 #[test]
146 fn packets_look_like_real_ones() {
147 let mut sim = Simulator::new();
148 let mut last = None;
149 for _ in 0..200 {
150 let p = sim.next_packet();
151 for s in &p.samples {
152 if let Some(last) = last {
153 assert_eq!(s.timestamp_us - last, SAMPLE_INTERVAL_US);
154 }
155 last = Some(s.timestamp_us);
156 let g = s.accel.iter().map(|v| v * v).sum::<f32>().sqrt() / GRAVITY;
157 assert!((g - 1.0).abs() < 0.01, "accelerometer reads {g} g");
158 }
159 assert_eq!(p.temperature, 25);
160 }
161 }
162
163 #[test]
164 fn the_filter_tracks_the_simulated_motion() {
165 let mut sim = Simulator::new();
166 let mut orientation = Orientation::new();
167 let mut worst = 0.0f32;
168 while sim.elapsed() < 25.0 {
170 orientation.update(&sim.next_packet());
171 if sim.elapsed() > 1.5 {
172 let truth = Simulator::pose_at(sim.elapsed() - time_of(1));
173 worst = worst.max(orientation.quaternion().angle_to(truth));
174 }
175 }
176 assert!(
177 worst.to_degrees() < 3.0,
178 "worst error {:.2}°",
179 worst.to_degrees()
180 );
181 }
182
183 #[test]
184 fn every_button_and_the_touchpad_are_exercised() {
185 let mut sim = Simulator::new();
186 let mut seen = Buttons::NONE;
187 let (mut touched, mut untouched) = (false, false);
188 let mut first = None;
189 while sim.elapsed() < CYCLE {
190 let p = sim.next_packet();
191 first.get_or_insert(p.buttons);
192 seen = seen | p.buttons;
193 match p.touch {
194 Some(t) => {
195 touched = true;
196 assert!(t.x <= TOUCH_MAX && t.y <= TOUCH_MAX);
197 }
198 None => untouched = true,
199 }
200 }
201 assert_eq!(seen.bits(), 0b11_1111);
202 assert!(touched && untouched);
203 assert_eq!(
204 first,
205 Some(Buttons::HOME),
206 "Home is pressed at the start, where yaw is 0"
207 );
208 }
209}