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
use crate::demo::message::packetentities::{EntityId, PacketEntity};
use crate::demo::message::Message;
use crate::demo::packet::datatable::{ParseSendTable, SendTableName, ServerClass, ServerClassName};
pub use crate::demo::parser::analyser::{Class, Team, UserId};
use crate::demo::parser::handler::BorrowMessageHandler;
use crate::demo::parser::MessageHandler;
use crate::demo::sendprop::{SendProp, SendPropIdentifier, SendPropName, SendPropValue};
use crate::demo::vector::{Vector, VectorXY};
use crate::{MessageType, ParserState};
use fnv::FnvHashMap;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::str::FromStr;

pub struct CachedEntities {}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub enum PlayerState {
    Alive = 0,
    Dying = 1,
    Death = 2,
    Respawnable = 3,
}

impl PlayerState {
    pub fn new(number: i64) -> Self {
        match number {
            1 => PlayerState::Dying,
            2 => PlayerState::Death,
            3 => PlayerState::Respawnable,
            _ => PlayerState::Alive,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Player {
    entity: EntityId,
    pub position: Vector,
    pub health: u16,
    pub max_health: u16,
    pub class: Class,
    pub team: Team,
    pub view_angle: f32,
    pub state: PlayerState,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Building {
    Sentry {
        builder: UserId,
        position: Vector,
        level: u8,
        max_health: u16,
        health: u16,
        building: bool,
        sapped: bool,
        team: Team,
        angle: f32,
        player_controller: bool,
        auto_aim_target: UserId,
        shells: u16,
        rockets: u16,
        is_mini: bool,
    },
    Dispenser {
        builder: UserId,
        position: Vector,
        level: u8,
        max_health: u16,
        health: u16,
        building: bool,
        sapped: bool,
        team: Team,
        angle: f32,
        healing: Vec<UserId>,
        metal: u16,
    },
    Teleporter {
        builder: UserId,
        position: Vector,
        level: u8,
        max_health: u16,
        health: u16,
        building: bool,
        sapped: bool,
        team: Team,
        angle: f32,
        is_entrance: bool,
        other_end: EntityId,
        recharge_time: f32,
        recharge_duration: f32,
        times_used: u16,
        yaw_to_exit: f32,
    },
}

#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct World {
    pub boundary_min: Vector,
    pub boundary_max: Vector,
}

#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct GameState {
    pub players: Vec<Player>,
    pub buildings: Vec<Building>,
    pub world: Option<World>,
}

impl GameState {
    pub fn get_or_create_player(&mut self, entity_id: EntityId) -> &mut Player {
        let index = match self
            .players
            .iter_mut()
            .enumerate()
            .find(|(_index, player)| player.entity == entity_id)
            .map(|(index, _)| index)
        {
            Some(index) => index,
            None => {
                let player = Player {
                    entity: entity_id,
                    position: Vector::default(),
                    health: 0,
                    max_health: 0,
                    class: Class::Other,
                    team: Team::Other,
                    view_angle: 0.0,
                    state: PlayerState::Alive,
                };

                let index = self.players.len();
                self.players.push(player);
                index
            }
        };

        &mut self.players[index]
    }
}

#[derive(Default, Debug)]
pub struct GameStateAnalyser {
    pub state: GameState,
    prop_names: FnvHashMap<SendPropIdentifier, (SendTableName, SendPropName)>,
    class_names: Vec<ServerClassName>, // indexed by ClassId
}

impl MessageHandler for GameStateAnalyser {
    type Output = GameState;

    fn does_handle(message_type: MessageType) -> bool {
        matches!(message_type, MessageType::PacketEntities)
    }

    fn handle_message(&mut self, message: &Message, _tick: u32) {
        if let Message::PacketEntities(message) = message {
            for entity in &message.entities {
                self.handle_entity(entity);
            }
        }
    }

    fn handle_data_tables(
        &mut self,
        parse_tables: &[ParseSendTable],
        server_classes: &[ServerClass],
    ) {
        for table in parse_tables {
            for prop_def in &table.props {
                self.prop_names.insert(
                    prop_def.identifier(),
                    (table.name.clone(), prop_def.name.clone()),
                );
            }
        }

        self.class_names = server_classes
            .iter()
            .map(|class| &class.name)
            .cloned()
            .collect();
    }

    fn into_output(self, _state: &ParserState) -> Self::Output {
        self.state
    }
}

impl BorrowMessageHandler for GameStateAnalyser {
    fn borrow_output(&self, _state: &ParserState) -> &Self::Output {
        &self.state
    }
}

impl GameStateAnalyser {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn handle_entity(&mut self, entity: &PacketEntity) {
        let class_name: &str = self
            .class_names
            .get(usize::from(entity.server_class))
            .map(|class_name| class_name.as_str())
            .unwrap_or("");
        match class_name {
            "CTFPlayer" => self.handle_player_entity(entity),
            "CTFPlayerResource" => self.handle_player_resource(entity),
            "CWorld" => self.handle_world_entity(entity),
            _ => {}
        }
    }

    pub fn handle_player_resource(&mut self, entity: &PacketEntity) {
        for prop in entity.props() {
            if let Some((table_name, prop_name)) = self.prop_names.get(&prop.identifier) {
                if let Ok(player_id) = u32::from_str(prop_name.as_str()) {
                    let entity_id = EntityId::from(player_id);
                    if let Some(player) = self
                        .state
                        .players
                        .iter_mut()
                        .find(|player| player.entity == entity_id)
                    {
                        match table_name.as_str() {
                            "m_iTeam" => {
                                player.team =
                                    Team::new(i64::try_from(&prop.value).unwrap_or_default())
                            }
                            "m_iMaxHealth" => {
                                player.max_health =
                                    i64::try_from(&prop.value).unwrap_or_default() as u16
                            }
                            "m_iPlayerClass" => {
                                player.class =
                                    Class::new(i64::try_from(&prop.value).unwrap_or_default())
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
    }

    pub fn handle_player_entity(&mut self, entity: &PacketEntity) {
        let player = self.state.get_or_create_player(entity.entity_index);

        for prop in entity.props() {
            if let Some((table_name, prop_name)) = self.prop_names.get(&prop.identifier) {
                match table_name.as_str() {
                    "DT_BasePlayer" => match prop_name.as_str() {
                        "m_iHealth" => {
                            player.health = i64::try_from(&prop.value).unwrap_or_default() as u16
                        }
                        "m_iMaxHealth" => {
                            player.max_health =
                                i64::try_from(&prop.value).unwrap_or_default() as u16
                        }
                        "m_lifeState" => {
                            player.state =
                                PlayerState::new(i64::try_from(&prop.value).unwrap_or_default())
                        }
                        _ => {}
                    },
                    "DT_TFLocalPlayerExclusive" | "DT_TFNonLocalPlayerExclusive" => {
                        match prop_name.as_str() {
                            "m_vecOrigin" => {
                                let pos_xy = VectorXY::try_from(&prop.value).unwrap_or_default();
                                player.position.x = pos_xy.x;
                                player.position.y = pos_xy.y;
                            }
                            "m_vecOrigin[2]" => {
                                player.position.z = f32::try_from(&prop.value).unwrap_or_default()
                            }
                            "m_angEyeAngles[1]" => {
                                player.view_angle = f32::try_from(&prop.value).unwrap_or_default()
                            }
                            _ => {}
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    pub fn handle_world_entity(&mut self, entity: &PacketEntity) {
        if let (
            Some(SendProp {
                value: SendPropValue::Vector(boundary_min),
                ..
            }),
            Some(SendProp {
                value: SendPropValue::Vector(boundary_max),
                ..
            }),
        ) = (
            entity.get_prop_by_name("DT_WORLD", "m_WorldMins"),
            entity.get_prop_by_name("DT_WORLD", "m_WorldMaxs"),
        ) {
            self.state.world = Some(World {
                boundary_min: *boundary_min,
                boundary_max: *boundary_max,
            })
        }
    }
}