Fix heatmap issue and implement per round analysis
This commit is contained in:
1
Cargo.lock
generated
1
Cargo.lock
generated
@@ -45,6 +45,7 @@ dependencies = [
|
||||
"colors-transform",
|
||||
"csdemo",
|
||||
"image",
|
||||
"phf",
|
||||
"pretty_assertions",
|
||||
"serde",
|
||||
"tracing",
|
||||
|
||||
@@ -12,6 +12,8 @@ colors-transform = { version = "0.2" }
|
||||
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
|
||||
phf = { version = "0.11" }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { version = "1.4" }
|
||||
tracing-test = { version = "0.2", features = ["no-env-filter"] }
|
||||
|
||||
@@ -52,11 +52,32 @@ impl HeatMap {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct HeatMapOutput {
|
||||
pub player_heatmaps: std::collections::HashMap<i32, HeatMap>,
|
||||
pub entity_to_player: std::collections::HashMap<i32, csdemo::UserId>,
|
||||
pub player_heatmaps: std::collections::HashMap<csdemo::UserId, HeatMap>,
|
||||
pub player_info: std::collections::HashMap<csdemo::UserId, csdemo::parser::Player>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Team {
|
||||
pub num: u32,
|
||||
pub name: String,
|
||||
pub players: Vec<u32>,
|
||||
pub pawns: Vec<PawnID>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
|
||||
pub struct PawnID(u32);
|
||||
|
||||
impl From<i32> for PawnID {
|
||||
fn from(value: i32) -> Self {
|
||||
Self((value & 0x7FF) as u32)
|
||||
}
|
||||
}
|
||||
impl From<u32> for PawnID {
|
||||
fn from(value: u32) -> Self {
|
||||
Self(value & 0x7FF)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(config: &Config, buf: &[u8]) -> Result<HeatMapOutput, ()> {
|
||||
let tmp = csdemo::Container::parse(buf).map_err(|e| ())?;
|
||||
let output = csdemo::parser::parse(
|
||||
@@ -66,14 +87,14 @@ pub fn parse(config: &Config, buf: &[u8]) -> Result<HeatMapOutput, ()> {
|
||||
.map_err(|e| ())?;
|
||||
|
||||
let pawn_ids = {
|
||||
let mut tmp = std::collections::HashMap::new();
|
||||
let mut tmp = std::collections::HashMap::<PawnID,_>::new();
|
||||
|
||||
for event in output.events.iter() {
|
||||
let entry = match event {
|
||||
csdemo::DemoEvent::GameEvent(ge) => match ge.as_ref() {
|
||||
csdemo::game_event::GameEvent::PlayerSpawn(pspawn) => match pspawn.userid_pawn.as_ref() {
|
||||
Some(csdemo::RawValue::I32(v)) => {
|
||||
Some((*v, pspawn.userid.unwrap()))
|
||||
Some((PawnID::from(*v), pspawn.userid.unwrap()))
|
||||
}
|
||||
other => {
|
||||
// tracing::info!("Unknown Pawn-ID: {:?}", other);
|
||||
@@ -95,11 +116,8 @@ pub fn parse(config: &Config, buf: &[u8]) -> Result<HeatMapOutput, ()> {
|
||||
tmp
|
||||
};
|
||||
|
||||
tracing::debug!("Pawn-IDs: {:?}", pawn_ids);
|
||||
|
||||
let mut entity_id_to_user = std::collections::HashMap::<i32, csdemo::UserId>::new();
|
||||
let mut player_lifestate = std::collections::HashMap::<i32, u32>::new();
|
||||
let mut player_position = std::collections::HashMap::<i32, (f32, f32, f32)>::new();
|
||||
let mut player_lifestate = std::collections::HashMap::<csdemo::UserId, u32>::new();
|
||||
let mut player_position = std::collections::HashMap::<csdemo::UserId, (f32, f32, f32)>::new();
|
||||
let mut player_cells = std::collections::HashMap::new();
|
||||
|
||||
let mut heatmaps = std::collections::HashMap::new();
|
||||
@@ -109,7 +127,6 @@ pub fn parse(config: &Config, buf: &[u8]) -> Result<HeatMapOutput, ()> {
|
||||
process_tick(
|
||||
config,
|
||||
tick_state,
|
||||
&mut entity_id_to_user,
|
||||
&pawn_ids,
|
||||
&mut player_lifestate,
|
||||
&mut player_position,
|
||||
@@ -118,55 +135,40 @@ pub fn parse(config: &Config, buf: &[u8]) -> Result<HeatMapOutput, ()> {
|
||||
);
|
||||
}
|
||||
|
||||
tracing::debug!("Pawn-IDs: {:?}", pawn_ids);
|
||||
|
||||
Ok(HeatMapOutput {
|
||||
player_heatmaps: heatmaps,
|
||||
entity_to_player: entity_id_to_user,
|
||||
player_info: output.player_info,
|
||||
})
|
||||
}
|
||||
|
||||
fn get_entityid(props: &[csdemo::parser::entities::EntityProp]) -> Option<i32> {
|
||||
props.iter().find_map(|prop| {
|
||||
if prop.prop_info.prop_name.as_ref() != "CCSPlayerPawn.m_nEntityId" {
|
||||
return None;
|
||||
}
|
||||
|
||||
let pawn_id: i32 = match &prop.value {
|
||||
csdemo::parser::Variant::U32(v) => *v as i32,
|
||||
other => panic!("Unexpected Variant: {:?}", other),
|
||||
};
|
||||
|
||||
Some(pawn_id)
|
||||
})
|
||||
}
|
||||
|
||||
pub const MAX_COORD: f32 = (1 << 14) as f32;
|
||||
|
||||
fn process_tick(
|
||||
config: &Config,
|
||||
tick_state: &csdemo::parser::EntityTickStates,
|
||||
entity_id_to_user: &mut std::collections::HashMap<i32, csdemo::UserId>,
|
||||
pawn_ids: &std::collections::HashMap<i32, csdemo::UserId>,
|
||||
player_lifestate: &mut std::collections::HashMap<i32, u32>,
|
||||
player_position: &mut std::collections::HashMap<i32, (f32, f32, f32)>,
|
||||
player_cells: &mut std::collections::HashMap<i32, (u32, u32, u32)>,
|
||||
heatmaps: &mut std::collections::HashMap<i32, HeatMap>,
|
||||
pawn_ids: &std::collections::HashMap<PawnID, csdemo::UserId>,
|
||||
player_lifestate: &mut std::collections::HashMap<csdemo::UserId, u32>,
|
||||
player_position: &mut std::collections::HashMap<csdemo::UserId, (f32, f32, f32)>,
|
||||
player_cells: &mut std::collections::HashMap<csdemo::UserId, (u32, u32, u32)>,
|
||||
heatmaps: &mut std::collections::HashMap<csdemo::UserId, HeatMap>,
|
||||
) {
|
||||
for entity_state in tick_state
|
||||
.states
|
||||
.iter()
|
||||
.filter(|s| s.class.as_ref() == "CCSPlayerPawn")
|
||||
{
|
||||
if let Some(pawn_id) = get_entityid(&entity_state.props) {
|
||||
let user_id = pawn_ids.get(&pawn_id).cloned().unwrap();
|
||||
entity_id_to_user.insert(entity_state.id, user_id.clone());
|
||||
}
|
||||
|
||||
let user_id = entity_state.id;
|
||||
let pawn_id = PawnID::from(entity_state.id);
|
||||
let user_id = match pawn_ids.get(&pawn_id).cloned() {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
continue
|
||||
}
|
||||
};
|
||||
|
||||
let _inner_guard =
|
||||
tracing::trace_span!("Entity", entity_id=?entity_state.id).entered();
|
||||
tracing::trace_span!("Entity", entity_id=?entity_state.id).entered();
|
||||
|
||||
let x_cell = match entity_state.get_prop("CCSPlayerPawn.CBodyComponentBaseAnimGraph.m_cellX").map(|prop| prop.value.as_u32()).flatten() {
|
||||
Some(c) => c,
|
||||
@@ -277,7 +279,7 @@ impl HeatMap {
|
||||
let mut buffer = image::RgbImage::new((self.max_x - self.min_x) as u32 + 1, (self.max_y - self.min_y) as u32 + 1);
|
||||
|
||||
for (y, row) in self.rows.iter().rev().enumerate() {
|
||||
for (x, cell) in row.iter().copied().chain(core::iter::repeat(0)).enumerate().take((self.max_x - self.min_x)) {
|
||||
for (x, cell) in row.iter().copied().chain(core::iter::repeat(0)).enumerate().take(self.max_x - self.min_x) {
|
||||
let scaled = (1.0/(1.0 + (cell as f32))) * 240.0;
|
||||
let raw_rgb = colors_transform::Hsl::from(scaled, 100.0, 50.0).to_rgb();
|
||||
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod endofgame;
|
||||
pub mod heatmap;
|
||||
pub mod perround;
|
||||
|
||||
177
analysis/src/perround.rs
Normal file
177
analysis/src/perround.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum WinReason {
|
||||
StillInProgress,
|
||||
BombExploded,
|
||||
VipEscaped,
|
||||
VipKilled,
|
||||
TSaved,
|
||||
CtStoppedEscape,
|
||||
RoundEndReasonTerroristsStopped,
|
||||
BombDefused,
|
||||
TKilled,
|
||||
CTKilled,
|
||||
Draw,
|
||||
HostageRescued,
|
||||
TimeRanOut,
|
||||
RoundEndReasonHostagesNotRescued,
|
||||
TerroristsNotEscaped,
|
||||
VipNotEscaped,
|
||||
GameStart,
|
||||
TSurrender,
|
||||
CTSurrender,
|
||||
TPlanted,
|
||||
CTReachedHostage,
|
||||
}
|
||||
|
||||
// https://github.com/markus-wa/demoinfocs-golang/blob/205b0bb25e9f3e96e1d306d154199b4a6292940e/pkg/demoinfocs/events/events.go#L53
|
||||
pub static ROUND_WIN_REASON: phf::Map<i32, WinReason> = phf::phf_map! {
|
||||
0_i32 => WinReason::StillInProgress,
|
||||
1_i32 => WinReason::BombExploded,
|
||||
2_i32 => WinReason::VipEscaped,
|
||||
3_i32 => WinReason::VipKilled,
|
||||
4_i32 => WinReason::TSaved,
|
||||
5_i32 => WinReason::CtStoppedEscape,
|
||||
6_i32 => WinReason::RoundEndReasonTerroristsStopped,
|
||||
7_i32 => WinReason::BombDefused,
|
||||
8_i32 => WinReason::TKilled,
|
||||
9_i32 => WinReason::CTKilled,
|
||||
10_i32 => WinReason::Draw,
|
||||
11_i32 => WinReason::HostageRescued,
|
||||
12_i32 => WinReason::TimeRanOut,
|
||||
13_i32 => WinReason::RoundEndReasonHostagesNotRescued,
|
||||
14_i32 => WinReason::TerroristsNotEscaped,
|
||||
15_i32 => WinReason::VipNotEscaped,
|
||||
16_i32 => WinReason::GameStart,
|
||||
17_i32 => WinReason::TSurrender,
|
||||
18_i32 => WinReason::CTSurrender,
|
||||
19_i32 => WinReason::TPlanted,
|
||||
20_i32 => WinReason::CTReachedHostage,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Round {
|
||||
pub winreason: WinReason,
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
pub events: Vec<RoundEvent>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum RoundEvent {
|
||||
BombPlanted,
|
||||
BombDefused,
|
||||
Kill {
|
||||
attacker: u64,
|
||||
died: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PerRound {
|
||||
pub rounds: Vec<Round>
|
||||
}
|
||||
|
||||
pub fn parse(buf: &[u8]) -> Result<PerRound, ()> {
|
||||
let tmp = csdemo::Container::parse(buf).map_err(|e| ())?;
|
||||
let output = csdemo::parser::parse(
|
||||
csdemo::FrameIterator::parse(tmp.inner),
|
||||
csdemo::parser::EntityFilter::all()
|
||||
).map_err(|e| ())?;
|
||||
|
||||
let mut rounds: Vec<Round> = Vec::new();
|
||||
for tick in output.entity_states.ticks.iter() {
|
||||
for state in tick.states.iter() {
|
||||
let round_start_count = state.get_prop("CCSGameRulesProxy.CCSGameRules.m_nRoundStartCount").map(|v| v.value.as_u32()).flatten();
|
||||
if let Some(round_start_count) = round_start_count {
|
||||
if rounds.len() < (round_start_count - 1) as usize {
|
||||
rounds.push(Round {
|
||||
winreason: WinReason::StillInProgress,
|
||||
start: tick.tick,
|
||||
end: u32::MAX,
|
||||
events: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let round_end_count = state.get_prop("CCSGameRulesProxy.CCSGameRules.m_nRoundEndCount").map(|v| v.value.as_u32()).flatten();
|
||||
if let Some(round_end_count) = round_end_count {
|
||||
if rounds.len() == (round_end_count - 1) as usize {
|
||||
rounds.last_mut().unwrap().end = tick.tick;
|
||||
}
|
||||
}
|
||||
|
||||
let total_rounds_played = state.get_prop("CCSGameRulesProxy.CCSGameRules.m_totalRoundsPlayed").map(|v| v.value.as_i32()).flatten();
|
||||
if let Some(total_rounds_played) = total_rounds_played {
|
||||
debug_assert_eq!(total_rounds_played, rounds.len() as i32);
|
||||
}
|
||||
|
||||
|
||||
if state.class.as_ref() == "CCSGameRulesProxy" {
|
||||
let round_win_reason = state.get_prop("CCSGameRulesProxy.CCSGameRules.m_eRoundWinReason").map(|p| p.value.as_i32()).flatten().map(|v| ROUND_WIN_REASON.get(&v)).flatten().filter(|r| !matches!(r, WinReason::StillInProgress));
|
||||
if let Some(round_win_reason) = round_win_reason {
|
||||
rounds.last_mut().unwrap().winreason = round_win_reason.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut rounds_iter = rounds.iter_mut();
|
||||
|
||||
let mut current_tick = 0;
|
||||
let mut current_round = rounds_iter.next().unwrap();
|
||||
'events: for event in output.events.iter() {
|
||||
match event {
|
||||
csdemo::DemoEvent::Tick(tick) => {
|
||||
current_tick = tick.tick();
|
||||
}
|
||||
csdemo::DemoEvent::GameEvent(ge) => {
|
||||
if current_tick < current_round.start {
|
||||
continue;
|
||||
}
|
||||
while current_tick > current_round.end {
|
||||
match rounds_iter.next() {
|
||||
Some(r) => {
|
||||
current_round = r;
|
||||
}
|
||||
None => break 'events,
|
||||
};
|
||||
}
|
||||
|
||||
let event = match ge.as_ref() {
|
||||
csdemo::game_event::GameEvent::BombPlanted(planted) => {
|
||||
RoundEvent::BombPlanted
|
||||
}
|
||||
csdemo::game_event::GameEvent::BombDefused(defused) => {
|
||||
RoundEvent::BombDefused
|
||||
}
|
||||
csdemo::game_event::GameEvent::PlayerDeath(death) => {
|
||||
let died = match death.userid {
|
||||
Some(d) => d,
|
||||
None => continue,
|
||||
};
|
||||
let attacker = match death.attacker.filter(|p| p.0 <= 10) {
|
||||
Some(a) => a,
|
||||
None => died.clone(),
|
||||
};
|
||||
|
||||
let died_player = output.player_info.get(&died).unwrap();
|
||||
let attacker_player = output.player_info.get(&attacker).unwrap();
|
||||
|
||||
RoundEvent::Kill {
|
||||
attacker: attacker_player.xuid,
|
||||
died: died_player.xuid,
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
current_round.events.push(event);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
|
||||
Ok(PerRound {
|
||||
rounds,
|
||||
})
|
||||
}
|
||||
@@ -11,8 +11,7 @@ fn heatmap_nuke() {
|
||||
let config = heatmap::Config { cell_size: 5.0 };
|
||||
let result = heatmap::parse(&config, &input_bytes).unwrap();
|
||||
|
||||
assert_eq!(result.player_heatmaps.len(), 11);
|
||||
assert_eq!(result.entity_to_player.len(), 12);
|
||||
assert_eq!(result.player_heatmaps.len(), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -25,7 +24,7 @@ fn heatmap_inferno() {
|
||||
let config = heatmap::Config { cell_size: 5.0 };
|
||||
let result = heatmap::parse(&config, &input_bytes).unwrap();
|
||||
|
||||
assert_eq!(result.player_heatmaps.len(), result.player_info.len(), "Players: {:?}", result.player_heatmaps.keys().collect::<Vec<_>>());
|
||||
assert_eq!(result.player_heatmaps.len(), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -38,18 +37,5 @@ fn heatmap_dust2() {
|
||||
let config = heatmap::Config { cell_size: 5.0 };
|
||||
let result = heatmap::parse(&config, &input_bytes).unwrap();
|
||||
|
||||
assert_eq!(result.player_heatmaps.len(), result.player_info.len(), "Players: {:?}", result.player_heatmaps.keys().collect::<Vec<_>>());
|
||||
assert_eq!(
|
||||
result.player_info.len(),
|
||||
result.entity_to_player.len(),
|
||||
"Missing Entity-to-Player: {:?} - Missing Player-Info: {:?}",
|
||||
result.player_heatmaps.keys().filter(|entity| !result.entity_to_player.contains_key(*entity)).collect::<Vec<_>>(),
|
||||
result.player_info.iter().filter_map(|(user_id, info)| {
|
||||
if result.entity_to_player.values().any(|p| p == user_id) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(info)
|
||||
}).collect::<Vec<_>>(),
|
||||
);
|
||||
assert_eq!(result.player_heatmaps.len(), 10);
|
||||
}
|
||||
|
||||
14
analysis/tests/perround.rs
Normal file
14
analysis/tests/perround.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use analysis::perround;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn perround_nuke() {
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../testfiles/nuke.dem");
|
||||
dbg!(path);
|
||||
let input_bytes = std::fs::read(path).unwrap();
|
||||
|
||||
let result = perround::parse(&input_bytes).unwrap();
|
||||
dbg!(&result);
|
||||
|
||||
assert_eq!(21, result.rounds.len());
|
||||
}
|
||||
57523
analysis/text.txt
Normal file
57523
analysis/text.txt
Normal file
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,22 @@ use std::path::PathBuf;
|
||||
use diesel::prelude::*;
|
||||
use diesel_async::RunQueryDsl;
|
||||
|
||||
pub mod perround;
|
||||
pub mod base;
|
||||
pub mod heatmap;
|
||||
|
||||
pub trait Analysis {
|
||||
fn analyse(&self, input: AnalysisInput) -> Result<Box<dyn FnOnce(&mut diesel_async::pg::AsyncPgConnection) -> core::pin::Pin<Box<(dyn core::future::Future<Output = Result<(), diesel::result::Error>> + Send + '_)>> + Send>, ()>;
|
||||
}
|
||||
|
||||
pub static ANALYSIS_METHODS: std::sync::LazyLock<[std::sync::Arc<dyn Analysis + Send + Sync>; 3]> = std::sync::LazyLock::new(|| {
|
||||
[
|
||||
std::sync::Arc::new(base::BaseAnalysis::new()),
|
||||
std::sync::Arc::new(heatmap::HeatmapAnalysis::new()),
|
||||
std::sync::Arc::new(perround::PerRoundAnalysis::new()),
|
||||
]
|
||||
});
|
||||
|
||||
pub async fn poll_next_task(
|
||||
upload_folder: &std::path::Path,
|
||||
db_con: &mut diesel_async::pg::AsyncPgConnection,
|
||||
@@ -17,7 +33,7 @@ pub async fn poll_next_task(
|
||||
loop {
|
||||
let result = db_con
|
||||
.build_transaction()
|
||||
.run::<'_, _, diesel::result::Error, _>(|conn| {
|
||||
.run::<_, diesel::result::Error, _>(|conn| {
|
||||
Box::pin(async move {
|
||||
let mut results: Vec<crate::models::AnalysisTask> = query.load(conn).await?;
|
||||
let final_result = match results.pop() {
|
||||
@@ -92,65 +108,3 @@ pub struct BasePlayerStats {
|
||||
pub damage: usize,
|
||||
pub assists: usize,
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(input))]
|
||||
pub fn analyse_base(input: AnalysisInput) -> BaseInfo {
|
||||
tracing::info!("Performing Base analysis");
|
||||
|
||||
let file = std::fs::File::open(&input.path).unwrap();
|
||||
let mmap = unsafe { memmap2::MmapOptions::new().map(&file).unwrap() };
|
||||
|
||||
let result = analysis::endofgame::parse(&mmap).unwrap();
|
||||
|
||||
BaseInfo {
|
||||
map: result.map,
|
||||
players: result.players.into_iter().map(|(info, stats)| {
|
||||
(BasePlayerInfo {
|
||||
name: info.name,
|
||||
steam_id: info.steam_id,
|
||||
team: info.team,
|
||||
ingame_id: info.ingame_id,
|
||||
color: info.color,
|
||||
}, BasePlayerStats {
|
||||
kills: stats.kills,
|
||||
assists: stats.assists,
|
||||
damage: stats.damage,
|
||||
deaths: stats.deaths,
|
||||
})
|
||||
}).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(input))]
|
||||
pub fn analyse_heatmap(input: AnalysisInput) -> std::collections::HashMap<String, analysis::heatmap::HeatMap> {
|
||||
tracing::info!("Generating HEATMAPs");
|
||||
|
||||
let file = std::fs::File::open(&input.path).unwrap();
|
||||
let mmap = unsafe { memmap2::MmapOptions::new().map(&file).unwrap() };
|
||||
|
||||
let config = analysis::heatmap::Config {
|
||||
cell_size: 5.0,
|
||||
};
|
||||
let result = analysis::heatmap::parse(&config, &mmap).unwrap();
|
||||
|
||||
tracing::info!("Got {} Entity-Heatmaps", result.player_heatmaps.len());
|
||||
result.player_heatmaps.into_iter().filter_map(|(entity_id, heatmap)| {
|
||||
let userid = match result.entity_to_player.get(&entity_id) {
|
||||
Some(u) => u,
|
||||
None => {
|
||||
tracing::warn!("Could not find User for Entity: {:?}", entity_id);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let player = match result.player_info.get(userid) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
tracing::warn!("Could not find player: {:?}", userid);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
Some((player.xuid.to_string(), heatmap))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
114
backend/src/analysis/base.rs
Normal file
114
backend/src/analysis/base.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
use super::*;
|
||||
|
||||
pub struct BaseAnalysis {}
|
||||
|
||||
impl BaseAnalysis {
|
||||
pub fn new() -> Self {
|
||||
Self {}
|
||||
}
|
||||
}
|
||||
|
||||
impl Analysis for BaseAnalysis {
|
||||
#[tracing::instrument(name = "Base", skip(self, input))]
|
||||
fn analyse(&self, input: AnalysisInput) -> Result<Box<dyn FnOnce(&mut diesel_async::pg::AsyncPgConnection) -> core::pin::Pin<Box<(dyn core::future::Future<Output = Result<(), diesel::result::Error>> + Send + '_)>> + Send>, ()> { tracing::info!("Performing Base analysis");
|
||||
|
||||
let file = std::fs::File::open(&input.path).unwrap();
|
||||
let mmap = unsafe { memmap2::MmapOptions::new().map(&file).unwrap() };
|
||||
|
||||
let result = analysis::endofgame::parse(&mmap).unwrap();
|
||||
|
||||
let base_result = BaseInfo {
|
||||
map: result.map,
|
||||
players: result.players.into_iter().map(|(info, stats)| {
|
||||
(BasePlayerInfo {
|
||||
name: info.name,
|
||||
steam_id: info.steam_id,
|
||||
team: info.team,
|
||||
ingame_id: info.ingame_id,
|
||||
color: info.color,
|
||||
}, BasePlayerStats {
|
||||
kills: stats.kills,
|
||||
assists: stats.assists,
|
||||
damage: stats.damage,
|
||||
deaths: stats.deaths,
|
||||
})
|
||||
}).collect()
|
||||
};
|
||||
|
||||
let (player_info, player_stats): (Vec<_>, Vec<_>) = base_result
|
||||
.players
|
||||
.into_iter()
|
||||
.map(|(info, stats)| {
|
||||
(
|
||||
crate::models::DemoPlayer {
|
||||
demo_id: input.demoid,
|
||||
name: info.name,
|
||||
steam_id: info.steam_id.clone(),
|
||||
team: info.team as i16,
|
||||
color: info.color as i16,
|
||||
},
|
||||
crate::models::DemoPlayerStats {
|
||||
demo_id: input.demoid,
|
||||
steam_id: info.steam_id,
|
||||
deaths: stats.deaths as i16,
|
||||
kills: stats.kills as i16,
|
||||
damage: stats.damage as i16,
|
||||
assists: stats.assists as i16,
|
||||
},
|
||||
)
|
||||
})
|
||||
.unzip();
|
||||
|
||||
let demo_info = crate::models::DemoInfo {
|
||||
demo_id: input.demoid,
|
||||
map: base_result.map,
|
||||
};
|
||||
|
||||
Ok(Box::new(move |connection| {
|
||||
let store_demo_info_query =
|
||||
diesel::dsl::insert_into(crate::schema::demo_info::dsl::demo_info)
|
||||
.values(demo_info)
|
||||
.on_conflict(crate::schema::demo_info::dsl::demo_id)
|
||||
.do_update()
|
||||
.set(
|
||||
crate::schema::demo_info::dsl::map
|
||||
.eq(diesel::upsert::excluded(crate::schema::demo_info::dsl::map)),
|
||||
);
|
||||
let store_demo_players_query =
|
||||
diesel::dsl::insert_into(crate::schema::demo_players::dsl::demo_players)
|
||||
.values(player_info)
|
||||
.on_conflict_do_nothing();
|
||||
|
||||
let store_demo_player_stats_query =
|
||||
diesel::dsl::insert_into(crate::schema::demo_player_stats::dsl::demo_player_stats)
|
||||
.values(player_stats)
|
||||
.on_conflict((
|
||||
crate::schema::demo_player_stats::dsl::demo_id,
|
||||
crate::schema::demo_player_stats::dsl::steam_id,
|
||||
))
|
||||
.do_update()
|
||||
.set((
|
||||
crate::schema::demo_player_stats::dsl::deaths.eq(diesel::upsert::excluded(
|
||||
crate::schema::demo_player_stats::dsl::deaths,
|
||||
)),
|
||||
crate::schema::demo_player_stats::dsl::kills.eq(diesel::upsert::excluded(
|
||||
crate::schema::demo_player_stats::dsl::kills,
|
||||
)),
|
||||
crate::schema::demo_player_stats::dsl::assists.eq(diesel::upsert::excluded(
|
||||
crate::schema::demo_player_stats::dsl::assists,
|
||||
)),
|
||||
crate::schema::demo_player_stats::dsl::damage.eq(diesel::upsert::excluded(
|
||||
crate::schema::demo_player_stats::dsl::damage,
|
||||
)),
|
||||
));
|
||||
|
||||
Box::pin(async move {
|
||||
store_demo_info_query.execute(connection).await?;
|
||||
store_demo_players_query.execute(connection).await?;
|
||||
store_demo_player_stats_query.execute(connection).await?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
61
backend/src/analysis/heatmap.rs
Normal file
61
backend/src/analysis/heatmap.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
use super::*;
|
||||
|
||||
pub struct HeatmapAnalysis {}
|
||||
|
||||
impl HeatmapAnalysis {
|
||||
pub fn new() -> Self {
|
||||
Self {}
|
||||
}
|
||||
}
|
||||
|
||||
impl Analysis for HeatmapAnalysis {
|
||||
#[tracing::instrument(name = "Heatmap", skip(self, input))]
|
||||
fn analyse(&self, input: AnalysisInput) -> Result<Box<dyn FnOnce(&mut diesel_async::pg::AsyncPgConnection) -> core::pin::Pin<Box<(dyn core::future::Future<Output = Result<(), diesel::result::Error>> + Send + '_)>> + Send>, ()> {
|
||||
tracing::info!("Generating HEATMAPs");
|
||||
|
||||
let file = std::fs::File::open(&input.path).unwrap();
|
||||
let mmap = unsafe { memmap2::MmapOptions::new().map(&file).unwrap() };
|
||||
|
||||
let config = analysis::heatmap::Config {
|
||||
cell_size: 5.0,
|
||||
};
|
||||
let result = analysis::heatmap::parse(&config, &mmap).unwrap();
|
||||
|
||||
tracing::info!("Got {} Entity-Heatmaps", result.player_heatmaps.len());
|
||||
let heatmap_result: Vec<_> = result.player_heatmaps.into_iter().filter_map(|(userid, heatmap)| {
|
||||
let player = match result.player_info.get(&userid) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
tracing::warn!("Could not find player: {:?}", userid);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
Some((player.xuid.to_string(), heatmap))
|
||||
}).collect();
|
||||
|
||||
let player_heatmaps: Vec<_> = heatmap_result.into_iter().map(|(player, heatmap)| {
|
||||
tracing::trace!("HeatMap for Player: {:?}", player);
|
||||
|
||||
crate::models::DemoPlayerHeatmap {
|
||||
demo_id: input.demoid,
|
||||
steam_id: player,
|
||||
data: serde_json::to_string(&heatmap).unwrap(),
|
||||
}
|
||||
}).collect();
|
||||
|
||||
Ok(Box::new(move |connection| {
|
||||
let store_demo_player_heatmaps_query = diesel::dsl::insert_into(crate::schema::demo_heatmaps::dsl::demo_heatmaps)
|
||||
.values(player_heatmaps)
|
||||
.on_conflict((crate::schema::demo_heatmaps::dsl::demo_id, crate::schema::demo_heatmaps::dsl::steam_id))
|
||||
.do_update()
|
||||
.set(crate::schema::demo_heatmaps::dsl::data.eq(diesel::upsert::excluded(crate::schema::demo_heatmaps::dsl::data)));
|
||||
|
||||
Box::pin(async move {
|
||||
store_demo_player_heatmaps_query.execute(connection).await?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
42
backend/src/analysis/perround.rs
Normal file
42
backend/src/analysis/perround.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use super::*;
|
||||
|
||||
pub struct PerRoundAnalysis {}
|
||||
|
||||
impl PerRoundAnalysis {
|
||||
pub fn new() -> Self {
|
||||
Self {}
|
||||
}
|
||||
}
|
||||
|
||||
impl Analysis for PerRoundAnalysis {
|
||||
#[tracing::instrument(name = "PerRoundAnalysis", skip(self, input))]
|
||||
fn analyse(&self, input: AnalysisInput) -> Result<Box<dyn FnOnce(&mut diesel_async::pg::AsyncPgConnection) -> core::pin::Pin<Box<(dyn core::future::Future<Output = Result<(), diesel::result::Error>> + Send + '_)>> + Send>, ()> {
|
||||
let file = std::fs::File::open(&input.path).unwrap();
|
||||
let mmap = unsafe { memmap2::MmapOptions::new().map(&file).unwrap() };
|
||||
|
||||
let result = analysis::perround::parse(&mmap).unwrap();
|
||||
|
||||
let values: Vec<crate::models::DemoRound> = result.rounds.into_iter().enumerate().map(|(i, r)| {
|
||||
crate::models::DemoRound {
|
||||
demo_id: input.demoid,
|
||||
round_number: i as i16,
|
||||
start_tick: r.start as i64,
|
||||
end_tick: r.end as i64,
|
||||
win_reason: serde_json::to_string(&r.winreason).unwrap(),
|
||||
events: serde_json::to_value(&r.events).unwrap(),
|
||||
}
|
||||
}).collect();
|
||||
|
||||
Ok(Box::new(move |connection| {
|
||||
Box::pin(async move {
|
||||
let query = diesel::dsl::insert_into(crate::schema::demo_round::dsl::demo_round)
|
||||
.values(&values)
|
||||
.on_conflict_do_nothing();
|
||||
|
||||
query.execute(connection).await?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,9 @@ where
|
||||
.layer(axum::extract::DefaultBodyLimit::max(500 * 1024 * 1024)),
|
||||
)
|
||||
.route("/:id/info", axum::routing::get(info))
|
||||
.route("/:id/analysis/scoreboard", axum::routing::get(scoreboard))
|
||||
.route("/:id/reanalyse", axum::routing::get(analyise))
|
||||
.route("/:id/analysis/scoreboard", axum::routing::get(scoreboard))
|
||||
.route("/:id/analysis/perround", axum::routing::get(perround))
|
||||
.route("/:id/analysis/heatmap", axum::routing::get(heatmap))
|
||||
.with_state(Arc::new(DemoState {
|
||||
upload_folder: upload_folder.into(),
|
||||
@@ -305,19 +306,117 @@ async fn heatmap(
|
||||
Ok(axum::Json(data))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(session))]
|
||||
async fn perround(
|
||||
session: UserSession,
|
||||
Path(demo_id): Path<i64>,
|
||||
) -> Result<axum::response::Json<Vec<common::demo_analysis::DemoRound>>, axum::http::StatusCode> {
|
||||
let rounds_query = crate::schema::demo_round::dsl::demo_round.filter(crate::schema::demo_round::dsl::demo_id.eq(demo_id));
|
||||
let round_players_query = crate::schema::demo_players::dsl::demo_players.filter(crate::schema::demo_players::dsl::demo_id.eq(demo_id));
|
||||
|
||||
let mut db_con = crate::db_connection().await;
|
||||
|
||||
let raw_rounds: Vec<crate::models::DemoRound> = rounds_query.load(&mut db_con).await.unwrap();
|
||||
let players: Vec<crate::models::DemoPlayer> = round_players_query.load(&mut db_con).await.unwrap();
|
||||
|
||||
let mut result = Vec::with_capacity(raw_rounds.len());
|
||||
for raw_round in raw_rounds.into_iter() {
|
||||
let reason = match serde_json::from_str(&raw_round.win_reason) {
|
||||
Ok(analysis::perround::WinReason::StillInProgress) => common::demo_analysis::RoundWinReason::StillInProgress,
|
||||
Ok(analysis::perround::WinReason::TKilled) => common::demo_analysis::RoundWinReason::TKilled,
|
||||
Ok(analysis::perround::WinReason::CTKilled) => common::demo_analysis::RoundWinReason::CTKilled,
|
||||
Ok(analysis::perround::WinReason::BombDefused) => common::demo_analysis::RoundWinReason::BombDefused,
|
||||
Ok(analysis::perround::WinReason::BombExploded) => common::demo_analysis::RoundWinReason::BombExploded,
|
||||
Ok(analysis::perround::WinReason::TimeRanOut) => common::demo_analysis::RoundWinReason::TimeRanOut,
|
||||
Ok(other) => {
|
||||
tracing::error!("Unknown Mapping {:?}", other);
|
||||
return Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Deserializing Win Reason: {:?}", e);
|
||||
return Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
};
|
||||
|
||||
let parsed_events: Vec<analysis::perround::RoundEvent> = serde_json::from_value(raw_round.events).unwrap();
|
||||
let events: Vec<_> = parsed_events.into_iter().map(|event| {
|
||||
match event {
|
||||
analysis::perround::RoundEvent::BombPlanted => common::demo_analysis::RoundEvent::BombPlanted,
|
||||
analysis::perround::RoundEvent::BombDefused => common::demo_analysis::RoundEvent::BombDefused,
|
||||
analysis::perround::RoundEvent::Kill { attacker, died } => {
|
||||
let attacker_name = players.iter().find(|p| p.steam_id == attacker.to_string()).map(|p| p.name.clone()).unwrap();
|
||||
let died_name = players.iter().find(|p| p.steam_id == died.to_string()).map(|p| p.name.clone()).unwrap();
|
||||
|
||||
common::demo_analysis::RoundEvent::Killed {
|
||||
attacker: attacker_name,
|
||||
died: died_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
}).collect();
|
||||
|
||||
result.push(common::demo_analysis::DemoRound {
|
||||
reason,
|
||||
events,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(axum::Json(result))
|
||||
}
|
||||
|
||||
// The corresponding values for each map can be found using the Source2 Viewer and opening the
|
||||
// files in 'game/csgo/pak01_dir.vpk' and then 'resource/overviews/{map}.txt'
|
||||
static MINIMAP_COORDINATES: phf::Map<&str, MiniMapDefinition> = phf::phf_map! {
|
||||
"de_inferno" => MiniMapDefinition {
|
||||
pos_x: -2087.0,
|
||||
pos_y: 3870.0,
|
||||
scale: 4.9,
|
||||
"cs_italy" => MiniMapDefinition {
|
||||
pos_x: -2647.0,
|
||||
pos_y: 2592.0,
|
||||
scale: 4.6
|
||||
},
|
||||
"cs_office" => MiniMapDefinition {
|
||||
pos_x: -1838.0,
|
||||
pos_y: 1858.0,
|
||||
scale: 4.1,
|
||||
},
|
||||
"de_ancient" => MiniMapDefinition {
|
||||
pos_x: -2953.0,
|
||||
pos_y: 2164.0,
|
||||
scale: 5.0,
|
||||
},
|
||||
"de_anubis" => MiniMapDefinition {
|
||||
pos_x: -2796.0,
|
||||
pos_y: 3328.0,
|
||||
scale: 5.22,
|
||||
},
|
||||
"de_dust2" => MiniMapDefinition {
|
||||
pos_x: -2476.0,
|
||||
pos_y: 3239.0,
|
||||
scale: 4.4
|
||||
},
|
||||
"de_inferno" => MiniMapDefinition {
|
||||
pos_x: -2087.0,
|
||||
pos_y: 3870.0,
|
||||
scale: 4.9,
|
||||
},
|
||||
"de_mirage" => MiniMapDefinition {
|
||||
pos_x: -3230.0,
|
||||
pos_y: 1713.0,
|
||||
scale: 5.0,
|
||||
},
|
||||
"de_nuke" => MiniMapDefinition {
|
||||
pos_x: -3453.0,
|
||||
pos_y: 2887.0,
|
||||
scale: 7.0,
|
||||
},
|
||||
"de_overpass" => MiniMapDefinition {
|
||||
pos_x: -4831.0,
|
||||
pos_y: 1781.0,
|
||||
scale: 5.2,
|
||||
},
|
||||
"de_vertigo" => MiniMapDefinition {
|
||||
pos_x: -3168.0,
|
||||
pos_y: 1762.0,
|
||||
scale: 4.0,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
|
||||
@@ -101,96 +101,26 @@ pub async fn run_analysis(upload_folder: impl Into<std::path::PathBuf>) {
|
||||
|
||||
let demo_id = input.demoid;
|
||||
|
||||
let base_input = input.clone();
|
||||
let base_result = tokio::task::spawn_blocking(move || crate::analysis::analyse_base(base_input))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut store_result_fns = Vec::new();
|
||||
for analysis in analysis::ANALYSIS_METHODS.iter().map(|a| a.clone()) {
|
||||
let input = input.clone();
|
||||
let store_result = match tokio::task::spawn_blocking(move || analysis.analyse(input)).await {
|
||||
Ok(Ok(r)) => r,
|
||||
Ok(Err(e)) => {
|
||||
tracing::error!("Analysis failed: {:?}", e);
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Joining Task: {:?}", e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let heatmap_result = tokio::task::spawn_blocking(move || crate::analysis::analyse_heatmap(input))
|
||||
.await
|
||||
.unwrap();
|
||||
store_result_fns.push(store_result);
|
||||
}
|
||||
|
||||
let mut db_con = crate::db_connection().await;
|
||||
|
||||
let (player_info, player_stats): (Vec<_>, Vec<_>) = base_result
|
||||
.players
|
||||
.into_iter()
|
||||
.map(|(info, stats)| {
|
||||
(
|
||||
crate::models::DemoPlayer {
|
||||
demo_id,
|
||||
name: info.name,
|
||||
steam_id: info.steam_id.clone(),
|
||||
team: info.team as i16,
|
||||
color: info.color as i16,
|
||||
},
|
||||
crate::models::DemoPlayerStats {
|
||||
demo_id,
|
||||
steam_id: info.steam_id,
|
||||
deaths: stats.deaths as i16,
|
||||
kills: stats.kills as i16,
|
||||
damage: stats.damage as i16,
|
||||
assists: stats.assists as i16,
|
||||
},
|
||||
)
|
||||
})
|
||||
.unzip();
|
||||
|
||||
let player_heatmaps: Vec<_> = heatmap_result.into_iter().map(|(player, heatmap)| {
|
||||
tracing::trace!("HeatMap for Player: {:?}", player);
|
||||
|
||||
crate::models::DemoPlayerHeatmap {
|
||||
demo_id,
|
||||
steam_id: player,
|
||||
data: serde_json::to_string(&heatmap).unwrap(),
|
||||
}
|
||||
}).collect();
|
||||
|
||||
let demo_info = crate::models::DemoInfo {
|
||||
demo_id,
|
||||
map: base_result.map,
|
||||
};
|
||||
|
||||
let store_demo_info_query =
|
||||
diesel::dsl::insert_into(crate::schema::demo_info::dsl::demo_info)
|
||||
.values(&demo_info)
|
||||
.on_conflict(crate::schema::demo_info::dsl::demo_id)
|
||||
.do_update()
|
||||
.set(
|
||||
crate::schema::demo_info::dsl::map
|
||||
.eq(diesel::upsert::excluded(crate::schema::demo_info::dsl::map)),
|
||||
);
|
||||
let store_demo_players_query =
|
||||
diesel::dsl::insert_into(crate::schema::demo_players::dsl::demo_players)
|
||||
.values(player_info)
|
||||
.on_conflict_do_nothing();
|
||||
let store_demo_player_stats_query =
|
||||
diesel::dsl::insert_into(crate::schema::demo_player_stats::dsl::demo_player_stats)
|
||||
.values(player_stats)
|
||||
.on_conflict((
|
||||
crate::schema::demo_player_stats::dsl::demo_id,
|
||||
crate::schema::demo_player_stats::dsl::steam_id,
|
||||
))
|
||||
.do_update()
|
||||
.set((
|
||||
crate::schema::demo_player_stats::dsl::deaths.eq(diesel::upsert::excluded(
|
||||
crate::schema::demo_player_stats::dsl::deaths,
|
||||
)),
|
||||
crate::schema::demo_player_stats::dsl::kills.eq(diesel::upsert::excluded(
|
||||
crate::schema::demo_player_stats::dsl::kills,
|
||||
)),
|
||||
crate::schema::demo_player_stats::dsl::assists.eq(diesel::upsert::excluded(
|
||||
crate::schema::demo_player_stats::dsl::assists,
|
||||
)),
|
||||
crate::schema::demo_player_stats::dsl::damage.eq(diesel::upsert::excluded(
|
||||
crate::schema::demo_player_stats::dsl::damage,
|
||||
)),
|
||||
));
|
||||
let store_demo_player_heatmaps_query = diesel::dsl::insert_into(crate::schema::demo_heatmaps::dsl::demo_heatmaps)
|
||||
.values(player_heatmaps)
|
||||
.on_conflict((crate::schema::demo_heatmaps::dsl::demo_id, crate::schema::demo_heatmaps::dsl::steam_id))
|
||||
.do_update()
|
||||
.set((crate::schema::demo_heatmaps::dsl::data.eq(diesel::upsert::excluded(crate::schema::demo_heatmaps::dsl::data))));
|
||||
let update_process_info =
|
||||
diesel::dsl::update(crate::schema::processing_status::dsl::processing_status)
|
||||
.set(crate::schema::processing_status::dsl::info.eq(1))
|
||||
@@ -199,11 +129,11 @@ pub async fn run_analysis(upload_folder: impl Into<std::path::PathBuf>) {
|
||||
db_con
|
||||
.transaction::<'_, '_, '_, _, diesel::result::Error, _>(|conn| {
|
||||
Box::pin(async move {
|
||||
store_demo_info_query.execute(conn).await?;
|
||||
store_demo_players_query.execute(conn).await?;
|
||||
store_demo_player_stats_query.execute(conn).await?;
|
||||
store_demo_player_heatmaps_query.execute(conn).await?;
|
||||
for store_fn in store_result_fns {
|
||||
store_fn(conn).await?;
|
||||
}
|
||||
update_process_info.execute(conn).await?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -88,3 +88,15 @@ pub struct DemoPlayerHeatmap {
|
||||
pub steam_id: String,
|
||||
pub data: String,
|
||||
}
|
||||
|
||||
#[derive(Queryable, Selectable, Insertable, Debug)]
|
||||
#[diesel(table_name = crate::schema::demo_round)]
|
||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
||||
pub struct DemoRound {
|
||||
pub demo_id: i64,
|
||||
pub round_number: i16,
|
||||
pub start_tick: i64,
|
||||
pub end_tick: i64,
|
||||
pub win_reason: String,
|
||||
pub events: serde_json::Value,
|
||||
}
|
||||
|
||||
@@ -44,6 +44,17 @@ diesel::table! {
|
||||
}
|
||||
}
|
||||
|
||||
diesel::table! {
|
||||
demo_round (demo_id, round_number) {
|
||||
demo_id -> Int8,
|
||||
round_number -> Int2,
|
||||
start_tick -> Int8,
|
||||
end_tick -> Int8,
|
||||
win_reason -> Text,
|
||||
events -> Json,
|
||||
}
|
||||
}
|
||||
|
||||
diesel::table! {
|
||||
demos (demo_id) {
|
||||
steam_id -> Text,
|
||||
@@ -78,6 +89,7 @@ diesel::joinable!(demo_heatmaps -> demo_info (demo_id));
|
||||
diesel::joinable!(demo_info -> demos (demo_id));
|
||||
diesel::joinable!(demo_player_stats -> demo_info (demo_id));
|
||||
diesel::joinable!(demo_players -> demo_info (demo_id));
|
||||
diesel::joinable!(demo_round -> demo_info (demo_id));
|
||||
diesel::joinable!(processing_status -> demos (demo_id));
|
||||
|
||||
diesel::allow_tables_to_appear_in_same_query!(
|
||||
@@ -86,6 +98,7 @@ diesel::allow_tables_to_appear_in_same_query!(
|
||||
demo_info,
|
||||
demo_player_stats,
|
||||
demo_players,
|
||||
demo_round,
|
||||
demos,
|
||||
processing_status,
|
||||
sessions,
|
||||
|
||||
@@ -37,4 +37,45 @@ pub mod demo_analysis {
|
||||
pub name: String,
|
||||
pub png_data: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DemoRound {
|
||||
pub reason: RoundWinReason,
|
||||
pub events: Vec<RoundEvent>
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum RoundWinReason {
|
||||
StillInProgress,
|
||||
BombExploded,
|
||||
VipEscaped,
|
||||
VipKilled,
|
||||
TSaved,
|
||||
CtStoppedEscape,
|
||||
RoundEndReasonTerroristsStopped,
|
||||
BombDefused,
|
||||
TKilled,
|
||||
CTKilled,
|
||||
Draw,
|
||||
HostageRescued,
|
||||
TimeRanOut,
|
||||
RoundEndReasonHostagesNotRescued,
|
||||
TerroristsNotEscaped,
|
||||
VipNotEscaped,
|
||||
GameStart,
|
||||
TSurrender,
|
||||
CTSurrender,
|
||||
TPlanted,
|
||||
CTReachedHostage,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum RoundEvent {
|
||||
BombPlanted,
|
||||
BombDefused,
|
||||
Killed {
|
||||
attacker: String,
|
||||
died: String,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ use leptos::*;
|
||||
use leptos_router::{Outlet, A};
|
||||
|
||||
pub mod heatmap;
|
||||
pub mod scoreboard;
|
||||
pub mod perround;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct CurrentDemoName(ReadSignal<String>);
|
||||
@@ -87,95 +89,3 @@ pub fn demo() -> impl leptos::IntoView {
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[leptos::component]
|
||||
pub fn scoreboard() -> impl leptos::IntoView {
|
||||
use leptos::Suspense;
|
||||
|
||||
let scoreboard_resource =
|
||||
create_resource(leptos_router::use_params_map(), |params| async move {
|
||||
let id = params.get("id").unwrap();
|
||||
|
||||
let res =
|
||||
reqwasm::http::Request::get(&format!("/api/demos/{}/analysis/scoreboard", id))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
res.json::<common::demo_analysis::ScoreBoard>()
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
let team_display_func = |team: &[common::demo_analysis::ScoreBoardPlayer]| {
|
||||
team.iter()
|
||||
.map(|player| {
|
||||
view! {
|
||||
<tr>
|
||||
<td> { player.name.clone() } </td>
|
||||
<td> { player.kills } </td>
|
||||
<td> { player.assists } </td>
|
||||
<td> { player.deaths } </td>
|
||||
<td> { player.damage } </td>
|
||||
</tr>
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
view! {
|
||||
<h2>Scoreboard</h2>
|
||||
|
||||
<Suspense
|
||||
fallback=move || view! { <p>Loading Scoreboard data</p> }
|
||||
>
|
||||
<div>
|
||||
<h3>Team 1</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Kills</th>
|
||||
<th>Assists</th>
|
||||
<th>Deaths</th>
|
||||
<th>Damage</th>
|
||||
</tr>
|
||||
{
|
||||
move || {
|
||||
scoreboard_resource.get().map(|s| {
|
||||
let team = s.team1;
|
||||
team_display_func(&team)
|
||||
})
|
||||
}
|
||||
}
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>Team 2</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Kills</th>
|
||||
<th>Assists</th>
|
||||
<th>Deaths</th>
|
||||
<th>Damage</th>
|
||||
</tr>
|
||||
{
|
||||
move || {
|
||||
scoreboard_resource.get().map(|s| {
|
||||
let team = s.team2;
|
||||
team_display_func(&team)
|
||||
})
|
||||
}
|
||||
}
|
||||
</table>
|
||||
</div>
|
||||
</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
#[leptos::component]
|
||||
pub fn per_round() -> impl leptos::IntoView {
|
||||
view! {
|
||||
<h3>Per Round</h3>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,20 +18,28 @@ pub fn heatmaps() -> impl leptos::IntoView {
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
view! {
|
||||
<h3>Heatmaps</h3>
|
||||
|
||||
<Suspense fallback=move || view! { <p>Loading Heatmaps</p> }>
|
||||
<div>
|
||||
{
|
||||
move || {
|
||||
heatmaps_resource.get().map(|h| {
|
||||
view! { <HeatmapView heatmaps=h /> }
|
||||
})
|
||||
}
|
||||
let style = stylers::style! {
|
||||
"Heatmap-Wrapper",
|
||||
.container {
|
||||
margin-top: 1vh;
|
||||
}
|
||||
</div>
|
||||
</Suspense>
|
||||
};
|
||||
|
||||
view! {
|
||||
class=style,
|
||||
<div class="container">
|
||||
<Suspense fallback=move || view! { <p>Loading Heatmaps</p> }>
|
||||
<div>
|
||||
{
|
||||
move || {
|
||||
heatmaps_resource.get().map(|h| {
|
||||
view! { <HeatmapView heatmaps=h /> }
|
||||
})
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</Suspense>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,12 +67,21 @@ fn heatmap_view(heatmaps: Vec<common::demo_analysis::PlayerHeatmap>) -> impl lep
|
||||
.heatmap_image > .heatmap {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.heatmap_image > img {
|
||||
width: min(70vw, 70vh);
|
||||
height: min(70vh, 70vw);
|
||||
}
|
||||
|
||||
.player_select {
|
||||
width: min(70vw, 70vh);
|
||||
}
|
||||
};
|
||||
|
||||
view! {
|
||||
class=style,
|
||||
<div>
|
||||
<select on:change=move |ev| {
|
||||
<select class="player_select" on:change=move |ev| {
|
||||
let new_value = event_target_value(&ev);
|
||||
let idx: usize = new_value.parse().unwrap();
|
||||
set_value(heatmaps.get(idx).cloned());
|
||||
@@ -87,7 +104,7 @@ fn heatmap_view(heatmaps: Vec<common::demo_analysis::PlayerHeatmap>) -> impl lep
|
||||
class=style,
|
||||
<div class="heatmap_image">
|
||||
<img class="radar" src=format!("/static/minimaps/{}.png", map.0.get()) />
|
||||
<img class="heatmap" width=1024 height=1024 src=format!("data:image/png;base64,{}", heatmap.png_data) />
|
||||
<img class="heatmap" src=format!("data:image/png;base64,{}", heatmap.png_data) />
|
||||
</div>
|
||||
}.into_any(),
|
||||
None => view! { <p>ERROR</p> }.into_any(),
|
||||
|
||||
143
frontend/src/demo/perround.rs
Normal file
143
frontend/src/demo/perround.rs
Normal file
@@ -0,0 +1,143 @@
|
||||
use leptos::*;
|
||||
|
||||
fn to_roman(mut number: u32) -> char {
|
||||
if number < 12 {
|
||||
char::from_u32(8544 + number).unwrap()
|
||||
} else if number < 24 {
|
||||
char::from_u32(8544 + (number - 12)).unwrap()
|
||||
} else if number < 27 {
|
||||
char::from_u32(8544 + (number - 24)).unwrap()
|
||||
} else {
|
||||
char::from_u32(8544 + (number - 27)).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn to_coloumn(idx: usize) -> usize {
|
||||
if idx < 12 {
|
||||
1 + idx
|
||||
} else if idx < 24 {
|
||||
1 + idx + 1
|
||||
} else if idx < 27 {
|
||||
1 + idx + 2
|
||||
} else {
|
||||
1 + idx + 3
|
||||
}
|
||||
}
|
||||
|
||||
#[leptos::component]
|
||||
pub fn per_round() -> impl leptos::IntoView {
|
||||
let perround_resource =
|
||||
create_resource(leptos_router::use_params_map(), |params| async move {
|
||||
let id = params.get("id").unwrap();
|
||||
|
||||
let res =
|
||||
reqwasm::http::Request::get(&format!("/api/demos/{}/analysis/perround", id))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
res.json::<Vec<common::demo_analysis::DemoRound>>()
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
let style = stylers::style! {
|
||||
"PerRound",
|
||||
.round_overview {
|
||||
display: inline-grid;
|
||||
|
||||
width: 90vw;
|
||||
grid-template-columns: repeat(12, 1fr) 5px repeat(12, 1fr) 5px repeat(3, 1fr) 5px repeat(3, 1fr);
|
||||
grid-template-rows: repeat(3, auto);
|
||||
}
|
||||
|
||||
.round_entry {
|
||||
display: inline-block;
|
||||
|
||||
border-left: 1px solid #101010;
|
||||
border-right: 1px solid #101010;
|
||||
|
||||
padding-left: 2px;
|
||||
padding-right: 2px;
|
||||
}
|
||||
|
||||
.round_number {
|
||||
border-top: 1px solid #101010;
|
||||
border-bottom: 1px solid #101010;
|
||||
}
|
||||
|
||||
p.round_entry {
|
||||
margin: 0px;
|
||||
}
|
||||
};
|
||||
|
||||
let (round, set_round) = create_signal(0);
|
||||
|
||||
let events_list = move || {
|
||||
let round_index = round();
|
||||
let current_round = perround_resource.get().map(|rs| rs.get(round_index).cloned()).flatten();
|
||||
|
||||
match current_round {
|
||||
Some(round) => {
|
||||
round.events.iter().map(|event| {
|
||||
match event {
|
||||
common::demo_analysis::RoundEvent::BombPlanted => view! { <li>Bomb has been planted</li> }.into_view(),
|
||||
common::demo_analysis::RoundEvent::BombDefused => view! { <li>Bomb has been defused</li> }.into_view(),
|
||||
common::demo_analysis::RoundEvent::Killed { attacker, died } => view! { <li>{"'"}{ attacker }{"'"} killed {"'"}{ died }{"'"}</li> }.into_view(),
|
||||
}
|
||||
}).collect::<Vec<_>>().into_view()
|
||||
}
|
||||
None => view! {}.into_view(),
|
||||
}
|
||||
};
|
||||
|
||||
let round_overview = move || {
|
||||
(0..30).map(|r| {
|
||||
let set_round = move |_| {
|
||||
set_round.set(r);
|
||||
};
|
||||
|
||||
let round = perround_resource.get().map(|rs| rs.get(r).cloned()).flatten();
|
||||
let reason = round.map(|r| r.reason);
|
||||
|
||||
// Upper is CT by default and lower is T by default
|
||||
let mut upper_symbol = match &reason {
|
||||
Some(common::demo_analysis::RoundWinReason::TKilled) => view! { <span>Killed Ts</span> }.into_view(),
|
||||
Some(common::demo_analysis::RoundWinReason::BombDefused) => view! { <span>Defused</span> }.into_view(),
|
||||
Some(common::demo_analysis::RoundWinReason::TimeRanOut) => view! { <span>Out of Time</span> }.into_view(),
|
||||
_ => view! {}.into_view(),
|
||||
};
|
||||
let mut lower_symbol = match &reason {
|
||||
Some(common::demo_analysis::RoundWinReason::CTKilled) => view! { <span>Killed CTs</span> }.into_view(),
|
||||
Some(common::demo_analysis::RoundWinReason::BombExploded) => view! { <span>Exploded</span> }.into_view(),
|
||||
_ => view! {}.into_view(),
|
||||
};
|
||||
|
||||
if (12..27).contains(&r) {
|
||||
core::mem::swap(&mut upper_symbol, &mut lower_symbol);
|
||||
}
|
||||
|
||||
view! {
|
||||
class=style,
|
||||
<div class="round_entry" style=format!("grid-column: {}; grid-row: 1", to_coloumn(r))> { upper_symbol } </div>
|
||||
<p on:click=set_round class="round_entry round_number" style=format!("grid-column: {}; grid-row: 2", to_coloumn(r))>{ r + 1 }</p>
|
||||
<div class="round_entry" style=format!("grid-column: {}; grid-row: 3", to_coloumn(r))> { lower_symbol } </div>
|
||||
}
|
||||
}).collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
view! {
|
||||
class=style,
|
||||
<h3>Per Round</h3>
|
||||
|
||||
<div class="round_overview">
|
||||
{ round_overview }
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3> Round { move || round.get() + 1 } </h3>
|
||||
<div>
|
||||
<ul> { events_list } </ul>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
76
frontend/src/demo/scoreboard.rs
Normal file
76
frontend/src/demo/scoreboard.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use leptos::*;
|
||||
|
||||
#[leptos::component]
|
||||
pub fn scoreboard() -> impl leptos::IntoView {
|
||||
use leptos::Suspense;
|
||||
|
||||
let scoreboard_resource =
|
||||
create_resource(leptos_router::use_params_map(), |params| async move {
|
||||
let id = params.get("id").unwrap();
|
||||
|
||||
let res =
|
||||
reqwasm::http::Request::get(&format!("/api/demos/{}/analysis/scoreboard", id))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
res.json::<common::demo_analysis::ScoreBoard>()
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
view! {
|
||||
<h2>Scoreboard</h2>
|
||||
|
||||
<Suspense
|
||||
fallback=move || view! { <p>Loading Scoreboard data</p> }
|
||||
>
|
||||
<TeamScoreboard info=scoreboard_resource team_name="Team 1".to_string() part=|s| s.team1 />
|
||||
<TeamScoreboard info=scoreboard_resource team_name="Team 2".to_string() part=|s| s.team2 />
|
||||
</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
#[leptos::component]
|
||||
fn team_scoreboard(info: Resource<leptos_router::ParamsMap, common::demo_analysis::ScoreBoard>, team_name: String, part: fn(common::demo_analysis::ScoreBoard) -> Vec<common::demo_analysis::ScoreBoardPlayer>) -> impl IntoView {
|
||||
let style = stylers::style! {
|
||||
"Team-Scoreboard",
|
||||
tr:nth-child(even) {
|
||||
background-color: #dddddd;
|
||||
}
|
||||
|
||||
th {
|
||||
padding-left: 10px;
|
||||
padding-right: 10px;
|
||||
}
|
||||
th:nth-child(1) {
|
||||
width: 200px;
|
||||
}
|
||||
};
|
||||
|
||||
view! {
|
||||
class = style,
|
||||
<div>
|
||||
<h3>{ team_name }</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Kills</th>
|
||||
<th>Assists</th>
|
||||
<th>Deaths</th>
|
||||
<th>Damage</th>
|
||||
</tr>
|
||||
{
|
||||
move || {
|
||||
let value = info.get().map(|v| part(v));
|
||||
(value).into_iter().flat_map(|v| v).map(|s| {
|
||||
view! {
|
||||
class=style,
|
||||
<tr><td>{ s.name }</td><td>{ s.kills }</td><td>{ s.assists }</td><td>{ s.deaths }</td><td>{ s.damage }</td></tr>
|
||||
}
|
||||
}).collect::<Vec<_>>()
|
||||
}
|
||||
}
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,6 @@ use leptos_router::*;
|
||||
|
||||
use frontend::{Demo, Homepage, TopBar, UploadDemo};
|
||||
|
||||
async fn load_demos() -> Vec<common::BaseDemoInfo> {
|
||||
let res = reqwasm::http::Request::get("/api/demos/list")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let demos: Vec<common::BaseDemoInfo> = res.json().await.unwrap();
|
||||
|
||||
demos
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let (upload_demo_read, upload_demo_write) = create_signal(frontend::DemoUploadStatus::Hidden);
|
||||
|
||||
@@ -28,10 +18,10 @@ fn main() {
|
||||
<Routes>
|
||||
<Route path="/" view=Homepage />
|
||||
<Route path="/demo/:id" view=Demo>
|
||||
<Route path="perround" view=frontend::demo::PerRound />
|
||||
<Route path="scoreboard" view=frontend::demo::Scoreboard />
|
||||
<Route path="perround" view=frontend::demo::perround::PerRound />
|
||||
<Route path="scoreboard" view=frontend::demo::scoreboard::Scoreboard />
|
||||
<Route path="heatmaps" view=frontend::demo::heatmap::Heatmaps />
|
||||
<Route path="" view=frontend::demo::Scoreboard />
|
||||
<Route path="" view=frontend::demo::scoreboard::Scoreboard />
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
|
||||
2
migrations/2024-10-06-171346_perround/down.sql
Normal file
2
migrations/2024-10-06-171346_perround/down.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
DROP TABLE demo_round;
|
||||
10
migrations/2024-10-06-171346_perround/up.sql
Normal file
10
migrations/2024-10-06-171346_perround/up.sql
Normal file
@@ -0,0 +1,10 @@
|
||||
-- Your SQL goes here
|
||||
CREATE TABLE IF NOT EXISTS demo_round (
|
||||
demo_id bigint REFERENCES demo_info(demo_id),
|
||||
round_number int2 NOT NULL,
|
||||
start_tick bigint NOT NULL,
|
||||
end_tick bigint NOT NULL,
|
||||
win_reason TEXT NOT NULL,
|
||||
events JSON NOT NULL,
|
||||
PRIMARY KEY (demo_id, round_number)
|
||||
);
|
||||
Reference in New Issue
Block a user