Skip to main content

ghast_protocol/types/
move_delta.rs

1//! The relative entity move of protocol 777+ (`rel_entity_move`, `entity_move_look`).
2//!
3//! Wire format: a VarInt of properties — bit 0 is `on_ground`, the bits above it (read as
4//! an unsigned shift) are the step count. A step count of 0 is a linear move: three `i16`
5//! deltas in 1/4096 block follow. Otherwise that many steps follow, each a VarInt tick
6//! offset and three `i16` deltas.
7//!
8//! A step costs at least 7 bytes, so a step count above `remaining / 7` is rejected before
9//! anything is allocated (vanilla rejects the same counts).
10
11use bytes::BytesMut;
12
13use crate::codec::{Decode, DecodeResult, Encode, EncodeResult, McWrite, Reader};
14use crate::error::DecodeError;
15
16/// One step of a stepped move.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18pub struct MoveStep {
19    /// Tick offset of the step.
20    pub ticks: i32,
21    /// x, y, z deltas in 1/4096 block.
22    pub delta: [i16; 3],
23}
24
25/// The position change of a relative entity move.
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27pub enum MovePath {
28    /// One delta (x, y, z in 1/4096 block), applied over the usual interpolation.
29    Linear([i16; 3]),
30    /// Several deltas with tick offsets. Never empty on the wire: an empty list would
31    /// encode as step count 0, which reads back as [`MovePath::Linear`].
32    Stepped(Vec<MoveStep>),
33}
34
35impl Default for MovePath {
36    fn default() -> Self {
37        MovePath::Linear([0; 3])
38    }
39}
40
41/// `on_ground` and the position change of a relative entity move (protocol 777+).
42#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
43pub struct EntityMoveDelta {
44    /// Whether the entity is on the ground.
45    pub on_ground: bool,
46    /// The position change.
47    pub path: MovePath,
48}
49
50impl EntityMoveDelta {
51    /// Reads the wire form.
52    pub fn read(r: &mut Reader<'_>) -> DecodeResult<Self> {
53        let properties = r.read_varint()? as u32;
54        let on_ground = properties & 1 != 0;
55        let steps = (properties >> 1) as usize;
56        let read_delta = |r: &mut Reader<'_>| -> DecodeResult<[i16; 3]> {
57            Ok([r.read_i16()?, r.read_i16()?, r.read_i16()?])
58        };
59        let path = if steps == 0 {
60            MovePath::Linear(read_delta(r)?)
61        } else {
62            if steps > r.remaining() / 7 {
63                return Err(DecodeError::Invalid("move delta: more steps than bytes"));
64            }
65            let mut v = Vec::with_capacity(steps);
66            for _ in 0..steps {
67                let ticks = r.read_varint()?;
68                v.push(MoveStep {
69                    ticks,
70                    delta: read_delta(r)?,
71                });
72            }
73            MovePath::Stepped(v)
74        };
75        Ok(EntityMoveDelta { on_ground, path })
76    }
77
78    /// Writes the wire form.
79    pub fn write(&self, w: &mut BytesMut) {
80        let steps = match &self.path {
81            MovePath::Linear(_) => 0,
82            MovePath::Stepped(v) => v.len() as u32,
83        };
84        w.put_varint((u32::from(self.on_ground) | steps << 1) as i32);
85        let put = |w: &mut BytesMut, d: &[i16; 3]| {
86            for c in d {
87                bytes::BufMut::put_i16(w, *c);
88            }
89        };
90        match &self.path {
91            MovePath::Linear(d) => put(w, d),
92            MovePath::Stepped(v) => {
93                for s in v {
94                    w.put_varint(s.ticks);
95                    put(w, &s.delta);
96                }
97            }
98        }
99    }
100}
101
102impl Decode for EntityMoveDelta {
103    #[inline]
104    fn decode(r: &mut Reader<'_>) -> DecodeResult<Self> {
105        Self::read(r)
106    }
107}
108
109impl Encode for EntityMoveDelta {
110    #[inline]
111    fn encode(&self, w: &mut BytesMut) -> EncodeResult {
112        self.write(w);
113        Ok(())
114    }
115}
116
117#[cfg(feature = "testgen")]
118impl crate::testgen::Generate for EntityMoveDelta {
119    fn generate(g: &mut crate::testgen::Gen) -> Self {
120        let delta = |g: &mut crate::testgen::Gen| [g.u64() as i16, g.u64() as i16, g.u64() as i16];
121        let on_ground = g.bool();
122        let path = if g.chance(60) {
123            MovePath::Linear(delta(g))
124        } else {
125            let n = 1 + g.below(4) as usize;
126            MovePath::Stepped(
127                (0..n)
128                    .map(|_| MoveStep {
129                        ticks: g.int_in(0, i64::from(i32::MAX), &[0, 1, 2, 127, 128]) as i32,
130                        delta: delta(g),
131                    })
132                    .collect(),
133            )
134        };
135        EntityMoveDelta { on_ground, path }
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::codec::decode_exact;
143
144    fn rt(v: &EntityMoveDelta) -> Vec<u8> {
145        let mut w = BytesMut::new();
146        v.write(&mut w);
147        assert_eq!(
148            &decode_exact::<EntityMoveDelta>(&w.clone().freeze()).unwrap(),
149            v
150        );
151        w.to_vec()
152    }
153
154    #[test]
155    fn linear_and_stepped() {
156        let lin = EntityMoveDelta {
157            on_ground: true,
158            path: MovePath::Linear([1, -1, 256]),
159        };
160        assert_eq!(rt(&lin), vec![1, 0, 1, 0xff, 0xff, 1, 0]);
161        let st = EntityMoveDelta {
162            on_ground: false,
163            path: MovePath::Stepped(vec![
164                MoveStep {
165                    ticks: 0,
166                    delta: [0, 0, 1],
167                },
168                MoveStep {
169                    ticks: 3,
170                    delta: [2, 0, 0],
171                },
172            ]),
173        };
174        assert_eq!(rt(&st), vec![4, 0, 0, 0, 0, 0, 0, 1, 3, 0, 2, 0, 0, 0, 0]);
175    }
176
177    #[test]
178    fn step_count_is_bounded_by_the_input() {
179        // 10 steps announced, 7 bytes present.
180        let b = bytes::Bytes::from(vec![20, 0, 0, 0, 0, 0, 0, 0]);
181        assert!(decode_exact::<EntityMoveDelta>(&b).is_err());
182    }
183}