diff --git a/airdef-mod/src/sim/durable.rs b/airdef-mod/src/sim/durable.rs index 8df7d57..38155e3 100644 --- a/airdef-mod/src/sim/durable.rs +++ b/airdef-mod/src/sim/durable.rs @@ -9,6 +9,11 @@ //! picture is mixed into a replay: a recording keeps trajectories, and this section is written and //! read for the live simulation only. //! +//! Reconnaissance flights and the partial picture they radioed home are part of the same +//! section (#135): their marks (an area, a category and an age, never a unit's truth), the +//! sorties still out with their pending reports, and the zones already checked. A save keeps +//! that memory across raids, and a restored flight finishes the same way. +//! //! The format is its own versioned section of `state_text` (`air 1 ...`). A save without the section //! (every save made before #127) loads exactly as before: the layout, and an empty sky. Every value is //! checked before anything is restored, like [`layout`](crate::layout): a bad line refuses the whole @@ -25,6 +30,9 @@ const MAX_DRONES: usize = 512; /// Bytes the section may take before further drones are left out (the host allows 1 MiB a write; /// the layout and the headroom of the rest of the state stay clear of it). const MAX_BYTES: usize = 900_000; +/// Bytes the recon block (marks, checked zones, sorties) may take. The drone loop keeps this much +/// room free, so the recon memory never pushes the section past `MAX_BYTES` (#135). +const MAX_RECON_BYTES: usize = 150_000; /// Route points one drone may have in a save. const MAX_ROUTE: usize = 512; /// Contacts (the picture, and a job's picture rebuilt from it) a save may hold. @@ -32,6 +40,10 @@ const MAX_CONTACTS: usize = 4096; /// Relief versions a save may hold, and the cells of each. const MAX_RELIEFS: usize = 8; const MAX_CELLS: usize = 40_000; +/// Recon marks, checked zones and sorties a save may hold (#135). +const MAX_RECON_MARKS: usize = recon::MAX_MARKS; +const MAX_RECON_CHECKED: usize = recon::MAX_CHECKED; +const MAX_RECON_SORTIES: usize = recon::SORTIES_MAX * 2; /// What the air section of a save holds, checked as a whole before the scene is touched. pub struct AirSave { @@ -45,6 +57,8 @@ pub struct AirSave { jobs: Vec, /// The land new retarget jobs take as their version. known_relief: Option>, + /// The enemy's recon flights and the partial picture they radioed home (#135). + recon: recon::Recon, } pub(crate) struct JobRec { @@ -198,6 +212,7 @@ impl Sim { ^ (self.retargets.len() as u64) << 24 ^ (self.intel.contacts().len() as u64) << 36 ^ (self.job_next as u64) << 48 + ^ self.recon.mark().rotate_left(12) } /// The air section of the state text: `None` when there is nothing to keep (an empty sky and no @@ -273,7 +288,7 @@ impl Sim { // job with it (a job whose drone is not saved could never be restored). let mut body = String::new(); let mut saved: std::collections::HashSet = std::collections::HashSet::new(); - let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() <= MAX_BYTES; + let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() + MAX_RECON_BYTES <= MAX_BYTES; let mut drone_count = 0usize; for d in &drones { let line = d.air_line("airdrone", ""); @@ -296,14 +311,15 @@ impl Sim { saved.insert(d.id); queued_count += 1; } - let units: std::collections::HashSet = contacts.iter().map(|c| c.id).collect(); + // A job's unit may be an exact contact or a recon mark's synthetic id (#135). + let units: std::collections::HashSet = contacts.iter().map(|c| c.id).chain(self.recon.marks.keys().copied()).collect(); let jobs: Vec<(&ew::RouteJob, Option)> = self .retargets .iter() .zip(job_relief) .filter(|(j, _)| saved.contains(&j.drone) && (j.unit == 0 || units.contains(&j.unit))) .collect(); - if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() { + if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() && self.recon.is_empty() { return None; } let head = head.replacen( @@ -328,6 +344,89 @@ impl Sim { relief.map_or_else(|| "-".into(), |t| t.to_string()) ); } + // Recon: the marks are memory (survive a new raid), the sorties are the aircraft still + // out, and the zones already reported empty. Everything is bounded, and each line is + // added only while the block stays inside its budget (#135). + if !self.recon.is_empty() { + let room = MAX_RECON_BYTES.min(MAX_BYTES.saturating_sub(text.len() + 96)); + let mut recon_body = String::new(); + let mut add = |line: &str| -> bool { + if recon_body.len() + line.len() > room { + return false; + } + recon_body.push_str(line); + true + }; + let mut marks = 0usize; + for m in self.recon.marks.values().take(MAX_RECON_MARKS) { + let truth = self.recon.truth.get(&m.id).copied().unwrap_or(0); + let line = format!( + "airreconmark {} {} {} {} {} {} {} {} {} {} {} {} {}\n", + m.id, + truth, + coord(m.area.x), + coord(m.area.y), + coord(m.area.z), + coord(m.radius), + m.category.name(), + m.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()), + m.source.name(), + m.quality.name(), + m.observed, + m.reported, + m.looks, + ); + if !add(&line) { + break; + } + marks += 1; + } + let mut checked = 0usize; + for ((i, j), t) in self.recon.checked.iter().take(MAX_RECON_CHECKED) { + if !add(&format!("airreconchecked {i} {j} {t}\n")) { + break; + } + checked += 1; + } + let mut sorties = 0usize; + for s in self.recon.sorties.iter().filter(|s| saved.contains(&s.drone)).take(MAX_RECON_SORTIES) { + // A sortie is written whole or not at all: its look and zone lines follow its header. + let mut body = format!( + "airrec {} {} {} {} {} {} {}\n", + s.drone, + s.launched, + s.next, + tick(s.report_at), + s.report_zone.map_or_else(|| "-".into(), |z| z.to_string()), + s.pending.len(), + s.zones.len(), + ); + for l in &s.pending { + body += &format!( + "airrecobs {} {} {} {} {} {} {} {} {} {}\n", + l.truth, + coord(l.area.x), + coord(l.area.y), + coord(l.area.z), + coord(l.radius), + l.category.name(), + l.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()), + l.quality.name(), + l.source.name(), + l.observed, + ); + } + for z in &s.zones { + body += &format!("airreczone {} {} {} {}\n", coord(z.center.x), coord(z.center.y), coord(z.center.z), coord(z.radius)); + } + if !add(&body) { + break; + } + sorties += 1; + } + text += &format!("airrecon {} {} {} {} {}\n", self.recon.next, self.recon.drone_next, marks, sorties, checked); + text += &recon_body; + } Some(text) } @@ -373,6 +472,12 @@ impl Sim { let mut drones: BTreeMap = BTreeMap::new(); let mut queue: Vec<(u64, Drone)> = Vec::new(); let mut jobs: Vec = Vec::new(); + // Recon (#135): a mark line carries the unit it is of (the observer's secret, never in + // the planner's picture); a sortie's look and zone lines follow its header. + let mut recon = recon::Recon::default(); + let mut recon_head: Option<(usize, usize, usize)> = None; + let mut recon_sortie_at: Option = None; + let mut recon_expect: Vec<(usize, usize)> = Vec::new(); for (n, w) in &lines { if w.first() == Some(&"air") { continue; @@ -512,6 +617,148 @@ impl Sim { }; jobs.push(JobRec { id, drone, aim, unit, version, intent, relief }); } + "airrecon" => { + if w.len() != 6 { + return Err(l.bad("разведка", "нужны счётчики отметок и дронов, отметки, разведчики и проверенные зоны")); + } + let next = l.int(1, "счётчик отметок", 0, i64::from(recon::MARK_TOP - recon::ID_BASE - 1))? as u32; + let drone_next = l.int(2, "счётчик дронов", 0, i64::from(recon::DRONE_TOP - recon::DRONE_BASE - 1))? as u32; + let marks = l.count(3, "отметки", MAX_RECON_MARKS)?; + let sorties = l.count(4, "разведчики", MAX_RECON_SORTIES)?; + let checked = l.count(5, "проверенные зоны", MAX_RECON_CHECKED)?; + if recon_head.is_some() { + return Err(l.bad("разведка", "заголовок записан дважды")); + } + recon_head = Some((marks, sorties, checked)); + recon.next = next; + recon.drone_next = drone_next; + } + "airreconmark" => { + if w.len() != 14 { + return Err(l.bad("отметка разведки", "нужны id, юнит, место, категория, источник, качество и времена")); + } + let id = l.int(1, "id отметки", 0, i64::from(u32::MAX))? as u32; + if !recon::is_mark(id) { + return Err(l.bad("id отметки", "не в диапазоне отметок")); + } + let truth = l.int(2, "юнит отметки", 0, 1 << 30)? as u32; + let area = DVec3::new(l.num(3, "отметка X")?, l.num(4, "отметка Y")?, l.num(5, "отметка Z")?); + let radius = l.num(6, "радиус отметки")?; + if radius <= 0.0 { + return Err(l.bad("радиус отметки", "должен быть больше нуля")); + } + let category = recon::Category::from_key(l.word(7, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?; + let role = match l.word(8, "роль")? { + "-" => None, + key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?), + }; + let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?; + let quality = recon::Quality::from_key(l.word(10, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?; + let observed = l.int(11, "такт наблюдения", 0, tick as i64)? as u64; + let reported = l.int(12, "такт донесения", 0, tick as i64)? as u64; + let looks = l.int(13, "число взглядов", 0, u16::MAX as i64)? as u16; + if recon.marks.contains_key(&id) { + return Err(l.bad("id отметки", "отметка записана дважды")); + } + recon.truth.insert(id, truth); + recon.marks.insert(id, recon::Mark { + id, + area, + radius, + category, + role, + source, + observed, + reported, + quality, + looks, + }); + let slot = id.saturating_sub(recon::ID_BASE); + recon.next = recon.next.max(slot); + } + "airreconchecked" => { + if w.len() != 4 { + return Err(l.bad("проверенная зона", "нужны X, Z и такт")); + } + let i = l.int(1, "зона X", -3_000_000, 3_000_000)?; + let j = l.int(2, "зона Z", -3_000_000, 3_000_000)?; + let t = l.int(3, "такт проверки", 0, tick as i64)? as u64; + recon.checked.insert((i, j), t); + } + "airrec" => { + if w.len() != 8 { + return Err(l.bad("разведчик", "нужны дрон, вылет, зона, донесение и счётчики")); + } + let drone = l.int(1, "дрон разведчика", 1, 1 << 30)? as u32; + let launched = l.int(2, "вылет", 0, tick as i64)? as u64; + let next = l.count(3, "следующая зона", 1_000_000)?; + let report_at = l.opt_tick(4, "такт донесения")?; + let report_zone = match l.word(5, "зона донесения")? { + "-" => None, + v => Some(v.parse::().map_err(|_| l.bad("зона донесения", "не номер"))?), + }; + let pending = l.count(6, "ожидающие наблюдения", recon::MAX_OBSERVED)?; + let zones = l.count(7, "зоны разведчика", recon::ZONES_MAX)?; + if recon.sorties.iter().any(|s| s.drone == drone) { + return Err(l.bad("дрон разведчика", "разведчик записан дважды")); + } + recon.sorties.push(recon::Sortie { + drone, + zones: Vec::new(), + next, + launched, + report_at, + report_zone, + pending: Vec::new(), + }); + recon_sortie_at = Some(recon.sorties.len() - 1); + recon_expect.push((pending, zones)); + } + "airrecobs" => { + if w.len() != 11 { + return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник и такт")); + } + let Some(at) = recon_sortie_at else { + return Err(l.bad("наблюдение разведки", "строка без разведчика")); + }; + let (want, _) = recon_expect[at]; + if recon.sorties[at].pending.len() >= want { + return Err(l.bad("наблюдение разведки", "наблюдений больше объявленного")); + } + let truth = l.int(1, "юнит наблюдения", 0, 1 << 30)? as u32; + let area = DVec3::new(l.num(2, "наблюдение X")?, l.num(3, "наблюдение Y")?, l.num(4, "наблюдение Z")?); + let radius = l.num(5, "радиус наблюдения")?; + if radius <= 0.0 { + return Err(l.bad("радиус наблюдения", "должен быть больше нуля")); + } + let category = recon::Category::from_key(l.word(6, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?; + let role = match l.word(7, "роль")? { + "-" => None, + key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?), + }; + let quality = recon::Quality::from_key(l.word(8, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?; + let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?; + let observed = l.int(10, "такт наблюдения", 0, tick as i64)? as u64; + recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed }); + } + "airreczone" => { + if w.len() != 5 { + return Err(l.bad("зона разведчика", "нужны X, Y, Z и радиус")); + } + let Some(at) = recon_sortie_at else { + return Err(l.bad("зона разведчика", "строка без разведчика")); + }; + let (_, want) = recon_expect[at]; + if recon.sorties[at].zones.len() >= want { + return Err(l.bad("зона разведчика", "зон больше объявленного")); + } + let center = DVec3::new(l.num(1, "зона X")?, l.num(2, "зона Y")?, l.num(3, "зона Z")?); + let radius = l.num(4, "радиус зоны")?; + if radius <= 0.0 { + return Err(l.bad("радиус зоны", "должен быть больше нуля")); + } + recon.sorties[at].zones.push(recon::Zone { center, radius }); + } other => return Err(l.bad("строка", &format!("неизвестная строка воздушной части «{other}»"))), } } @@ -540,6 +787,32 @@ impl Sim { if let Some(g) = global && reliefs[g].is_none() { return Err("воздушная часть: глобальный рельеф не записан".into()); } + if let Some((marks, sorties, checked)) = recon_head { + if recon.marks.len() != marks { + return Err(format!("воздушная часть: отметок разведки {} вместо {marks}", recon.marks.len())); + } + if recon.sorties.len() != sorties { + return Err(format!("воздушная часть: разведчиков {} вместо {sorties}", recon.sorties.len())); + } + if recon.checked.len() != checked { + return Err(format!("воздушная часть: проверенных зон {} вместо {checked}", recon.checked.len())); + } + } else if !recon.is_empty() { + return Err("воздушная часть: разведка без заголовка airrecon".into()); + } + for (i, (pending, zones)) in recon_expect.iter().enumerate() { + if recon.sorties[i].pending.len() != *pending || recon.sorties[i].zones.len() != *zones { + return Err(format!("воздушная часть: разведчик {i} записан не полностью")); + } + if recon.sorties[i].next > recon.sorties[i].zones.len() { + return Err(format!("воздушная часть: разведчик {i} смотрит за пределами зон")); + } + if let Some(z) = recon.sorties[i].report_zone + && z >= recon.sorties[i].zones.len() + { + return Err(format!("воздушная часть: разведчик {i} доносит из несуществующей зоны")); + } + } let intel = intel.ok_or("воздушная часть: нет счётчиков секторов")?; let mut kills = [0u32; ew::SECTORS]; let mut hits = [0u32; ew::SECTORS]; @@ -555,6 +828,7 @@ impl Sim { queue, jobs, known_relief: global.and_then(|g| reliefs[g].clone()), + recon, })) } @@ -571,6 +845,10 @@ impl Sim { self.known_relief = save.known_relief; self.drones = save.drones; self.queue = save.queue; + self.recon = save.recon; + let alive: std::collections::HashSet = self.drones.iter().map(|d| d.id).chain(self.queue.iter().map(|(_, d)| d.id)).collect(); + self.recon.retain_drones(&alive); + self.recon.expire(self.tick); self.retargets.clear(); // A job's picture is its version's: the contacts observed no later than it, plus its own // target (whose last saved observation stands in for one made after the version). diff --git a/airdef-mod/src/sim/ew.rs b/airdef-mod/src/sim/ew.rs index 3d37fa9..14fb366 100644 --- a/airdef-mod/src/sim/ew.rs +++ b/airdef-mod/src/sim/ew.rs @@ -19,6 +19,12 @@ //! contact is a plain function of the contact's age, and its idea of a unit's //! capabilities is the type's published one — a contact says nothing about //! damage, roles, link health or magazine. +//! +//! A smart raid may also send a few recon aircraft ahead (#135). What they see is a +//! different, coarser kind of knowledge: an area, a public category, the channel that +//! showed it and its age, radioed home only after a delay and only while the aircraft +//! lives. It is kept as a `recon::Mark`, separate from a disclosure `Contact`; its +//! confidence is age alone and a duplicate report does not improve it. use super::*; use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; @@ -323,6 +329,15 @@ pub(super) const CONTACT_TTL: u64 = 6000; const CONFIRMED_AGE: u64 = 600; const PROBABLE_AGE: u64 = 3000; +/// The one source of confidence: a contact's age, in the bands the picture trusts. +pub(super) fn confidence_for_age(age: u64) -> Confidence { + match age { + 0..=CONFIRMED_AGE => Confidence::Confirmed, + ..=PROBABLE_AGE => Confidence::Probable, + _ => Confidence::Doubtful, + } +} + impl Contact { pub fn age(&self, now: u64) -> u64 { now.saturating_sub(self.tick) @@ -332,11 +347,7 @@ impl Contact { self.destroyed.is_none() && self.age(now) < CONTACT_TTL } pub fn confidence(&self, now: u64) -> Confidence { - match self.age(now) { - 0..=CONFIRMED_AGE => Confidence::Confirmed, - ..=PROBABLE_AGE => Confidence::Probable, - _ => Confidence::Doubtful, - } + confidence_for_age(self.age(now)) } /// Whether the enemy believes this unit sees on its own radar (#127). A kind without a /// sensor never does. A kind with one does while an emission fix of this contact is @@ -556,6 +567,9 @@ impl Sim { /// Whether the picture holds a live contact for this unit: what the old revelation log /// answered at a scan, now one map lookup. pub(super) fn known_live(&self, id: u32) -> bool { + if recon::is_mark(id) { + return self.recon.live(id, self.tick); + } self.intel.contacts.get(&id).is_some_and(|c| c.live(self.tick)) } @@ -578,8 +592,10 @@ impl Sim { /// the picture killed is a distinct, lower-priority decision. fn adapt_targets(&mut self) { self.intel.expire(self.tick); + self.recon.expire(self.tick); let picture = Arc::new(self.picture_of_defences()); - if picture.is_empty() { + let leads = self.recon.leads(self.tick); + if picture.is_empty() && leads.is_empty() { return; } // Every job of this adaptive tick plans over the same relief version, even if another smart @@ -601,9 +617,17 @@ impl Sim { if !eligible { continue; } + // A recon mark is an area, not a unit: it is kept while the mark lives. A + // hidden move does not move the aim; only a newer report can re-place it (#135). + if recon::is_mark(d.aim.unit) { + if self.recon.live(d.aim.unit, now) { + continue; + } + // The mark aged out: the drone falls through to a fresh lead below. + } // What it is aiming at in the picture now, if anything (a unit merely moved is still // aimed where it was seen: a contact is matched by its observed place). - if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) { + else if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) { // Already aiming at a unit: a fresh disclosure may be worth a switch, under the throttle. let Some(c) = Self::switch_candidate(&picture, current, d, now) else { continue }; if per_contact.get(&c.id).copied().unwrap_or(0) >= ASSIGN_PER_CONTACT { @@ -627,13 +651,30 @@ impl Sim { if assigned >= ASSIGN_PER_TICK { continue; } - let Some(c) = Self::fresh_target(&picture, &per_contact, d.kind, n) else { continue }; - *per_contact.entry(c.id).or_insert(0) += 1; + let exact = Self::fresh_target(&picture, &per_contact, d.kind, n); + // No disclosure contact to take: a recon mark whose observed role fits this drone, + // best role and freshest first, bounded per mark as any assignment is. Where both + // exist, the better observed role and fresher mark wins; a hidden unit is in neither. + let mark = Self::fresh_recon_target(&leads, &per_contact); + let (at, unit, confidence) = match (exact, mark) { + (Some(c), Some(m)) => { + let exact_rank = Self::exact_rank(&c, now); + if m.priority(now) > exact_rank { + (m.area, m.id, m.confidence(now)) + } else { + (c.at, c.id, c.confidence(now)) + } + } + (Some(c), None) => (c.at, c.id, c.confidence(now)), + (None, Some(m)) => (m.area, m.id, m.confidence(now)), + (None, None) => continue, + }; + *per_contact.entry(unit).or_insert(0) += 1; assigned += 1; - d.target = c.at + d.err; + d.target = at + d.err; d.intent = Intent::React; // A first assignment is not a switch: the aim's clock starts here, the count is kept. - d.aim = Aim { unit: c.id, since: now, switches: d.aim.switches, confidence: Some(c.confidence(now)) }; + d.aim = Aim { unit, since: now, switches: d.aim.switches, confidence: Some(confidence) }; if Self::route_plannable(d) { jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&picture), relief.clone())); job_next += 1; @@ -648,11 +689,14 @@ impl Sim { // moved is still aimed where seen. for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart) { let aim = d.target - d.err; - let aim_gone = self - .intel - .contacts - .values() - .any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick)); + let aim_gone = if recon::is_mark(d.aim.unit) { + !self.recon.live(d.aim.unit, self.tick) + } else { + self.intel + .contacts + .values() + .any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick)) + }; if !aim_gone { continue; } @@ -663,17 +707,37 @@ impl Sim { if d.aim.switches >= SWITCH_CAP || assigned >= ASSIGN_PER_TICK { continue; } - let next = picture + let exact = picture .iter() .filter(|c| !plannable || Self::can_turn_to(d, c.at)) .filter(|c| per_contact.get(&c.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT) - .min_by(|a, b| a.at.distance(d.pos).total_cmp(&b.at.distance(d.pos))); - if let Some(c) = next { - *per_contact.entry(c.id).or_insert(0) += 1; + .map(|c| (c.at.distance(d.pos), c.id, c.at, c.confidence(now))) + .min_by(|a, b| a.0.total_cmp(&b.0)); + let mark = leads + .iter() + .filter(|m| !plannable || Self::can_turn_to(d, m.area)) + .filter(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT) + .map(|m| (m.area.distance(d.pos), m.id, m.area, m.confidence(now), m.priority(now))) + .min_by(|a, b| b.4.cmp(&a.4).then(a.0.total_cmp(&b.0))); + // A confirmed recon mark outranks a doubtful disclosure; an exact contact of equal + // freshness is preferred, because it is a fix rather than an area. + let exact_rank = exact.map(|(_, _, _, c)| match c { + Confidence::Confirmed => 30, + Confidence::Probable => 15, + Confidence::Doubtful => 0, + }); + let next = match (exact, mark) { + (Some(_), Some(m)) if m.4 > exact_rank.unwrap_or(0) + 3 => Some((m.0, m.1, m.2, m.3)), + (Some(e), _) => Some(e), + (None, Some(m)) => Some((m.0, m.1, m.2, m.3)), + (None, None) => None, + }; + if let Some((_, unit, at, confidence)) = next { + *per_contact.entry(unit).or_insert(0) += 1; assigned += 1; - d.target = c.at + d.err; + d.target = at + d.err; d.intent = Intent::Replace; - d.aim = d.aim.replaced(c.id, now, c.confidence(now)); + d.aim = d.aim.replaced(unit, now, confidence); if plannable { jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Replace, Arc::clone(&picture), relief.clone())); job_next += 1; @@ -716,6 +780,28 @@ impl Sim { all.get(n % all.len().max(1)).map(|c| **c) } + /// The rank of an exact disclosure contact: its confidence, what its observed kind is + /// worth, and a small premium for being a fix rather than an area. + fn exact_rank(c: &Contact, now: u64) -> u8 { + let seen = match c.confidence(now) { + Confidence::Confirmed => 30, + Confidence::Probable => 15, + Confidence::Doubtful => 0, + }; + seen + recon::Category::of(c.kind).weight() + 3 + } + + /// The best recon mark a drone not yet sent at a unit may be given: observed role and + /// freshness first (the list is sorted), bounded per mark. A mark's category must be one + /// worth a strike; a support or unknown mark is only navigation interest. + fn fresh_recon_target(leads: &[recon::Mark], per_contact: &HashMap) -> Option { + leads + .iter() + .copied() + .filter(|m| m.category.weight() >= 2) + .find(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT) + } + /// Whether a fresh disclosure is worth replacing this drone's aim: a contact observed after the /// aim was chosen, trusted (not `Doubtful`), clearly better placed or better believed, and the /// throttle (hold time, switch cap) allows it (#127). A route change costs the planner a new @@ -1009,7 +1095,7 @@ pub struct ContactReport { #[derive(Clone, Debug, PartialEq)] pub struct AimReport { pub drone: u32, - /// The unit aimed at (0: a marked object). + /// The unit aimed at (0: a marked object; a recon mark has a synthetic id). pub unit: u32, /// "plan", "sead", "react" or "replace". pub intent: &'static str, @@ -1019,6 +1105,43 @@ pub struct AimReport { pub switches: u16, /// The confidence of the contact the aim rests on, when it is a unit. pub confidence: Option, + /// Whether the aim is a recon mark's area rather than a unit contact. + pub recon: bool, + /// A recon mark's priority (observed role, freshness, quality); `None` for a unit contact. + pub priority: Option, +} + +/// A recon mark as the diagnostic reports it (#135): an area, a coarse category, the channel, +/// its age and quality. There is no true place, SamKind, health, magazine, link or real id here. +#[derive(Clone, Debug, PartialEq)] +pub struct ReconReport { + pub id: u32, + pub area: DVec3, + pub radius: f64, + /// "unknown", "radar", "launcher", "gun", "ew" or "support". + pub category: &'static str, + /// A radar's role once a refined look told it. + pub role: Option<&'static str>, + /// "flyby", "emission", "jamming" or "launch". + pub source: &'static str, + pub age: u64, + /// "coarse" or "refined". + pub quality: &'static str, + pub confidence: Confidence, + pub live: bool, + /// What the planner makes of it, in words: observed role and freshness only. + pub priority: u8, +} + +/// One recon sortie as the diagnostic reports it (#135). +#[derive(Clone, Debug, PartialEq)] +pub struct ReconSortieReport { + pub drone: u32, + /// "outbound", "looking", "reporting" or "done". + pub phase: &'static str, + pub zones_left: usize, + /// The tick its pending report is due. + pub report_in: Option, } /// A route job the planner has not finished (#127): what it is for, why it is still waiting, @@ -1052,6 +1175,10 @@ pub struct EnemyPictureReport { pub pending: Vec, /// The planner's work a tick, for the pending queue's budget. pub work_per_tick: usize, + /// The partial picture recon flights radioed home (#135). + pub recon: Vec, + /// The recon flights still out. + pub recon_sorties: Vec, } impl Sim { @@ -1099,13 +1226,18 @@ impl Sim { .map(|(_, d)| d) .chain(self.drones.iter()) .filter(|d| d.alive() && d.smart) - .map(|d| AimReport { - drone: d.id, - unit: d.aim.unit, - intent: d.intent.name(), - since: d.aim.since, - switches: d.aim.switches, - confidence: d.aim.confidence, + .map(|d| { + let mark = self.recon.marks.get(&d.aim.unit).filter(|m| m.live(now)).copied(); + AimReport { + drone: d.id, + unit: d.aim.unit, + intent: d.intent.name(), + since: d.aim.since, + switches: d.aim.switches, + confidence: d.aim.confidence, + recon: mark.is_some(), + priority: mark.map(|m| m.priority(now)), + } }) .collect(); let pending = self @@ -1129,7 +1261,42 @@ impl Sim { }, }) .collect(); - EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK } + let recon = self + .recon + .marks + .values() + .map(|m| ReconReport { + id: m.id, + area: m.area, + radius: m.radius, + category: m.category.name(), + role: m.role.map(|r| r.key()), + source: m.source.name(), + age: m.age(now), + quality: m.quality.name(), + confidence: m.confidence(now), + live: m.live(now), + priority: m.priority(now), + }) + .collect(); + let recon_sorties = self + .recon + .sorties + .iter() + .map(|s| ReconSortieReport { + drone: s.drone, + phase: if s.report_at.is_some() { + "reporting" + } else if s.next < s.zones.len() { + "outbound" + } else { + "done" + }, + zones_left: s.zones.len().saturating_sub(s.next), + report_in: s.report_at.map(|t| t.saturating_sub(now)), + }) + .collect(); + EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK, recon, recon_sorties } } /// What the planner makes of a contact, in words for the diagnostic (#127). diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 7707860..55bc7c7 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -25,8 +25,10 @@ pub mod record; mod sight; mod terrain; mod ew; +mod recon; mod durable; pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport}; +pub use recon::{Category, Mark, Quality, Source}; pub mod lights; mod logistics; mod orders; @@ -171,6 +173,11 @@ impl Rng { pub fn state(&self) -> u64 { self.0 } + /// Puts the generator back exactly where it was (a recon launch must not spend the + /// strike's combat randomness). + pub(super) fn set_state(&mut self, state: u64) { + self.0 = state; + } pub fn next(&mut self) -> u64 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 7; @@ -1446,6 +1453,8 @@ pub struct Sim { pub tally: record::Tally, /// What the enemy has learned. intel: ew::Intel, + /// Reconnaissance flights and the partial picture they radioed home (#135). + recon: recon::Recon, /// Night: guns need light (the mod sets it from the game's clock). pub night: bool, /// The long fires at crash and impact points (#52). @@ -1522,6 +1531,7 @@ impl Sim { recordings: 0, tally: record::Tally::default(), intel: ew::Intel::default(), + recon: recon::Recon::default(), night: false, fires: fires::Fires::default(), day_time: None, @@ -1625,6 +1635,7 @@ impl Sim { self.plan = None; self.retargets.clear(); self.known_relief = None; + self.recon.clear_sorties(); self.wave = None; // Ammunition still to cook off, flares in the sky. self.later.clear(); @@ -1672,6 +1683,7 @@ impl Sim { self.release_queue(ground, out); self.begin_recording_if_active(); self.step_drones(ground, player, out); + self.step_recon(out); self.step_later(ground, player, out); self.step_moves(ground, out); self.step_supply(out); diff --git a/airdef-mod/src/sim/raid.rs b/airdef-mod/src/sim/raid.rs index 5df1120..cb1a398 100644 --- a/airdef-mod/src/sim/raid.rs +++ b/airdef-mod/src/sim/raid.rs @@ -284,6 +284,9 @@ impl Sim { // read-only while the plan is built, and taking it per drone made a big second order // quadratic in the force's size (#122); a map of contacts makes it linear in them (#127). let picture = self.picture_of_defences(); + // The partial picture the recon flights have radioed home. It is memory, not the + // force: a mark has an area, a category and an age, never a unit's exact place (#135). + let leads = self.recon.leads(self.tick); // A smart enemy comes from where its raids got through best. let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU }; // The raid's sides (1, 2, or 4-5): its launch sites go there (#100). @@ -312,7 +315,7 @@ impl Sim { index += 1; let (target, at_sam) = match job { Some((at, id)) => (at, Some(id)), - None => self.choose_target(kind, object, order.aim, &picture), + None => self.choose_target(kind, object, order.aim, &picture, &leads), }; let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0); let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0; @@ -323,7 +326,11 @@ impl Sim { // The plan's own decision, recorded as such (#127): a radar job is SEAD, a unit // chosen for the raid is the plan's objective, anything else is a marked object. if let Some(id) = at_sam { - let confidence = picture.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick)); + let confidence = picture + .iter() + .find(|c| c.id == id) + .map(|c| c.confidence(self.tick)) + .or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick))); d.intent = if job.is_some() { ew::Intent::Sead } else { ew::Intent::Plan }; d.aim = confidence.map_or_else(|| ew::Aim::point(self.tick), |c| ew::Aim::unit(id, self.tick, c)); } else { @@ -363,6 +370,11 @@ impl Sim { waited: 0, mapped: !smart, }); + // The smart enemy may send a small recon flight ahead of the strike -- physically in + // the air, not a pause: the strike is planned while they fly (#135). + if smart { + self.start_recon(objects, bearing, order.dist, out); + } // A raid without routes is ready at once. self.plan_step(None, out); total @@ -580,12 +592,25 @@ impl Sim { /// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid. /// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile. pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact]) -> Vec> { - let mut radars: Vec<(u32, DVec3)> = picture + // Exact disclosure contacts and recon marks of radars, best first. The order is the + // observed role, freshness and quality -- never the id: a hidden station has no id, + // and a big observed radar is worth more than a modest one (#135). + let now = self.tick; + let mut radars: Vec<(u8, u64, u32, DVec3)> = picture .iter() - .filter(|c| c.kind == SamKind::Radar && c.confidence(self.tick) >= ew::Confidence::Probable) - .map(|c| (c.id, c.at)) + .filter(|c| c.kind == SamKind::Radar && c.confidence(now) >= ew::Confidence::Probable) + .map(|c| { + let seen = match c.confidence(now) { + ew::Confidence::Confirmed => 4, + ew::Confidence::Probable => 2, + ew::Confidence::Doubtful => 0, + }; + (seen * 10 + 3, c.tick, c.id, c.at) + }) + .chain(self.recon.leads(now).into_iter().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area))) .collect(); - radars.sort_by_key(|(id, _)| *id); + radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2))); + let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect(); let flat: Vec = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect(); let mut jobs = vec![None; flat.len()]; if radars.is_empty() { @@ -609,8 +634,8 @@ impl Sim { /// point and the unit's id. The planner has only the picture (#93, #127): what it knows of a /// unit is the last observation — the place seen then, the type identified then — never where /// the unit actually is or what it has become since. - fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact]) -> (DVec3, Option) { - if picture.is_empty() || kind.spec().decoy || aim == Aim::Objects { + fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact], leads: &[recon::Mark]) -> (DVec3, Option) { + if (picture.is_empty() && leads.is_empty()) || kind.spec().decoy || aim == Aim::Objects { return (object, None); } let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> { @@ -641,7 +666,15 @@ impl Sim { DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r), _ => None, }; - choice.map_or((object, None), |(p, id)| (p, Some(id))) + if let Some((p, id)) = choice { + return (p, Some(id)); + } + // Nothing disclosed and nothing the kind's usual preference picked: a recon mark + // whose observed role fits is the next best reason to turn a strike off the object. + if let Some(m) = recon_pick(kind, leads, r) { + return (m.area, Some(m.id)); + } + (object, None) } /// The price of each cell of `grid` for this kind flying low: 1, and much more where a @@ -935,6 +968,11 @@ const AIR_START_WAIT: u32 = 120; if !why.is_empty() { out.messages.push(format!("Неудачи ПВО: {why}")); } + // What the enemy's recon flights saw: the marks are memory, so the picture may be old (#135). + let marks = self.recon.marks.values().filter(|m| m.live(self.tick)).count(); + if marks > 0 { + out.messages.push(format!("Разведка противника: в картине {marks} отметок (возраст и качество — в разборе)")); + } // What the counter-strikes did to the raid (#101): the launches that never happened. let cut: u32 = self.strikes.cancelled.iter().map(|c| c.1).sum(); if cut > 0 { @@ -956,6 +994,21 @@ fn route_length(from: DVec3, route: &[DVec3], to: DVec3) -> f64 { len } +/// A recon mark whose observed category fits this kind. The list is already in priority +/// order, so the first fit is the best reason. +fn recon_pick(kind: DroneKind, leads: &[recon::Mark], r: f64) -> Option { + use recon::Category as C; + let fits = |c: C| match kind { + DroneKind::Lancet => matches!(c, C::Gun | C::Launcher | C::Ew), + DroneKind::Kh22 | DroneKind::Zircon => matches!(c, C::Radar | C::Launcher | C::Ew), + DroneKind::Iskander | DroneKind::Kinzhal => matches!(c, C::Radar | C::Launcher), + DroneKind::Shahed | DroneKind::Geran3 => matches!(c, C::Radar | C::Launcher | C::Gun | C::Ew), + _ => false, + }; + let fits: Vec<&recon::Mark> = leads.iter().filter(|m| fits(m.category)).collect(); + fits.get((r * fits.len() as f64) as usize).copied().copied() +} + #[cfg(test)] mod tests { use super::*; diff --git a/airdef-mod/src/sim/recon.rs b/airdef-mod/src/sim/recon.rs new file mode 100644 index 0000000..85f95dc --- /dev/null +++ b/airdef-mod/src/sim/recon.rs @@ -0,0 +1,1082 @@ +//! Reconnaissance sorties and the enemy's partial picture of the defences (#135). +//! +//! A smart raid may send a few unarmed aircraft ahead of its strike. They fly through +//! game zones round the marked objectives and look while they are there: a unit inside +//! a zone is seen as an *area*, a coarse category, the channel that showed it and the +//! tick it was seen. Nothing of the unit's live state — its exact place, kind, health, +//! magazine, radar role or data link — enters the picture. A look is radioed home only +//! after `REPORT_DELAY` ticks and only if the aircraft is still flying: a sortie lost +//! before its report leaves no mark, while marks already reported stay. +//! +//! What is reported is memory, not truth. A hidden move, a switch-off, a re-role or a +//! kill does not rewrite a mark; only a later look can. A repeated report of the same +//! observation does not raise its confidence: confidence is the mark's age alone, and a +//! second independent look may refine the area and (for a radar) its role. +use super::*; +use std::collections::BTreeMap; + +/// A zone a recon aircraft flies through. Its radius is the best it can say about where +/// a unit it saw there is. +pub const ZONE_RADIUS: f64 = 220.0; +/// How many zones one sortie may look through, and how many sorties may be out at once. +pub const ZONES_MAX: usize = 4; +pub const SORTIES_MAX: usize = 3; +/// Ticks from a look to its report: the aircraft must still be flying then. +pub const REPORT_DELAY: u64 = 90; +/// Ticks a sortie may stay out; past this its unreported look is lost. +pub const SORTIE_TTL: u64 = 5000; +/// A second independent look this much later may refine the mark. A duplicate report of +/// the same observation never does. +pub const REFINE_GAP: u64 = 600; +/// The area a first report leaves, and the smaller one a refined report leaves. Neither +/// is the unit's place: the reported point is a cell centre, jittered away from it. +pub const COARSE_AREA: f64 = 120.0; +pub const REFINED_AREA: f64 = 48.0; +/// How long a mark is remembered (five minutes, as a disclosure contact). +pub const MARK_TTL: u64 = 6000; +/// How long a checked empty zone is not worth another look (unless there is nothing else). +pub const REVISIT: u64 = 6000; +/// Synthetic contact ids: the planner never sees a real unit id through a recon mark. The range +/// is its own: it must not overlap the drawn-only effects (`FX_IDS`, 0x2000_0000), the engine +/// keys (0x4000_0000) or the recon aircraft below. +pub const ID_BASE: u32 = 0x1000_0000; +/// One past the last mark id a report may take (space for far more reports than a match holds). +pub const MARK_TOP: u32 = 0x1800_0000; +/// Recon aircraft ids come from their own range: launching the flight must not move the +/// strike's id sequence, and so its tie-breaks and recorded tracks. +pub const DRONE_BASE: u32 = 0x3000_0000; +/// One past the last recon aircraft id a save may hold: the drone parser's own bound (`1 << 30`). +pub const DRONE_TOP: u32 = 0x4000_0000; +/// Contacts and checked zones one save may hold (the section stays bounded). +pub const MAX_MARKS: usize = 512; +pub const MAX_CHECKED: usize = 128; +/// Observations one report may carry, and pending observations a sortie may hold. +pub const MAX_OBSERVED: usize = 64; + +pub(super) fn is_mark(id: u32) -> bool { + (ID_BASE..MARK_TOP).contains(&id) +} + +/// Whether an id belongs to a recon aircraft (a role of its own, not a strike drone). +pub(super) fn is_drone_id(id: u32) -> bool { + id >= DRONE_BASE +} + +/// What a look can tell about a unit's role, in the terms the game already publishes. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Category { + /// A unit was there, nothing more. + Unknown, + Radar, + Launcher, + Gun, + Ew, + Support, +} + +impl Category { + pub fn name(self) -> &'static str { + match self { + Self::Unknown => "unknown", + Self::Radar => "radar", + Self::Launcher => "launcher", + Self::Gun => "gun", + Self::Ew => "ew", + Self::Support => "support", + } + } + pub(super) fn from_key(key: &str) -> Option { + [Self::Unknown, Self::Radar, Self::Launcher, Self::Gun, Self::Ew, Self::Support].into_iter().find(|c| c.name() == key) + } + /// The public role a look at this kind can tell apart, nothing finer. + pub(super) fn of(kind: SamKind) -> Self { + match kind { + SamKind::Radar => Self::Radar, + SamKind::Ew => Self::Ew, + SamKind::Depot | SamKind::Tzm | SamKind::Light => Self::Support, + _ if kind.armed() => { + if kind.has_gun() && kind.missile_magazine().is_none() { Self::Gun } else { Self::Launcher } + } + _ => Self::Unknown, + } + } + /// What a confirmed contact of this category is worth to the planner, before freshness. + pub(super) fn weight(self) -> u8 { + match self { + Self::Radar | Self::Launcher => 3, + Self::Ew | Self::Gun => 2, + Self::Support => 1, + Self::Unknown => 0, + } + } +} + +/// A radar role is public only after a refined look; a coarse report leaves it unknown. +pub(super) fn role_weight(role: battery::RadarRole) -> u8 { + match role { + battery::RadarRole::Multifunction | battery::RadarRole::Engagement => 3, + battery::RadarRole::Search => 2, + battery::RadarRole::Height => 1, + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Quality { + Coarse, + Refined, +} + +impl Quality { + pub fn name(self) -> &'static str { + match self { + Self::Coarse => "coarse", + Self::Refined => "refined", + } + } + pub(super) fn from_key(key: &str) -> Option { + [Self::Coarse, Self::Refined].into_iter().find(|q| q.name() == key) + } +} + +/// The channel a recon mark came from. A flyby sees the unit itself; an emitting radar or a +/// jamming station is recognizable while it transmits; a silent one is just a unit. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Source { + Flyby, + Emission, + Jamming, + Launch, +} + +impl Source { + pub fn name(self) -> &'static str { + match self { + Self::Flyby => "flyby", + Self::Emission => "emission", + Self::Jamming => "jamming", + Self::Launch => "launch", + } + } + pub(super) fn from_key(key: &str) -> Option { + [Self::Flyby, Self::Emission, Self::Jamming, Self::Launch].into_iter().find(|s| s.name() == key) + } +} + +/// A mark in the enemy's picture: an area, a coarse category, where it came from, when it +/// was seen and how well. There is deliberately no unit id, SamKind, exact point, health, +/// magazine or link here. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Mark { + /// Synthetic id: stable for the mark, never the unit's. + pub(super) id: u32, + pub(super) area: DVec3, + pub(super) radius: f64, + pub(super) category: Category, + /// A radar's role, once a refined look told it; never for a coarse mark. + pub(super) role: Option, + pub(super) source: Source, + /// The tick of the look this mark rests on. + pub(super) observed: u64, + /// The tick its report arrived (for the record; confidence is age alone). + pub(super) reported: u64, + pub(super) quality: Quality, + pub(super) looks: u16, +} + +impl Mark { + pub fn age(&self, now: u64) -> u64 { + now.saturating_sub(self.observed) + } + pub fn live(&self, now: u64) -> bool { + self.age(now) < MARK_TTL + } + pub fn confidence(&self, now: u64) -> Confidence { + ew::confidence_for_age(self.age(now)) + } + /// How much the planner wants this mark: its observed public role, its freshness and + /// how well it is known. The unit's id and its true importance are not in it. + pub fn priority(&self, now: u64) -> u8 { + let seen = match self.confidence(now) { + Confidence::Confirmed => 4, + Confidence::Probable => 2, + Confidence::Doubtful => 0, + }; + let quality = match self.quality { + Quality::Refined => 2, + Quality::Coarse => 0, + }; + let role = self.role.map_or_else(|| self.category.weight(), role_weight); + seen * 4 + quality * 3 + role + } +} + +/// A look waiting for its report: the aircraft saw it, but has not radioed it yet. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Look { + pub(super) truth: u32, + pub(super) area: DVec3, + pub(super) radius: f64, + pub(super) category: Category, + pub(super) role: Option, + pub(super) quality: Quality, + pub(super) source: Source, + pub(super) observed: u64, +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Zone { + pub(super) center: DVec3, + pub(super) radius: f64, +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Sortie { + pub(super) drone: u32, + pub(super) zones: Vec, + /// The next zone to look through. + pub(super) next: usize, + pub(super) launched: u64, + /// The report waiting to be sent: when, from which zone, and what it saw. + pub(super) report_at: Option, + pub(super) report_zone: Option, + pub(super) pending: Vec, +} + +/// What the enemy remembers from its recon flights, across raids. +#[derive(Default)] +pub(super) struct Recon { + pub(super) sorties: Vec, + pub(super) marks: BTreeMap, + /// The unit a mark is of. Internal to the observer: the planner only ever sees `Mark`. + pub(super) truth: BTreeMap, + /// Zones already reported as looked through, by their rounded centre. + pub(super) checked: BTreeMap<(i64, i64), u64>, + pub(super) next: u32, + pub(super) drone_next: u32, + pub(super) reports: u32, + pub(super) lost: u32, +} + +impl Recon { + pub(super) fn clear_sorties(&mut self) { + self.sorties.clear(); + } + + /// A cheap shape of the recon memory for the autosave's dirty check: a new mark, a checked + /// zone, a sortie's progress — and, because a report can refine an existing mark without + /// changing any count, the marks' own observed content (#135). + pub(super) fn mark(&self) -> u64 { + let mut h: u64 = 0xCBF2_9CE4_8422_2325; + let mut mix = |v: u64| h = (h ^ v).wrapping_mul(0x0000_0100_0000_01B3); + mix(self.sorties.len() as u64); + mix(self.marks.len() as u64); + mix(self.checked.len() as u64); + mix(u64::from(self.next)); + mix(u64::from(self.drone_next)); + for (id, m) in &self.marks { + mix(u64::from(*id)); + mix(m.observed); + mix(m.reported); + mix(u64::from(m.looks)); + mix(m.quality as u64); + mix(m.category as u64); + mix(m.source as u64); + mix(m.role.map_or(0xff, |r| r as u64)); + mix(m.area.x.to_bits()); + mix(m.area.z.to_bits()); + mix(m.radius.to_bits()); + } + for ((i, j), t) in &self.checked { + mix(*i as u64); + mix(*j as u64); + mix(*t); + } + for s in &self.sorties { + mix(u64::from(s.drone)); + mix(s.next as u64); + mix(s.pending.len() as u64); + mix(s.report_at.unwrap_or(u64::MAX)); + mix(s.report_zone.map_or(u64::MAX, |z| z as u64)); + } + h + } + + pub(super) fn is_empty(&self) -> bool { + self.sorties.is_empty() && self.marks.is_empty() && self.checked.is_empty() + } + + /// The marks the planner may see, newest and best first. The order uses the observed + /// public role, freshness and quality; the synthetic id is only a deterministic last tie. + pub(super) fn leads(&self, now: u64) -> Vec { + let mut out: Vec = self.marks.values().copied().filter(|m| m.live(now)).collect(); + out.sort_by(|a, b| { + b.priority(now) + .cmp(&a.priority(now)) + .then(b.observed.cmp(&a.observed)) + .then(a.id.cmp(&b.id)) + }); + out + } + + pub(super) fn live(&self, id: u32, now: u64) -> bool { + self.marks.get(&id).is_some_and(|m| m.live(now)) + } + + /// Remembers a zone that was reported as looked through, bounded. The oldest goes first. + pub(super) fn remember_zone(&mut self, center: DVec3, now: u64) { + self.checked.insert(zone_key(center), now); + while self.checked.len() > MAX_CHECKED { + let Some(oldest) = self.checked.iter().min_by_key(|(_, t)| **t).map(|(k, _)| *k) else { break }; + self.checked.remove(&oldest); + } + } + + pub(super) fn recently_checked(&self, center: DVec3, now: u64) -> bool { + self.checked.get(&zone_key(center)).is_some_and(|t| now.saturating_sub(*t) < REVISIT) + } + + pub(super) fn mark_for_truth(&self, truth: u32) -> Option { + self.truth.iter().find_map(|(id, t)| (*t == truth).then(|| self.marks.get(id).copied()).flatten()) + } + + /// A report that has arrived. The same observation twice changes nothing; a genuinely + /// later look updates the mark and may refine it. The mark keeps its synthetic id. + pub(super) fn report(&mut self, look: Look, now: u64) { + let existing = self.truth.iter().find_map(|(id, t)| (*t == look.truth).then_some(*id)); + match existing { + Some(id) => { + let Some(old) = self.marks.get(&id).copied() else { return }; + if look.observed <= old.observed { + return; + } + let refine = look.observed.saturating_sub(old.observed) >= REFINE_GAP; + let m = self.marks.get_mut(&id).unwrap(); + m.area = look.area; + m.radius = if refine { REFINED_AREA } else { m.radius }; + m.category = look.category; + m.source = look.source; + m.observed = look.observed; + m.reported = now; + m.looks = m.looks.saturating_add(1); + if refine { + m.quality = Quality::Refined; + m.role = look.role; + } + } + None => { + if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 { + return; + } + self.next += 1; + let id = ID_BASE + self.next; + self.truth.insert(id, look.truth); + self.marks.insert(id, Mark { + id, + area: look.area, + radius: look.radius, + category: look.category, + role: if look.quality == Quality::Refined { look.role } else { None }, + source: look.source, + observed: look.observed, + reported: now, + quality: look.quality, + looks: 1, + }); + } + } + } + + /// Marks older than a disclosure contact's life are forgotten. + pub(super) fn expire(&mut self, now: u64) { + self.marks.retain(|_, m| m.live(now)); + let ids: std::collections::HashSet = self.marks.keys().copied().collect(); + self.truth.retain(|id, _| ids.contains(id)); + } + + /// Drops sorties whose aircraft is gone and keeps the rest; a save may omit a drone it + /// could not write. + pub(super) fn retain_drones(&mut self, alive: &std::collections::HashSet) { + self.sorties.retain(|s| alive.contains(&s.drone)); + } +} + +/// The rounded place a zone is remembered by (the report, not the truth). +pub(super) fn zone_key(center: DVec3) -> (i64, i64) { + (center.x.round() as i64, center.z.round() as i64) +} + +/// The point a report gives for a unit seen at `at`: the centre of an area cell, moved +/// deterministically off the true point so the mark is an area, not a fix. +pub(super) fn area_of(at: DVec3, cell: f64, salt: u32) -> DVec3 { + let j = |k: u32| { + let h = salt.wrapping_mul(2_654_435_761).rotate_left(7) ^ k.wrapping_mul(2_246_822_519); + (f64::from(h % 1000) / 1000.0 - 0.5) * cell * 0.6 + }; + DVec3::new((at.x / cell).round() * cell + j(1), at.y, (at.z / cell).round() * cell + j(2)) +} + +/// One look through a zone: the units inside it, as the channels can tell them. The true +/// place and kind are read here, at the observation, and leave only as an area/category. +pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone, now: u64) -> Vec { + let mut out = Vec::new(); + for s in sams { + if horizontal(s.pos - zone.center).length() > zone.radius { + continue; + } + if out.len() >= MAX_OBSERVED { + break; + } + let old = state.mark_for_truth(s.id); + let refine = old.is_some_and(|m| now.saturating_sub(m.observed) >= REFINE_GAP); + let quality = if refine { Quality::Refined } else { Quality::Coarse }; + let cell = if refine { REFINED_AREA } else { COARSE_AREA }; + let category = Category::of(s.kind); + // A launch is a public event already watched by the disclosure channel; a look that + // passes just after one can name that source too. Health, magazine and link never are. + let launched = intel.contacts().get(&s.id).is_some_and(|c| c.seen == ew::Seen::Launch && now.saturating_sub(c.tick) < 200); + let source = match s.kind { + SamKind::Ew if s.ew_on => Source::Jamming, + SamKind::Radar if s.radar_on => Source::Emission, + _ if launched => Source::Launch, + _ => Source::Flyby, + }; + // The role is a public radar configuration only when a close second look can tell it. + let role = (refine && s.kind == SamKind::Radar).then_some(s.radar_role); + // The jitter is the zone's, not the unit's: the mark must not carry the unit id even + // indirectly. + let salt = (zone.center.x.round() as i64 as u32) ^ (zone.center.z.round() as i64 as u32).rotate_left(16); + out.push(Look { + truth: s.id, + area: area_of(s.pos, cell, salt), + radius: cell, + category, + role, + quality, + source, + observed: now, + }); + } + out +} + +/// The zones a smart raid sends its aircraft through: round the marked objectives, then +/// (when every one of those has been checked lately) round a mark the picture still doubts. +pub(super) fn plan_zones(objects: &[DVec3], state: &Recon, now: u64) -> Vec { + let mut out = Vec::new(); + for (i, p) in objects.iter().take(2).enumerate() { + // The marked objective itself, then one ring round it: the defence around the target + // is what the enemy came to look at, and a ring alone would miss a unit on the mark. + let a = i as f64 * 2.399_963_229_728_653; + let ring = *p + DVec3::new(a.sin() * 260.0, 0.0, a.cos() * 260.0); + for center in [*p, ring] { + if !state.recently_checked(center, now) { + out.push(Zone { center, radius: ZONE_RADIUS }); + } + } + } + if out.is_empty() { + // Nothing unchecked round the objectives: re-look at a mark the picture still doubts. + if let Some(m) = state.leads(now).into_iter().find(|m| m.confidence(now) == Confidence::Doubtful) { + out.push(Zone { center: m.area, radius: ZONE_RADIUS }); + } + } + out.truncate(ZONES_MAX); + out +} + +impl Sim { + /// Sends the raid's recon flight: a few unarmed aircraft, physically in the air, ahead + /// of the strike. Their zones come from the marked objectives alone, never from the + /// hidden force, so the same seed and objectives order the same flight whatever the + /// defences are. + pub(super) fn start_recon(&mut self, objects: &[DVec3], bearing: f64, dist: f64, out: &mut Out) { + let zones = plan_zones(objects, &self.recon, self.tick); + // The allowance is the raid's whole recon budget, not one order's: a second wave does not + // launch more aircraft while the first flight is still out. + let room = SORTIES_MAX.saturating_sub(self.recon.sorties.len()); + if zones.is_empty() || room == 0 { + return; + } + let Some(&last) = objects.last() else { return }; + // Ids beyond the drone parser's bound would make the next save unreadable. + if self.recon.drone_next >= DRONE_TOP - DRONE_BASE - 1 { + return; + } + let want = room.min(2).min(zones.len()); + let centre = objects[0]; + let from = centre + DVec3::new(bearing.sin() * dist, 120.0, bearing.cos() * dist); + // The recon flight must not spend the strike's combat randomness: its own aim error + // may differ, but a new role must not re-roll the raid that follows it. + let combat_rng = self.rng.state(); + for n in 0..want { + // Each aircraft takes every `want`-th zone from `n` on: the first the first zones, + // the second the ones after them, so a loss does not take every look with it. + let mine: Vec = zones.iter().skip(n).step_by(want).cloned().collect(); + if mine.is_empty() { + continue; + } + let dir = (mine[0].center - from).normalize_or(DVec3::NEG_Z); + // The launch helper takes an id from the strike's counter; the recon aircraft + // gives it back and takes one from its own range, so the strike's ids and + // tie-breaks are exactly what they would have been without the flight. + let main_next = self.next; + self.launch(DroneKind::Gerbera, from, dir, last, out); + self.next = main_next; + let Some(d) = self.drones.last_mut() else { continue }; + self.recon.drone_next += 1; + d.id = DRONE_BASE + self.recon.drone_next; + d.low = true; + d.sector = ew::sector(bearing) as u8; + let at = d.id; + d.route = mine.iter().map(|z| z.center + DVec3::Y * 40.0).chain(std::iter::once(last)).collect(); + d.target = last; + self.recon.sorties.push(Sortie { + drone: at, + zones: mine, + next: 0, + launched: self.tick, + report_at: None, + report_zone: None, + pending: Vec::new(), + }); + } + self.rng.set_state(combat_rng); + if !self.recon.sorties.is_empty() { + out.messages.push("Разведка противника: впереди налёта высланы разведчики".into()); + } + } + + /// One tick of the recon flight: a look is radioed after its delay if the aircraft is + /// still flying; a lost aircraft leaves its unreported look behind. + pub(super) fn step_recon(&mut self, out: &mut Out) { + let now = self.tick; + if self.recon.sorties.is_empty() { + return; + } + let mut sorties = std::mem::take(&mut self.recon.sorties); + let mut kept = Vec::with_capacity(sorties.len()); + let mut lost = 0u32; + for mut s in sorties.drain(..) { + let alive = self.drones.iter().any(|d| d.id == s.drone && d.alive()); + if !alive { + // An aircraft that finished its look and flew on to the aim is not a loss: only a + // sortie with a zone left or a report still unsent ended before its work was done. + let unfinished = s.report_at.is_some() || s.next < s.zones.len(); + if unfinished { + lost += 1; + out.messages.push(if s.report_at.take().is_some() { + "Разведка противника: разведчик сбит до донесения".into() + } else { + "Разведка противника: разведчик сбит".into() + }); + } + continue; + } + if now.saturating_sub(s.launched) > SORTIE_TTL { + if s.report_at.is_some() || s.next < s.zones.len() { + lost += 1; + } + s.pending.clear(); + s.report_at = None; + out.messages.push("Разведка противника: разведчик вернулся ни с чем".into()); + continue; + } + if let Some(at) = s.report_at { + if now >= at { + if let Some(z) = s.report_zone.take() { + self.recon.remember_zone(s.zones[z].center, now); + } + let n = s.pending.len(); + for look in std::mem::take(&mut s.pending) { + self.recon.report(look, now); + } + self.recon.reports = self.recon.reports.saturating_add(1); + s.report_at = None; + out.messages.push(if n == 0 { + "Разведка противника: зона проверена, целей не обнаружено".into() + } else { + format!("Разведка противника: донесение, отметок {n}") + }); + } else { + kept.push(s); + continue; + } + } + if s.next < s.zones.len() { + let at = self.drones.iter().find(|d| d.id == s.drone).map(|d| d.pos); + let inside = at.is_some_and(|p| horizontal(p - s.zones[s.next].center).length() <= s.zones[s.next].radius); + if inside { + let z = s.zones[s.next].clone(); + s.pending = look(&self.sams, &self.recon, &self.intel, &z, now); + s.report_at = Some(now + REPORT_DELAY); + s.report_zone = Some(s.next); + s.next += 1; + kept.push(s); + continue; + } + kept.push(s); + continue; + } + // Every zone looked through and its report sent: the aircraft flies on to its aim. + } + self.recon.sorties = kept; + self.recon.expire(now); + if lost > 0 { + self.recon.lost = self.recon.lost.saturating_add(lost); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::sites::testland::{Land, serve}; + + fn sam(sim: &mut Sim, kind: SamKind, at: DVec3) -> u32 { + let id = sim.id(); + sim.sams.push(Sam::new(id, kind, at, 0.0)); + id + } + + fn order() -> RaidOrder { + RaidOrder { kinds: vec![(DroneKind::Shahed, 4)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart } + } + + /// Moves the first recon aircraft into its next zone and returns the tick of the look. + fn look_once(sim: &mut Sim) -> (u32, u64) { + let s = sim.recon.sorties.first().expect("no recon sortie").clone(); + let d = sim.drones.iter_mut().find(|d| d.id == s.drone).expect("the sortie has no aircraft"); + d.pos = s.zones[s.next].center + DVec3::Y * 40.0; + sim.tick += 1; + sim.step_recon(&mut Out::default()); + (s.drone, sim.tick) + } + + // #135: before anything is observed the recon flight and the strike's decisions are a + // function of the seed, the objectives and the published plan alone. Two hidden layouts + // -- different kinds and places, neither observed -- order the same flight and aims. + #[test] + fn the_same_seed_orders_the_same_flight_whatever_is_hidden() { + let object = DVec3::new(0.0, 70.0, 0.0); + let build = |hidden: bool| { + let mut sim = Sim::new(135); + if hidden { + sam(&mut sim, SamKind::S400, DVec3::new(-180.0, 70.0, 40.0)); + sam(&mut sim, SamKind::Radar, DVec3::new(210.0, 70.0, -60.0)); + sam(&mut sim, SamKind::Gepard, DVec3::new(20.0, 70.0, 240.0)); + } else { + sam(&mut sim, SamKind::Pantsir, DVec3::new(300.0, 70.0, 300.0)); + } + sim.targets.push(object); + sim.target_health.push(100.0); + let mut out = Out::default(); + sim.order_raid(&order(), &[object], &mut out); + let flight: Vec<_> = sim + .recon + .sorties + .iter() + .map(|s| s.zones.iter().map(|z| (z.center, z.radius)).collect::>()) + .collect(); + let aircraft: Vec<_> = sim + .drones + .iter() + .filter(|d| sim.recon.sorties.iter().any(|s| s.drone == d.id)) + .map(|d| (d.pos, d.target, d.route.clone())) + .collect(); + let aims: Vec<_> = sim.planned_aims().into_iter().map(|(_, i)| i).collect(); + let intents: Vec<_> = sim.planned_intents().into_iter().map(|(_, i)| i).collect(); + (flight, aircraft, aims, intents) + }; + let a = build(false); + let b = build(true); + assert_eq!(a, b, "a hidden layout changed the recon flight or the plan before any observation"); + } + + // #135: an empty zone proves nothing. The look reports no mark, and only the fact that + // this zone was looked through is remembered. + #[test] + fn an_empty_zone_reports_no_mark() { + let mut sim = Sim::new(1); + let object = DVec3::new(0.0, 70.0, 0.0); + sim.targets.push(object); + sim.target_health.push(100.0); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + assert!(!sim.recon.sorties.is_empty()); + let (_, at) = look_once(&mut sim); + assert!(sim.recon.marks.is_empty(), "an empty zone made a mark"); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + assert!(sim.recon.marks.is_empty(), "an empty zone proved a unit after the report"); + assert!(sim.recon.checked.values().any(|t| *t == sim.tick), "the checked zone was not remembered"); + } + + // #135: a report exists only once the aircraft that made the look is still flying when it + // is due. A sortie lost first leaves no mark; a mark already reported does not disappear + // when the aircraft is lost later. + #[test] + fn a_sortie_lost_before_its_report_sends_nothing() { + let mut sim = Sim::new(2); + let object = DVec3::new(0.0, 70.0, 0.0); + let id = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (drone, at) = look_once(&mut sim); + assert_eq!(sim.recon.marks.len(), 0, "a look reached the picture before its report"); + sim.drones.retain(|d| d.id != drone); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + assert_eq!(sim.recon.marks.len(), 0, "a lost sortie still delivered its look"); + + // The same look reported in time: the mark arrives and stays after the loss. + let mut sim = Sim::new(2); + let object = DVec3::new(0.0, 70.0, 0.0); + let _ = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (drone, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + assert_eq!(sim.recon.marks.len(), 1, "a timely report made no mark"); + let area = sim.recon.marks.values().next().unwrap().area; + sim.drones.retain(|d| d.id != drone); + sim.step_recon(&mut Out::default()); + assert_eq!(sim.recon.marks.values().next().unwrap().area, area, "a lost aircraft rewrote a delivered mark"); + let _ = id; + } + + // #135: confidence is the mark's age, not a count of reports. The same observation + // reported twice changes neither the mark's quality nor its looks. + #[test] + fn a_duplicate_report_does_not_raise_confidence() { + let mut sim = Sim::new(3); + let object = DVec3::new(0.0, 70.0, 0.0); + let _ = sam(&mut sim, SamKind::Radar, object + DVec3::new(30.0, 0.0, 0.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (_, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + let before = *sim.recon.marks.values().next().unwrap(); + // The same look arrives again, even much later: it is still the same observation. + let look = Look { + truth: sim.recon.truth.values().next().copied().unwrap(), + area: before.area, + radius: before.radius, + category: before.category, + role: before.role, + quality: Quality::Refined, + source: before.source, + observed: before.observed, + }; + sim.recon.report(look, before.reported + 10_000); + let after = *sim.recon.marks.values().next().unwrap(); + assert_eq!((after.quality, after.looks, after.observed, after.radius), (before.quality, before.looks, before.observed, before.radius)); + assert!(after.confidence(before.reported + 10_000) <= before.confidence(before.reported)); + } + + // #135: a hidden move or a hidden change does not rewrite the old mark. Only a new look, + // reported later, can re-place it. + #[test] + fn a_hidden_move_does_not_rewrite_the_mark() { + let mut sim = Sim::new(4); + let object = DVec3::new(0.0, 70.0, 0.0); + let id = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (_, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + let before = sim.enemy_picture().recon; + let key = |r: &[super::ew::ReconReport]| -> Vec<_> { r.iter().map(|m| (m.id, m.area, m.radius, m.category, m.role, m.source, m.quality)).collect() }; + // A hidden move, a re-role and damage: none of it is an observation. Age moves on, + // the mark's area, category, role and quality do not. + let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap(); + s.pos = DVec3::new(900.0, 70.0, 900.0); + s.health = 0.0; + s.radar_role = battery::RadarRole::Height; + s.missiles = 0; + sim.tick += 1000; + assert_eq!(key(&sim.enemy_picture().recon), key(&before), "a hidden change rewrote the recon picture"); + } + + + // #135: the channel matters. A silent radar is seen only by the flyby, a transmitting + // radar by its emission, a jamming station by its transmission, and a just-fired system + // by the launch the disclosure channel already watched. A hidden switch or magazine is + // not read: only what the game shows. + #[test] + fn the_source_is_the_channel_that_showed_the_unit() { + let mut sim = Sim::new(8); + let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS }; + let radar = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0)); + let ew = sam(&mut sim, SamKind::Ew, DVec3::new(-10.0, 70.0, 0.0)); + let s400 = sam(&mut sim, SamKind::S400, DVec3::new(0.0, 70.0, 10.0)); + sim.recon.checked.clear(); + let source = |sim: &Sim, id: u32| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).unwrap().source; + + sim.sams.iter_mut().find(|s| s.id == radar).unwrap().radar_on = false; + assert_eq!(source(&sim, radar), Source::Flyby, "a silent radar was read as emitting"); + sim.sams.iter_mut().find(|s| s.id == radar).unwrap().radar_on = true; + assert_eq!(source(&sim, radar), Source::Emission); + assert_eq!(source(&sim, ew), Source::Flyby, "a silent jammer was read as transmitting"); + sim.sams.iter_mut().find(|s| s.id == ew).unwrap().ew_on = true; + assert_eq!(source(&sim, ew), Source::Jamming); + sim.intel.observe(sim.sams.iter().find(|s| s.id == s400).unwrap(), sim.tick, ew::Seen::Launch); + assert_eq!(source(&sim, s400), Source::Launch); + // A hidden empty magazine does not change the source. + sim.sams.iter_mut().find(|s| s.id == s400).unwrap().missiles = 0; + assert_eq!(source(&sim, s400), Source::Launch); + } + + // #135: the planner's order is the observed public role, freshness and quality, not the + // unit id or its true importance. A fresh modest mark outranks an old doubtful big one; + // the synthetic ids are only the last deterministic tie. + #[test] + fn priority_is_observed_role_and_freshness_not_id_or_truth() { + let mut r = Recon::default(); + let mark = |id: u32, at: DVec3, category, role, observed, quality| Mark { + id, + area: at, + radius: REFINED_AREA, + category, + role, + source: Source::Flyby, + observed, + reported: observed, + quality, + looks: 1, + }; + r.marks.insert(ID_BASE + 1, mark(ID_BASE + 1, DVec3::ZERO, Category::Radar, Some(battery::RadarRole::Engagement), 100, Quality::Refined)); + r.marks.insert(ID_BASE + 2, mark(ID_BASE + 2, DVec3::X, Category::Launcher, None, 100, Quality::Refined)); + let now = 200; + let leads = r.leads(now); + assert_eq!((leads[0].id, leads[1].id), (ID_BASE + 1, ID_BASE + 2), "a bigger observed role did not lead"); + // The same observations age: the big one becomes doubtful, the modest one is fresh. + r.marks.insert(ID_BASE + 2, mark(ID_BASE + 2, DVec3::X, Category::Gun, None, 3900, Quality::Coarse)); + let leads = r.leads(4000); + assert_eq!(leads[0].id, ID_BASE + 2, "a stale doubtful mark outranked a fresh modest one"); + assert!(leads.iter().all(|m| m.id != 1 && m.id != 2), "a true id leaked into the marks"); + } + + + // #135: only the smart enemy gets the phase. A simple preset's raid gets no aircraft and + // spends no time on a role it never had. + #[test] + fn a_simple_preset_gets_no_recon() { + let mut sim = Sim::new(9); + let object = DVec3::new(0.0, 70.0, 0.0); + sim.targets.push(object); + sim.target_health.push(100.0); + let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Objects }; + sim.order_raid(&order, &[object], &mut Out::default()); + assert!(sim.recon.sorties.is_empty()); + } + + // #135: save/load keeps the flight, the pending report, the marks and the checked zones; + // the restored flight finishes the same way. + #[test] + fn save_and_load_keep_the_recon_flight_and_its_marks() { + let mut sim = Sim::new(5); + let object = DVec3::new(0.0, 70.0, 0.0); + let _ = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (_, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + // A second sortie still out with a pending look. + if sim.recon.sorties.is_empty() { + sim.recon.checked.clear(); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + } + let _ = look_once(&mut sim); + // A drone turned onto a mark has a pending route job keyed by the synthetic id. + let mark = *sim.recon.marks.values().next().expect("no mark to aim at"); + let mut d = sim.make_drone(DroneKind::Kh22, DVec3::new(-800.0, 120.0, 0.0), DVec3::X, mark.area); + d.smart = true; + d.target = mark.area; + d.aim = ew::Aim::unit(mark.id, sim.tick, mark.confidence(sim.tick)); + let drone = d.id; + sim.drones.push(d); + sim.retargets.push_back(ew::RouteJob::restored(900, drone, mark.area, mark.id, sim.tick, ew::Intent::Plan, std::sync::Arc::new(Vec::new()), None)); + let text = sim.air_text().expect("a recon flight is durable"); + assert!(text.contains("airrecon"), "the recon section was not written"); + let mut back = Sim::new(6); + back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there")); + assert_eq!(back.recon.marks.len(), sim.recon.marks.len()); + assert_eq!(back.recon.sorties.len(), sim.recon.sorties.len()); + assert!(back.retargets.iter().any(|j| j.unit == mark.id), "a job on a recon mark was lost with the save"); + for (a, b) in sim.recon.marks.values().zip(back.recon.marks.values()) { + assert_eq!((a.id, a.category, a.quality, a.observed, a.reported), (b.id, b.category, b.quality, b.observed, b.reported)); + assert!(a.area.distance(b.area) < 0.02 && (a.radius - b.radius).abs() < 1e-6); + } + for (a, b) in sim.recon.sorties.iter().zip(&back.recon.sorties) { + assert_eq!((a.drone, a.next, a.launched, a.report_at, a.report_zone), (b.drone, b.next, b.launched, b.report_at, b.report_zone)); + assert_eq!(a.pending.len(), b.pending.len()); + assert_eq!(a.zones.len(), b.zones.len()); + } + // The restored pending report arrives on its tick and leaves a mark. + back.tick = at + REPORT_DELAY * 2; + back.step_recon(&mut Out::default()); + assert!(!back.recon.marks.is_empty()); + } + + // #135: a normal smart wave with a recon flight still ends. The recon phase is bounded and + // never holds the raid open; a lost or empty sortie does not pause the match. + #[test] + fn a_normal_smart_wave_with_recon_finishes() { + let mut sim = Sim::new(7); + sim.targets.push(DVec3::new(0.0, 70.0, 0.0)); + sim.target_health.push(100.0); + let mut ground = Ground::default(); + let land = Land(|_, _| 64); + let mut out = Out::default(); + for _ in 0..20 { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + } + let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2), (DroneKind::Gerbera, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart }; + assert_eq!(sim.order_raid(&order, &[DVec3::new(0.0, 70.0, 0.0)], &mut out), 4); + assert!(!sim.recon.sorties.is_empty(), "the smart wave sent no recon"); + let mut ticks = 0; + for _ in 0..8000 { + serve(&mut ground, &land, sim.tick); + out = Out::default(); + sim.step(&mut ground, None, &mut out); + ticks += 1; + if !sim.planning() && sim.queue.is_empty() && !sim.drones.iter().any(|d| d.alive()) { + break; + } + } + assert!(!sim.planning(), "the raid never stopped planning"); + assert!(sim.queue.is_empty(), "the raid still has launches waiting"); + assert!(!sim.drones.iter().any(|d| d.alive()), "a drone flew for ever"); + assert!(ticks < 8000); + } + + // #135: a later raid inherits the picture the earlier one radioed home -- the marks do not + // vanish with the wave -- and its flight never grows past the budget while an aircraft of + // the first wave is still out. + #[test] + fn a_new_raid_keeps_the_marks_and_stays_within_the_flight_budget() { + let mut sim = Sim::new(11); + let object = DVec3::new(0.0, 70.0, 0.0); + let _ = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.targets.push(object); + sim.target_health.push(100.0); + let mut out = Out::default(); + // Far out, so no aircraft starts inside a zone and the second one can stay out. + sim.start_recon(&[object], 0.0, 900.0, &mut out); + let (_, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut out); + let seen = *sim.recon.marks.values().next().expect("the first flight reported nothing"); + assert!(!sim.recon.sorties.is_empty(), "the first flight left no aircraft out"); + sim.order_raid(&order(), &[object], &mut out); + assert!(sim.recon.sorties.len() <= SORTIES_MAX, "a second order launched past the recon budget"); + let kept = sim.recon.marks.get(&seen.id).copied().expect("a new raid forgot what the first one saw"); + assert_eq!((kept.area, kept.observed, kept.category), (seen.area, seen.observed, seen.category), "a new raid rewrote a mark"); + assert!(!sim.recon.leads(sim.tick).is_empty(), "the new wave planned without the old picture"); + } + + // #135: a refinement of an existing mark changes the save's dirty shape. A report that only + // updates the area, age, quality or role leaves every count as it was, so the counts alone + // would let an autosave miss it. + #[test] + fn a_refined_mark_changes_the_durable_shape() { + let mut r = Recon::default(); + let coarse_look = Look { + truth: 5, + area: DVec3::ZERO, + radius: COARSE_AREA, + category: Category::Radar, + role: None, + quality: Quality::Coarse, + source: Source::Flyby, + observed: 100, + }; + r.report(coarse_look, 200); + let coarse = r.mark(); + r.report( + Look { observed: 100 + REFINE_GAP, quality: Quality::Refined, role: Some(battery::RadarRole::Engagement), source: Source::Emission, area: DVec3::new(30.0, 70.0, 0.0), radius: REFINED_AREA, ..coarse_look }, + 200 + REFINE_GAP, + ); + assert_eq!(r.marks.len(), 1, "a refinement made a second mark"); + assert_ne!(r.mark(), coarse, "a refined mark is invisible to the autosave's dirty check"); + } + + // #135: among equally fresh, equally well known radars, the one whose observed role is the + // bigger is offered the strikers first; the modest one is still worked over, so the raid keeps + // its breadth. The seed does not change it: the order is the observed role, not a draw or an id. + #[test] + fn a_big_observed_radar_is_offered_the_strikers_first() { + for seed in [1u64, 2, 3] { + let mut sim = Sim::new(seed); + sim.tick = 1000; + let look = |truth: u32, role: battery::RadarRole| Look { + truth, + area: DVec3::new(f64::from(truth) * 100.0, 70.0, 0.0), + radius: REFINED_AREA, + category: Category::Radar, + role: Some(role), + quality: Quality::Refined, + source: Source::Emission, + observed: 1000, + }; + sim.recon.report(look(1, battery::RadarRole::Search), 1000); + sim.recon.report(look(2, battery::RadarRole::Engagement), 1000); + let id_of = |truth: u32| sim.recon.truth.iter().find_map(|(id, t)| (*t == truth).then_some(*id)).unwrap(); + let (modest, big) = (id_of(1), id_of(2)); + let jobs = sim.radar_strikes(&[(DroneKind::Kh22, 8)], &[]); + let first: Vec = jobs.iter().flatten().map(|(_, id)| *id).collect(); + assert_eq!(first.first().copied(), Some(big), "seed {seed}: a modest station was offered the first striker"); + assert!(first.contains(&modest), "seed {seed}: the modest station got no striker at all"); + } + } + + // #135: a recon aircraft is a role of its own: it neither opens a strike's replay nor keeps + // one open. A strike drone still does, so the check is not vacuous. + #[test] + fn a_recon_flight_does_not_open_the_strike_replay() { + let mut sim = Sim::new(12); + let object = DVec3::new(0.0, 70.0, 0.0); + sim.targets.push(object); + sim.target_health.push(100.0); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + assert!(!sim.recon.sorties.is_empty(), "no recon aircraft to test with"); + sim.begin_recording_if_active(); + assert!(sim.rec.is_none(), "a recon aircraft opened a strike replay"); + sim.launch(DroneKind::Shahed, DVec3::new(-300.0, 120.0, 0.0), DVec3::X, object, &mut Out::default()); + sim.begin_recording_if_active(); + assert!(sim.rec.is_some(), "a strike drone did not open its replay"); + } + + // #135: the recon memory is as durable as the rest of the air state and stays inside the + // section's byte budget: every mark, checked zone and sortie written is read back. + #[test] + fn the_whole_recon_memory_fits_a_save_and_reads_back() { + let mut sim = Sim::new(13); + sim.tick = 100; + for truth in 1..=MAX_MARKS as u32 { + sim.recon.report( + Look { + truth, + area: DVec3::new(f64::from(truth), 70.0, -0.5), + radius: COARSE_AREA, + category: Category::Launcher, + role: None, + quality: Quality::Coarse, + source: Source::Flyby, + observed: 100, + }, + 100, + ); + } + for x in 0..MAX_CHECKED as i64 { + sim.recon.remember_zone(DVec3::new(x as f64 * 10.0, 70.0, 5.0), 100); + } + assert_eq!(sim.recon.marks.len(), MAX_MARKS); + let text = sim.air_text().expect("a full recon memory is durable"); + assert!(text.len() < 1 << 20, "the air section grew to {} bytes", text.len()); + let mut back = Sim::new(14); + back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there")); + assert_eq!(back.recon.marks.len(), MAX_MARKS); + assert_eq!(back.recon.checked.len(), MAX_CHECKED); + assert_eq!(back.recon.marks.values().map(|m| m.observed).sum::(), MAX_MARKS as u64 * 100); + } +} diff --git a/airdef-mod/src/sim/record.rs b/airdef-mod/src/sim/record.rs index e9ca74d..5259ef0 100644 --- a/airdef-mod/src/sim/record.rs +++ b/airdef-mod/src/sim/record.rs @@ -1,8 +1,9 @@ //! 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 drone in the sky and ends when the sky -//! has been clear a while; the last few are kept. +//! 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. @@ -834,8 +835,11 @@ impl Sim { } /// 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()) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) { + 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)); } @@ -853,7 +857,13 @@ impl Sim { 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. - let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty(); + // 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); @@ -867,7 +877,7 @@ impl Sim { if r.len % STEP == 0 { let now = r.len; r.note_sams(&self.sams, now); - for d in &self.drones { + 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 {