| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- use std::collections::HashSet;
- use std::path::{Path, PathBuf};
- use serde::{Deserialize, Serialize};
- use crate::net::handshake::HandshakeMapSource;
- use crate::net::protocol::{
- NetCombatFx, NetDestructionEvent, NetPlayerRoster, NetSoldierState, NetSoundFx, NetTracer,
- NetVehicleState,
- };
- use crate::replay::cinematic::CinematicTimeline;
- use crate::sim::session::PlayerId;
- use crate::world::{Faction, VehicleKind};
- pub const REPLAY_SCHEMA_VERSION: u32 = 1;
- pub const REPLAYS_DIR: &str = "replays";
- #[derive(Clone, Debug, Serialize, Deserialize)]
- pub struct ReplayWeatherSnapshot {
- pub sun_elevation_deg: f32,
- pub sun_azimuth_deg: f32,
- pub cloud_coverage: f32,
- pub cloud_seed_offset: [f32; 2],
- pub cloud_seed_angle: f32,
- pub wetness: f32,
- }
- impl Default for ReplayWeatherSnapshot {
- fn default() -> Self {
- Self {
- sun_elevation_deg: 24.0,
- sun_azimuth_deg: 218.0,
- cloud_coverage: 0.54,
- cloud_seed_offset: [137.4, -84.2],
- cloud_seed_angle: 0.63,
- wetness: 0.78,
- }
- }
- }
- #[derive(Clone, Debug, Serialize, Deserialize)]
- pub struct ReplayHeader {
- pub schema_version: u32,
- pub title: String,
- pub recorded_unix_secs: u64,
- pub map_label: String,
- pub map_source: HandshakeMapSource,
- pub sample_hz: f32,
- pub duration_secs: f32,
- pub server_name: Option<String>,
- pub is_multiplayer: bool,
- pub weather: ReplayWeatherSnapshot,
- }
- impl ReplayHeader {
- /// Recovers a custom map blueprint by label/id when an older replay was recorded
- /// with a fallback `ClassicFoothills` header.
- pub fn resolve_map_source(
- &self,
- mods: &crate::modding::registry::ModRegistry,
- ) -> HandshakeMapSource {
- if matches!(self.map_source, HandshakeMapSource::ClassicFoothills) {
- let lbl = self.map_label.trim();
- if !lbl.is_empty()
- && !lbl.eq_ignore_ascii_case("Foothill Valley")
- && !lbl.eq_ignore_ascii_case("Classic: Foothill River Town")
- {
- if let Some(bp) = mods
- .maps
- .iter()
- .find(|m| m.id.eq_ignore_ascii_case(lbl) || m.name.eq_ignore_ascii_case(lbl))
- {
- return HandshakeMapSource::CustomMap(bp.clone());
- }
- }
- }
- self.map_source.clone()
- }
- }
- #[derive(Clone, Debug, Serialize, Deserialize)]
- pub enum ReplayEventKind {
- Kill {
- killer_name: String,
- victim_name: String,
- victim_soldier_id: usize,
- weapon: String,
- headshot: bool,
- distance_m: f32,
- },
- Explosion {
- radius: f32,
- },
- Destruction {
- radius: f32,
- seed: u64,
- },
- ObjectiveCapture {
- name: String,
- faction: Faction,
- },
- RadioLog {
- sender: String,
- freq_khz: Option<u32>,
- text: String,
- },
- AdminBookmark {
- label: String,
- note: String,
- },
- }
- impl ReplayEventKind {
- pub fn short_tag(&self) -> &'static str {
- match self {
- Self::Kill { .. } => "KILL",
- Self::Explosion { .. } => "BLAST",
- Self::Destruction { .. } => "DESTRUCT",
- Self::ObjectiveCapture { .. } => "CAP",
- Self::RadioLog { .. } => "RADIO",
- Self::AdminBookmark { .. } => "BOOKMARK",
- }
- }
- pub fn summary(&self) -> String {
- match self {
- Self::Kill {
- killer_name,
- victim_name,
- weapon,
- headshot,
- distance_m,
- ..
- } => {
- let hs = if *headshot { " [HS]" } else { "" };
- format!("{killer_name} -> {victim_name} ({weapon}{hs}, {distance_m:.0}m)")
- }
- Self::Explosion { radius } => format!("Explosion (r={radius:.1}m)"),
- Self::Destruction { radius, .. } => format!("CSG Breach (r={radius:.1}m)"),
- Self::ObjectiveCapture { name, faction } => format!("{name} captured by {faction:?}"),
- Self::RadioLog { sender, freq_khz, text } => {
- if let Some(f) = freq_khz {
- format!("[{:.3}] {sender}: {text}", *f as f32 / 1000.0)
- } else {
- format!("{sender}: {text}")
- }
- }
- Self::AdminBookmark { label, note } => {
- if note.is_empty() {
- format!("Bookmark: {label}")
- } else {
- format!("{label} — {note}")
- }
- }
- }
- }
- }
- #[derive(Clone, Debug, Serialize, Deserialize)]
- pub struct ReplayEvent {
- pub time_secs: f32,
- pub pos: [f32; 3],
- pub kind: ReplayEventKind,
- }
- #[derive(Clone, Debug, Default, Serialize, Deserialize)]
- pub struct ReplayFrame {
- pub time_secs: f32,
- pub soldiers: Vec<NetSoldierState>,
- pub vehicles: Vec<NetVehicleState>,
- pub tracers: Vec<NetTracer>,
- pub fx_events: Vec<NetCombatFx>,
- pub sounds: Vec<NetSoundFx>,
- pub roster: Vec<NetPlayerRoster>,
- pub player_soldier_map: Vec<(PlayerId, String, usize)>,
- }
- #[derive(Clone, Debug, Serialize, Deserialize)]
- pub struct ReplayVehicleDesc {
- pub id: usize,
- pub name: String,
- pub kind: VehicleKind,
- pub faction: Faction,
- #[serde(default)]
- pub custom_mod_id: Option<String>,
- }
- #[derive(Clone, Debug, Serialize, Deserialize)]
- pub struct ReplayFile {
- pub header: ReplayHeader,
- pub frames: Vec<ReplayFrame>,
- pub destruction_events: Vec<(f32, NetDestructionEvent)>,
- pub events: Vec<ReplayEvent>,
- pub cinematic: CinematicTimeline,
- #[serde(default)]
- pub vehicle_catalog: Vec<ReplayVehicleDesc>,
- }
- impl ReplayFile {
- pub fn save(&self, path: &Path) -> Result<(), String> {
- if let Some(parent) = path.parent() {
- if !parent.as_os_str().is_empty() {
- std::fs::create_dir_all(parent)
- .map_err(|e| format!("Failed to create dir {}: {e}", parent.display()))?;
- }
- }
- let json = serde_json::to_string(self)
- .map_err(|e| format!("Failed to serialize replay: {e}"))?;
- std::fs::write(path, json)
- .map_err(|e| format!("Failed to write {}: {e}", path.display()))
- }
- pub fn load(path: &Path) -> Result<Self, String> {
- let raw = std::fs::read_to_string(path)
- .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
- let mut replay: Self = serde_json::from_str(&raw)
- .map_err(|e| format!("Invalid replay {}: {e}", path.display()))?;
- if replay.header.schema_version > REPLAY_SCHEMA_VERSION {
- return Err(format!(
- "Unsupported replay schema v{} (engine supports <= v{})",
- replay.header.schema_version, REPLAY_SCHEMA_VERSION
- ));
- }
- replay.sanitize_and_deduplicate();
- Ok(replay)
- }
- /// Removes duplicate craters/events caused by repeated per-tick emission in older recordings.
- pub fn sanitize_and_deduplicate(&mut self) {
- let mut seen_destr: HashSet<(i32, i32, i32, u32, u64)> = HashSet::new();
- self.destruction_events.retain(|(_, ev)| {
- let key = (
- (ev.pos.x * 20.0).round() as i32,
- (ev.pos.y * 20.0).round() as i32,
- (ev.pos.z * 20.0).round() as i32,
- (ev.radius * 100.0).round() as u32,
- ev.seed,
- );
- seen_destr.insert(key)
- });
- let mut seen_ev_destr: HashSet<(i32, i32, i32, u32, u64)> = HashSet::new();
- let mut seen_ev_exp: HashSet<(i32, i32, i32, i32, u32)> = HashSet::new();
- self.events.retain(|ev| match ev.kind {
- ReplayEventKind::Destruction { radius, seed } => {
- let key = (
- (ev.pos[0] * 20.0).round() as i32,
- (ev.pos[1] * 20.0).round() as i32,
- (ev.pos[2] * 20.0).round() as i32,
- (radius * 100.0).round() as u32,
- seed,
- );
- seen_ev_destr.insert(key)
- }
- ReplayEventKind::Explosion { radius } => {
- let key = (
- (ev.time_secs * 10.0).round() as i32,
- (ev.pos[0] * 4.0).round() as i32,
- (ev.pos[1] * 4.0).round() as i32,
- (ev.pos[2] * 4.0).round() as i32,
- (radius * 10.0).round() as u32,
- );
- seen_ev_exp.insert(key)
- }
- _ => true,
- });
- }
- pub fn kill_count(&self) -> usize {
- self.events
- .iter()
- .filter(|e| matches!(e.kind, ReplayEventKind::Kill { .. }))
- .count()
- }
- pub fn bookmark_count(&self) -> usize {
- self.events
- .iter()
- .filter(|e| matches!(e.kind, ReplayEventKind::AdminBookmark { .. }))
- .count()
- }
- }
- #[derive(Clone, Debug)]
- pub struct ReplayCatalogEntry {
- pub path: PathBuf,
- pub file_name: String,
- pub title: String,
- pub map_label: String,
- pub duration_secs: f32,
- pub recorded_unix_secs: u64,
- pub kill_count: usize,
- pub bookmark_count: usize,
- pub file_bytes: u64,
- pub is_multiplayer: bool,
- }
- pub fn default_replay_filename(title: &str, unix_secs: u64) -> String {
- let clean: String = title
- .chars()
- .map(|c| {
- if c.is_ascii_alphanumeric() {
- c.to_ascii_lowercase()
- } else {
- '_'
- }
- })
- .collect();
- let trimmed = clean.trim_matches('_');
- let slug = if trimmed.is_empty() { "replay" } else { trimmed };
- format!("{slug}_{unix_secs}.cwrep.json")
- }
- pub fn list_replay_files(dir: &Path) -> Vec<ReplayCatalogEntry> {
- let Ok(rd) = std::fs::read_dir(dir) else {
- return Vec::new();
- };
- let mut entries = Vec::new();
- for item in rd.flatten() {
- let path = item.path();
- let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
- continue;
- };
- if !name.ends_with(".cwrep.json") {
- continue;
- }
- let file_bytes = std::fs::metadata(&path).map_or(0, |m| m.len());
- if let Ok(rep) = ReplayFile::load(&path) {
- entries.push(ReplayCatalogEntry {
- path: path.clone(),
- file_name: name.to_string(),
- title: rep.header.title.clone(),
- map_label: rep.header.map_label.clone(),
- duration_secs: rep.header.duration_secs,
- recorded_unix_secs: rep.header.recorded_unix_secs,
- kill_count: rep.kill_count(),
- bookmark_count: rep.bookmark_count(),
- file_bytes,
- is_multiplayer: rep.header.is_multiplayer,
- });
- }
- }
- entries.sort_by(|a, b| b.recorded_unix_secs.cmp(&a.recorded_unix_secs));
- entries
- }
|