Add recon flights and partial reports to the smart enemy (#135)

A smart raid may send a small, bounded flight of unarmed Gerbera aircraft
ahead of its strike. They fly physically through zones round the marked
objectives (and revisit a doubtful mark when nothing is unchecked), look
at units inside a zone, and radio home an area, a public category, the
channel, age and quality only after a delay and only while the aircraft
is alive. A sortie lost before its report sends nothing; marks already
delivered stay, and the picture remembers them across raids.

The planner now reads recon marks as well as disclosure contacts. A mark
carries a synthetic id, an area, a category and a radar role only once a
second independent look refines it -- never a real id, SamKind, exact
point, health, magazine or link. Aims are chosen by observed role,
freshness and quality; a fresh modest mark can outrank a stale doubtful
big one, and a hidden unit is in neither list. In-flight recon aims keep
their old area: hidden moves, re-roles and damage do not rewrite a mark.

Bounded assignments, the route-job queue, the original wave objectives
and the no-eternal-pause rule are preserved. Recon aircraft take ids from
their own range, do not spend the strike's combat RNG and are not part of
the strike's replay. Save/load keeps marks, sorties, pending reports and
checked zones. No new models, textures or weapons.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
2026-11-20 22:20:18 +03:00
parent 53fbeced22
commit 245aceb434
6 changed files with 1650 additions and 48 deletions
+281 -3
View File
@@ -9,6 +9,11 @@
//! picture is mixed into a replay: a recording keeps trajectories, and this section is written and
//! read for the live simulation only.
//!
//! Reconnaissance flights and the partial picture they radioed home are part of the same
//! section (#135): their marks (an area, a category and an age, never a unit's truth), the
//! sorties still out with their pending reports, and the zones already checked. A save keeps
//! that memory across raids, and a restored flight finishes the same way.
//!
//! The format is its own versioned section of `state_text` (`air 1 ...`). A save without the section
//! (every save made before #127) loads exactly as before: the layout, and an empty sky. Every value is
//! checked before anything is restored, like [`layout`](crate::layout): a bad line refuses the whole
@@ -25,6 +30,9 @@ const MAX_DRONES: usize = 512;
/// Bytes the section may take before further drones are left out (the host allows 1 MiB a write;
/// the layout and the headroom of the rest of the state stay clear of it).
const MAX_BYTES: usize = 900_000;
/// Bytes the recon block (marks, checked zones, sorties) may take. The drone loop keeps this much
/// room free, so the recon memory never pushes the section past `MAX_BYTES` (#135).
const MAX_RECON_BYTES: usize = 150_000;
/// Route points one drone may have in a save.
const MAX_ROUTE: usize = 512;
/// Contacts (the picture, and a job's picture rebuilt from it) a save may hold.
@@ -32,6 +40,10 @@ const MAX_CONTACTS: usize = 4096;
/// Relief versions a save may hold, and the cells of each.
const MAX_RELIEFS: usize = 8;
const MAX_CELLS: usize = 40_000;
/// Recon marks, checked zones and sorties a save may hold (#135).
const MAX_RECON_MARKS: usize = recon::MAX_MARKS;
const MAX_RECON_CHECKED: usize = recon::MAX_CHECKED;
const MAX_RECON_SORTIES: usize = recon::SORTIES_MAX * 2;
/// What the air section of a save holds, checked as a whole before the scene is touched.
pub struct AirSave {
@@ -45,6 +57,8 @@ pub struct AirSave {
jobs: Vec<JobRec>,
/// The land new retarget jobs take as their version.
known_relief: Option<std::sync::Arc<ew::KnownRelief>>,
/// The enemy's recon flights and the partial picture they radioed home (#135).
recon: recon::Recon,
}
pub(crate) struct JobRec {
@@ -198,6 +212,7 @@ impl Sim {
^ (self.retargets.len() as u64) << 24
^ (self.intel.contacts().len() as u64) << 36
^ (self.job_next as u64) << 48
^ self.recon.mark().rotate_left(12)
}
/// The air section of the state text: `None` when there is nothing to keep (an empty sky and no
@@ -273,7 +288,7 @@ impl Sim {
// job with it (a job whose drone is not saved could never be restored).
let mut body = String::new();
let mut saved: std::collections::HashSet<u32> = std::collections::HashSet::new();
let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() <= MAX_BYTES;
let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() + MAX_RECON_BYTES <= MAX_BYTES;
let mut drone_count = 0usize;
for d in &drones {
let line = d.air_line("airdrone", "");
@@ -296,14 +311,15 @@ impl Sim {
saved.insert(d.id);
queued_count += 1;
}
let units: std::collections::HashSet<u32> = contacts.iter().map(|c| c.id).collect();
// A job's unit may be an exact contact or a recon mark's synthetic id (#135).
let units: std::collections::HashSet<u32> = contacts.iter().map(|c| c.id).chain(self.recon.marks.keys().copied()).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() {
if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() && self.recon.is_empty() {
return None;
}
let head = head.replacen(
@@ -328,6 +344,89 @@ impl Sim {
relief.map_or_else(|| "-".into(), |t| t.to_string())
);
}
// Recon: the marks are memory (survive a new raid), the sorties are the aircraft still
// out, and the zones already reported empty. Everything is bounded, and each line is
// added only while the block stays inside its budget (#135).
if !self.recon.is_empty() {
let room = MAX_RECON_BYTES.min(MAX_BYTES.saturating_sub(text.len() + 96));
let mut recon_body = String::new();
let mut add = |line: &str| -> bool {
if recon_body.len() + line.len() > room {
return false;
}
recon_body.push_str(line);
true
};
let mut marks = 0usize;
for m in self.recon.marks.values().take(MAX_RECON_MARKS) {
let truth = self.recon.truth.get(&m.id).copied().unwrap_or(0);
let line = format!(
"airreconmark {} {} {} {} {} {} {} {} {} {} {} {} {}\n",
m.id,
truth,
coord(m.area.x),
coord(m.area.y),
coord(m.area.z),
coord(m.radius),
m.category.name(),
m.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()),
m.source.name(),
m.quality.name(),
m.observed,
m.reported,
m.looks,
);
if !add(&line) {
break;
}
marks += 1;
}
let mut checked = 0usize;
for ((i, j), t) in self.recon.checked.iter().take(MAX_RECON_CHECKED) {
if !add(&format!("airreconchecked {i} {j} {t}\n")) {
break;
}
checked += 1;
}
let mut sorties = 0usize;
for s in self.recon.sorties.iter().filter(|s| saved.contains(&s.drone)).take(MAX_RECON_SORTIES) {
// A sortie is written whole or not at all: its look and zone lines follow its header.
let mut body = format!(
"airrec {} {} {} {} {} {} {}\n",
s.drone,
s.launched,
s.next,
tick(s.report_at),
s.report_zone.map_or_else(|| "-".into(), |z| z.to_string()),
s.pending.len(),
s.zones.len(),
);
for l in &s.pending {
body += &format!(
"airrecobs {} {} {} {} {} {} {} {} {} {}\n",
l.truth,
coord(l.area.x),
coord(l.area.y),
coord(l.area.z),
coord(l.radius),
l.category.name(),
l.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()),
l.quality.name(),
l.source.name(),
l.observed,
);
}
for z in &s.zones {
body += &format!("airreczone {} {} {} {}\n", coord(z.center.x), coord(z.center.y), coord(z.center.z), coord(z.radius));
}
if !add(&body) {
break;
}
sorties += 1;
}
text += &format!("airrecon {} {} {} {} {}\n", self.recon.next, self.recon.drone_next, marks, sorties, checked);
text += &recon_body;
}
Some(text)
}
@@ -373,6 +472,12 @@ impl Sim {
let mut drones: BTreeMap<u32, Drone> = BTreeMap::new();
let mut queue: Vec<(u64, Drone)> = Vec::new();
let mut jobs: Vec<JobRec> = 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<usize> = None;
let mut recon_expect: Vec<(usize, usize)> = Vec::new();
for (n, w) in &lines {
if w.first() == Some(&"air") {
continue;
@@ -512,6 +617,148 @@ impl Sim {
};
jobs.push(JobRec { id, drone, aim, unit, version, intent, relief });
}
"airrecon" => {
if w.len() != 6 {
return Err(l.bad("разведка", "нужны счётчики отметок и дронов, отметки, разведчики и проверенные зоны"));
}
let next = l.int(1, "счётчик отметок", 0, i64::from(recon::MARK_TOP - recon::ID_BASE - 1))? as u32;
let drone_next = l.int(2, "счётчик дронов", 0, i64::from(recon::DRONE_TOP - recon::DRONE_BASE - 1))? as u32;
let marks = l.count(3, "отметки", MAX_RECON_MARKS)?;
let sorties = l.count(4, "разведчики", MAX_RECON_SORTIES)?;
let checked = l.count(5, "проверенные зоны", MAX_RECON_CHECKED)?;
if recon_head.is_some() {
return Err(l.bad("разведка", "заголовок записан дважды"));
}
recon_head = Some((marks, sorties, checked));
recon.next = next;
recon.drone_next = drone_next;
}
"airreconmark" => {
if w.len() != 14 {
return Err(l.bad("отметка разведки", "нужны id, юнит, место, категория, источник, качество и времена"));
}
let id = l.int(1, "id отметки", 0, i64::from(u32::MAX))? as u32;
if !recon::is_mark(id) {
return Err(l.bad("id отметки", "не в диапазоне отметок"));
}
let truth = l.int(2, "юнит отметки", 0, 1 << 30)? as u32;
let area = DVec3::new(l.num(3, "отметка X")?, l.num(4, "отметка Y")?, l.num(5, "отметка Z")?);
let radius = l.num(6, "радиус отметки")?;
if radius <= 0.0 {
return Err(l.bad("радиус отметки", "должен быть больше нуля"));
}
let category = recon::Category::from_key(l.word(7, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?;
let role = match l.word(8, "роль")? {
"-" => None,
key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?),
};
let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?;
let quality = recon::Quality::from_key(l.word(10, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?;
let observed = l.int(11, "такт наблюдения", 0, tick as i64)? as u64;
let reported = l.int(12, "такт донесения", 0, tick as i64)? as u64;
let looks = l.int(13, "число взглядов", 0, u16::MAX as i64)? as u16;
if recon.marks.contains_key(&id) {
return Err(l.bad("id отметки", "отметка записана дважды"));
}
recon.truth.insert(id, truth);
recon.marks.insert(id, recon::Mark {
id,
area,
radius,
category,
role,
source,
observed,
reported,
quality,
looks,
});
let slot = id.saturating_sub(recon::ID_BASE);
recon.next = recon.next.max(slot);
}
"airreconchecked" => {
if w.len() != 4 {
return Err(l.bad("проверенная зона", "нужны X, Z и такт"));
}
let i = l.int(1, "зона X", -3_000_000, 3_000_000)?;
let j = l.int(2, "зона Z", -3_000_000, 3_000_000)?;
let t = l.int(3, "такт проверки", 0, tick as i64)? as u64;
recon.checked.insert((i, j), t);
}
"airrec" => {
if w.len() != 8 {
return Err(l.bad("разведчик", "нужны дрон, вылет, зона, донесение и счётчики"));
}
let drone = l.int(1, "дрон разведчика", 1, 1 << 30)? as u32;
let launched = l.int(2, "вылет", 0, tick as i64)? as u64;
let next = l.count(3, "следующая зона", 1_000_000)?;
let report_at = l.opt_tick(4, "такт донесения")?;
let report_zone = match l.word(5, "зона донесения")? {
"-" => None,
v => Some(v.parse::<usize>().map_err(|_| l.bad("зона донесения", "не номер"))?),
};
let pending = l.count(6, "ожидающие наблюдения", recon::MAX_OBSERVED)?;
let zones = l.count(7, "зоны разведчика", recon::ZONES_MAX)?;
if recon.sorties.iter().any(|s| s.drone == drone) {
return Err(l.bad("дрон разведчика", "разведчик записан дважды"));
}
recon.sorties.push(recon::Sortie {
drone,
zones: Vec::new(),
next,
launched,
report_at,
report_zone,
pending: Vec::new(),
});
recon_sortie_at = Some(recon.sorties.len() - 1);
recon_expect.push((pending, zones));
}
"airrecobs" => {
if w.len() != 11 {
return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник и такт"));
}
let Some(at) = recon_sortie_at else {
return Err(l.bad("наблюдение разведки", "строка без разведчика"));
};
let (want, _) = recon_expect[at];
if recon.sorties[at].pending.len() >= want {
return Err(l.bad("наблюдение разведки", "наблюдений больше объявленного"));
}
let truth = l.int(1, "юнит наблюдения", 0, 1 << 30)? as u32;
let area = DVec3::new(l.num(2, "наблюдение X")?, l.num(3, "наблюдение Y")?, l.num(4, "наблюдение Z")?);
let radius = l.num(5, "радиус наблюдения")?;
if radius <= 0.0 {
return Err(l.bad("радиус наблюдения", "должен быть больше нуля"));
}
let category = recon::Category::from_key(l.word(6, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?;
let role = match l.word(7, "роль")? {
"-" => None,
key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?),
};
let quality = recon::Quality::from_key(l.word(8, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?;
let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?;
let observed = l.int(10, "такт наблюдения", 0, tick as i64)? as u64;
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed });
}
"airreczone" => {
if w.len() != 5 {
return Err(l.bad("зона разведчика", "нужны X, Y, Z и радиус"));
}
let Some(at) = recon_sortie_at else {
return Err(l.bad("зона разведчика", "строка без разведчика"));
};
let (_, want) = recon_expect[at];
if recon.sorties[at].zones.len() >= want {
return Err(l.bad("зона разведчика", "зон больше объявленного"));
}
let center = DVec3::new(l.num(1, "зона X")?, l.num(2, "зона Y")?, l.num(3, "зона Z")?);
let radius = l.num(4, "радиус зоны")?;
if radius <= 0.0 {
return Err(l.bad("радиус зоны", "должен быть больше нуля"));
}
recon.sorties[at].zones.push(recon::Zone { center, radius });
}
other => return Err(l.bad("строка", &format!("неизвестная строка воздушной части «{other}»"))),
}
}
@@ -540,6 +787,32 @@ impl Sim {
if let Some(g) = global && reliefs[g].is_none() {
return Err("воздушная часть: глобальный рельеф не записан".into());
}
if let Some((marks, sorties, checked)) = recon_head {
if recon.marks.len() != marks {
return Err(format!("воздушная часть: отметок разведки {} вместо {marks}", recon.marks.len()));
}
if recon.sorties.len() != sorties {
return Err(format!("воздушная часть: разведчиков {} вместо {sorties}", recon.sorties.len()));
}
if recon.checked.len() != checked {
return Err(format!("воздушная часть: проверенных зон {} вместо {checked}", recon.checked.len()));
}
} else if !recon.is_empty() {
return Err("воздушная часть: разведка без заголовка airrecon".into());
}
for (i, (pending, zones)) in recon_expect.iter().enumerate() {
if recon.sorties[i].pending.len() != *pending || recon.sorties[i].zones.len() != *zones {
return Err(format!("воздушная часть: разведчик {i} записан не полностью"));
}
if recon.sorties[i].next > recon.sorties[i].zones.len() {
return Err(format!("воздушная часть: разведчик {i} смотрит за пределами зон"));
}
if let Some(z) = recon.sorties[i].report_zone
&& z >= recon.sorties[i].zones.len()
{
return Err(format!("воздушная часть: разведчик {i} доносит из несуществующей зоны"));
}
}
let intel = intel.ok_or("воздушная часть: нет счётчиков секторов")?;
let mut kills = [0u32; ew::SECTORS];
let mut hits = [0u32; ew::SECTORS];
@@ -555,6 +828,7 @@ impl Sim {
queue,
jobs,
known_relief: global.and_then(|g| reliefs[g].clone()),
recon,
}))
}
@@ -571,6 +845,10 @@ impl Sim {
self.known_relief = save.known_relief;
self.drones = save.drones;
self.queue = save.queue;
self.recon = save.recon;
let alive: std::collections::HashSet<u32> = 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).
+198 -31
View File
@@ -19,6 +19,12 @@
//! contact is a plain function of the contact's age, and its idea of a unit's
//! capabilities is the type's published one — a contact says nothing about
//! damage, roles, link health or magazine.
//!
//! A smart raid may also send a few recon aircraft ahead (#135). What they see is a
//! different, coarser kind of knowledge: an area, a public category, the channel that
//! showed it and its age, radioed home only after a delay and only while the aircraft
//! lives. It is kept as a `recon::Mark`, separate from a disclosure `Contact`; its
//! confidence is age alone and a duplicate report does not improve it.
use super::*;
use std::collections::{BTreeMap, VecDeque};
use std::sync::Arc;
@@ -323,6 +329,15 @@ pub(super) const CONTACT_TTL: u64 = 6000;
const CONFIRMED_AGE: u64 = 600;
const PROBABLE_AGE: u64 = 3000;
/// The one source of confidence: a contact's age, in the bands the picture trusts.
pub(super) fn confidence_for_age(age: u64) -> Confidence {
match age {
0..=CONFIRMED_AGE => Confidence::Confirmed,
..=PROBABLE_AGE => Confidence::Probable,
_ => Confidence::Doubtful,
}
}
impl Contact {
pub fn age(&self, now: u64) -> u64 {
now.saturating_sub(self.tick)
@@ -332,11 +347,7 @@ impl Contact {
self.destroyed.is_none() && self.age(now) < CONTACT_TTL
}
pub fn confidence(&self, now: u64) -> Confidence {
match self.age(now) {
0..=CONFIRMED_AGE => Confidence::Confirmed,
..=PROBABLE_AGE => Confidence::Probable,
_ => Confidence::Doubtful,
}
confidence_for_age(self.age(now))
}
/// Whether the enemy believes this unit sees on its own radar (#127). A kind without a
/// sensor never does. A kind with one does while an emission fix of this contact is
@@ -556,6 +567,9 @@ impl Sim {
/// Whether the picture holds a live contact for this unit: what the old revelation log
/// answered at a scan, now one map lookup.
pub(super) fn known_live(&self, id: u32) -> bool {
if recon::is_mark(id) {
return self.recon.live(id, self.tick);
}
self.intel.contacts.get(&id).is_some_and(|c| c.live(self.tick))
}
@@ -578,8 +592,10 @@ impl Sim {
/// the picture killed is a distinct, lower-priority decision.
fn adapt_targets(&mut self) {
self.intel.expire(self.tick);
self.recon.expire(self.tick);
let picture = Arc::new(self.picture_of_defences());
if picture.is_empty() {
let leads = self.recon.leads(self.tick);
if picture.is_empty() && leads.is_empty() {
return;
}
// Every job of this adaptive tick plans over the same relief version, even if another smart
@@ -601,9 +617,17 @@ impl Sim {
if !eligible {
continue;
}
// A recon mark is an area, not a unit: it is kept while the mark lives. A
// hidden move does not move the aim; only a newer report can re-place it (#135).
if recon::is_mark(d.aim.unit) {
if self.recon.live(d.aim.unit, now) {
continue;
}
// The mark aged out: the drone falls through to a fresh lead below.
}
// What it is aiming at in the picture now, if anything (a unit merely moved is still
// aimed where it was seen: a contact is matched by its observed place).
if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) {
else if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) {
// Already aiming at a unit: a fresh disclosure may be worth a switch, under the throttle.
let Some(c) = Self::switch_candidate(&picture, current, d, now) else { continue };
if per_contact.get(&c.id).copied().unwrap_or(0) >= ASSIGN_PER_CONTACT {
@@ -627,13 +651,30 @@ impl Sim {
if assigned >= ASSIGN_PER_TICK {
continue;
}
let Some(c) = Self::fresh_target(&picture, &per_contact, d.kind, n) else { continue };
*per_contact.entry(c.id).or_insert(0) += 1;
let exact = Self::fresh_target(&picture, &per_contact, d.kind, n);
// No disclosure contact to take: a recon mark whose observed role fits this drone,
// best role and freshest first, bounded per mark as any assignment is. Where both
// exist, the better observed role and fresher mark wins; a hidden unit is in neither.
let mark = Self::fresh_recon_target(&leads, &per_contact);
let (at, unit, confidence) = match (exact, mark) {
(Some(c), Some(m)) => {
let exact_rank = Self::exact_rank(&c, now);
if m.priority(now) > exact_rank {
(m.area, m.id, m.confidence(now))
} else {
(c.at, c.id, c.confidence(now))
}
}
(Some(c), None) => (c.at, c.id, c.confidence(now)),
(None, Some(m)) => (m.area, m.id, m.confidence(now)),
(None, None) => continue,
};
*per_contact.entry(unit).or_insert(0) += 1;
assigned += 1;
d.target = c.at + d.err;
d.target = at + d.err;
d.intent = Intent::React;
// A first assignment is not a switch: the aim's clock starts here, the count is kept.
d.aim = Aim { unit: c.id, since: now, switches: d.aim.switches, confidence: Some(c.confidence(now)) };
d.aim = Aim { unit, since: now, switches: d.aim.switches, confidence: Some(confidence) };
if Self::route_plannable(d) {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&picture), relief.clone()));
job_next += 1;
@@ -648,11 +689,14 @@ impl Sim {
// moved is still aimed where seen.
for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart) {
let aim = d.target - d.err;
let aim_gone = self
.intel
.contacts
.values()
.any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick));
let aim_gone = if recon::is_mark(d.aim.unit) {
!self.recon.live(d.aim.unit, self.tick)
} else {
self.intel
.contacts
.values()
.any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick))
};
if !aim_gone {
continue;
}
@@ -663,17 +707,37 @@ impl Sim {
if d.aim.switches >= SWITCH_CAP || assigned >= ASSIGN_PER_TICK {
continue;
}
let next = picture
let exact = picture
.iter()
.filter(|c| !plannable || Self::can_turn_to(d, c.at))
.filter(|c| per_contact.get(&c.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
.min_by(|a, b| a.at.distance(d.pos).total_cmp(&b.at.distance(d.pos)));
if let Some(c) = next {
*per_contact.entry(c.id).or_insert(0) += 1;
.map(|c| (c.at.distance(d.pos), c.id, c.at, c.confidence(now)))
.min_by(|a, b| a.0.total_cmp(&b.0));
let mark = leads
.iter()
.filter(|m| !plannable || Self::can_turn_to(d, m.area))
.filter(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
.map(|m| (m.area.distance(d.pos), m.id, m.area, m.confidence(now), m.priority(now)))
.min_by(|a, b| b.4.cmp(&a.4).then(a.0.total_cmp(&b.0)));
// A confirmed recon mark outranks a doubtful disclosure; an exact contact of equal
// freshness is preferred, because it is a fix rather than an area.
let exact_rank = exact.map(|(_, _, _, c)| match c {
Confidence::Confirmed => 30,
Confidence::Probable => 15,
Confidence::Doubtful => 0,
});
let next = match (exact, mark) {
(Some(_), Some(m)) if m.4 > exact_rank.unwrap_or(0) + 3 => Some((m.0, m.1, m.2, m.3)),
(Some(e), _) => Some(e),
(None, Some(m)) => Some((m.0, m.1, m.2, m.3)),
(None, None) => None,
};
if let Some((_, unit, at, confidence)) = next {
*per_contact.entry(unit).or_insert(0) += 1;
assigned += 1;
d.target = c.at + d.err;
d.target = at + d.err;
d.intent = Intent::Replace;
d.aim = d.aim.replaced(c.id, now, c.confidence(now));
d.aim = d.aim.replaced(unit, now, confidence);
if plannable {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Replace, Arc::clone(&picture), relief.clone()));
job_next += 1;
@@ -716,6 +780,28 @@ impl Sim {
all.get(n % all.len().max(1)).map(|c| **c)
}
/// The rank of an exact disclosure contact: its confidence, what its observed kind is
/// worth, and a small premium for being a fix rather than an area.
fn exact_rank(c: &Contact, now: u64) -> u8 {
let seen = match c.confidence(now) {
Confidence::Confirmed => 30,
Confidence::Probable => 15,
Confidence::Doubtful => 0,
};
seen + recon::Category::of(c.kind).weight() + 3
}
/// The best recon mark a drone not yet sent at a unit may be given: observed role and
/// freshness first (the list is sorted), bounded per mark. A mark's category must be one
/// worth a strike; a support or unknown mark is only navigation interest.
fn fresh_recon_target(leads: &[recon::Mark], per_contact: &HashMap<u32, usize>) -> Option<recon::Mark> {
leads
.iter()
.copied()
.filter(|m| m.category.weight() >= 2)
.find(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
}
/// Whether a fresh disclosure is worth replacing this drone's aim: a contact observed after the
/// aim was chosen, trusted (not `Doubtful`), clearly better placed or better believed, and the
/// throttle (hold time, switch cap) allows it (#127). A route change costs the planner a new
@@ -1009,7 +1095,7 @@ pub struct ContactReport {
#[derive(Clone, Debug, PartialEq)]
pub struct AimReport {
pub drone: u32,
/// The unit aimed at (0: a marked object).
/// The unit aimed at (0: a marked object; a recon mark has a synthetic id).
pub unit: u32,
/// "plan", "sead", "react" or "replace".
pub intent: &'static str,
@@ -1019,6 +1105,43 @@ pub struct AimReport {
pub switches: u16,
/// The confidence of the contact the aim rests on, when it is a unit.
pub confidence: Option<Confidence>,
/// Whether the aim is a recon mark's area rather than a unit contact.
pub recon: bool,
/// A recon mark's priority (observed role, freshness, quality); `None` for a unit contact.
pub priority: Option<u8>,
}
/// A recon mark as the diagnostic reports it (#135): an area, a coarse category, the channel,
/// its age and quality. There is no true place, SamKind, health, magazine, link or real id here.
#[derive(Clone, Debug, PartialEq)]
pub struct ReconReport {
pub id: u32,
pub area: DVec3,
pub radius: f64,
/// "unknown", "radar", "launcher", "gun", "ew" or "support".
pub category: &'static str,
/// A radar's role once a refined look told it.
pub role: Option<&'static str>,
/// "flyby", "emission", "jamming" or "launch".
pub source: &'static str,
pub age: u64,
/// "coarse" or "refined".
pub quality: &'static str,
pub confidence: Confidence,
pub live: bool,
/// What the planner makes of it, in words: observed role and freshness only.
pub priority: u8,
}
/// One recon sortie as the diagnostic reports it (#135).
#[derive(Clone, Debug, PartialEq)]
pub struct ReconSortieReport {
pub drone: u32,
/// "outbound", "looking", "reporting" or "done".
pub phase: &'static str,
pub zones_left: usize,
/// The tick its pending report is due.
pub report_in: Option<u64>,
}
/// A route job the planner has not finished (#127): what it is for, why it is still waiting,
@@ -1052,6 +1175,10 @@ pub struct EnemyPictureReport {
pub pending: Vec<PendingReport>,
/// The planner's work a tick, for the pending queue's budget.
pub work_per_tick: usize,
/// The partial picture recon flights radioed home (#135).
pub recon: Vec<ReconReport>,
/// The recon flights still out.
pub recon_sorties: Vec<ReconSortieReport>,
}
impl Sim {
@@ -1099,13 +1226,18 @@ impl Sim {
.map(|(_, d)| d)
.chain(self.drones.iter())
.filter(|d| d.alive() && d.smart)
.map(|d| AimReport {
drone: d.id,
unit: d.aim.unit,
intent: d.intent.name(),
since: d.aim.since,
switches: d.aim.switches,
confidence: d.aim.confidence,
.map(|d| {
let mark = self.recon.marks.get(&d.aim.unit).filter(|m| m.live(now)).copied();
AimReport {
drone: d.id,
unit: d.aim.unit,
intent: d.intent.name(),
since: d.aim.since,
switches: d.aim.switches,
confidence: d.aim.confidence,
recon: mark.is_some(),
priority: mark.map(|m| m.priority(now)),
}
})
.collect();
let pending = self
@@ -1129,7 +1261,42 @@ impl Sim {
},
})
.collect();
EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK }
let recon = self
.recon
.marks
.values()
.map(|m| ReconReport {
id: m.id,
area: m.area,
radius: m.radius,
category: m.category.name(),
role: m.role.map(|r| r.key()),
source: m.source.name(),
age: m.age(now),
quality: m.quality.name(),
confidence: m.confidence(now),
live: m.live(now),
priority: m.priority(now),
})
.collect();
let recon_sorties = self
.recon
.sorties
.iter()
.map(|s| ReconSortieReport {
drone: s.drone,
phase: if s.report_at.is_some() {
"reporting"
} else if s.next < s.zones.len() {
"outbound"
} else {
"done"
},
zones_left: s.zones.len().saturating_sub(s.next),
report_in: s.report_at.map(|t| t.saturating_sub(now)),
})
.collect();
EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK, recon, recon_sorties }
}
/// What the planner makes of a contact, in words for the diagnostic (#127).
+12
View File
@@ -25,8 +25,10 @@ pub mod record;
mod sight;
mod terrain;
mod ew;
mod recon;
mod durable;
pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport};
pub use recon::{Category, Mark, Quality, Source};
pub mod lights;
mod logistics;
mod orders;
@@ -171,6 +173,11 @@ impl Rng {
pub fn state(&self) -> u64 {
self.0
}
/// Puts the generator back exactly where it was (a recon launch must not spend the
/// strike's combat randomness).
pub(super) fn set_state(&mut self, state: u64) {
self.0 = state;
}
pub fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
@@ -1446,6 +1453,8 @@ pub struct Sim {
pub tally: record::Tally,
/// What the enemy has learned.
intel: ew::Intel,
/// Reconnaissance flights and the partial picture they radioed home (#135).
recon: recon::Recon,
/// Night: guns need light (the mod sets it from the game's clock).
pub night: bool,
/// The long fires at crash and impact points (#52).
@@ -1522,6 +1531,7 @@ impl Sim {
recordings: 0,
tally: record::Tally::default(),
intel: ew::Intel::default(),
recon: recon::Recon::default(),
night: false,
fires: fires::Fires::default(),
day_time: None,
@@ -1625,6 +1635,7 @@ impl Sim {
self.plan = None;
self.retargets.clear();
self.known_relief = None;
self.recon.clear_sorties();
self.wave = None;
// Ammunition still to cook off, flares in the sky.
self.later.clear();
@@ -1672,6 +1683,7 @@ impl Sim {
self.release_queue(ground, out);
self.begin_recording_if_active();
self.step_drones(ground, player, out);
self.step_recon(out);
self.step_later(ground, player, out);
self.step_moves(ground, out);
self.step_supply(out);
+62 -9
View File
@@ -284,6 +284,9 @@ impl Sim {
// read-only while the plan is built, and taking it per drone made a big second order
// quadratic in the force's size (#122); a map of contacts makes it linear in them (#127).
let picture = self.picture_of_defences();
// The partial picture the recon flights have radioed home. It is memory, not the
// force: a mark has an area, a category and an age, never a unit's exact place (#135).
let leads = self.recon.leads(self.tick);
// A smart enemy comes from where its raids got through best.
let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU };
// The raid's sides (1, 2, or 4-5): its launch sites go there (#100).
@@ -312,7 +315,7 @@ impl Sim {
index += 1;
let (target, at_sam) = match job {
Some((at, id)) => (at, Some(id)),
None => self.choose_target(kind, object, order.aim, &picture),
None => self.choose_target(kind, object, order.aim, &picture, &leads),
};
let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0);
let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0;
@@ -323,7 +326,11 @@ impl Sim {
// The plan's own decision, recorded as such (#127): a radar job is SEAD, a unit
// chosen for the raid is the plan's objective, anything else is a marked object.
if let Some(id) = at_sam {
let confidence = picture.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick));
let confidence = picture
.iter()
.find(|c| c.id == id)
.map(|c| c.confidence(self.tick))
.or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick)));
d.intent = if job.is_some() { ew::Intent::Sead } else { ew::Intent::Plan };
d.aim = confidence.map_or_else(|| ew::Aim::point(self.tick), |c| ew::Aim::unit(id, self.tick, c));
} else {
@@ -363,6 +370,11 @@ impl Sim {
waited: 0,
mapped: !smart,
});
// The smart enemy may send a small recon flight ahead of the strike -- physically in
// the air, not a pause: the strike is planned while they fly (#135).
if smart {
self.start_recon(objects, bearing, order.dist, out);
}
// A raid without routes is ready at once.
self.plan_step(None, out);
total
@@ -580,12 +592,25 @@ impl Sim {
/// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid.
/// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile.
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact]) -> Vec<Option<(DVec3, u32)>> {
let mut radars: Vec<(u32, DVec3)> = picture
// Exact disclosure contacts and recon marks of radars, best first. The order is the
// observed role, freshness and quality -- never the id: a hidden station has no id,
// and a big observed radar is worth more than a modest one (#135).
let now = self.tick;
let mut radars: Vec<(u8, u64, u32, DVec3)> = picture
.iter()
.filter(|c| c.kind == SamKind::Radar && c.confidence(self.tick) >= ew::Confidence::Probable)
.map(|c| (c.id, c.at))
.filter(|c| c.kind == SamKind::Radar && c.confidence(now) >= ew::Confidence::Probable)
.map(|c| {
let seen = match c.confidence(now) {
ew::Confidence::Confirmed => 4,
ew::Confidence::Probable => 2,
ew::Confidence::Doubtful => 0,
};
(seen * 10 + 3, c.tick, c.id, c.at)
})
.chain(self.recon.leads(now).into_iter().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area)))
.collect();
radars.sort_by_key(|(id, _)| *id);
radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect();
let flat: Vec<DroneKind> = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect();
let mut jobs = vec![None; flat.len()];
if radars.is_empty() {
@@ -609,8 +634,8 @@ impl Sim {
/// point and the unit's id. The planner has only the picture (#93, #127): what it knows of a
/// unit is the last observation — the place seen then, the type identified then — never where
/// the unit actually is or what it has become since.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact]) -> (DVec3, Option<u32>) {
if picture.is_empty() || kind.spec().decoy || aim == Aim::Objects {
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact], leads: &[recon::Mark]) -> (DVec3, Option<u32>) {
if (picture.is_empty() && leads.is_empty()) || kind.spec().decoy || aim == Aim::Objects {
return (object, None);
}
let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> {
@@ -641,7 +666,15 @@ impl Sim {
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r),
_ => None,
};
choice.map_or((object, None), |(p, id)| (p, Some(id)))
if let Some((p, id)) = choice {
return (p, Some(id));
}
// Nothing disclosed and nothing the kind's usual preference picked: a recon mark
// whose observed role fits is the next best reason to turn a strike off the object.
if let Some(m) = recon_pick(kind, leads, r) {
return (m.area, Some(m.id));
}
(object, None)
}
/// The price of each cell of `grid` for this kind flying low: 1, and much more where a
@@ -935,6 +968,11 @@ const AIR_START_WAIT: u32 = 120;
if !why.is_empty() {
out.messages.push(format!("Неудачи ПВО: {why}"));
}
// What the enemy's recon flights saw: the marks are memory, so the picture may be old (#135).
let marks = self.recon.marks.values().filter(|m| m.live(self.tick)).count();
if marks > 0 {
out.messages.push(format!("Разведка противника: в картине {marks} отметок (возраст и качество — в разборе)"));
}
// What the counter-strikes did to the raid (#101): the launches that never happened.
let cut: u32 = self.strikes.cancelled.iter().map(|c| c.1).sum();
if cut > 0 {
@@ -956,6 +994,21 @@ fn route_length(from: DVec3, route: &[DVec3], to: DVec3) -> f64 {
len
}
/// A recon mark whose observed category fits this kind. The list is already in priority
/// order, so the first fit is the best reason.
fn recon_pick(kind: DroneKind, leads: &[recon::Mark], r: f64) -> Option<recon::Mark> {
use recon::Category as C;
let fits = |c: C| match kind {
DroneKind::Lancet => matches!(c, C::Gun | C::Launcher | C::Ew),
DroneKind::Kh22 | DroneKind::Zircon => matches!(c, C::Radar | C::Launcher | C::Ew),
DroneKind::Iskander | DroneKind::Kinzhal => matches!(c, C::Radar | C::Launcher),
DroneKind::Shahed | DroneKind::Geran3 => matches!(c, C::Radar | C::Launcher | C::Gun | C::Ew),
_ => false,
};
let fits: Vec<&recon::Mark> = leads.iter().filter(|m| fits(m.category)).collect();
fits.get((r * fits.len() as f64) as usize).copied().copied()
}
#[cfg(test)]
mod tests {
use super::*;
File diff suppressed because it is too large Load Diff
+15 -5
View File
@@ -1,8 +1,9 @@
//! Raids are recorded for their replays: every drone's and interceptor's
//! track (a point every other tick, falling wrecks included) and what
//! happened (shot down, by what; hits; systems lost; the Oreshnik's split).
//! A recording starts with the first drone in the sky and ends when the sky
//! has been clear a while; the last few are kept.
//! A recording starts with the first strike drone in the sky and ends when the sky
//! has been clear a while; the last few are kept. A recon aircraft is a role of its own
//! and is not part of the strike's replay (#135).
use super::*;
/// A system's pose at a moment of a recording.
@@ -834,8 +835,11 @@ impl Sim {
}
/// Open before the combat update so transitions on the first active tick are not lost.
/// A recon aircraft neither opens nor holds a strike's recording (#135).
pub(super) fn begin_recording_if_active(&mut self) {
if self.rec.is_none() && (self.drones.iter().any(|d| d.alive()) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) {
if self.rec.is_none()
&& (self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id)) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty())
{
self.recordings += 1;
self.rec = Some(Recording::new(self.recordings, self));
}
@@ -853,7 +857,13 @@ impl Sim {
pub(super) fn record(&mut self) {
// Wrecks still falling (far off they fall a long while) don't keep it going. A counter-strike is a recorded
// object in its own right (#109): it holds the recording open until it lands, whatever the sky is doing.
let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty();
// A recon flight is not part of the strike's replay: it neither opens nor holds a
// recording open. The strike's own drones and interceptors do (#135).
let busy = self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id))
|| !self.missiles.is_empty()
|| !self.queue.is_empty()
|| !self.strikes.flights.is_empty()
|| !self.strikes.pending.is_empty();
self.begin_recording_if_active();
let Some(r) = &mut self.rec else { return };
r.note_tracks(&self.sams);
@@ -867,7 +877,7 @@ impl Sim {
if r.len % STEP == 0 {
let now = r.len;
r.note_sams(&self.sams, now);
for d in &self.drones {
for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) {
r.point(d.id, What::Drone(d.kind), d.pos);
}
for m in &self.missiles {