Skip to main content

ghast_protocol/types/
mod.rs

1//! Hand-written protocol types shared by the generated packet code.
2
3pub mod position;
4pub mod slot;
5
6pub use bytestring::ByteString;
7pub use position::{BlockPos, PositionLayout};
8pub use uuid::Uuid;
9
10/// Converts a protocol angle byte (1/256 of a full turn) to degrees in `[-180, 180)`.
11#[inline]
12pub fn angle_to_degrees(a: i8) -> f32 {
13    f32::from(a) * (360.0 / 256.0)
14}
15
16/// Converts degrees to a protocol angle byte the way vanilla does
17/// (`(int)(deg * 256 / 360)`, truncated, then wrapped to a byte).
18#[inline]
19pub fn degrees_to_angle(deg: f32) -> i8 {
20    ((deg * 256.0 / 360.0) as i32) as i8
21}
22
23/// Converts a 1.8-style fixed-point coordinate (1/32 block, as in spawn/teleport
24/// packets) to blocks.
25#[inline]
26pub fn fixed_to_f64(v: i32) -> f64 {
27    f64::from(v) / 32.0
28}
29
30/// Converts blocks to a 1.8-style fixed-point coordinate (`floor(v * 32)`, like vanilla).
31#[inline]
32pub fn f64_to_fixed(v: f64) -> i32 {
33    (v * 32.0).floor() as i32
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn angles_and_fixed_point() {
42        assert_eq!(angle_to_degrees(64), 90.0);
43        assert_eq!(angle_to_degrees(-128), -180.0);
44        assert_eq!(degrees_to_angle(90.0), 64);
45        assert_eq!(degrees_to_angle(270.0), -64);
46        assert_eq!(fixed_to_f64(48), 1.5);
47        assert_eq!(f64_to_fixed(-0.01), -1);
48        assert_eq!(f64_to_fixed(1.5), 48);
49    }
50}