kills module

This commit is contained in:
Robin Appelman 2026-11-12 18:10:44 +01:00
commit c8664f9e47
Signed by: robin
SSH key fingerprint: SHA256:kifqgrqnut7q1YUIrI0AdMNC23qiKAS/T9uGFmIYvbE
13 changed files with 233 additions and 36 deletions

28
Cargo.lock generated
View file

@ -407,6 +407,12 @@ version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]] [[package]]
name = "iana-time-zone" name = "iana-time-zone"
version = "0.1.65" version = "0.1.65"
@ -1053,6 +1059,27 @@ dependencies = [
"syn 2.0.119", "syn 2.0.119",
] ]
[[package]]
name = "strum"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
dependencies = [
"strum_macros",
]
[[package]]
name = "strum_macros"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "supports-color" name = "supports-color"
version = "3.0.2" version = "3.0.2"
@ -1205,6 +1232,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"steamid-ng", "steamid-ng",
"strum",
"test-case", "test-case",
"tf-log-parser-derive", "tf-log-parser-derive",
"thiserror", "thiserror",

View file

@ -24,6 +24,7 @@ paste = "1.0.15"
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154" serde_json = "1.0.154"
steamid-ng = "3.0.0" steamid-ng = "3.0.0"
strum = { version = "0.28", features = ["derive"] }
tf-log-parser-derive = { path = "./derive", version = "0.1" } tf-log-parser-derive = { path = "./derive", version = "0.1" }
thiserror = "2.0.21" thiserror = "2.0.21"
walkdir = "2.5.0" walkdir = "2.5.0"

View file

