1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use attributes::Attribute;
use bitter::BitGet;
use std::fmt;

/// An object's current vector
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Vector {
    pub bias: i32,
    pub dx: i32,
    pub dy: i32,
    pub dz: i32,
}

impl Vector {
    pub fn decode(bits: &mut BitGet, net_version: i32) -> Option<Vector> {
        if_chain! {
            if let Some(size_bits) = bits.read_bits_max(5, if net_version >= 7 { 22 } else { 20 });
            let bias = 1 << (size_bits + 1);
            let bit_limit = (size_bits + 2) as i32;
            if let Some(dx) = bits.read_u32_bits(bit_limit);
            if let Some(dy) = bits.read_u32_bits(bit_limit);
            if let Some(dz) = bits.read_u32_bits(bit_limit);
            then {
                Some(Vector {
                    bias: bias as i32,
                    dx: dx as i32,
                    dy: dy as i32,
                    dz: dz as i32,
                })
            } else {
                None
            }
        }
    }

    pub fn decode_unchecked(bits: &mut BitGet, net_version: i32) -> Vector {
        let size_bits = bits.read_bits_max_unchecked(5, if net_version >= 7 { 22 } else { 20 });
        let bias = 1 << (size_bits + 1);
        let bit_limit = (size_bits + 2) as i32;
        let dx = bits.read_u32_bits_unchecked(bit_limit);
        let dy = bits.read_u32_bits_unchecked(bit_limit);
        let dz = bits.read_u32_bits_unchecked(bit_limit);
        Vector {
            bias: bias as i32,
            dx: dx as i32,
            dy: dy as i32,
            dz: dz as i32,
        }
    }
}

/// An object's current rotation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Rotation {
    pub yaw: Option<i8>,
    pub pitch: Option<i8>,
    pub roll: Option<i8>,
}

impl Rotation {
    pub fn decode(bits: &mut BitGet) -> Option<Rotation> {
        if_chain! {
            if let Some(yaw) = bits.if_get(|b| b.read_i8());
            if let Some(pitch) = bits.if_get(|b| b.read_i8());
            if let Some(roll) = bits.if_get(|b| b.read_i8());
            then {
                Some(Rotation {
                    yaw,
                    pitch,
                    roll,
                })
            } else {
                None
            }
        }
    }

    pub fn decode_unchecked(bits: &mut BitGet) -> Rotation {
        let yaw = bits.if_get_unchecked(|b| b.read_i8_unchecked());
        let pitch = bits.if_get_unchecked(|b| b.read_i8_unchecked());
        let roll = bits.if_get_unchecked(|b| b.read_i8_unchecked());
        Rotation { yaw, pitch, roll }
    }
}

/// When a new actor spawns in rocket league it will either have a location, location and rotation,
/// or none of the above
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpawnTrajectory {
    None,
    Location,
    LocationAndRotation,
}

/// Notifies that an actor has had one of their properties updated (most likely their rigid body
/// state (location / rotation) has changed)
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct UpdatedAttribute {
    /// The actor that had an attribute updated
    pub actor_id: ActorId,

    /// The attribute stream id that was decoded
    pub stream_id: StreamId,

    /// The actual data from the decoded attribute
    pub attribute: Attribute,
}

/// Contains the time and any new information that occurred during a frame
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Frame {
    /// The time in seconds that the frame is recorded at
    pub time: f32,

    /// Time difference between previous frame
    pub delta: f32,

    /// List of new actors seen during the frame
    pub new_actors: Vec<NewActor>,

    /// List of actor id's that are deleted / destroyed
    pub deleted_actors: Vec<ActorId>,

    /// List of properties updated on the actors
    pub updated_actors: Vec<UpdatedAttribute>,
}

/// A replay encodes a list of objects that appear in the network data. The index of an object in
/// this list is used as a key in many places: reconstructing the attribute hierarchy and new
/// actors in the network data.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Serialize)]
pub struct ObjectId(pub i32);

impl From<ObjectId> for i32 {
    fn from(x: ObjectId) -> i32 {
        x.0
    }
}

impl From<ObjectId> for usize {
    fn from(x: ObjectId) -> usize {
        x.0 as usize
    }
}

impl fmt::Display for ObjectId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A `StreamId` is an attribute's object id in the network data. It is a more compressed form of
/// the object id. Whereas the an object id might need to take up 9 bits, a stream id may only take
/// up 6 bits.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Serialize)]
pub struct StreamId(pub i32);

impl From<StreamId> for i32 {
    fn from(x: StreamId) -> i32 {
        x.0
    }
}

impl fmt::Display for StreamId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// An actor in the network data stream. Could identify a ball, car, etc. Ids are not unique
/// across a replay (eg. an actor that is destroyed may have its id repurposed).
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Serialize)]
pub struct ActorId(pub i32);

