chunkedge_protocol/
velocity.rs

1use std::fmt;
2
3use chunkedge_binary::{Decode, Encode};
4use derive_more::{From, Into};
5
6/// Quantized entity velocity.
7#[derive(Copy, Clone, PartialEq, Eq, Encode, Decode, From, Into)]
8pub struct Velocity(pub [i16; 3]);
9
10impl Velocity {
11    /// From meters/second.
12    pub fn from_ms_f32(ms: [f32; 3]) -> Self {
13        Self(ms.map(|v| (8000.0 / 20.0 * v) as i16))
14    }
15
16    /// From meters/second.
17    pub fn from_ms_f64(ms: [f64; 3]) -> Self {
18        Self(ms.map(|v| (8000.0 / 20.0 * v) as i16))
19    }
20
21    /// To meters/second.
22    pub fn to_ms_f32(self) -> [f32; 3] {
23        self.0.map(|v| f32::from(v) / (8000.0 / 20.0))
24    }
25
26    /// To meters/second.
27    pub fn to_ms_f64(self) -> [f64; 3] {
28        self.0.map(|v| f64::from(v) / (8000.0 / 20.0))
29    }
30}
31
32impl fmt::Debug for Velocity {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        fmt::Display::fmt(self, f)
35    }
36}
37
38impl fmt::Display for Velocity {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        let [x, y, z] = self.to_ms_f32();
41        write!(f, "⟨{x},{y},{z}⟩ m/s")
42    }
43}
44
45#[cfg(test)]
46#[test]
47fn velocity_from_ms() {
48    let val_1 = Velocity::from_ms_f32([(); 3].map(|()| -3.3575)).0[0];
49    let val_2 = Velocity::from_ms_f64([(); 3].map(|()| -3.3575)).0[0];
50
51    assert_eq!(val_1, val_2);
52    assert_eq!(val_1, -1343);
53}