@ -79,7 +79,7 @@ fn main() -> Result<(), MainError> {
}; };
black_box(output); black_box(output);
}, },
|| eprintln!("Paniced on {}", path.display()), || eprintln!("Panicked on {}", path.display()),
); );
parse_time.fetch_add( parse_time.fetch_add(
@ -98,8 +98,8 @@ fn main() -> Result<(), MainError> {
println!( println!(
"Parsed {} in {:01}s, spend {:01}s reading files, in {:01}s of real time", "Parsed {} in {:01}s, spend {:01}s reading files, in {:01}s of real time",
count.load(Ordering::Relaxed), count.load(Ordering::Relaxed),
micros_as_sec(read_time),
micros_as_sec(parse_time), micros_as_sec(parse_time),
micros_as_sec(read_time),
micros_as_sec(total.as_micros() as usize) micros_as_sec(total.as_micros() as usize)
); );

17
examples/kills.rs Normal file
View file

@ -0,0 +1,17 @@
use main_error::MainError;
use std::env::args;
use std::fs;
use tf_log_parser::module::Kills;
use tf_log_parser::parse_with_handler;
fn main() -> Result<(), MainError> {
let path = args().nth(1).expect("No path provided");
let content = fs::read_to_string(path)?;
let kills = parse_with_handler::<Kills>(&content)?.0;
for kill in kills {
println!("{}", serde_json::to_string(&kill)?);
}
Ok(())
}

3
src/data/mod.rs Normal file
View file

@ -0,0 +1,3 @@
mod weapons;
pub use weapons::Weapon;

23
src/data/weapons.rs Normal file
View file

@ -0,0 +1,23 @@
use serde::Serialize;
use strum::{AsRefStr, EnumString};
#[derive(EnumString, AsRefStr, Debug, PartialEq)]
#[strum(serialize_all = "lowercase")]
pub enum Weapon {
// todo, add all weapons...
Scattergun,
#[strum(default)]
Other(String),
}
impl Serialize for Weapon {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Weapon::Other(other) => other.serialize(serializer),
_ => self.as_ref().serialize(serializer),
}
}
}

View file

@ -29,7 +29,6 @@ pub struct DamageEvent<'a> {
pub struct KillEvent<'a> { pub struct KillEvent<'a> {
#[event(unnamed)] #[event(unnamed)]
#[event(subject)] #[event(subject)]
#[event(skip_after = 1)]
pub target: RawSubject<'a>, pub target: RawSubject<'a>,
#[event(name = "with")] #[event(name = "with")]
pub weapon: &'a str, pub weapon: &'a str,
@ -41,7 +40,7 @@ pub struct KillEvent<'a> {
pub struct KillAssistEvent<'a> { pub struct KillAssistEvent<'a> {
#[event(name = "against")] #[event(name = "against")]
pub target: RawSubject<'a>, pub target: RawSubject<'a>,
pub attacker_position: Option<(i32, i32, i32)>, pub assister_position: Option<(i32, i32, i32)>,
pub victim_position: Option<(i32, i32, i32)>, pub victim_position: Option<(i32, i32, i32)>,
} }

View file

@ -18,6 +18,7 @@ mod common;
pub mod event; pub mod event;
#[macro_use] #[macro_use]
pub mod module; pub mod module;
pub mod data;
mod error; mod error;
pub(crate) mod parsing; pub(crate) mod parsing;
pub mod raw_event; pub mod raw_event;

115
src/module/kills.rs Normal file
View file

@ -0,0 +1,115 @@
use crate::common::SubjectId;
use crate::data::Weapon;
use crate::event::{GameEvent, KillAssistEvent, KillEvent};
use crate::module::GlobalData;
use crate::raw_event::RawEventType;
use crate::{EventMeta, SubjectMap};
use serde::Serialize;
use steamid_ng::SteamID;
#[derive(PartialEq)]
pub struct RawKill {
pub time: u32,
pub killer: SubjectId,
pub assister: Option<SubjectId>,
pub victim: SubjectId,
pub weapon: Weapon,
pub attacker_position: Option<(i32, i32, i32)>,
pub assister_position: Option<(i32, i32, i32)>,
pub victim_position: Option<(i32, i32, i32)>,
}
impl RawKill {
fn from_event(time: u32, subject: SubjectId, event: &KillEvent) -> Option<Self> {
Some(RawKill {
time,
killer: subject,
assister: None,
victim: event.target.id().ok()?,
weapon: Weapon::from(event.weapon),
attacker_position: event.attacker_position,
assister_position: None,
victim_position: event.victim_position,
})
}
fn add_assist(&mut self, subject: SubjectId, event: &KillAssistEvent) {
self.assister = Some(subject);
self.assister_position = event.assister_position;
}
}
#[derive(Serialize, PartialEq)]
pub struct Kill {
pub time: u32,
#[serde(with = "super::serde_steamid")]
pub killer: SteamID,
#[serde(with = "super::serde_steamid::opt")]
pub assister: Option<SteamID>,
#[serde(with = "super::serde_steamid")]
pub victim: SteamID,
pub weapon: Weapon,
pub attacker_position: Option<(i32, i32, i32)>,
pub assister_position: Option<(i32, i32, i32)>,
pub victim_position: Option<(i32, i32, i32)>,
}
impl Kill {
pub fn from_raw(raw: RawKill, subjects: &SubjectMap) -> Option<Kill> {
let killer = subjects.steam_id(raw.killer)?;
let assister = raw.assister.and_then(|subject| subjects.steam_id(subject));
let victim = subjects.steam_id(raw.victim)?;
Some(Kill {
time: raw.time,
killer,
assister,
victim,
weapon: raw.weapon,
attacker_position: raw.attacker_position,
assister_position: raw.assister_position,
victim_position: raw.victim_position,
})
}
}
#[derive(Default)]
pub struct Kills(Vec<RawKill>);
impl GlobalData for Kills {
type Output = Vec<Kill>;
fn does_handle(ty: RawEventType) -> bool {
matches!(ty, RawEventType::Killed | RawEventType::KillAssist)
}
fn handle_event(&mut self, meta: &EventMeta, subject: SubjectId, event: &GameEvent) {
let time = meta.time;
if !matches!(subject, SubjectId::Player(_)) {
return;
}
match event {
GameEvent::Killed(event) => {
if let Some(kill) = RawKill::from_event(time, subject, event) {
self.0.push(kill);
}
}
GameEvent::KillAssist(event) => {
if let Some(kill) = self.0.last_mut() {
debug_assert_eq!(kill.time, time);
debug_assert_eq!(kill.victim, event.target.id().unwrap());
kill.add_assist(subject, event);
}
}
_ => {}
}
}
fn finish(self, subjects: &SubjectMap) -> Self::Output {
self.0
.into_iter()
.filter_map(|raw| Kill::from_raw(raw, subjects))
.collect()
}
}

View file

@ -6,6 +6,7 @@ pub use chat::{ChatMessage, ChatMessages, ChatType};
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
pub use classstats::{ClassStats, ClassStatsHandler}; pub use classstats::{ClassStats, ClassStatsHandler};
pub use healspread::HealSpread; pub use healspread::HealSpread;
pub use kills::{Kill, Kills};
pub use lobbysettings::{ pub use lobbysettings::{
LobbySettingsError, LobbySettingsHandler, Location, Settings as LobbySettings, LobbySettingsError, LobbySettingsHandler, Location, Settings as LobbySettings,
}; };
@ -17,6 +18,7 @@ use std::marker::PhantomData;
mod chat; mod chat;
mod classstats; mod classstats;
mod healspread; mod healspread;
mod kills;
mod lobbysettings; mod lobbysettings;
mod medicstats; mod medicstats;

View file

@ -3,6 +3,7 @@ use crate::{SubjectData, SubjectError, SubjectId};
use ahash::{AHashMap, RandomState}; use ahash::{AHashMap, RandomState};
use std::convert::TryInto; use std::convert::TryInto;
use std::ops::{Index, IndexMut}; use std::ops::{Index, IndexMut};
use steamid_ng::SteamID;
#[derive(Default)] #[derive(Default)]
pub struct SubjectMap<T = ()>(AHashMap<SubjectId, (SubjectData, T)>); pub struct SubjectMap<T = ()>(AHashMap<SubjectId, (SubjectData, T)>);
@ -50,6 +51,13 @@ impl<T> SubjectMap<T> {
&self[id].0 &self[id].0
} }
pub fn steam_id(&self, id: SubjectId) -> Option<SteamID> {
match self.0.get(&id) {
Some((SubjectData::Player { steam_id, .. }, _)) => Some(*steam_id),
_ => None,
}
}
pub fn to_just_subjects(&self) -> SubjectMap<()> { pub fn to_just_subjects(&self) -> SubjectMap<()> {
SubjectMap( SubjectMap(
self.0 self.0