//! The enemy's air state in the autosave (#127): the raid's drones, the launch queue, the retarget //! jobs still waiting, the picture they were chosen from and the land they were planned over. //! //! A route job alone is not durable. Its drone may still be on the ground or already flying, and its //! aim is only meaningful with the picture the adaptive tick chose it from and the relief snapshot of //! that knowledge version. So the save writes the whole air state that a pending job depends on, and //! the load rebuilds it: drones, launch queue, jobs (with their id, aim, unit, version, priority and //! intent), the contacts, and each relief version a pending job still uses. Nothing of the live //! 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 //! save and names the line and the field. Everything is bounded — drones, queued launches, jobs, //! contacts, route points and relief cells — so a saved air state can never grow the file without limit. use super::*; use std::collections::{BTreeMap, HashMap}; /// The section's format version. A different one is refused rather than half-read. const VERSION: u32 = 1; /// Drones in the air a save may hold. A raid is normally tens of drones; this bound keeps the /// section far inside the host's per-write storage budget even if a scenario makes thousands. 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. 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 { tick: u64, job_next: u32, kills: [u32; ew::SECTORS], hits: [u32; ew::SECTORS], contacts: Vec, drones: Vec, queue: Vec<(u64, Drone)>, 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 { id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: ew::Intent, relief: Option>, } /// A saved line's words, with the line number for the refusal. struct Line<'a> { n: usize, word: &'a str, w: Vec<&'a str>, } impl Line<'_> { fn bad(&self, field: &str, why: &str) -> String { format!("строка {}: «{}», поле {field}: {why}", self.n, self.word) } fn word(&self, i: usize, field: &str) -> Result<&str, String> { self.w.get(i).copied().ok_or_else(|| self.bad(field, "строка оборвана")) } fn count(&self, i: usize, field: &str, max: usize) -> Result { let v = self.word(i, field)?; let n: usize = v.parse().map_err(|_| self.bad(field, &format!("«{v}» не целое число")))?; if n > max { return Err(self.bad(field, &format!("{n} больше {max}"))); } Ok(n) } fn int(&self, i: usize, field: &str, lo: i64, hi: i64) -> Result { let v = self.word(i, field)?; let n: i64 = v.parse().map_err(|_| self.bad(field, &format!("«{v}» не целое число")))?; if n < lo || n > hi { return Err(self.bad(field, &format!("{n} вне допустимого {lo}..{hi}"))); } Ok(n) } fn flag(&self, i: usize, field: &str) -> Result { match self.word(i, field)? { "true" => Ok(true), "false" => Ok(false), v => Err(self.bad(field, &format!("«{v}»: нужно true или false"))), } } fn num(&self, i: usize, field: &str) -> Result { let v = self.word(i, field)?; let x: f64 = v.parse().map_err(|_| self.bad(field, &format!("«{v}» не число")))?; if !x.is_finite() || x.abs() > 3.0e7 { return Err(self.bad(field, &format!("«{v}» не конечное допустимое число"))); } Ok(x) } fn opt_tick(&self, i: usize, field: &str) -> Result, String> { if self.word(i, field)? == "-" { return Ok(None); } Ok(Some(self.int(i, field, 0, 1 << 40)? as u64)) } } /// `x` as the save writes coordinates: centimetres are plenty for a flight, and keep the file small. fn coord(x: f64) -> String { format!("{x:.2}") } /// One run of the relief as the save writes it: `u` for unknown land, `x` for known. fn run_token(height: Option, run: usize) -> String { height.map_or_else(|| format!("u{run}"), |h| format!("{h}x{run}")) } fn tick(x: Option) -> String { x.map_or_else(|| "-".into(), |v| v.to_string()) } fn intent_of(key: &str) -> Option { ew::Intent::from_key(key) } fn flight_key(f: Flight) -> &'static str { match f { Flight::Cruise => "cruise", Flight::Dive => "dive", Flight::Ballistic => "ballistic", Flight::Falling => "falling", } } fn flight_of(key: &str) -> Option { [Flight::Cruise, Flight::Dive, Flight::Ballistic, Flight::Falling].into_iter().find(|f| flight_key(*f) == key) } impl Drone { /// The drone as one line of the save: its flight, its aim and intent, and its route. fn air_line(&self, word: &str, lead: &str) -> String { let mut route = String::from("-"); if !self.route.is_empty() { route = self.route.len().to_string(); for p in &self.route { route += &format!(" {} {} {}", coord(p.x), coord(p.y), coord(p.z)); } } format!( "{word} {lead}{id} {kind} {} {} {} {} {} {} {} {} {} {flight} {intent} {unit} {since} {switches} {conf} {} {} {} {age} {engaged} {sector} {low} {jammed} {smart} {hold} {} {} {} {route}", coord(self.pos.x), coord(self.pos.y), coord(self.pos.z), coord(self.vel.x), coord(self.vel.y), coord(self.vel.z), coord(self.target.x), coord(self.target.y), coord(self.target.z), coord(self.err.x), coord(self.err.y), coord(self.err.z), if self.pace.best.is_finite() { coord(self.pace.best) } else { "-".into() }, self.pace.at, if self.pace.route == usize::MAX { "-".to_string() } else { self.pace.route.to_string() }, kind = self.kind.spec().key, flight = flight_key(self.flight), intent = self.intent.key(), unit = self.aim.unit, since = self.aim.since, switches = self.aim.switches, conf = self.aim.confidence.map_or("-", |c| c.name()), age = self.age, engaged = self.engaged, sector = self.sector, low = self.low, jammed = self.jammed, smart = self.smart, hold = self.hold, id = self.id, ) } } impl Sim { /// A cheap shape of the air state for the autosave's dirty check: a launch, a loss, a new or /// finished job changes it, a drone's own progress through the sky does not. A save takes the /// air state at those moments, not on every tick of a flight (#127). pub fn air_mark(&self) -> u64 { let drones = self.drones.iter().filter(|d| d.alive()).count() as u64; drones ^ (self.queue.len() as u64) << 12 ^ (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 /// picture), so a save of a quiet world does not grow. Every pending job's drone is written with /// it, together with the picture and the relief versions the job still plans over (#127). pub fn air_text(&self) -> Option { // What the parser accepts is what is written: a save this build writes always reads back. let contacts: Vec = self.intel.contacts().values().copied().take(MAX_CONTACTS).collect(); let drones: Vec<&Drone> = self.drones.iter().filter(|d| d.alive()).take(MAX_DRONES).collect(); let queued: Vec<&(u64, Drone)> = self.queue.iter().take(MAX_DRONES).collect(); // The relief versions still referenced: the global one and every pending job's. They are // resolved before the drone lines so the head is fixed while the body's size is measured. let mut reliefs: Vec> = Vec::new(); let token_of = |r: &std::sync::Arc, reliefs: &mut Vec>| -> Option { let at = std::sync::Arc::as_ptr(r) as usize; if let Some(i) = reliefs.iter().position(|x| std::sync::Arc::as_ptr(x) as usize == at) { return Some(i); } if reliefs.len() >= MAX_RELIEFS { return None; } reliefs.push(std::sync::Arc::clone(r)); Some(reliefs.len() - 1) }; let global = self.known_relief.as_ref().and_then(|r| token_of(r, &mut reliefs)); let job_relief: Vec> = self.retargets.iter().map(|j| j.relief.as_ref().and_then(|r| token_of(r, &mut reliefs))).collect(); let (kills, hits) = self.intel.sectors(); // The head, with the counts filled in later; its length is what the body is measured against. let mut head = format!("air {VERSION} {} {} 0 0 0 {} {}\n", self.tick, self.job_next, contacts.len(), reliefs.len()); head += "airintel"; for v in kills.iter().chain(hits.iter()) { head += &format!(" {v}"); } head += "\n"; head += &format!("airglobal {}\n", global.map_or_else(|| "-".into(), |t| t.to_string())); for (i, r) in reliefs.iter().enumerate() { let g = r.grid(); let mut line = format!("airrelief {i} {} {} {} {} ", coord(g.min.x), coord(g.min.z), coord(g.cell), g.size); let mut run: Option<(Option, usize)> = None; for h in r.heights() { let key = h.is_finite().then(|| h.round() as i32); match run { Some((k, n)) if k == key => run = Some((k, n + 1)), Some((k, n)) => { line += &format!("{} ", run_token(k, n)); run = Some((key, 1)); } None => run = Some((key, 1)), } } if let Some((k, n)) = run { line += &run_token(k, n); } head += &line; head += "\n"; } for c in &contacts { head += &format!( "aircontact {} {} {} {} {} {} {} {} {} {}\n", c.id, c.kind.spec().key, coord(c.at.x), coord(c.at.y), coord(c.at.z), c.tick, c.seen.name(), tick(c.emission), tick(c.destroyed), c.launches ); } // The bodies go in while the section stays inside its byte bound; a drone left out takes its // 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_RECON_BYTES <= MAX_BYTES; let mut drone_count = 0usize; for d in &drones { let line = d.air_line("airdrone", ""); if !fits(&head, &body, &line) { break; } body += &line; body += "\n"; saved.insert(d.id); drone_count += 1; } let mut queued_count = 0usize; for (at, d) in &queued { let line = d.air_line("airqueue", &format!("{at} ")); if !fits(&head, &body, &line) { break; } body += &line; body += "\n"; saved.insert(d.id); queued_count += 1; } // 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() && self.recon.is_empty() { return None; } let head = head.replacen( &format!("air {VERSION} {} {} 0 0 0 ", self.tick, self.job_next), &format!("air {VERSION} {} {} {drone_count} {queued_count} {} ", self.tick, self.job_next, jobs.len()), 1, ); let mut text = head; text += &body; for (job, relief) in jobs { text += &format!( "airjob {} {} {} {} {} {} {} {} {} {}\n", job.id, job.drone, coord(job.aim.x), coord(job.aim.y), coord(job.aim.z), job.unit, job.version, job.priority(), job.intent.key(), 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) } /// Reads the air section of `text` (the lines `air_text` writes). `None` when the text has none: /// an older save, restored with an empty sky as before. Everything is checked before it is used. pub fn parse_air(text: &str) -> Result, String> { let lines: Vec<(usize, Vec<&str>)> = text .lines() .enumerate() .map(|(n, raw)| (n + 1, raw.split_whitespace().collect::>())) .collect(); let heads: Vec<&(usize, Vec<&str>)> = lines.iter().filter(|(_, w)| w.first() == Some(&"air")).collect(); let Some((head_n, head)) = heads.first().copied() else { // Lines of a section whose header is gone are a corrupt file, not an old save. if let Some((n, w)) = lines.iter().find(|(_, w)| w.first().is_some_and(|w| w.starts_with("air"))) { return Err(format!("строка {n}: «{}», воздушная часть без заголовка air", w[0])); } return Ok(None); }; if heads.len() > 1 { return Err(format!("строка {}: воздушная часть записана дважды", heads[1].0)); } let l = Line { n: *head_n, word: "air", w: head.clone() }; if head.len() != 9 { return Err(l.bad("заголовок", "нужны версия, такт, счётчики и число версий рельефа")); } let version = l.int(1, "версия воздушной части", 0, 1 << 30)? as u32; if version != VERSION { return Err(l.bad("версия воздушной части", &format!("эта сборка читает только {VERSION}"))); } let tick = l.int(2, "такт", 0, 1 << 40)?.max(0) as u64; let job_next = l.int(3, "номер задания", 0, 1 << 30)? as u32; let n_drones = l.count(4, "дроны", MAX_DRONES)?; let n_queue = l.count(5, "очередь запуска", MAX_DRONES)?; let n_jobs = l.count(6, "задания", ew::JOBS_MAX)?; let n_contacts = l.count(7, "контакты", MAX_CONTACTS)?; let n_reliefs = l.count(8, "версии рельефа", MAX_RELIEFS)?; // Every line of the section, and nothing else: a truncated or foreign line is refused. let mut intel: Option<[u32; ew::SECTORS * 2]> = None; let mut global: Option = None; let mut reliefs: Vec>> = vec![None; n_reliefs]; let mut contacts: BTreeMap = BTreeMap::new(); 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; } let Some(&word) = w.first() else { continue }; if !word.starts_with("air") { continue; } let l = Line { n: *n, word, w: w.clone() }; match word { "airintel" => { if w.len() != 1 + ew::SECTORS * 2 { return Err(l.bad("счётчики секторов", &format!("нужны {} чисел", ew::SECTORS * 2))); } let mut v = [0u32; ew::SECTORS * 2]; for (i, slot) in v.iter_mut().enumerate() { *slot = l.int(i + 1, "счётчики секторов", 0, 1 << 30)? as u32; } intel = Some(v); } "airglobal" => { if w.len() != 2 { return Err(l.bad("рельеф", "нужна одна ссылка на версию рельефа")); } let t = l.word(1, "рельеф")?; if t != "-" { let at = l.count(1, "рельеф", MAX_RELIEFS)?; if at >= n_reliefs { return Err(l.bad("рельеф", "ссылка на неписаную версию")); } global = Some(at); } } "airrelief" => { let at = l.count(1, "номер рельефа", MAX_RELIEFS)?; if at >= n_reliefs { return Err(l.bad("номер рельефа", "больше объявленных")); } let grid = raid::Grid { min: DVec3::new(l.num(2, "рельеф X")?, 0.0, l.num(3, "рельеф Z")?), cell: l.num(4, "размер клетки")?, size: l.int(5, "сторона сетки", 1, 400)? as i32, }; if grid.cell <= 0.0 { return Err(l.bad("размер клетки", "должен быть больше нуля")); } let cells = (grid.size * grid.size) as usize; if cells > MAX_CELLS { return Err(l.bad("рельеф", &format!("{cells} клеток больше {MAX_CELLS}"))); } let mut heights = Vec::with_capacity(cells); for t in &w[6..] { // `u` is unknown land, `x` a known height repeated. let (h, run) = if let Some(n) = t.strip_prefix('u') { (f32::NAN, n) } else { let Some((head, n)) = t.split_once('x') else { return Err(l.bad("рельеф", &format!("«{t}» не повтор высоты"))); }; let v: i32 = head.parse().map_err(|_| l.bad("рельеф", &format!("«{head}» не высота")))?; (v as f32, n) }; let run: usize = run.parse().map_err(|_| l.bad("рельеф", "длина повтора не число"))?; if run == 0 || run > cells { return Err(l.bad("рельеф", &format!("повтор {run} вне 1..{cells}"))); } if heights.len() + run > cells { return Err(l.bad("рельеф", "повторы длиннее сетки")); } heights.extend(std::iter::repeat_n(h, run)); } if heights.len() != cells { return Err(l.bad("рельеф", "повторы не покрывают сетку")); } if reliefs[at].is_some() { return Err(l.bad("номер рельефа", "версия записана дважды")); } reliefs[at] = Some(std::sync::Arc::new(ew::KnownRelief::new(grid, heights))); } "aircontact" => { if w.len() != 11 { return Err(l.bad("контакт", "нужны 10 полей наблюдения")); } let id = l.int(1, "номер юнита", 0, 1 << 30)? as u32; let kind = SamKind::from_key(l.word(2, "тип")?).ok_or_else(|| l.bad("тип", "неизвестный тип"))?; let at = DVec3::new(l.num(3, "контакт X")?, l.num(4, "контакт Y")?, l.num(5, "контакт Z")?); let seen = ew::Seen::from_key(l.word(7, "канал")?).ok_or_else(|| l.bad("канал", "launch, emission или jamming"))?; let c = ew::Contact { id, kind, at, tick: l.int(6, "такт наблюдения", 0, tick as i64)? as u64, seen, emission: l.opt_tick(8, "фиксация эмиссии")?, destroyed: l.opt_tick(9, "наблюдённое уничтожение")?, launches: l.int(10, "наблюдённые пуски", 0, u16::MAX as i64)? as u16, }; if contacts.insert(id, c).is_some() { return Err(l.bad("номер юнита", "контакт записан дважды")); } } "airdrone" | "airqueue" => { let at = if word == "airqueue" { Some(l.int(1, "такт запуска", 0, 1 << 40)? as u64) } else { None }; let (d, end) = parse_drone(&l, if at.is_some() { 2 } else { 1 })?; if w.len() != end { return Err(l.bad("дрон", "лишние поля")); } if at.is_some() { queue.push((at.unwrap(), d)); } else if drones.insert(d.id, d).is_some() { return Err(l.bad("номер дрона", "дрон записан дважды")); } } "airjob" => { if w.len() != 11 { return Err(l.bad("задание", "нужны 9 полей задания")); } let id = l.int(1, "номер задания", 0, 1 << 30)? as u32; let drone = l.int(2, "дрон задания", 0, 1 << 30)? as u32; let aim = DVec3::new(l.num(3, "цель X")?, l.num(4, "цель Y")?, l.num(5, "цель Z")?); let unit = l.int(6, "юнит", 0, 1 << 30)? as u32; let version = l.int(7, "версия знаний", 0, tick as i64)? as u64; let priority = l.int(8, "приоритет", 0, 9)? as u8; let intent = intent_of(l.word(9, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react или replace"))?; if priority != intent.priority() { return Err(l.bad("приоритет", "не совпадает с намерением")); } let relief = match l.word(10, "рельеф")? { "-" => None, t => { let at = t.parse::().map_err(|_| l.bad("рельеф", "не номер версии"))?; if at >= n_reliefs { return Err(l.bad("рельеф", "ссылка на неписаную версию")); } reliefs[at].clone() } }; 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}»"))), } } // The counts are the file's own promise: a section cut short is refused, not half-restored. if contacts.len() != n_contacts { return Err(format!("воздушная часть: контактов {} вместо {n_contacts}", contacts.len())); } if drones.len() != n_drones { return Err(format!("воздушная часть: дронов {} вместо {n_drones}", drones.len())); } if queue.len() != n_queue { return Err(format!("воздушная часть: очередь {} вместо {n_queue}", queue.len())); } if jobs.len() != n_jobs { return Err(format!("воздушная часть: заданий {} вместо {n_jobs}", jobs.len())); } if reliefs.iter().any(Option::is_none) { return Err("воздушная часть: объявленная версия рельефа не записана".into()); } let mut seen_drones: std::collections::HashSet = drones.keys().copied().collect(); for (_, d) in &queue { if !seen_drones.insert(d.id) { return Err("воздушная часть: дрон записан и в небе, и в очереди".into()); } } 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]; kills.copy_from_slice(&intel[..ew::SECTORS]); hits.copy_from_slice(&intel[ew::SECTORS..]); Ok(Some(AirSave { tick, job_next, kills, hits, contacts: contacts.into_values().collect(), drones: drones.into_values().collect(), queue, jobs, known_relief: global.and_then(|g| reliefs[g].clone()), recon, })) } /// Puts a checked air section back: the drones, the launch queue, the jobs (with the picture and /// relief of each version) and the contacts. Stale jobs are cancelled, the queue is bounded, and a /// job whose drone, aim or unit no longer stands is dropped — a restored job is never a ghost. /// The live air state is replaced, never merged: what the sky held before the load goes. pub fn restore_air(&mut self, save: AirSave) -> u32 { self.tick = save.tick; // New jobs must not reuse an id a restored job already holds. let highest = save.jobs.iter().map(|j| j.id).max().unwrap_or(0); self.job_next = save.job_next.max(1).max(highest.saturating_add(1)); self.intel = ew::Intel::restore(save.contacts.clone(), save.kills, save.hits); 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). let mut by_version: HashMap>> = HashMap::new(); for rec in save.jobs { let known = by_version.entry(rec.version).or_insert_with(|| { let picture: Vec = save .contacts .iter() .filter(|c| c.tick <= rec.version || c.id == rec.unit) .copied() .collect(); std::sync::Arc::new(picture) }); let job = ew::RouteJob::restored(rec.id, rec.drone, rec.aim, rec.unit, rec.version, rec.intent, std::sync::Arc::clone(known), rec.relief); self.retargets.push_back(job); } // Jobs the saved picture no longer stands behind, and anything past the bound, go now. self.prune_air() } } /// One drone's line (after its word and, for the queue, its launch tick). Returns the drone and the /// number of words the body took. fn parse_drone(l: &Line, first: usize) -> Result<(Drone, usize), String> { let id = l.int(first, "номер дрона", 1, 1 << 30)? as u32; let kind = DroneKind::from_key(l.word(first + 1, "тип дрона")?).ok_or_else(|| l.bad("тип дрона", "неизвестный тип"))?; let pos = DVec3::new(l.num(first + 2, "дрон X")?, l.num(first + 3, "дрон Y")?, l.num(first + 4, "дрон Z")?); let vel = DVec3::new(l.num(first + 5, "скорость X")?, l.num(first + 6, "скорость Y")?, l.num(first + 7, "скорость Z")?); let target = DVec3::new(l.num(first + 8, "цель X")?, l.num(first + 9, "цель Y")?, l.num(first + 10, "цель Z")?); let flight = flight_of(l.word(first + 11, "полёт")?).ok_or_else(|| l.bad("полёт", "cruise, dive, ballistic или falling"))?; let intent = intent_of(l.word(first + 12, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react или replace"))?; let unit = l.int(first + 13, "юнит намерения", 0, 1 << 30)? as u32; let since = l.int(first + 14, "такт выбора цели", 0, 1 << 40)? as u64; let switches = l.int(first + 15, "переключения", 0, u16::MAX as i64)? as u16; let conf = match l.word(first + 16, "уверенность")? { "-" => None, key => Some(ew::Confidence::from_key(key).ok_or_else(|| l.bad("уверенность", "doubtful, probable или confirmed"))?), }; let err = DVec3::new(l.num(first + 17, "ошибка X")?, l.num(first + 18, "ошибка Y")?, l.num(first + 19, "ошибка Z")?); let age = l.int(first + 20, "возраст", 0, 1 << 30)? as u32; let engaged = l.int(first + 21, "обстрелян", 0, 1 << 20)? as u32; let sector = l.int(first + 22, "сектор", 0, ew::SECTORS as i64)? as u8; let low = l.flag(first + 23, "низко")?; let jammed = l.flag(first + 24, "подавлен")?; let smart = l.flag(first + 25, "умный")?; let hold = l.int(first + 26, "задержка", 0, u16::MAX as i64)? as u16; let best = match l.word(first + 27, "лучшее приближение")? { "-" => f64::INFINITY, _ => l.num(first + 27, "лучшее приближение")?, }; let pat = l.int(first + 28, "такт приближения", 0, 1 << 30)? as u32; let proute = match l.word(first + 29, "точек приближения")? { "-" => usize::MAX, _ => l.count(first + 29, "точек приближения", MAX_ROUTE)?, }; let mut at = first + 30; let mut route = Vec::new(); if l.word(at, "маршрут")? != "-" { let n = l.count(at, "точек маршрута", MAX_ROUTE)?; at += 1; for _ in 0..n { route.push(DVec3::new(l.num(at, "маршрут X")?, l.num(at + 1, "маршрут Y")?, l.num(at + 2, "маршрут Z")?)); at += 3; } } else { at += 1; } let drone = Drone { id, kind, pos, vel, target, flight, roll: 0.0, spin: 0.0, age, engaged, route, low, jammed, sector, smart, nav: Nav::default(), err, intent, aim: ew::Aim { unit, since, switches, confidence: conf }, hold, pace: Pace { best, at: pat, route: proute }, }; Ok((drone, at)) } /// The jobs' priorities and intents as the report words them (tests and diagnostics). #[cfg(test)] impl Sim { pub(super) fn pending_intents(&self) -> Vec<(u32, ew::Intent)> { self.retargets.iter().map(|j| (j.id, j.intent)).collect() } } #[cfg(test)] mod durable_tests { use super::*; fn contact(id: u32, kind: SamKind, at: DVec3, tick: u64, seen: ew::Seen, launches: u16) -> ew::Contact { ew::Contact { id, kind, at, tick, seen, emission: Some(tick), destroyed: None, launches } } /// A small force, a few known contacts and a relief version, as a smart raid leaves them. fn raid_state(seed: u64) -> Sim { let mut sim = Sim::new(seed); let grid = raid::Grid { min: DVec3::new(-1024.0, 0.0, -1024.0), cell: 32.0, size: 64 }; let mut heights = vec![71.0f32; (grid.size * grid.size) as usize]; for i in 0..8 { heights[(i * grid.size + 3) as usize] = f32::NAN; } sim.known_relief = Some(std::sync::Arc::new(ew::KnownRelief::new(grid, heights))); let mut ids = Vec::new(); for (k, kind) in [SamKind::S400, SamKind::Radar, SamKind::Ew].into_iter().enumerate() { let id = sim.id(); let at = DVec3::new(-400.0 + k as f64 * 400.0, 70.0, 0.0); let c = contact(id, kind, at, 10, if kind == SamKind::Ew { ew::Seen::Jamming } else { ew::Seen::Emission }, k as u16); sim.intel = ew::Intel::restore([c].to_vec(), [0; ew::SECTORS], [0; ew::SECTORS]); ids.push(id); } sim.intel = ew::Intel::restore( ids.iter().enumerate().map(|(k, id)| contact(*id, [SamKind::S400, SamKind::Radar, SamKind::Ew][k], DVec3::new(-400.0 + k as f64 * 400.0, 70.0, 0.0), 10, ew::Seen::Emission, k as u16)).collect(), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], ); sim.tick = 120; sim.job_next = 7; // One drone in the air with a route and an aim, one still on the ground. let mut flying = sim.make_drone(DroneKind::Kh22, DVec3::new(-900.0, 130.0, -300.0), DVec3::X, DVec3::new(-400.0, 70.0, 0.0)); flying.smart = true; flying.intent = ew::Intent::React; flying.aim = ew::Aim::unit(ids[0], 100, ew::Confidence::Confirmed); flying.target = DVec3::new(-400.0, 70.0, 0.0) + flying.err; flying.route = vec![DVec3::new(-900.0, 70.0, -300.0), DVec3::new(-600.0, 70.0, -100.0), DVec3::new(-400.0, 70.0, 0.0)]; flying.low = true; flying.jammed = true; flying.sector = 5; flying.age = 77; sim.drones.push(flying); let mut queued = sim.make_drone(DroneKind::Geran3, DVec3::new(-1000.0, 90.0, 200.0), DVec3::X, DVec3::new(400.0, 70.0, 0.0)); queued.smart = true; queued.intent = ew::Intent::Sead; queued.aim = ew::Aim::unit(ids[1], 110, ew::Confidence::Probable); queued.route = vec![DVec3::new(-1000.0, 70.0, 200.0), DVec3::new(400.0, 70.0, 0.0)]; let queued_id = queued.id; sim.queue.push((300, queued)); // Two pending jobs: one of the plan, one a replacement, both with their own version. let job = |id, drone, aim, unit, version, intent| { ew::RouteJob::restored(id, drone, aim, unit, version, intent, std::sync::Arc::new(sim.intel.contacts().values().copied().collect()), sim.known_relief.clone()) }; sim.retargets.push_back(job(5, sim.drones[0].id, sim.drones[0].target, ids[0], 100, ew::Intent::React)); let queued_target = sim.queue[0].1.target; sim.retargets.push_back(job(6, queued_id, queued_target, ids[1], 120, ew::Intent::Replace)); sim } #[test] fn the_air_state_round_trips_every_job_field() { let sim = raid_state(71); let text = sim.air_text().expect("a raid state has something to keep"); let save = Sim::parse_air(&text).expect("the written section must read back").expect("the section is there"); let mut back = Sim::new(1); back.restore_air(save); assert_eq!(back.tick, sim.tick); assert_eq!(back.job_next, sim.job_next); assert_eq!(back.intel.sectors(), sim.intel.sectors()); assert_eq!(back.intel.contacts().len(), sim.intel.contacts().len()); for (id, c) in sim.intel.contacts() { let b = back.intel.contacts().get(id).expect("a contact was lost"); assert_eq!(b.kind, c.kind); assert!((b.at.distance(c.at)).abs() < 0.02 && b.tick == c.tick && b.seen == c.seen && b.launches == c.launches); } assert_eq!(back.drones.len(), 1); let (a, b) = (&sim.drones[0], &back.drones[0]); assert_eq!((a.id, a.kind, a.smart, a.intent, a.sector, a.age, a.low, a.jammed), (b.id, b.kind, b.smart, b.intent, b.sector, b.age, b.low, b.jammed)); assert_eq!((a.aim.unit, a.aim.since, a.aim.switches, a.aim.confidence), (b.aim.unit, b.aim.since, b.aim.switches, b.aim.confidence)); assert!(a.pos.distance(b.pos) < 0.02 && a.target.distance(b.target) < 0.02 && a.vel.distance(b.vel) < 0.02); assert_eq!(a.route.len(), b.route.len()); assert!(a.route.iter().zip(&b.route).all(|(x, y)| x.distance(*y) < 0.02)); assert_eq!(back.queue.len(), 1); assert_eq!(back.queue[0].0, 300); let (qa, qb) = (&sim.queue[0].1, &back.queue[0].1); assert_eq!((qa.id, qa.intent, qa.aim.unit), (qb.id, qb.intent, qb.aim.unit)); assert!(qa.route.iter().zip(&qb.route).all(|(x, y)| x.distance(*y) < 0.02)); // The jobs keep their ids, aims, units, versions, priorities and intents; so do their pictures // (the same version shares one) and the land they plan over. assert_eq!(back.retargets.len(), 2); for (j, b) in sim.retargets.iter().zip(&back.retargets) { assert_eq!((j.id, j.drone, j.unit, j.version, j.priority(), j.intent), (b.id, b.drone, b.unit, b.version, b.priority(), b.intent)); assert!(j.aim.distance(b.aim) < 0.02); assert_eq!(j.relief.is_some(), b.relief.is_some()); } let (ra, rb) = (sim.known_relief.as_ref().unwrap(), back.known_relief.as_ref().unwrap()); assert_eq!(ra.heights().len(), rb.heights().len()); assert!(ra.heights().iter().zip(rb.heights()).all(|(x, y)| (x.is_nan() && y.is_nan()) || x == y)); // Nothing is written for an empty sky. assert!(Sim::new(3).air_text().is_none()); } /// 40 smart drones, one adaptive tick, a bounded number of aims and jobs: the state a save is /// taken in while routes are still being worked out. fn pending_raid(seed: u64) -> Sim { let mut sim = Sim::new(seed); let mut contacts = Vec::new(); for k in 0..8 { let id = sim.id(); contacts.push(contact(id, SamKind::S400, DVec3::new(-560.0 + k as f64 * 160.0, 70.0, -320.0), 0, ew::Seen::Emission, 0)); } sim.intel = ew::Intel::restore(contacts, [0; ew::SECTORS], [0; ew::SECTORS]); for i in 0..40 { let from = DVec3::new(-1800.0, 100.0, -800.0 + i as f64 * 40.0); let mut d = sim.make_drone(DroneKind::Kh22, from, DVec3::X, DVec3::new(1800.0, 70.0, 1800.0)); d.smart = true; d.route = vec![from, DVec3::new(1800.0, 70.0, 1800.0)]; sim.queue.push((0, d)); } sim.tick = 40; sim.adapt(); sim } #[test] fn a_pending_route_continues_after_a_save_and_a_load() { let mut original = pending_raid(73); assert!(!original.retargets.is_empty(), "the test no longer saves mid-queue"); let text = original.air_text().expect("a queued raid must be durable"); let mut restored = Sim::new(73); restored.restore_air(Sim::parse_air(&text).unwrap().unwrap()); assert_eq!(restored.retargets.len(), original.retargets.len(), "the pending jobs did not survive the save"); assert_eq!(restored.retarget_route_state(), original.retarget_route_state(), "the restored jobs differ from the saved ones"); // Both go on: the same adaptive ticks, the same jobs finished, the same routes. for _ in 0..400 { original.tick += 1; restored.tick += 1; original.adapt(); restored.adapt(); assert_eq!(restored.retarget_route_state(), original.retarget_route_state(), "the restored queue drifted"); if original.retargets.is_empty() && restored.retargets.is_empty() && original.queue.iter().all(|(_, d)| d.aim.unit != 0) { break; } } assert!(original.retargets.is_empty() && restored.retargets.is_empty(), "the restored queue never finished"); // Every drone of the restored raid has a real route, and every aim it was given is one it planned. assert!(restored.queue.iter().all(|(_, d)| !d.route.is_empty() && d.aim.unit != 0)); assert!(restored.queue.iter().all(|(_, d)| d.route.last().is_some_and(|p| p.distance(d.target) < 1e-6))); } // #127: the section has a byte bound of its own. A raid with more (and longer-routed) drones than a // save can hold keeps as many as fit, and every job it writes belongs to a drone that was written. #[test] fn the_section_stays_inside_its_byte_bound() { let mut sim = Sim::new(101); for i in 0..600 { let from = DVec3::new(-2000.0 + i as f64, 120.0, 0.0); let mut d = sim.make_drone(DroneKind::Kh22, from, DVec3::X, DVec3::new(2000.0, 70.0, 0.0)); d.smart = true; d.route = (0..200).map(|k| DVec3::new(-2000.0 + k as f64 * 20.0, 70.0, 0.0)).collect(); sim.drones.push(d); } let text = sim.air_text().expect("a sky full of drones is durable"); assert!(text.len() <= MAX_BYTES, "the section grew to {} bytes", text.len()); let save = Sim::parse_air(&text).expect("a bounded section must read back").unwrap(); assert!(save.drones.len() <= MAX_DRONES); assert!(save.drones.len() > 100, "the bound left almost nothing"); } #[test] fn stale_ghost_and_duplicate_jobs_are_cancelled() { let mut sim = pending_raid(79); let kept = sim.retargets.len(); let some = sim.retargets[0].clone(); // A job for a drone that is not here. sim.retargets.push_back(ew::RouteJob::restored(900, 999_999, DVec3::ZERO, 0, sim.tick, ew::Intent::Plan, std::sync::Arc::new(Vec::new()), None)); // A job whose aim is no longer its drone's. let mut stale = some.clone(); stale.id = 901; stale.aim += DVec3::X * 40.0; sim.retargets.push_back(stale); // An older duplicate for a drone that already has a newer job. let mut older = some.clone(); older.id = 902; older.version = sim.tick.saturating_sub(1); sim.retargets.push_back(older); // A job older than the TTL. let mut old = sim.retargets[0].clone(); old.id = 903; old.version = sim.tick.saturating_sub(ew::JOB_TTL + 1); sim.retargets.push_back(old); let cancelled = sim.prune_air(); assert_eq!(cancelled, 4, "the stale, ghost, duplicate and old jobs were not all cancelled"); assert_eq!(sim.retargets.len(), kept); assert!(sim.retargets.iter().all(|j| j.id < 900)); } #[test] fn a_job_for_a_unit_the_picture_lost_is_cancelled_on_load() { let sim = pending_raid(83); let unit = sim.retargets[0].unit; let text = sim.air_text().unwrap(); assert!(sim.intel.contacts().contains_key(&unit)); // Cut the job's unit out of the saved picture (and its count): the job cannot stand behind it. let mut lines: Vec = text.lines().map(str::to_string).collect(); let head = lines.iter().position(|l| l.starts_with("air ")).unwrap(); let mut w: Vec = lines[head].split_whitespace().map(str::to_string).collect(); w[7] = (w[7].parse::().unwrap() - 1).to_string(); lines[head] = w.join(" "); lines.retain(|l| !l.starts_with(&format!("aircontact {unit} "))); let cut = lines.join("\n") + "\n"; let mut restored = Sim::new(83); let cancelled = restored.restore_air(Sim::parse_air(&cut).expect("the cut section is still well formed").unwrap()); assert!(cancelled > 0, "a job for a unit the picture lost was kept"); assert!(restored.retargets.iter().all(|j| j.unit != unit), "the ghost job survived the load"); } #[test] fn a_damaged_air_section_is_refused_with_its_line_and_field() { let sim = raid_state(89); let text = sim.air_text().unwrap(); assert!(Sim::parse_air("sam s400 0 70 0 0\n").unwrap().is_none(), "an older save must read as an empty sky"); let e = Sim::parse_air(&text.replace("air 1 ", "air 2 ")).err().expect("a future version was accepted"); assert!(e.contains("версия"), "{e}"); let e = Sim::parse_air(&format!("{text}airbogus 1\n")).err().expect("a foreign line in the section was accepted"); assert!(e.contains("неизвестная строка"), "{e}"); // A count that does not match the lines is a cut-off file, refused rather than half restored. let cut: String = text.lines().filter(|l| !l.starts_with("airjob ")).map(|l| format!("{l}\n")).collect(); let e = Sim::parse_air(&cut).err().expect("a cut-off section was accepted"); assert!(e.contains("заданий"), "{e}"); // A coordinate that is not a number, and a broken relief run, name their line. let mut lines: Vec = text.lines().map(str::to_string).collect(); let drone = lines.iter().position(|l| l.starts_with("airdrone ")).unwrap(); let mut w: Vec = lines[drone].split_whitespace().map(str::to_string).collect(); w[3] = "NaN".into(); lines[drone] = w.join(" "); let e = Sim::parse_air(&lines.join("\n")).err().expect("a non-finite coordinate was accepted"); assert!(e.contains(&format!("строка {}", drone + 1)) && e.contains("дрон X"), "{e}"); let e = Sim::parse_air(&text.replace("airrelief 0 ", "airrelief 0 x ")).err().expect("a broken relief line was accepted"); assert!(e.contains("рельеф"), "{e}"); } } #[cfg(test)] impl Sim { /// The pending jobs and the routes of their drones, for the save/restore comparison. pub(super) fn retarget_route_state(&self) -> Vec<(u32, u32, u32, u64, u8, i64, Vec<(i64, i64, i64)>)> { self.retargets .iter() .map(|j| { let route = self .queue .iter() .map(|(_, d)| d) .chain(self.drones.iter()) .find(|d| d.id == j.drone) .map(|d| d.route.iter().map(|p| ((p.x * 100.0).round() as i64, (p.y * 100.0).round() as i64, (p.z * 100.0).round() as i64)).collect()) .unwrap_or_default(); let q = |v: f64| (v * 100.0).round() as i64; (j.id, j.drone, j.unit, j.version, j.priority(), q(j.aim.x), route) }) .collect() } }