//! Raids are recorded for their replays: every drone's and interceptor's //! track (a point every other tick, falling wrecks included) and what //! happened (shot down, by what; hits; systems lost; the Oreshnik's split). //! A recording starts with the first strike drone in the sky and ends when the sky //! has been clear a while; the last few are kept. A recon aircraft is a role of its own //! and is not part of the strike's replay (#135). use super::*; /// A system's pose at a moment of a recording. #[derive(Clone, Copy, PartialEq, Debug)] pub struct SamKey { /// The recording's tick. pub at: u32, /// Relative to the recording's origin. pos: [f32; 3], heading: f32, /// Where the launcher or turret points. yaw: f32, pitch: f32, /// The antenna's turn. dish: f32, /// A searchlight's beam: how far it runs free (to 8 blocks), 0 when it is off. beam: f32, /// Hull and component health at the sampled tick. health: f32, parts: [f32; 6], mode: battery::SamMode, radar_role: battery::RadarRole, radar_on: bool, spent_cells: u8, cap_cell: u8, cap_open: f32, } impl SamKey { fn of(sam: &Sam, origin: DVec3, at: u32) -> Self { let p = sam.pos - origin; SamKey { at, pos: [p.x as f32, p.y as f32, p.z as f32], heading: sam.heading as f32, yaw: sam.yaw as f32, pitch: sam.pitch as f32, dish: sam.dish as f32, beam: if sam.beam_on { ((sam.beam_free / 8.0).round() * 8.0).max(8.0) as f32 } else { 0.0 }, health: sam.health as f32, parts: sam.comps.0.map(|v| v as f32), mode: sam.mode, radar_role: sam.radar_role, radar_on: sam.radar_on, spent_cells: sam.spent_cells, cap_cell: sam.cap_cell, cap_open: sam.cap_open, } } /// The same pose (to within what could be seen). fn same(&self, o: &SamKey) -> bool { let near = |a: f32, b: f32, e: f32| (a - b).abs() < e; (0..3).all(|i| near(self.pos[i], o.pos[i], 0.01)) && near(self.heading, o.heading, 0.002) && near(self.yaw, o.yaw, 0.002) && near(self.pitch, o.pitch, 0.002) && near(self.dish, o.dish, 0.002) && self.beam == o.beam && self.health == o.health && self.parts == o.parts && self.mode == o.mode && self.radar_role == o.radar_role && self.radar_on == o.radar_on && self.spent_cells == o.spent_cells && self.cap_cell == o.cap_cell && near(self.cap_open, o.cap_open, 0.001) } } /// A system through a recording: its poses (a new one only when it changed, with the /// stillness before it marked), and when it was lost. pub struct SamTrack { pub id: u32, pub kind: SamKind, pub keys: Vec, /// The recording's tick it was destroyed. pub lost: Option, } /// `a` turned toward `b` by `f` the short way round. fn turn(a: f32, b: f32, f: f32) -> f32 { let tau = std::f32::consts::TAU; let d = (b - a + std::f32::consts::PI).rem_euclid(tau) - std::f32::consts::PI; a + d * f } impl SamTrack { /// The pose at `t` (the recording's ticks, fractional); None before the system was first seen. pub fn pose(&self, t: f64) -> Option { let first = self.keys.first()?; if t < first.at as f64 { return None; } let i = self.keys.partition_point(|k| k.at as f64 <= t).saturating_sub(1); let a = self.keys[i]; let Some(b) = self.keys.get(i + 1) else { return Some(a) }; let f = ((t - a.at as f64) / (b.at - a.at).max(1) as f64).clamp(0.0, 1.0) as f32; let l = |x: f32, y: f32| x + (y - x) * f; Some(SamKey { at: a.at, pos: [l(a.pos[0], b.pos[0]), l(a.pos[1], b.pos[1]), l(a.pos[2], b.pos[2])], heading: turn(a.heading, b.heading, f), yaw: turn(a.yaw, b.yaw, f), pitch: l(a.pitch, b.pitch), dish: turn(a.dish, b.dish, f), beam: a.beam, health: a.health, parts: a.parts, mode: a.mode, radar_role: a.radar_role, radar_on: a.radar_on, spent_cells: a.spent_cells, cap_cell: a.cap_cell, cap_open: if a.cap_cell == b.cap_cell && a.spent_cells == b.spent_cells { l(a.cap_open, b.cap_open) } else { a.cap_open }, }) } /// The system as it stood at `t`, as a ghost to draw with the ids from `id`. pub fn ghost(&self, origin: DVec3, t: f64, id: u32) -> Option { let k = self.pose(t)?; let pos = origin + DVec3::new(k.pos[0] as f64, k.pos[1] as f64, k.pos[2] as f64); let mut sam = Sam::new(id, self.kind, pos, k.heading as f64); sam.yaw = k.yaw as f64; sam.pitch = k.pitch as f64; sam.dish = k.dish as f64; sam.beam_on = k.beam > 0.0; sam.beam_free = k.beam as f64; sam.health = if self.lost.is_some_and(|l| t >= l as f64) { 0.0 } else { k.health as f64 }; sam.comps = Comps(k.parts.map(|v| v as f64)); sam.mode = k.mode; sam.radar_role = k.radar_role; sam.radar_on = k.radar_on; sam.spent_cells = k.spent_cells; sam.cap_cell = k.cap_cell; sam.cap_open = k.cap_open; Some(sam) } } #[cfg(any(test, feature = "test-fixtures"))] impl Recording { /// A recording of `len` ticks with nothing in it (for the planner's tests). pub fn blank(len: u32) -> Self { Recording { number: 1, origin: DVec3::ZERO, len, tracks: Vec::new(), index: HashMap::new(), events: Vec::new(), scene: None, tally: Tally::default(), sams: Vec::new(), objects: Vec::new(), sam_tracks: Vec::new(), sam_index: HashMap::new(), sam_keys: 0, sam_step: STEP, ticks: Vec::new(), times: Vec::new(), quiet: 0, } } /// A straight track from `from` to `to` over the ticks `first..=last` (every `STEP`). pub fn straight(&mut self, id: u32, what: What, first: u32, last: u32, from: DVec3, to: DVec3) { let n = ((last - first) / STEP).max(1) as usize; let points = (0..=n).map(|k| { let p = from.lerp(to, k as f64 / n as f64); [p.x as f32, p.y as f32, p.z as f32] }); self.index.insert(id, self.tracks.len()); self.tracks.push(Track { id, what, first, points: points.collect(), fell: None }); } } impl Recording { /// The searchlights' beams at `t` as the recording had them (position and direction from the /// recorded poses, none for a lost light), never the live state. pub fn beams(&self, t: f64) -> Vec { self.sam_tracks.iter().filter_map(|st| st.ghost(self.origin, t, st.id)?.spot_beam()).collect() } } /// Ticks between a track's points. pub const STEP: u32 = 2; /// The longest recording (10 minutes) and how many are kept. const LONGEST: u32 = 12_000; const KEPT: usize = 3; /// SAM poses share a fixed memory budget; under pressure old poses are thinned and new ones slow down. const MAX_SAM_KEYS: usize = 32_768; #[derive(Clone, Copy, PartialEq, Debug)] pub enum What { Drone(DroneKind), /// An interceptor and the system that fired it. Missile(MissileKind, u32), /// A counter-strike missile on its way to a launch site (#109). Strike, /// An explicitly profiled ground strike and its physical carrier. StrikeCarrier(u32), } pub struct Track { pub id: u32, pub what: What, /// The recording's tick of its first point. pub first: u32, /// Its points, `STEP` ticks apart, relative to the recording's origin. points: Vec<[f32; 3]>, /// When it was shot down (a drone falling from then on). pub fell: Option, } #[derive(Clone, Copy, PartialEq, Debug)] pub enum EventKind { /// A drone shot down: by which system (its index then), with a missile or the guns, and how it ended /// (rolled once, live; a replay reads it and never rolls). Kill { drone: u32, kind: DroneKind, sam: u32, sam_kind: SamKind, sam_index: usize, missile: Option, outcome: Outcome }, /// A drone's warhead went off where it aimed: at an object, a system, or the land. Hit { drone: u32, kind: DroneKind, power: u32, object: Option, sam: Option<(SamKind, usize)> }, /// A system destroyed. SamLost { sam: u32, kind: SamKind, index: usize }, /// The Oreshnik's bus or a block splitting. Split { drone: u32 }, /// A drone's warhead went off against the land or a building short of its aim. Crash { drone: u32, kind: DroneKind, power: u32 }, /// A counter-strike on a launch site landed (#101): where it landed and how it ended. Launch sites themselves are /// not drawn in a replay. Strike { site: u32, result: StrikeResult }, } /// How a strike on a launch site ended. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum StrikeResult { Destroyed, /// The site was stunned for a while. Stunned, Missed, /// Shot down by the enemy's cover. Intercepted, /// Off the map: its launches ended, nothing to see. Halted, /// It met the land or a building short of its aim (#106): it went off there. Blocked, } #[derive(Clone, Copy, Debug)] pub struct Event { pub at: u32, pub pos: DVec3, pub kind: EventKind, } /// Measured scene transitions. These are facts, not inferred cinematic beats. #[derive(Clone, Copy, Debug, PartialEq)] pub enum SceneKind { MissileLaunch { missile: u32, sam: u32, target: u32, kind: MissileKind, sound: &'static str, pitch: f32 }, MotorIgnition { missile: u32, kind: MissileKind, sound: Option<&'static str> }, MotorBurnout { missile: u32, kind: MissileKind }, MotorEnergyLost { missile: u32, kind: MissileKind, speed: f64 }, TrackAcquired { sam: u32, target: u32, ever_own: bool }, TrackLost { sam: u32, target: u32 }, TrackSource { sam: u32, target: u32, ever_own: bool }, TrackLock { sam: u32, target: u32, locked: bool }, FireStarted { fire: u32, age: u32, life: u32, size: f32, quiet: bool, shown: bool, water: Option }, FireChanged { fire: u32, age: u32, life: u32, size: f32, quiet: bool, shown: bool, water: Option }, FireEnded { fire: u32 }, } #[derive(Clone, Copy, Debug, PartialEq)] pub struct SceneEvent { pub at: u32, pub pos: DVec3, pub kind: SceneKind, } /// At most this many scene transitions per recording; overflow is explicitly marked. const MAX_SCENE_EVENTS: usize = 65_536; #[derive(Default)] pub struct SceneJournal { events: Vec, pub truncated: bool, tracks: HashMap<(u32, u32), (bool, bool, DVec3)>, fires: HashMap)>, fire_events: Vec, launches: HashMap, ignitions: HashMap, burnouts: HashMap, } impl SceneJournal { /// Read-only transitions in chronological order. pub fn events(&self) -> &[SceneEvent] { &self.events } #[cfg(feature = "test-fixtures")] pub fn fixture_push(&mut self, event: SceneEvent) { self.push(event); } fn push(&mut self, event: SceneEvent) { if self.events.len() >= MAX_SCENE_EVENTS { self.truncated = true; return; } let index = self.events.len(); match event.kind { SceneKind::MissileLaunch { missile, .. } => { self.launches.insert(missile, index); } SceneKind::MotorIgnition { missile, .. } => { self.ignitions.insert(missile, index); } SceneKind::MotorBurnout { missile, .. } => { self.burnouts.insert(missile, index); } SceneKind::FireStarted { .. } | SceneKind::FireChanged { .. } | SceneKind::FireEnded { .. } => self.fire_events.push(index), _ => {} } self.events.push(event); } } /// Why interceptors and systems failed, as far as it was counted: only these are known. #[derive(Clone, Copy, Default, PartialEq, Debug)] pub struct Tally { /// Interceptors that reached their fuse and did not kill (the hit chance failed). pub missed: u32, /// Interceptors whose life ran out with the target still flying. pub expired: u32, /// Interceptors whose post-burn speed fell below their guidance threshold. pub energy_lost: u32, /// Interceptors whose target was gone (shot down by another, or lost) before they arrived. pub orphaned: u32, /// Times a system lost the track of the target it held, which was still in the sky. pub tracks_lost: u32, /// Times a system ran dry and began waiting for a reload truck. pub ammo_waits: u32, /// Interceptors lost against the land or a building on their way. pub blocked: u32, /// Interceptors that blew up in the air short of land they could not climb over. pub scrubbed: u32, } impl Tally { pub fn since(self, start: Tally) -> Tally { Tally { missed: self.missed.saturating_sub(start.missed), expired: self.expired.saturating_sub(start.expired), energy_lost: self.energy_lost.saturating_sub(start.energy_lost), orphaned: self.orphaned.saturating_sub(start.orphaned), tracks_lost: self.tracks_lost.saturating_sub(start.tracks_lost), ammo_waits: self.ammo_waits.saturating_sub(start.ammo_waits), blocked: self.blocked.saturating_sub(start.blocked), scrubbed: self.scrubbed.saturating_sub(start.scrubbed), } } /// The non-zero counts as a line, or nothing. pub fn text(&self) -> String { let parts: Vec = [ (self.missed, "промахов по взрывателю"), (self.expired, "ракет выработали ресурс"), (self.energy_lost, "ракет потеряли скорость после выгорания"), (self.orphaned, "ракет остались без цели"), (self.tracks_lost, "потерь трека"), (self.ammo_waits, "ожиданий БК"), (self.blocked, "ракет разбились о препятствие"), (self.scrubbed, "ракет самоуничтожились у рельефа"), ] .into_iter() .filter(|p| p.0 > 0) .map(|p| format!("{} {}", p.0, p.1)) .collect(); parts.join(", ") } } pub struct Recording { /// Which raid of the session (1, 2, …). pub number: u32, pub origin: DVec3, /// Its length in ticks. pub len: u32, pub tracks: Vec, index: HashMap, pub events: Vec, /// None is the legacy event/track-only format. pub scene: Option, /// The failures counted during the raid. pub tally: Tally, /// The systems and objects as they stood: (id, kind, where). pub sams: Vec<(u32, SamKind, DVec3)>, pub objects: Vec, /// Every system's poses through the raid (the drawing of a replay: where it stood, which way /// it pointed, whether it was still whole). pub sam_tracks: Vec, sam_index: HashMap, sam_keys: usize, sam_step: u32, /// The game's tick number as sampled with the clock: (recording tick, game tick). A replay /// shows the world's blocks as of this time. ticks: Vec<(u32, u64)>, /// The world clock's time of day as (recording tick, day ticks), sampled on every /// `TIME_STEP`-th tick the clock was known: replays show the sky of the raid, not the current /// one. A tick the clock was unknown has no sample (a gap), so a late start or a lost clock /// never shifts later samples; empty when the clock was never known. times: Vec<(u32, u64)>, /// Ticks the sky has been clear. quiet: u32, } /// Ticks between the recording's clock samples. const TIME_STEP: u32 = 20; impl Track { /// Where it was at `t` (the recording's ticks, fractional), if it was. pub fn at(&self, origin: DVec3, t: f64) -> Option { let k = (t - self.first as f64) / STEP as f64; if k < 0.0 || self.points.is_empty() || k > (self.points.len() - 1) as f64 { return None; } let i = (k.floor() as usize).min(self.points.len() - 1); let j = (i + 1).min(self.points.len() - 1); let f = k - i as f64; let p = |q: [f32; 3]| DVec3::new(q[0] as f64, q[1] as f64, q[2] as f64); Some(origin + p(self.points[i]).lerp(p(self.points[j]), f)) } /// Which way it was flying at `t`. pub fn dir(&self, origin: DVec3, t: f64) -> DVec3 { let a = self.at(origin, t - STEP as f64).or_else(|| self.at(origin, t)); let b = self.at(origin, t + STEP as f64).or_else(|| self.at(origin, t)); match (a, b) { (Some(a), Some(b)) => (b - a).normalize_or(DVec3::NEG_Z), _ => DVec3::NEG_Z, } } /// Its `i`-th point (every `STEP` ticks from `first`), if it has one. pub fn sample(&self, origin: DVec3, i: usize) -> Option { self.points.get(i).map(|q| origin + DVec3::new(q[0] as f64, q[1] as f64, q[2] as f64)) } /// The tick of its last point. pub fn last(&self) -> u32 { self.first + (self.points.len().max(1) as u32 - 1) * STEP } /// Its points, every `every`-th, up to tick `t`. pub fn path(&self, origin: DVec3, every: usize, t: f64) -> Vec { let p = |q: &[f32; 3]| origin + DVec3::new(q[0] as f64, q[1] as f64, q[2] as f64); let upto = ((t - self.first as f64) / STEP as f64).floor(); if upto < 0.0 { return Vec::new(); } let upto = (upto as usize).min(self.points.len().saturating_sub(1)); let mut out: Vec = self.points[..=upto].iter().step_by(every.max(1)).map(p).collect(); if upto % every.max(1) != 0 { out.push(p(&self.points[upto])); } out } } /// A fire as a replay shows it: what the events lit and kept alight, merged as the live fires are. #[derive(Clone, Copy, Debug)] pub struct ReplayFire { pub at: DVec3, /// The recording's tick it was lit. pub start: u32, pub life: u32, pub size: f32, /// Age already accumulated before recording began. pub age_offset: u32, pub quiet: bool, pub shown: bool, pub water: Option, /// The event that lit it (the models' ids). pub key: usize, } /// The look of an interception by the drone's warhead: (fireball radius, ticks it burns, loudness). /// A bare decoy pops; a big warhead lights the sky. The same in the live raid and its replay. pub fn kill_look(kind: DroneKind) -> (f32, u32, f32) { let (size, life, gain, _) = outcome::look(kind, Outcome::DisabledFalling); (size, life, gain) } /// The fire a strike's end leaves (0: none): the wreck of a site burns long, a crater a while. pub fn strike_power(result: StrikeResult) -> u32 { match result { StrikeResult::Destroyed => 3, StrikeResult::Stunned => 2, StrikeResult::Missed | StrikeResult::Blocked => 1, StrikeResult::Intercepted | StrikeResult::Halted => 0, } } /// A blast's look for an event: (fireball radius, ticks it burns). The live blasts use the same. pub fn blast_spec(kind: EventKind) -> (f32, u32) { const SIZE: [f32; 5] = [2.5, 4.5, 7.0, 10.0, 13.0]; const LIFE: [u32; 5] = [11, 11, 18, 22, 26]; match kind { EventKind::Kill { kind, outcome, .. } => { let (size, life, _, _) = outcome::look(kind, outcome); (size, life) } EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => { let p = (power as usize).min(4); (SIZE[p], LIFE[p] * 9) } EventKind::SamLost { .. } => (8.0, 18 * 9), EventKind::Split { .. } => (2.0, 7 * 9), EventKind::Strike { result, .. } => match result { StrikeResult::Destroyed => (SIZE[4], LIFE[4] * 9), StrikeResult::Stunned | StrikeResult::Missed | StrikeResult::Blocked => (SIZE[3], LIFE[3] * 9), StrikeResult::Intercepted => (SIZE[0], LIFE[0] * 9), StrikeResult::Halted => (0.0, 0), }, } } /// The blasts of the recording's events burning at `t` (its ticks, fractional): the same /// `Blast`s the live simulation keeps, with `start` in the recording's ticks and the event's /// own id range. A pure function of `t`, so a seek or a pause shows the same frame. pub fn replay_blasts(rec: &Recording, t: f64) -> Vec { replay_blasts_from_events(rec, t, false) } /// Recorded smoke billows persist after the short visual blast expires. Keep the same event /// classification and geometry within the bounded 900-tick smoke window. pub fn replay_smoke_blasts(rec: &Recording, t: f64) -> Vec { replay_blasts_from_events(rec, t, true) } fn replay_blasts_from_events(rec: &Recording, t: f64, keep_expired: bool) -> Vec { rec.events .iter() .enumerate() .filter_map(|(k, e)| { let (size, life) = blast_spec(e.kind); let age = t - e.at as f64; (if keep_expired { (0.0..=900.0).contains(&age) } else { (0.0..life as f64).contains(&age) }) .then_some(Blast { id: 0x4000_0000 | k as u32, at: e.pos, size, start: e.at as u64, life }) }) .collect() } /// The fires burning at `t` in the recording: events within 6 blocks of a fire still burning /// feed it (the greater size, the longer life), as `Sim::ignite` does; those after it died light /// a new one. A pure function of `t`. pub fn replay_fires(rec: &Recording, t: f64) -> Vec { if let Some(scene) = rec.scene.as_ref().filter(|s| !s.truncated) { let mut active: HashMap = HashMap::new(); for &index in &scene.fire_events { let e = &scene.events[index]; if e.at as f64 > t { break; } match e.kind { SceneKind::FireStarted { fire, age, life, size, quiet, shown, water } | SceneKind::FireChanged { fire, age, life, size, quiet, shown, water } => { active.insert(fire, ReplayFire { at: e.pos, start: e.at.saturating_sub(age), age_offset: age.saturating_sub(e.at), life, size, quiet, shown, water, key: fire as usize }); } SceneKind::FireEnded { fire } => { active.remove(&fire); } _ => {} } } let mut fires: Vec<_> = active.into_values().filter(|f| t - f.start as f64 + (f.age_offset as f64) < f.life as f64).collect(); fires.sort_by_key(|f| f.key); return fires; } let mut fires: Vec = Vec::new(); for (k, e) in rec.events.iter().enumerate() { if e.at as f64 > t { break; } let power = match e.kind { EventKind::Crash { power, .. } => power, EventKind::Hit { power, .. } => power.max(1), EventKind::SamLost { .. } => 2, EventKind::Strike { result, .. } => strike_power(result), _ => continue, }; let (size, life) = (fires::size_for(power), fires::life_for(power)); let alive = |f: &ReplayFire| e.at < f.start + f.life; if let Some(f) = fires.iter_mut().find(|f| alive(f) && f.at.distance(e.pos) < 6.0) { f.size = f.size.max(size); f.life = f.life.max(e.at - f.start + life); } else { fires.push(ReplayFire { at: e.pos, start: e.at, life, size, age_offset: 0, quiet: false, shown: true, water: None, key: k }); } } fires.retain(|f| t < (f.start + f.life) as f64); fires } impl Recording { fn new(number: u32, sim: &Sim) -> Self { let origin = sim.targets.first().copied().or_else(|| sim.sams.first().map(|s| s.pos)).unwrap_or(DVec3::ZERO); Recording { number, origin: origin.floor(), len: 0, tracks: Vec::new(), index: HashMap::new(), events: Vec::new(), scene: Some(SceneJournal::default()), tally: Tally::default(), sams: sim.sams.iter().map(|s| (s.id, s.kind, s.pos)).collect(), objects: sim.targets.clone(), sam_tracks: Vec::new(), sam_index: HashMap::new(), sam_keys: 0, sam_step: STEP, ticks: Vec::new(), times: Vec::new(), quiet: 0, } } fn thin_sam_tracks(&mut self) { for track in &mut self.sam_tracks { let len = track.keys.len(); let mut kept = 0; for read in (0..len).step_by(2) { track.keys[kept] = track.keys[read]; kept += 1; } if len % 2 == 0 && len > 0 { track.keys[kept] = track.keys[len - 1]; kept += 1; } track.keys.truncate(kept); track.keys.shrink_to_fit(); } self.sam_keys = self.sam_tracks.iter().map(|track| track.keys.len()).sum(); self.sam_step = self.sam_step.saturating_mul(2).min(LONGEST); } /// Notes the systems' poses at the recording's tick `now`: a pose only when it changed, with /// the pose it held marked before it so a replay doesn't glide through the stillness. fn note_sams(&mut self, sams: &[Sam], now: u32) { if now % self.sam_step != 0 { return; } for sam in sams { let key = SamKey::of(sam, self.origin, now); let i = *self.sam_index.entry(sam.id).or_insert_with(|| { self.sam_tracks.push(SamTrack { id: sam.id, kind: sam.kind, keys: Vec::new(), lost: None }); self.sam_tracks.len() - 1 }); let track = &mut self.sam_tracks[i]; let before = track.keys.len(); match track.keys.last().copied() { None => track.keys.push(key), Some(last) if last.same(&key) => {} Some(last) => { if last.at + self.sam_step < now { track.keys.push(SamKey { at: now - self.sam_step, ..last }); } track.keys.push(key); } } self.sam_keys += track.keys.len() - before; } if self.sam_keys > MAX_SAM_KEYS { self.thin_sam_tracks(); } } /// Actual launch, if observed during this recording. Missing is not proof of no launch: /// the recording may have started late or the bounded journal may have filled. pub fn missile_launch(&self, missile: u32) -> Option<&SceneEvent> { let scene = self.scene.as_ref()?; scene.events.get(*scene.launches.get(&missile)?) } /// Actual motor ignition, when it was recorded. pub fn missile_ignition(&self, missile: u32) -> Option<&SceneEvent> { let scene = self.scene.as_ref()?; scene.events.get(*scene.ignitions.get(&missile)?) } /// Recorded ignition takes precedence; older/incomplete tracks retain their original fallback. pub fn missile_is_lit(&self, tr: &Track, t: f64, cold: u32) -> bool { if let Some(scene) = &self.scene && let Some(index) = scene.burnouts.get(&tr.id) && t >= scene.events[*index].at as f64 { return false; } if let Some(event) = self.missile_ignition(tr.id) { let burn = match tr.what { What::Missile(kind, _) => kind.burn_ticks(), _ => return false }; return t >= event.at as f64 && t < event.at as f64 + burn as f64; } if self.missile_launch(tr.id).is_some() && self.scene.as_ref().is_some_and(|s| !s.truncated) { return false; } let age = t - tr.first as f64; let burn = match tr.what { What::Missile(kind, _) => kind.burn_ticks(), _ => return false }; age > cold as f64 && age <= (cold + burn) as f64 } fn note_tracks(&mut self, sams: &[Sam]) { let Some(journal) = &mut self.scene else { return }; let mut current = HashMap::new(); for sam in sams { for track in &sam.tracks { let key = (sam.id, track.id); let state = (track.own_tick > 0, track.locked, track.pos); let old = journal.tracks.get(&key).copied(); if old.is_none() { journal.push(SceneEvent { at: self.len, pos: track.pos, kind: SceneKind::TrackAcquired { sam: sam.id, target: track.id, ever_own: state.0 } }); } else if old.is_some_and(|old| old.0 != state.0) { journal.push(SceneEvent { at: self.len, pos: track.pos, kind: SceneKind::TrackSource { sam: sam.id, target: track.id, ever_own: state.0 } }); } if (old.is_none() && state.1) || old.is_some_and(|old| old.1 != state.1) { journal.push(SceneEvent { at: self.len, pos: track.pos, kind: SceneKind::TrackLock { sam: sam.id, target: track.id, locked: state.1 } }); } current.insert(key, state); } } let mut lost: Vec<_> = journal.tracks.iter().filter(|(key, _)| !current.contains_key(key)).map(|(key, state)| (*key, state.2)).collect(); lost.sort_by_key(|(key, _)| *key); for ((sam, target), pos) in lost { journal.push(SceneEvent { at: self.len, pos, kind: SceneKind::TrackLost { sam, target } }); } journal.tracks = current; } /// Sample actual fire state after the simulation update, including existing fires at start. fn note_fires(&mut self, fires: &[fires::Fire], now: u64) { let Some(journal) = &mut self.scene else { return }; let mut current = HashMap::new(); for fire in fires { let state = (fire.at, fire.life, fire.size, fire.quiet, fire.shown, fire.surface_is_water()); let age = now.saturating_sub(fire.start).min(u32::MAX as u64) as u32; let kind = match journal.fires.get(&fire.id) { None => Some(SceneKind::FireStarted { fire: fire.id, age, life: fire.life, size: fire.size, quiet: fire.quiet, shown: fire.shown, water: state.5 }), Some(old) if *old != state => Some(SceneKind::FireChanged { fire: fire.id, age, life: fire.life, size: fire.size, quiet: fire.quiet, shown: fire.shown, water: state.5 }), _ => None, }; if let Some(kind) = kind { journal.push(SceneEvent { at: self.len, pos: fire.at, kind }); } current.insert(fire.id, state); } let mut ended: Vec<_> = journal.fires.iter().filter(|(id, _)| !current.contains_key(id)).map(|(id, state)| (*id, state.0)).collect(); ended.sort_by_key(|(id, _)| *id); for (fire, pos) in ended { journal.push(SceneEvent { at: self.len, pos, kind: SceneKind::FireEnded { fire } }); } journal.fires = current; } /// The game's tick at the recording's tick `t` (fractional), if it was known: the samples run /// on at the pace of the ticks between them (a pause or a gap is a step). pub fn world_tick(&self, t: f64) -> Option { let t = t.max(0.0); let i = self.ticks.partition_point(|s| s.0 as f64 <= t).checked_sub(1).or(if self.ticks.is_empty() { None } else { Some(0) })?; let (ta, a) = self.ticks[i]; let ahead = (t - ta as f64).max(0.0); Some(match self.ticks.get(i + 1) { Some(&(tb, b)) if b >= a && b - a <= 2 * (tb - ta).max(1) as u64 => a + (ahead.min((tb - ta) as f64) * (b - a) as f64 / (tb - ta).max(1) as f64) as u64, _ => a + ahead as u64, }) } /// The game tick the recording began at. pub fn first_tick(&self) -> Option { self.ticks.first().map(|s| s.1) } fn point(&mut self, id: u32, what: What, pos: DVec3) { let rel = pos - self.origin; let q = [rel.x as f32, rel.y as f32, rel.z as f32]; let now = self.len; match self.index.get(&id) { Some(&i) => self.tracks[i].points.push(q), None => { self.index.insert(id, self.tracks.len()); self.tracks.push(Track { id, what, first: now, points: vec![q], fell: None }); } } } /// The time of day (ticks, 24000 a day) the world showed at the recording's tick `t`: the /// clock as sampled, run on between samples at the pace it ran (a jump is a step), or None /// when the clock was not known (the replay then shows the world's own time). pub fn day_time(&self, t: f64) -> Option { let t = t.max(0.0); // The last sample at or before `t`; none before the first one means unknown. let i = self.times.partition_point(|s| s.0 as f64 <= t).checked_sub(1)?; let (ta, a) = self.times[i]; match self.times.get(i + 1) { // Neighbouring samples with no gap between: run on at the pace between them. Some(&(tb, b)) if tb - ta <= TIME_STEP && b >= a && b - a <= 2 * TIME_STEP as u64 => { let f = ((t - ta as f64) / (tb - ta) as f64).clamp(0.0, 1.0); Some(a + ((b - a) as f64 * f) as u64) } _ => Some(a), } } pub fn track(&self, id: u32) -> Option<&Track> { self.index.get(&id).map(|&i| &self.tracks[i]) } /// Sampled pose at the replay time, falling back to the old static snapshot. pub fn sam_at(&self, id: u32, t: f64) -> Option<(SamKind, DVec3)> { if let Some(track) = self.sam_tracks.iter().find(|s| s.id == id) { let pose = track.pose(t)?; return Some((track.kind, self.origin + DVec3::new(pose.pos[0] as f64, pose.pos[1] as f64, pose.pos[2] as f64))); } self.sam(id) } /// The system with this id as it stood. pub fn sam(&self, id: u32) -> Option<(SamKind, DVec3)> { self.sams.iter().find(|s| s.0 == id).map(|s| (s.1, s.2)) } } impl Sim { /// The recording of raid `number`, while it is kept. pub fn replay(&self, number: u32) -> Option<&Recording> { self.replays.iter().find(|r| r.number == number) } } impl Sim { /// Counts something in the session's tally and in the recording going on. pub(super) fn note(&mut self, f: impl Fn(&mut Tally)) { f(&mut self.tally); if let Some(r) = &mut self.rec { f(&mut r.tally); } } /// Record an actual transition without modifying gameplay or random state. pub(super) fn scene_event(&mut self, pos: DVec3, kind: SceneKind) { if let Some(r) = &mut self.rec { if let Some(journal) = &mut r.scene { journal.push(SceneEvent { at: r.len, pos, kind }); } } } /// Append an already-applied fact. This never changes the live world. pub(super) fn record_event(&mut self, pos: DVec3, kind: EventKind) { if let Some(r) = &mut self.rec { let at = r.len; if let EventKind::Kill { drone, .. } = kind && let Some(&i) = r.index.get(&drone) { r.tracks[i].fell = Some(at); } if let EventKind::SamLost { sam, .. } = kind && let Some(&i) = r.sam_index.get(&sam) { r.sam_tracks[i].lost.get_or_insert(at); } r.events.push(Event { at, pos, kind }); } } /// Open before the combat update so transitions on the first active tick are not lost. /// A recon aircraft neither opens nor holds a strike's recording (#135). pub(super) fn begin_recording_if_active(&mut self) { if self.rec.is_none() && (self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id)) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) { self.recordings += 1; self.rec = Some(Recording::new(self.recordings, self)); } } pub(super) fn record_strike_launch(&mut self, id: u32, carrier: u32, at: DVec3) { self.begin_recording_if_active(); if let Some(r) = &mut self.rec { r.point(0x7100_0000 | id, What::StrikeCarrier(carrier), at); } } /// Once a tick: starts a recording with the first drone or counter-strike in the air, adds the tracks' points, /// ends it when the sky has been clear 5 s. pub(super) fn record(&mut self) { // Wrecks still falling (far off they fall a long while) don't keep it going. A counter-strike is a recorded // object in its own right (#109): it holds the recording open until it lands, whatever the sky is doing. // A recon flight is not part of the strike's replay: it neither opens nor holds a // recording open. The strike's own drones and interceptors do (#135). let busy = self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id)) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty(); self.begin_recording_if_active(); let Some(r) = &mut self.rec else { return }; r.note_tracks(&self.sams); r.note_fires(&self.fires.list, self.tick); if r.len % TIME_STEP == 0 { if let Some(dt) = self.day_time { r.times.push((r.len, dt)); } r.ticks.push((r.len, self.engine_tick)); } if r.len % STEP == 0 { let now = r.len; r.note_sams(&self.sams, now); for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) { r.point(d.id, What::Drone(d.kind), d.pos); } for m in &self.missiles { r.point(m.id, What::Missile(m.kind, m.sam), m.pos); } for f in self.strikes.flights.iter().filter(|f| f.carrier.is_none()) { r.point(f.track(), What::Strike, f.pos); } } // Physical strikes start with an exact muzzle point at launch. Continue that track on a // flight-relative STEP grid; global recording parity can be offset by the launch tick. for f in &self.strikes.flights { let Some(carrier) = f.carrier else { continue }; let age = self.tick.saturating_sub(f.start); if age > 0 && age % STEP as u64 == 0 { r.point(f.track(), What::StrikeCarrier(carrier), f.pos); } } r.len += 1; r.quiet = if busy { 0 } else { r.quiet + 1 }; if r.quiet >= 100 || r.len >= LONGEST { let mut done = self.rec.take().unwrap(); if let Some(scene) = &mut done.scene { scene.tracks = HashMap::new(); scene.fires = HashMap::new(); } done.len = done.len.saturating_sub(done.quiet.saturating_sub(40)); if !done.events.is_empty() || done.scene.as_ref().is_some_and(|s| !s.events.is_empty()) { self.replays.push(done); if self.replays.len() > KEPT { self.replays.remove(0); } } } } /// Draws the recording's drones and interceptors as they were at `t`, as ghosts: ids from `base`. pub fn draw_ghosts(&self, rec: &Recording, t: f64, base: u32, out: &mut Out) { let base_id = base; for (k, tr) in rec.tracks.iter().enumerate() { let Some(pos) = tr.at(rec.origin, t) else { continue }; let dir = tr.dir(rec.origin, t); let id = base + k as u32 * PARTS; match tr.what { What::Drone(kind) => { let spec = kind.spec(); let s = spec.scale; let falling = tr.fell.is_some_and(|f| t >= f as f64); let mut rot = look(dir, 0.0); if falling { let spin = (t - tr.fell.unwrap_or(0) as f64) * 0.35; rot = rot * DQuat::from_rotation_z(spin) * DQuat::from_rotation_x(-0.6); out.model(id, spec.model, pos, rot, s, false); out.model(id + 1, "airdef:flame", pos, rot, 0.6 + 0.2 * ((t * 1.7).sin() + 1.0), true); continue; } if !matches!(kind, DroneKind::OreshnikBlock | DroneKind::OreshnikSub) { out.model(id, spec.model, pos, rot, s, false); } match spec.engine { Engine::Prop(back, size) => { let at = pos + rot * DVec3::new(0.0, 0.0, back * s); out.model(id + 1, "airdef:shahed_prop", at, rot * DQuat::from_rotation_z(t * 1.1), s * size, false); } Engine::Jet(up, back, size) => { out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * s, back * s), rot, s * size, true); } Engine::Rocket(back, size) => { if matches!(kind, DroneKind::OreshnikBlock | DroneKind::OreshnikSub) { out.model(id + 1, "airdef:reentry", pos, rot, s, true); } else if spec.ballistic.is_none() || t - (tr.first as f64) < 60.0 { out.model(id + 1, "airdef:flame", pos + rot * DVec3::new(0.0, 0.0, back * s + size), rot, size, true); } else { out.model(id + 1, "airdef:reentry", pos, rot, s * 0.6, true); } } } } What::Missile(kind, _) => { let spec = kind.spec(); let rot = look(dir, 0.0) * DQuat::from_rotation_z(t * 0.3); out.model(id, spec.model, pos, rot, spec.scale, false); if rec.missile_is_lit(tr, t, spec.cold) && spec.flame > 0.0 { let back = (spec.rear - 8.0) / 16.0 * spec.scale + spec.flame; out.model(id + 1, "airdef:flame", pos + rot * DVec3::new(0.0, 0.0, back), rot, spec.flame, true); } } What::StrikeCarrier(_) => super::strike::round_visual( out, id, pos, look(dir, 0.0), t - tr.first as f64 >= super::strike::EJECT_TICKS as f64, ), What::Strike => { // The same model, flame and turn the live flight drew (#106, #109). let spec = DroneKind::Kalibr.spec(); let rot = look(dir, 0.0); out.model(id, spec.model, pos, rot, spec.scale, false); if let Engine::Jet(up, back, size) = spec.engine { let flicker = 0.7 + 0.3 * (t * 1.7).sin().abs(); out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * spec.scale, back * spec.scale), rot, spec.scale * size * flicker, true); } } } } // The air-defence systems as they stood: where, which way, the launcher or turret where it // pointed, a wreck once lost. let mut rng = Rng(1); for (k, st) in rec.sam_tracks.iter().enumerate() { if let Some(ghost) = st.ghost(rec.origin, t, base + 0x0040_0000 + k as u32 * PARTS) { units::draw_sam_model(&ghost, &mut rng, out); } } // The protected objects as marked in the raid (struck ones shrink), not the live ones. for (i, p) in rec.objects.iter().enumerate() { let struck = rec.events.iter().any(|e| e.at as f64 <= t && matches!(e.kind, EventKind::Hit { object: Some(o), .. } if o == i)); let bob = (t * 0.1 + i as f64).sin() * 0.25; let rot = DQuat::from_rotation_y(t * 0.08); out.model(base + 0x00e0_0000 + i as u32 * PARTS, "airdef:target", *p + DVec3::Y * (1.6 + bob), rot, if struck { 0.4 } else { 0.8 }, true); } // Fires: what the events left burning (the flames dim and the smoke thickens with time), // out when their life ends. for f in replay_fires(rec, t) { let age = t - f.start as f64 + f.age_offset as f64; let (mut flame, mut smoke) = fires::replay_fire_of(f.size, f.life, age); if f.water == Some(true) { flame = 0.0; smoke *= 0.5; } if f.quiet || !f.shown { flame = 0.0; } let id = base + 0x00c0_0000 + f.key as u32 * PARTS; if flame > 0.05 { let wob = 1.0 + 0.15 * (age * 0.9 + f.key as f64).sin(); out.model(id, "airdef:flame", f.at + DVec3::Y * 0.5, DQuat::from_rotation_y(age * 0.07), (flame as f64 * 0.8 * wob).max(0.05), true); } if smoke > 0.1 && (age as u64) % 3 == 0 { out.particles("minecraft:large_smoke", f.at + DVec3::Y, 0.8, DVec3::new(0.0, 0.1, 0.0), 0.03, 1 + (smoke * 2.0) as u32); } } // The pieces a breakup or an air detonation threw off, from the recorded outcome (never a new roll): the same // pieces the live raid made, moved by the same flight, a pure function of the time. for (k, e) in rec.events.iter().enumerate() { let EventKind::Kill { drone, outcome, .. } = e.kind else { continue }; let age = t - e.at as f64; if outcome == Outcome::DisabledFalling || !(0.0..outcome::PIECE_LIFE as f64).contains(&age) { continue; } let base = rec .track(drone) .and_then(|tr| Some((tr.at(rec.origin, e.at as f64)? - tr.at(rec.origin, e.at as f64 - STEP as f64)?) / STEP as f64)) .unwrap_or(DVec3::ZERO); let seed = (k as u64).wrapping_mul(0x2545_f491_4f6c_dd1d) ^ e.at as u64; for (n, p) in outcome::pieces(seed, outcome, base).iter().enumerate() { if age as u32 >= p.life { continue; } let at = outcome::piece_at(e.pos, p, age as u32); let id = base_id + 0x0060_0000 + (k as u32 * 16 + n as u32) * PARTS; out.model(id, "airdef:debris", at, outcome::piece_rot(p, age as u32), p.scale, false); if p.burns && (age as u32) % 3 == 0 { out.particles("minecraft:large_smoke", at, 0.1, DVec3::new(0.0, 0.03, 0.0), 0.01, 1); } } } // Blasts: with the shader effects on, the post pass and the HD lights draw them from // `replay_blasts` (the same as the live ones); the models are the fallback without them. if self.shader { return; } for (k, e) in rec.events.iter().enumerate() { let age = t - e.at as f64; if !(0.0..30.0).contains(&age) { continue; } let (size, _) = blast_spec(e.kind); let size = size as f64; let f = age / 30.0; let s = size * (f * 4.0).min(1.0) * (1.0 - f * f); let id = base + 0x0080_0000 + k as u32 * PARTS; let spin = DQuat::from_rotation_y(age * 0.05); out.model(id, "airdef:fireball", e.pos + DVec3::Y * age * 0.04, spin, s.max(0.01), true); if age < 4.0 { out.model(id + 1, "airdef:flash", e.pos, spin, size * 0.6, true); } } } } #[cfg(test)] mod tests { use super::*; fn sam_at(x: f64, heading: f64, yaw: f64) -> Sam { let mut s = Sam::new(7, SamKind::S400, DVec3::new(x, 64.0, 0.0), heading); s.yaw = yaw; s } fn recording() -> Recording { Recording { number: 1, origin: DVec3::ZERO, len: 0, tracks: Vec::new(), index: HashMap::new(), events: Vec::new(), scene: None, tally: Tally::default(), sams: Vec::new(), objects: Vec::new(), sam_tracks: Vec::new(), sam_index: HashMap::new(), sam_keys: 0, sam_step: STEP, ticks: Vec::new(), times: Vec::new(), quiet: 0, } } #[test] fn replay_seeks_radar_emission_stepwise() { let mut r = recording(); let sam = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0); r.note_sams(&[sam], 0); let mut off = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0); off.radar_on = false; r.note_sams(&[off], 10); assert!(r.sam_tracks[0].ghost(r.origin, 9.0, 1).unwrap().radar_on); assert!(!r.sam_tracks[0].ghost(r.origin, 10.0, 1).unwrap().radar_on); assert!(r.sam_tracks[0].ghost(r.origin, 0.0, 1).unwrap().radar_on); } #[test] fn replay_preserves_a_separate_radars_profile() { let mut r = recording(); for (at, role) in [(0, battery::RadarRole::Search), (10, battery::RadarRole::Height), (20, battery::RadarRole::Engagement)] { let mut sam = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0); sam.set_radar_role(role); r.note_sams(&[sam], at); } assert_eq!(r.sam_tracks[0].ghost(r.origin, 1.0, 1).unwrap().radar_profile().id, "radar_search"); assert_eq!(r.sam_tracks[0].ghost(r.origin, 11.0, 1).unwrap().radar_profile().id, "radar_height"); assert_eq!(r.sam_tracks[0].ghost(r.origin, 21.0, 1).unwrap().radar_profile().id, "radar_track"); } #[test] fn replay_preserves_launcher_configuration_and_individual_cover_poses() { let mut r = recording(); let mut sam = sam_at(0.0, 0.0, 0.0); sam.set_mode(battery::SamMode::LauncherOnly); sam.cap_cell = 2; sam.cap_open = 0.5; sam.spent_cells = 1; r.note_sams(&[sam], 10); for t in [10.0, 40.0, 10.0] { let ghost = r.sam_tracks[0].ghost(r.origin, t, 160).unwrap(); assert_eq!(ghost.mode, battery::SamMode::LauncherOnly); assert_eq!((ghost.spent_cells, ghost.cap_cell, ghost.cap_open), (1, 2, 0.5)); let mut out = Out::default(); units::draw_sam_model(&ghost, &mut Rng::new(1), &mut out); assert_eq!(out.models.iter().filter(|m| m.name == "airdef:tpk_cap").count(), 4); assert!(!out.models.iter().any(|m| m.name == "airdef:radar_panel")); } } fn physical_strike(record_len: Option) -> (Sim, u32, DVec3) { use crate::sim::sites::{LaunchSite, SiteClass}; use crate::sim::strike::{Estimate, Known, SiteState}; use glam::DVec2; let mut sim = Sim::new(11); sim.tick = 100 + u64::from(record_len.unwrap_or(0)); if let Some(len) = record_len { let mut rec = Recording::new(1, &sim); rec.len = len; sim.rec = Some(rec); } let site = 1; sim.sites.list.push(LaunchSite { id: site, side: 0, sector: 0, bearing: 0.0, class: SiteClass::Ramp, pos: DVec3::new(0.0, 64.0, 300.0), range: 300.0, water: false, stock: 0, planned: 0, alive: true, next_free: 0, offmap: false, }); sim.strikes.known.push(Known { site, class: SiteClass::Ramp, obs: Vec::new(), est: Some(Estimate { pos: DVec2::new(0.0, 300.0), radius: 5.0, fix: true, bearing: 0.0, bearing_err: 0.01, origin: DVec2::ZERO, }), launches: 1, last: 0, state: SiteState::Active, aimed: false, }); sim.order_test_strike(site, DVec3::new(0.0, 64.0, 0.0), &mut Out::default()) .unwrap(); let flight = &mut sim.strikes.flights[0]; let (id, muzzle) = (flight.id, flight.pos); let carrier = 77; flight.carrier = Some(carrier); sim.record_strike_launch(id, carrier, muzzle); (sim, id, muzzle) } #[test] fn physical_strike_track_keeps_muzzle_and_samples_on_flight_relative_grid() { // A fresh recording starts at launch; the other cases launch into odd/even positions on // an existing recording's global grid. for record_len in [None, Some(1), Some(2)] { let (mut sim, id, muzzle) = physical_strike(record_len); let track_id = 0x7100_0000 | id; { let rec = sim.rec.as_ref().unwrap(); let track = rec.track(track_id).unwrap(); assert_eq!(track.what, What::StrikeCarrier(77)); assert_eq!(track.points.len(), 1, "the launch records exactly one muzzle point"); assert_eq!(track.at(rec.origin, track.first as f64), Some(muzzle)); } for age in 1..=4u64 { sim.tick += 1; let pos = muzzle + DVec3::Z * (age as f64 * 8.0); sim.strikes.flights[0].pos = pos; sim.record(); let rec = sim.rec.as_ref().unwrap(); let track = rec.track(track_id).unwrap(); let expected_samples = 1 + (age / STEP as u64) as usize; assert_eq!(track.points.len(), expected_samples, "flight age {age}, recording len {}", record_len.unwrap_or(0)); assert_eq!(track.at(rec.origin, track.first as f64), Some(muzzle)); if age % STEP as u64 == 0 { assert_eq!(track.at(rec.origin, (track.first + age as u32) as f64), Some(pos)); } } } } #[test] fn full_recording_bounds_sam_keys_without_freezing_their_poses() { let mut r = recording(); let mut sams: Vec<_> = (0..64) .map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0)) .collect(); for now in (0..LONGEST).step_by(STEP as usize) { for sam in &mut sams { sam.dish = now as f64 * 0.01; } r.note_sams(&sams, now); } let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum(); let allocated: usize = r.sam_tracks.iter().map(|track| track.keys.capacity()).sum(); assert_eq!(keys, r.sam_keys); assert!(keys <= MAX_SAM_KEYS, "a full recording retained {keys} SamKeys"); assert!(allocated <= 2 * MAX_SAM_KEYS, "SamKey allocations reached {} MiB", allocated * size_of::() / (1024 * 1024)); assert!(r.sam_step > STEP, "the rotating radars never engaged adaptive sampling"); let last = r.sam_tracks[0].pose(LONGEST as f64).unwrap(); assert!(last.at >= LONGEST - 64, "poses stopped at tick {}", last.at); assert!(last.dish > 100.0, "the final radar pose was not recorded"); } #[test] fn a_system_keeps_its_pose_through_stillness_and_moves_when_it_moved() { let mut r = recording(); // Still for 20 ticks, then the turret swings and the vehicle drives. for now in (0..=20).step_by(STEP as usize) { r.note_sams(&[sam_at(0.0, 0.0, 0.0)], now); } assert_eq!(r.sam_tracks[0].keys.len(), 1, "stillness is one key"); r.note_sams(&[sam_at(4.0, 0.0, 1.0)], 22); let t = &r.sam_tracks[0]; let pose = |tick: f64| t.pose(tick).unwrap(); // Held at the old pose until just before the change, not gliding over the stillness. assert!(pose(10.0).pos[0].abs() < 1e-6 && pose(10.0).yaw.abs() < 1e-6); assert!(pose(20.0).pos[0].abs() < 1e-6); // Half way through the move. assert!((pose(21.0).pos[0] - 2.0).abs() < 1e-4 && (pose(21.0).yaw - 0.5).abs() < 1e-4); assert!((pose(100.0).pos[0] - 4.0).abs() < 1e-6); } #[test] fn recorder_is_passive_and_combat_effects_do_not_depend_on_it() { let kind = EventKind::Crash { drone: 1, kind: DroneKind::Shahed, power: 2 }; let mut recording = Sim::new(4); recording.rec = Some(Recording::new(1, &recording)); recording.record_event(DVec3::ZERO, kind); assert!(recording.fires.list.is_empty(), "recording a fact must not ignite the live world"); assert_eq!(recording.rec.as_ref().unwrap().events.len(), 1); let mut without = Sim::new(4); without.emit_combat_event(DVec3::ZERO, kind); assert_eq!(without.fires.list.len(), 1, "the domain effect must run without a recorder"); let mut with = Sim::new(4); with.rec = Some(Recording::new(1, &with)); with.emit_combat_event(DVec3::ZERO, kind); assert_eq!(with.fires.list.len(), 1); assert_eq!(with.rec.as_ref().unwrap().events.len(), 1); assert_eq!(with.fires.list[0].size, without.fires.list[0].size); } #[test] fn recorded_sam_health_and_parts_are_stepwise_and_seekable() { let mut r = recording(); let mut sam = Sam::new(7, SamKind::Patriot, DVec3::ZERO, 0.0); r.note_sams(std::slice::from_ref(&sam), 0); sam.health = 0.4; sam.comps.0[Part::Sensor as usize] = 0.25; r.note_sams(std::slice::from_ref(&sam), 10); let st = &r.sam_tracks[0]; let before = st.ghost(r.origin, 9.0, 7).unwrap(); let damaged = st.ghost(r.origin, 10.0, 7).unwrap(); assert_eq!(before.health, 1.0); assert!((damaged.health - 0.4).abs() < 1e-6); assert_eq!(damaged.comps.get(Part::Sensor), 0.25); assert_eq!(st.ghost(r.origin, 10.0, 7).unwrap().comps, damaged.comps); } #[test] fn sampled_track_and_fire_transitions_follow_real_changes() { let mut sim = Sim::new(3); let id = sim.id(); sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0)); let mut r = Recording::new(1, &sim); let tr = sight::Track { id: 77, class: ClassEst::Firm(Class::Drone), pos: DVec3::Z * 100.0, vel: -DVec3::Z, tick: 1, own_tick: 1, source: 1, product: battery::Measure::Fire, quality: 80, own_product: battery::Measure::Fire, own_quality: 80, ttl: 10, hits: 1, locked: false, }; sim.sams[0].tracks.push(tr); r.note_tracks(&sim.sams); r.len = 1; sim.sams[0].tracks[0].locked = true; r.note_tracks(&sim.sams); r.len = 2; sim.sams[0].tracks.clear(); r.note_tracks(&sim.sams); let events = &r.scene.as_ref().unwrap().events; assert!(matches!(events[0].kind, SceneKind::TrackAcquired { sam, target: 77, ever_own: true } if sam == id)); assert!(matches!(events[1].kind, SceneKind::TrackLock { sam, target: 77, locked: true } if sam == id)); assert!(matches!(events[2].kind, SceneKind::TrackLost { sam, target: 77 } if sam == id)); sim.ignite(DVec3::ZERO, 1, None); let fire = sim.fires.list[0].id; r.note_fires(&sim.fires.list, sim.tick); assert_eq!(replay_fires(&r, 2.0)[0].size, 1.0); sim.ignite(DVec3::ZERO, 4, None); r.len += 1; r.note_fires(&sim.fires.list, sim.tick); assert_eq!(replay_fires(&r, 3.0)[0].size, 3.0); assert_eq!(replay_fires(&r, 2.0)[0].size, 1.0, "seeking back uses old fire state"); sim.fires.extinguish(); r.len += 1; r.note_fires(&sim.fires.list, sim.tick); assert!(replay_fires(&r, 4.0).is_empty()); let events = &r.scene.as_ref().unwrap().events; assert!(events.iter().any(|e| matches!(e.kind, SceneKind::FireStarted { fire: id, .. } if id == fire))); assert!(events.iter().any(|e| matches!(e.kind, SceneKind::FireChanged { fire: id, size, .. } if id == fire && size == 3.0))); assert!(events.iter().any(|e| matches!(e.kind, SceneKind::FireEnded { fire: id } if id == fire))); } #[test] fn replay_fire_uses_sampled_existing_age_water_and_end() { let mut r = recording(); let mut scene = SceneJournal::default(); scene.push(SceneEvent { at: 0, pos: DVec3::X, kind: SceneKind::FireStarted { fire: 7, age: 50, life: 100, size: 1.0, quiet: false, shown: true, water: Some(true) } }); scene.push(SceneEvent { at: 10, pos: DVec3::X, kind: SceneKind::FireEnded { fire: 7 } }); r.scene = Some(scene); let a = replay_fires(&r, 5.0); assert_eq!(a.len(), 1); assert_eq!((a[0].start, a[0].age_offset, a[0].water), (0, 50, Some(true))); assert!(replay_fires(&r, 11.0).is_empty()); let b = replay_fires(&r, 5.0); assert_eq!((a[0].start, a[0].age_offset, a[0].water), (b[0].start, b[0].age_offset, b[0].water)); } #[test] fn scene_journal_is_bounded_and_incomplete_is_marked() { let mut j = SceneJournal::default(); for i in 0..=MAX_SCENE_EVENTS { j.push(SceneEvent { at: i as u32, pos: DVec3::ZERO, kind: SceneKind::FireEnded { fire: i as u32 } }); } assert_eq!(j.events.len(), MAX_SCENE_EVENTS); assert!(j.truncated); } #[test] fn ten_minute_transition_stream_is_bounded() { let started = std::time::Instant::now(); let mut sim = Sim::new(5); for _ in 0..4 { let id = sim.id(); let mut sam = Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0); for target in 1..=4 { sam.tracks.push(sight::Track { id: target, class: ClassEst::Firm(Class::Drone), pos: DVec3::Z, vel: DVec3::ZERO, tick: 1, own_tick: 1, source: sam.id, product: battery::Measure::Fire, quality: 80, own_product: battery::Measure::Fire, own_quality: 80, ttl: 1, hits: 1, locked: false, }); } sim.sams.push(sam); } let mut r = Recording::new(1, &sim); for t in 0..12_000 { r.len = t; for sam in &mut sim.sams { for tr in &mut sam.tracks { tr.locked = t % 2 == 0; } } r.note_tracks(&sim.sams); } let scene = r.scene.as_ref().unwrap(); assert_eq!(scene.events.len(), MAX_SCENE_EVENTS); assert!(scene.truncated); eprintln!("scene stress: 12000 ticks, {} events, event storage {:.2} MiB, elapsed {:?}", scene.events.len(), scene.events.capacity() * std::mem::size_of::() / (1024 * 1024), started.elapsed()); } #[test] fn real_launch_and_ignition_are_recorded_with_ids_and_sound() { let mut sim = Sim::new(0x87); let sam = sim.id(); sim.sams.push(Sam::new(sam, SamKind::Patriot, DVec3::new(0.0, 64.0, 0.0), 0.0)); let mut out = Out::default(); for (i, kind) in [DroneKind::Shahed, DroneKind::Kh101, DroneKind::Iskander].into_iter().enumerate() { sim.launch(kind, DVec3::new(i as f64 * 100.0, 110.0, 800.0), -DVec3::Z, DVec3::new(0.0, 64.0, 0.0), &mut out); } let mut ground = Ground::default(); for _ in 0..600 { let wanted = ground.take_wanted(); ground.answer(wanted.into_iter().map(|(x, z)| (x, z, 64)).collect(), sim.tick); out = Out::default(); sim.step(&mut ground, None, &mut out); if sim.rec.as_ref().and_then(|r| r.scene.as_ref()).is_some_and(|j| j.events.iter().any(|e| matches!(e.kind, SceneKind::MotorIgnition { .. }))) { break; } } let r = sim.rec.as_ref().expect("recording"); let launch = r.scene.as_ref().unwrap().events.iter().find(|e| matches!(e.kind, SceneKind::MissileLaunch { .. })).expect("actual launch"); let missile = match launch.kind { SceneKind::MissileLaunch { missile, sam: source, sound, .. } => { assert_eq!(source, sam); assert_eq!(sound, "airdef:launch.patriot"); missile }, _ => unreachable!() }; let ignition = r.missile_ignition(missile).expect("actual ignition"); assert!(ignition.at >= launch.at); assert_eq!(r.missile_launch(missile).unwrap().pos, launch.pos); } // #76: a replay's searchlights point where the recording had them, from the recorded pose. #[test] fn a_replay_has_the_recorded_searchlight_beams() { let mut r = recording(); let mut light = Sam::new(9, SamKind::Light, DVec3::new(10.0, 64.0, 0.0), 0.0); light.beam_on = true; light.beam_free = 300.0; light.yaw = 1.0; light.pitch = 0.8; r.note_sams(&[light], 0); // Swung round and switched off later. let mut later = Sam::new(9, SamKind::Light, DVec3::new(10.0, 64.0, 0.0), 0.0); later.yaw = 2.0; later.pitch = 0.8; r.note_sams(&[later], 100); assert!(r.beams(-1.0).is_empty(), "nothing before it was seen"); let b = r.beams(0.0); assert_eq!(b.len(), 1); assert_eq!(b[0].id, 9); assert!((b[0].free - 304.0).abs() < 1e-6 || (b[0].free - 296.0).abs() < 1e-6, "free {}", b[0].free); assert!(b[0].dir.y > 0.5, "pointing up: {:?}", b[0].dir); assert!(r.beams(100.0).is_empty(), "switched off"); r.sam_tracks[0].lost = Some(50); assert!(r.beams(10.0).len() == 1 && r.beams(60.0).is_empty(), "a lost light has no beam"); } #[test] fn a_system_first_seen_later_is_not_drawn_before() { let mut r = recording(); r.note_sams(&[sam_at(0.0, 0.0, 0.0)], 40); assert!(r.sam_tracks[0].pose(10.0).is_none()); assert!(r.sam_tracks[0].pose(40.0).is_some()); } #[test] fn angles_turn_the_short_way_and_a_lost_system_is_a_wreck() { let mut r = recording(); r.note_sams(&[sam_at(0.0, 0.0, 6.2)], 0); r.note_sams(&[sam_at(0.0, 0.0, 0.1)], 2); let t = &mut r.sam_tracks[0]; let mid = t.pose(1.0).unwrap().yaw; assert!(!(0.2..6.0).contains(&mid), "through zero, not back round: {mid}"); assert!(t.ghost(DVec3::ZERO, 1.0, 0).unwrap().alive()); t.lost = Some(30); assert!(t.ghost(DVec3::ZERO, 29.0, 0).unwrap().alive()); assert!(!t.ghost(DVec3::ZERO, 31.0, 0).unwrap().alive()); } #[test] fn the_games_tick_is_known_through_the_recording() { let mut r = recording(); assert_eq!(r.world_tick(5.0), None); r.ticks = vec![(0, 1000), (20, 1020), (40, 1040), (60, 1100)]; assert_eq!(r.first_tick(), Some(1000)); assert_eq!(r.world_tick(0.0), Some(1000)); assert_eq!(r.world_tick(10.0), Some(1010)); assert_eq!(r.world_tick(30.0), Some(1030)); // A jump of the game's ticks between samples (the recording paused or a gap) is a step. assert_eq!(r.world_tick(50.0), Some(1040 + 10)); assert_eq!(r.world_tick(70.0), Some(1100 + 10)); } // #97: the kill's outcome is a recorded fact: a replay draws the pieces of that outcome and rolls nothing; // an event without one (an old recording) is the plain fall it always was. #[test] fn a_replay_shows_the_recorded_outcome() { let mut sim = Sim::new(5); sim.rec = Some(Recording::new(1, &sim)); let sam = sim.id(); sim.sams.push(Sam::new(sam, SamKind::Patriot, DVec3::new(0.0, 70.0, 0.0), 0.0)); sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 120.0, 300.0), DVec3::X, DVec3::new(900.0, 70.0, 0.0)); let at = sim.drones[0].pos; let live = sim.shoot_down_by(0, sam, None, Impact::missile(MissileKind::M77n6, at, 6.0), &Ground::default(), &mut Out::default()).unwrap(); let rec = sim.rec.take().unwrap(); let recorded = rec.events.iter().find_map(|e| if let EventKind::Kill { outcome, .. } = e.kind { Some(outcome) } else { None }); assert_eq!(recorded, Some(live), "the live outcome is what was recorded"); let pieces = |rec: &Recording, t: f64| { let mut out = Out::default(); sim.draw_ghosts(rec, t, 0x5000_0000, &mut out); out.models.iter().filter(|m| m.name == "airdef:debris").count() }; let at_tick = rec.events[0].at as f64; // The same frame twice is the same (a pure function of the time), and the pieces are the outcome's. let mut forced = Recording { events: rec.events.clone(), ..Recording::blank(200) }; for (outcome, want) in [(Outcome::AirDetonation, true), (Outcome::Breakup, true), (Outcome::DisabledFalling, false)] { if let EventKind::Kill { outcome: o, .. } = &mut forced.events[0].kind { *o = outcome; } assert_eq!(pieces(&forced, at_tick + 5.0), pieces(&forced, at_tick + 5.0)); assert_eq!(pieces(&forced, at_tick + 5.0) > 0, want, "{outcome:?}"); assert_eq!(pieces(&forced, at_tick + f64::from(outcome::PIECE_LIFE) + 1.0), 0, "the pieces are gone in time"); } // Its flash and sound are the outcome's too. let spec = |o| { let mut e = rec.events[0]; if let EventKind::Kill { outcome, .. } = &mut e.kind { *outcome = o; } blast_spec(e.kind) }; assert!(spec(Outcome::AirDetonation).0 > spec(Outcome::DisabledFalling).0); assert_eq!(spec(Outcome::default()).0, kill_look(DroneKind::Shahed).0, "an old recording looks as it did"); } }