impl From<ActorId> for i32 {
    fn from(x: ActorId) -> i32 {
        x.0
    }
}

impl fmt::Display for ActorId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Information for a new actor that appears in the game
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct NewActor {
    /// The id given to the new actor
    pub actor_id: ActorId,

    /// An name id
    pub name_id: Option<i32>,

    /// The actor's object id.
    pub object_id: ObjectId,

    /// The initial trajectory of the new actor
    pub initial_trajectory: Trajectory,
}

/// Contains the optional location and rotation of an object when it spawns
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Trajectory {
    pub location: Option<Vector>,
    pub rotation: Option<Rotation>,
}

impl Trajectory {
    pub fn from_spawn(
        bits: &mut BitGet,
        sp: SpawnTrajectory,
        net_version: i32,
    ) -> Option<Trajectory> {
        match sp {
            SpawnTrajectory::None => Some(Trajectory {
                location: None,
                rotation: None,
            }),

            SpawnTrajectory::Location => Vector::decode(bits, net_version).map(|v| Trajectory {
                location: Some(v),
                rotation: None,
            }),

            SpawnTrajectory::LocationAndRotation => if_chain! {
                if let Some(v) = Vector::decode(bits, net_version);
                if let Some(r) = Rotation::decode(bits);
                then {
                    Some(Trajectory {
                        location: Some(v),
                        rotation: Some(r),
                    })
                } else {
                    None
                }
            },
        }
    }

    pub fn from_spawn_unchecked(
        bits: &mut BitGet,
        sp: SpawnTrajectory,
        net_version: i32,
    ) -> Trajectory {
        match sp {
            SpawnTrajectory::None => Trajectory {
                location: None,
                rotation: None,
            },

            SpawnTrajectory::Location => Trajectory {
                location: Some(Vector::decode_unchecked(bits, net_version)),
                rotation: None,
            },

            SpawnTrajectory::LocationAndRotation => Trajectory {
                location: Some(Vector::decode_unchecked(bits, net_version)),
                rotation: Some(Rotation::decode_unchecked(bits)),
            },
        }
    }
}

/// Oftentimes a replay contains many different objects of the same type. For instance, each rumble
/// pickup item is of the same type but has a different name. The name of:
/// `stadium_foggy_p.TheWorld:PersistentLevel.VehiclePickup_Boost_TA_30` should be normalized to
/// `TheWorld:PersistentLevel.VehiclePickup_Boost_TA` so that we don't have to work around each
/// stadium and pickup that is released.
pub fn normalize_object(name: &str) -> &str {
    if name.contains("TheWorld:PersistentLevel.CrowdActor_TA") {
        "TheWorld:PersistentLevel.CrowdActor_TA"
    } else if name.contains("TheWorld:PersistentLevel.CrowdManager_TA") {
        "TheWorld:PersistentLevel.CrowdManager_TA"
    } else if name.contains("TheWorld:PersistentLevel.VehiclePickup_Boost_TA") {
        "TheWorld:PersistentLevel.VehiclePickup_Boost_TA"
    } else if name.contains("TheWorld:PersistentLevel.InMapScoreboard_TA") {
        "TheWorld:PersistentLevel.InMapScoreboard_TA"
    } else if name.contains("TheWorld:PersistentLevel.BreakOutActor_Platform_TA") {
        "TheWorld:PersistentLevel.BreakOutActor_Platform_TA"
    } else {
        name
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_decode_vector() {
        let mut bitter = BitGet::new(&[0b0000_0110, 0b0000_1000, 0b1101_1000, 0b0000_1101]);
        let v = Vector::decode(&mut bitter, 5).unwrap();
        assert_eq!(
            v,
            Vector {
                bias: 128,
                dx: 128,
                dy: 128,
                dz: 221,
            }
        );
    }

    #[test]
    fn test_decode_vector_unchecked() {
        let mut bitter = BitGet::new(&[0b0000_0110, 0b0000_1000, 0b1101_1000, 0b0000_1101]);
        let v = Vector::decode_unchecked(&mut bitter, 5);
        assert_eq!(
            v,
            Vector {
                bias: 128,
                dx: 128,
                dy: 128,
                dz: 221,
            }
        );
    }

    #[test]
    fn test_decode_rotation() {
        let mut bitter = BitGet::new(&[0b0000_0101, 0b0000_0000]);
        let v = Rotation::decode(&mut bitter).unwrap();
        assert_eq!(
            v,
            Rotation {
                yaw: Some(2),
                pitch: None,
                roll: None,
            }
        );
    }

    #[test]
    fn test_decode_rotation_unchecked() {
        let mut bitter = BitGet::new(&[0b0000_0101, 0b0000_0000]);
        let v = Rotation::decode_unchecked(&mut bitter);
        assert_eq!(
            v,
            Rotation {
                yaw: Some(2),
                pitch: None,
                roll: None,
            }
        );
    }

}