Give the enemy a structured intent and a durable route queue (#127)
build / mod (push) Failing after 22s
release / windows (push) Failing after 2s

Stage 2 of #127. A smart drone now carries why it is aimed where it is
(Intent: plan, sead, react, replace) apart from the aim bookkeeping
(unit, since, switches, confidence). Assignments are throttled per
adaptive tick and per contact, a fresh disclosure replaces an aim only
after a hold, within a switch cap and when the change is worth a new
route, and a killed aim is replaced as a separate, lower-priority
decision. The queue is bounded and taken by priority (plan > sead >
react > replace); unknown land is no longer free in a replanned route.

The autosave now carries the air state: the drones in flight, the launch
queue, every pending job with its id, aim, unit, version, priority,
intent and relief version, the contacts the jobs were chosen from and
the relief snapshots they plan over. The format is a versioned `air 1`
section; older saves read as before, scenarios do not carry the sky,
stale, ghost and duplicate jobs are cancelled on load, and the section is
bounded (512 drones, 512 route points, 4096 contacts, 8 reliefs, 900 KB).
A periodic save waits while a raid is only being planned.

enemy_picture() now explains targets and pending jobs (aims, aimed_by,
pending_jobs, reason, work_per_tick) in English, and intel_bench records
the queue and intent evidence next to completion, losses and failures.
This commit is contained in:
2026-11-06 18:35:09 +03:00
parent 8fc10c07a1
commit e7934a1ebb
14 changed files with 2411 additions and 89 deletions
+941
View File
@@ -0,0 +1,941 @@
//! 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.
//!
//! 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;
/// 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;
/// 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<ew::Contact>,
drones: Vec<Drone>,
queue: Vec<(u64, Drone)>,
jobs: Vec<JobRec>,
/// The land new retarget jobs take as their version.
known_relief: Option<std::sync::Arc<ew::KnownRelief>>,
}
pub(crate) struct JobRec {
id: u32,
drone: u32,
aim: DVec3,
unit: u32,
version: u64,
intent: ew::Intent,
relief: Option<std::sync::Arc<ew::KnownRelief>>,
}
/// 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<usize, String> {
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<i64, String> {
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<bool, String> {
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<f64, String> {
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<Option<u64>, 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<run>` for unknown land, `<height>x<run>` for known.
fn run_token(height: Option<i32>, run: usize) -> String {
height.map_or_else(|| format!("u{run}"), |h| format!("{h}x{run}"))
}
fn tick(x: Option<u64>) -> String {
x.map_or_else(|| "-".into(), |v| v.to_string())
}
fn intent_of(key: &str) -> Option<ew::Intent> {
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> {
[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
}
/// 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<String> {
// What the parser accepts is what is written: a save this build writes always reads back.
let contacts: Vec<ew::Contact> = 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<std::sync::Arc<ew::KnownRelief>> = Vec::new();
let token_of = |r: &std::sync::Arc<ew::KnownRelief>, reliefs: &mut Vec<std::sync::Arc<ew::KnownRelief>>| -> Option<usize> {
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<Option<usize>> = 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<i32>, 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<u32> = std::collections::HashSet::new();
let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() <= 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;
}
let units: std::collections::HashSet<u32> = contacts.iter().map(|c| c.id).collect();
let jobs: Vec<(&ew::RouteJob, Option<usize>)> = 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() {
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())
);
}
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<Option<AirSave>, String> {
let lines: Vec<(usize, Vec<&str>)> = text
.lines()
.enumerate()
.map(|(n, raw)| (n + 1, raw.split_whitespace().collect::<Vec<_>>()))
.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<usize> = None;
let mut reliefs: Vec<Option<std::sync::Arc<ew::KnownRelief>>> = vec![None; n_reliefs];
let mut contacts: BTreeMap<u32, ew::Contact> = BTreeMap::new();
let mut drones: BTreeMap<u32, Drone> = BTreeMap::new();
let mut queue: Vec<(u64, Drone)> = Vec::new();
let mut jobs: Vec<JobRec> = 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<run>` is unknown land, `<height>x<run>` 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::<usize>().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 });
}
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<u32> = 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());
}
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()),
}))
}
/// 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.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<u64, std::sync::Arc<Vec<ew::Contact>>> = HashMap::new();
for rec in save.jobs {
let known = by_version.entry(rec.version).or_insert_with(|| {
let picture: Vec<ew::Contact> = 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<String> = text.lines().map(str::to_string).collect();
let head = lines.iter().position(|l| l.starts_with("air ")).unwrap();
let mut w: Vec<String> = lines[head].split_whitespace().map(str::to_string).collect();
w[7] = (w[7].parse::<usize>().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<String> = text.lines().map(str::to_string).collect();
let drone = lines.iter().position(|l| l.starts_with("airdrone ")).unwrap();
let mut w: Vec<String> = 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()
}
}
+780 -56
View File
File diff suppressed because it is too large Load Diff
+26 -1
View File
@@ -25,7 +25,8 @@ pub mod record;
mod sight;
mod terrain;
mod ew;
pub use ew::{Confidence, ContactReport, EnemyPictureReport};
mod durable;
pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport};
pub mod lights;
mod logistics;
mod orders;
@@ -732,6 +733,13 @@ pub struct Drone {
/// Its navigation error (#65): `target` is the nominal aim plus this, kept apart so a new aim (a retarget)
/// keeps the error this airframe was born with instead of becoming exact.
err: DVec3,
/// Why it is aimed where it is (#127): the structured intent a smart drone carries — the plan's
/// objective, a SEAD reaction to a disclosure, or a replacement after the picture killed the aim.
/// Kept apart from any random re-pick, reported by the diagnostics, and saved with the drone.
intent: ew::Intent,
/// What it aims at and how firmly (#127): the unit, when the aim was chosen and how often it has
/// changed. The switch throttle and the priority of its route job read this.
aim: ew::Aim,
/// Ticks held at the edge of blocks the game has not told of (#61); reset by a clear step.
hold: u16,
/// Its progress towards the aim: a flight that stops getting nearer runs out of fuel (see `Pace`).
@@ -792,6 +800,17 @@ impl Drone {
pub fn alive(&self) -> bool {
self.flight != Flight::Falling
}
/// Why it is aimed where it is (#127), and how often that aim has been changed.
pub fn intent(&self) -> ew::Intent {
self.intent
}
pub fn aim_switches(&self) -> u16 {
self.aim.switches
}
/// Sent by the smart enemy: it may be turned on what gives itself away.
pub fn smart(&self) -> bool {
self.smart
}
/// How much a system wants to shoot it: fast and heavy first, decoys look real.
fn threat(&self, from: DVec3) -> f64 {
self.threat_at(from, self.pos)
@@ -1340,6 +1359,9 @@ pub struct Sim {
/// The known land of the last smart raid's plan: its grid and cell heights (NaN unknown). New retarget
/// jobs take this `Arc` as their version; a later plan replaces the pointer, not a pending job's map (#127).
known_relief: Option<Arc<ew::KnownRelief>>,
/// The next route job's id (#127). A job keeps its id when it is replaced in place; the save writes
/// the counter so restored jobs keep theirs.
job_next: u32,
/// The vehicles' ground routes, and the jobs the trucks found out of reach (#94).
routes: route::Routes,
/// Each marked object's health, 0 to 100 (`targets`' order).
@@ -1421,6 +1443,7 @@ impl Sim {
plan: None,
retargets: VecDeque::new(),
known_relief: None,
job_next: 1,
routes: Default::default(),
target_health: Vec::new(),
wave: None,
@@ -1978,6 +2001,8 @@ impl Sim {
smart: false,
nav: Nav::default(),
err: DVec3::ZERO,
intent: ew::Intent::Plan,
aim: ew::Aim::point(0),
hold: 0,
pace: Pace::default(),
});
+32 -1
View File
@@ -164,11 +164,14 @@ impl Grid {
}
/// The land a route crosses: its height under each cell (NaN unknown), the climb a kind holds for long
/// (rise a block), and the height above which the land forces a drone up from its low altitude.
/// (rise a block), and the height above which the land forces a drone up from its low altitude. Unknown
/// land costs `unknown` per cell on top of the open ground: zero for a plan routed over land it is still
/// mapping, more than free for a replanned retarget (#127).
pub(super) struct Relief<'a> {
pub heights: &'a [f32],
pub slope: f32,
pub floor: f32,
pub unknown: f32,
}
/// [`plan_route`] over relief: a climb steeper than the kind holds is dear (a cliff or a ridge it would have to
@@ -215,6 +218,9 @@ pub(super) fn plan_route_on(grid: &Grid, prices: &[f32], relief: Option<&Relief>
price += (slope - r.slope) * 20.0 * len;
}
}
} else if r.unknown > 0.0 {
// Unmapped land is not free: the route prefers what the plan actually knew.
price += len * r.unknown;
}
}
let ng = g + price;
@@ -314,6 +320,16 @@ impl Sim {
// Where it starts is provisional: the site's pad, once the site is placed.
let from = centre + DVec3::new(a.sin() * dist, height + self.rng.s() * 6.0, a.cos() * dist);
let mut d = self.make_drone(kind, from, horizontal(aim - from), aim);
// 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));
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 {
d.intent = ew::Intent::Plan;
d.aim = ew::Aim::point(self.tick);
}
let range = spec.ballistic.map_or(order.dist, |far| far.max(order.dist));
let want = sites::want_index(&mut wants, centre, side, a, sites::SiteClass::of(kind), range, order.dist.max(120.0));
let pad = wants[want].jobs;
@@ -445,6 +461,7 @@ impl Sim {
heights: &plan.heights,
slope: (kind.climb_pitch().tan() * 0.5) as f32,
floor: (aim.y + spec.clearance) as f32,
unknown: 0.0,
});
let (r, cost) = plan_route_on(&plan.grid, &plan.prices[&kind], relief.as_ref(), from, aim);
work += cost;
@@ -505,6 +522,18 @@ impl Sim {
self.plan.is_some()
}
/// The plan's drones and the structured intent each was given (#127; tests and diagnostics).
#[cfg(test)]
pub(super) fn planned_intents(&self) -> Vec<(u32, ew::Intent)> {
self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.id, i.d.intent)).collect()).unwrap_or_default()
}
/// The plan's unit aims and their intent: the same list, keyed by what the drone goes for.
#[cfg(test)]
pub(super) fn planned_aims(&self) -> Vec<(u32, ew::Intent)> {
self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.aim.unit, i.d.intent)).collect()).unwrap_or_default()
}
/// A drone ready to fly from `from`, not yet in the sky.
pub(super) fn make_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) -> Drone {
let id = self.id();
@@ -539,6 +568,8 @@ impl Sim {
smart: false,
nav: Nav::default(),
err,
intent: ew::Intent::Plan,
aim: ew::Aim::point(0),
hold: 0,
pace: Pace::default(),
}
+24 -13
View File
@@ -205,35 +205,45 @@ fn mass_retarget_finishes_its_route_jobs_over_the_budget() {
let pending = sim.retarget_ids();
assert!(!pending.is_empty(), "the budget planned all 40 routes: the test no longer covers the queue");
assert_eq!(pending.len(), pending.iter().collect::<std::collections::HashSet<_>>().len(), "duplicate jobs");
assert!(pending.contains(&empty), "a drone left with no route by the budget was dropped from the queue");
// Assignments are throttled too: one adaptive tick hands out a bounded number of new aims,
// and the rest of the force is sent on the following adaptive ticks (#127).
assert!(pending.len() <= super::ew::ASSIGN_PER_TICK, "one adaptive tick assigned {} drones", pending.len());
for id in &pending {
let d = &sim.queue.iter().find(|(_, d)| d.id == *id).unwrap().1;
assert_eq!(&d.route, old.get(id).unwrap(), "an old safe route was replaced before the new one was ready");
}
assert!(
sim.queue.iter().all(|(_, d)| !d.route.is_empty() || d.id == empty),
"a route was wiped by the budget"
);
let mut left = pending.len();
for _ in 0..80 {
for _ in 0..400 {
sim.tick += 1;
sim.adapt();
assert!(sim.retargets.len() < left, "a budget tick made no progress: {left} jobs left");
left = sim.retargets.len();
if sim.tick % 40 == 0 {
// A new adaptive tick: more drones may be sent, still within the throttle.
let now = sim.retarget_ids().len();
assert!(now <= left + super::ew::ASSIGN_PER_TICK, "an adaptive tick assigned more than {} drones", super::ew::ASSIGN_PER_TICK);
left = now;
} else if left > 0 {
assert!(sim.retargets.len() < left, "a budget tick made no progress: {left} jobs left");
left = sim.retargets.len();
}
let still = sim.retarget_ids();
assert!(
sim.queue.iter().all(|(_, d)| !d.route.is_empty() || still.contains(&d.id)),
// A drone the throttle has not sent yet is still on its own plan's route or has none to lose;
// one already sent at a unit whose route is empty must have a job that will fill it.
sim.queue.iter().all(|(_, d)| !d.route.is_empty() || still.contains(&d.id) || d.aim.unit == 0),
"a route is still empty with no job left to fill it"
);
if left == 0 {
break;
}
}
assert_eq!(left, 0, "route jobs were never finished");
assert_eq!(sim.retargets.len(), 0, "route jobs were never finished");
// No drone is left with an empty route for ever, and every new route ends at its aim. The drone
// that started with no route at all got one too: its job waited for the budget, not for ever.
for (_, d) in &sim.queue {
assert!(!d.route.is_empty(), "a drone was left with no route");
assert!(d.route.last().is_some_and(|p| p.distance(d.target) < 1e-6), "the new route does not end at the new aim");
assert!(d.aim.unit != 0, "a drone was never sent at a unit");
}
let empty = sim.queue.iter().find(|(_, d)| d.id == empty).unwrap().1.clone();
assert!(!empty.route.is_empty(), "the drone that started with no route never got one");
}
#[test]
@@ -370,6 +380,7 @@ fn same_relief_different_known_snapshots_do_not_share_prices_or_routes() {
seen: super::ew::Seen::Emission,
emission: Some(0),
destroyed: None,
launches: 0,
};
let known_all = std::sync::Arc::new(vec![contact(threat, threat_at), contact(target, aim)]);
let known_target = std::sync::Arc::new(vec![contact(target, aim)]);