Files
airdef/airdef-mod/src/sim/ew.rs
T
chexit aa842d8a1f Fix raid gameplay, finite ammunition and truck routing
Check launch terrain, reserve ballistic targets for marked objectives, tune in-game reach and fallback fire, and support bounded terrain work on supply routes.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-25 18:53:17 +03:00

2283 lines
107 KiB
Rust

//! Electronic warfare, and what the enemy learns.
//!
//! An EW station jams the satellite navigation of the drones and cruise
//! missiles near it (ballistic missiles and the Lancet's optics don't care):
//! they lose their route and drift off their aim. It runs only a short while
//! before its transmitter overheats, and while it transmits it gives itself
//! away. The enemy keeps what it learns — which systems fired and which
//! stations jammed (its next drones go for them), and from which bearings its
//! raids were shot down or got through (its next raid comes from the best).
//!
//! What it learns is a picture, not the world (#127). Every unit it knows of
//! is a *contact*: the last observation a disclosure channel made of it —
//! a launch, a radar emission, a jamming transmission, or its fate watched by
//! the enemy's own munition. A contact is written only at the moment of the
//! observation and is never refreshed from what the unit does while
//! unobserved: a moved, switched-off, re-roled or destroyed unit stays in the
//! picture exactly as seen until something discloses it again. Between
//! observations the planner works from the picture alone; its confidence in a
//! 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;
/// Why a smart drone is aimed where it is (#127). The reason is fixed when the aim is set and
/// kept apart from the aim itself: the plan's own objective, a SEAD job the plan chose, a
/// reaction to a fresh disclosure and a replacement after the picture killed the aim are
/// different decisions, with different priorities and different room to switch.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Intent {
/// The raid's own objective: the marked object, or the unit the plan sent it at when it was ordered.
Plan,
/// Planned SEAD: a radar the plan picked when the raid was ordered.
Sead,
/// A reaction to a disclosure: a station showed itself (jamming, an emission fix, a launch)
/// after the raid was in the air, and a drone was turned onto it.
React,
/// A replacement: the picture watched the previous aim die or forgot it, and this contact
/// is the nearest live one.
Replace,
/// A bounded refresh (#149): a recon report arrived while the raid's drones were still
/// waiting to launch, and the plan's own picks were re-aimed once on the fresh snapshot.
Refresh,
}
impl Intent {
pub fn name(self) -> &'static str {
match self {
Self::Plan => "plan",
Self::Sead => "sead",
Self::React => "react",
Self::Replace => "replace",
Self::Refresh => "refresh",
}
}
/// The key a save writes and reads.
pub(super) fn key(self) -> &'static str {
self.name()
}
pub(super) fn from_key(key: &str) -> Option<Self> {
[Self::Plan, Self::Sead, Self::React, Self::Replace, Self::Refresh].into_iter().find(|i| i.key() == key)
}
/// The planner's share of a tick this aim is worth: a planned SEAD job and a reaction to a
/// disclosure are finished before a replacement, and the plan's own objective before both (#127).
/// A refresh of the unreleased portion is worth a SEAD job's share (#149).
pub(super) fn priority(self) -> u8 {
match self {
Self::Plan => 3,
Self::Sead | Self::Refresh => 2,
Self::React => 1,
Self::Replace => 0,
}
}
}
/// What a smart drone aims at and how firmly (#127): the unit (0 for a marked object), when the
/// aim was chosen, how many times it has been changed since, and the confidence of the contact it
/// rests on. This is the bookkeeping the switch throttle reads; [`Intent`] is why it aims there.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Aim {
pub(super) unit: u32,
pub(super) since: u64,
pub(super) switches: u16,
pub(super) confidence: Option<Confidence>,
}
impl Aim {
/// An aim at a marked object: no unit, and no confidence to speak of.
pub(super) fn point(since: u64) -> Self {
Self { unit: 0, since, switches: 0, confidence: None }
}
pub(super) fn unit(id: u32, since: u64, confidence: Confidence) -> Self {
Self { unit: id, since, switches: 0, confidence: Some(confidence) }
}
/// The same aim, chosen again: the switch count is kept, the clock and the belief are new.
pub(super) fn replaced(&self, unit: u32, since: u64, confidence: Confidence) -> Self {
Self { unit, since, switches: self.switches.saturating_add(1), confidence: Some(confidence) }
}
}
/// A route still to be worked out after a retarget (#127). The drone already has its new aim; the job
/// gives it a route as the planner's budget allows, and its old route stays until then.
#[derive(Clone)]
pub(super) struct RouteJob {
/// The job's own id, for the save and the report: jobs may be replaced in place.
pub(super) id: u32,
/// The drone, by id: queue indices move as launches happen.
pub(super) drone: u32,
/// The new aim, the drone's navigation error included.
pub(super) aim: DVec3,
/// The unit it was sent at (0 when the aim is not a unit).
pub(super) unit: u32,
/// The adaptive tick whose picture chose the aim: the knowledge version.
pub(super) version: u64,
/// The enemy knowledge that tick chose the aim from, shared by every job of the tick: its
/// contacts are aged at its own tick, not at the tick the job gets its budget (#146).
pub(super) known: Arc<KnowledgeSnapshot>,
/// The land that tick's plan knew, shared by every job of the version. A later plan replacing the
/// global snapshot must not change a pending job's relief (#127).
pub(super) relief: Option<Arc<KnownRelief>>,
/// Why the aim was chosen, and the planner's share of a tick it is worth (#127).
pub(super) intent: Intent,
}
impl RouteJob {
/// A job of this tick's picture; the id and the priority follow from the intent.
fn new(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc<KnowledgeSnapshot>, relief: Option<Arc<KnownRelief>>) -> Self {
Self { id, drone, aim, unit, version, known, relief, intent }
}
pub(super) fn priority(&self) -> u8 {
self.intent.priority()
}
/// A job read back from a save: its id, aim, unit, version, picture and relief are the file's.
pub(super) fn restored(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc<KnowledgeSnapshot>, relief: Option<Arc<KnownRelief>>) -> Self {
Self { id, drone, aim, unit, version, known, relief, intent }
}
}
/// The known land of a smart plan (#127): the grid it was mapped on and its cell heights (NaN unknown).
/// Every retarget job of that knowledge version shares one.
pub(super) struct KnownRelief {
grid: raid::Grid,
heights: Vec<f32>,
}
impl KnownRelief {
/// What the relief holds, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.heights)
}
pub(super) fn new(grid: raid::Grid, heights: Vec<f32>) -> Self {
Self { grid, heights }
}
/// The grid the land was mapped on, and its heights (NaN unknown): for the save.
pub(super) fn grid(&self) -> raid::Grid {
self.grid
}
pub(super) fn heights(&self) -> &[f32] {
&self.heights
}
/// This land sampled on `grid`: the height of the nearest cell, NaN where this plan knew nothing.
/// None when no sampled cell was known at all.
pub(super) fn sampled_on(&self, grid: &raid::Grid) -> Option<Vec<f32>> {
let src = &self.grid;
let n = grid.size;
let mut out = vec![f32::NAN; (n * n) as usize];
let (x1, z1) = (src.min.x + src.size as f64 * src.cell, src.min.z + src.size as f64 * src.cell);
let mut any = false;
for i in 0..n {
for j in 0..n {
let p = grid.centre((i, j), 0.0);
if p.x < src.min.x || p.x >= x1 || p.z < src.min.z || p.z >= z1 {
continue;
}
let (si, sj) = src.index(p);
let h = self.heights[(si * src.size + sj) as usize];
if h.is_finite() {
out[(i * n + j) as usize] = h;
any = true;
}
}
}
any.then_some(out)
}
}
#[cfg(test)]
impl RouteJob {
pub(super) fn for_test(
drone: u32,
aim: DVec3,
unit: u32,
version: u64,
known: Arc<KnowledgeSnapshot>,
relief: Option<Arc<KnownRelief>>,
) -> Self {
Self { id: drone, drone, aim, unit, version, known, relief, intent: Intent::Plan }
}
pub(super) fn with_intent(mut self, intent: Intent) -> Self {
self.intent = intent;
self
}
pub(super) fn id(&self) -> u32 {
self.id
}
}
/// The knowledge a route job was made with: its adaptive tick and the pointers to its known-units and
/// relief snapshots. A planner cache keyed only by one of them could mix two jobs' pictures (#127).
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct KnowledgeVersion {
tick: u64,
known: usize,
relief: Option<usize>,
}
/// How far a station jams.
pub const EW_RADIUS: f64 = 350.0;
/// Heat a tick on (20 s to overheat), and cooling a tick off (45 s from hot).
const HEAT: f64 = 1.0 / 400.0;
const COOL: f64 = 1.0 / 900.0;
/// After overheating it may switch on again only below this.
const READY: f64 = 0.3;
/// Approach sectors the enemy keeps score of.
pub const SECTORS: usize = 12;
/// Ticks an aim is kept before a fresh disclosure may replace it: a drone is not turned on
/// every adaptive tick, only when something new has actually shown itself (#127).
pub(super) const SWITCH_HOLD: u64 = 160;
/// How many times one drone's aim may be changed after its plan chose it. Past this it keeps
/// the aim it has: a long raid must not churn its routes on every new fix (#127).
pub(super) const SWITCH_CAP: u16 = 3;
/// New aims one adaptive tick may hand out, and ones it may give to the same contact: a mass
/// retarget is spread over the following ticks instead of replacing every route at once (#127).
pub(super) const ASSIGN_PER_TICK: usize = 16;
pub(super) const ASSIGN_PER_CONTACT: usize = 6;
/// How much nearer (blocks) a candidate must be than the current aim to be worth a switch when
/// its confidence is no better. A switch throws the current route away and costs the planner a
/// new one, so a marginal one is not made (#127).
pub(super) const SWITCH_GAIN: f64 = 120.0;
/// Route jobs the queue may hold at once, in memory and in a save (#127). Past this the lowest
/// priority (then the oldest) go: a retarget is best-effort, never an unbounded log.
pub(super) const JOBS_MAX: usize = 256;
/// A restored job older than this (ticks) is stale: the picture has moved on and the job is
/// cancelled rather than planned for an aim nobody chose any more (#127).
pub(super) const JOB_TTL: u64 = 1200;
/// What a cell of land a job's knowledge version does not know costs on top of the open ground
/// (the base cell is 1): unknown land is not free, so a replanned route keeps to what was mapped (#127).
pub(super) const UNKNOWN_LAND: f32 = 6.0;
/// How long a smart raid's unreleased portion may wait for a recon report to refresh its aims
/// (#149). A report due later than this is left to the adaptive ticks; nothing pauses for ever.
pub(super) const REFRESH_WINDOW: u64 = 600;
/// The pending refresh of a raid's unreleased portion (#149): the absolute deadline and the
/// report count it waits to pass. Transient — a save drops it, the launches keep their times.
pub(super) struct Refresh {
pub(super) deadline: u64,
pub(super) reports: u32,
}
/// How a contact's trust decays with age alone (#127). The bands are the only source of
/// confidence: nothing is invented about a unit between observations.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Confidence {
/// Older than `PROBABLE_AGE`: kept on the map and priced, not worth a strike of its own.
Doubtful,
/// Seen within `PROBABLE_AGE`: good enough to send SEAD at.
Probable,
/// Seen within `CONFIRMED_AGE`: as observed.
Confirmed,
}
impl Confidence {
pub fn name(self) -> &'static str {
match self {
Self::Doubtful => "doubtful",
Self::Probable => "probable",
Self::Confirmed => "confirmed",
}
}
pub(super) fn from_key(key: &str) -> Option<Self> {
[Self::Doubtful, Self::Probable, Self::Confirmed].into_iter().find(|c| c.name() == key)
}
}
/// What a disclosure channel showed the moment it disclosed a unit (#127). The channel
/// shows only its own fact: a launch says nothing about the unit's radar, an emission
/// fix says nothing about its weapons.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Seen {
/// A launch was seen: it fired a missile.
Launch,
/// Its radar emission was fixed: the radar was up and transmitting.
Emission,
/// Its EW transmission was fixed: it was jamming.
Jamming,
}
impl Seen {
pub fn name(self) -> &'static str {
match self {
Self::Launch => "launch",
Self::Emission => "emission",
Self::Jamming => "jamming",
}
}
pub(super) fn from_key(key: &str) -> Option<Self> {
[Self::Launch, Self::Emission, Self::Jamming].into_iter().find(|s| s.name() == key)
}
}
/// The enemy's last observation of one unit (#127): where it was, what it was seen doing,
/// and when. Written only when a channel discloses the unit; what the unit does while
/// unobserved — moves, switches off, re-roles, spends its magazine, dies — never updates
/// it. Only a newer observation of the same unit can.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Contact {
pub id: u32,
/// The type identified at the observation.
pub kind: SamKind,
/// Where it was when last observed.
pub at: DVec3,
/// When that was.
pub tick: u64,
/// What the last observation showed.
pub seen: Seen,
/// When its emission was last fixed (within this contact's life): the belief that its
/// own radar works rests on this, never on the unit's actual switch.
pub emission: Option<u64>,
/// When the enemy's own munition watched it die (battle damage assessment). Truth
/// read at that moment only; a unit destroyed unobserved keeps living in the picture.
pub destroyed: Option<u64>,
/// Launches seen of this unit, as observations. The channel counts what it watched go up;
/// it says nothing about the magazine that is left, which is never in the picture (#127).
pub launches: u16,
}
/// A contact this old (ticks) is forgotten entirely (five minutes of silence).
pub(super) const CONTACT_TTL: u64 = 6000;
/// Younger than this a contact is `Confirmed`; younger than `PROBABLE_AGE`, `Probable`.
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)
}
/// Whether the picture counts it as a live unit: observed, not watched dead, not aged out.
pub fn live(&self, now: u64) -> bool {
self.destroyed.is_none() && self.age(now) < CONTACT_TTL
}
pub fn confidence(&self, now: u64) -> Confidence {
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
/// alive; the only contrary evidence the channels give is a launch seen with the unit's
/// emissions never fixed — a launcher fighting on the network (its radar is off or it
/// has none in its launcher-only mode).
pub fn believes_own_sensor(&self, now: u64) -> bool {
let spec = self.kind.spec();
if spec.sensor <= 0.0 {
return false;
}
match self.emission {
Some(t) => now.saturating_sub(t) < CONTACT_TTL,
None => !(self.seen == Seen::Launch && self.network_launcher_kind()),
}
}
/// The kinds that can fire without their own radar in some configuration: an observation
/// of a launch without any emission fix reads as that configuration.
fn network_launcher_kind(&self) -> bool {
matches!(self.kind, SamKind::S400 | SamKind::S500)
}
}
/// One version of the enemy's knowledge (#146): the tick it was observed at, the disclosure
/// contacts and the recon marks live then. A smart order chooses its targets and prices every
/// kind's routes on this one snapshot; a retarget version ages its contacts at its own tick,
/// never at the tick the planner's budget happens to reach the job. The current time may cancel
/// a stale job, but it never re-ages the snapshot the job was chosen from.
#[derive(Clone)]
pub(super) struct KnowledgeSnapshot {
/// The tick the contacts and marks were observed at.
pub(super) tick: u64,
pub(super) contacts: Vec<Contact>,
pub(super) marks: Vec<recon::Mark>,
}
impl KnowledgeSnapshot {
/// What the snapshot holds, about (see `sim::memory`); shared `Arc`s are counted per holder.
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.contacts) + vec_bytes(&self.marks)
}
pub(super) fn new(tick: u64, contacts: Vec<Contact>, marks: Vec<recon::Mark>) -> Self {
Self { tick, contacts, marks }
}
/// A version that knows nothing: for a job whose picture is empty.
#[cfg(test)]
pub(super) fn empty(tick: u64) -> Self {
Self { tick, contacts: Vec::new(), marks: Vec::new() }
}
/// The one public hint list of this version (#149): contacts and marks merged by public
/// features, ranked on the single scale. The snapshot's own tick ages every hint.
pub(super) fn observations(&self) -> Vec<Observation> {
observe::merge(&self.contacts, &self.marks, self.tick)
}
}
/// The radar reach the enemy's planners price by: the type's published figure, undamaged
/// and role-default. What a unit suffers or is configured to while unobserved is not in it.
pub(super) fn published_reach(kind: SamKind, drone: DroneKind, height: f64) -> f64 {
let spec = kind.spec();
if spec.sensor <= 0.0 {
return 0.0;
}
let radar = spec.sensor * drone.rcs().powf(0.25);
let horizon = sight::HORIZON * (spec.mast.sqrt() + height.max(0.0).sqrt());
radar.min(horizon).max(sight::NEAR)
}
/// One raid outcome the bearing memory keeps (#149): the sector it came from, when, and its fate.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Learned {
pub(super) sector: u8,
pub(super) tick: u64,
pub(super) killed: bool,
}
/// The bearing memory is a small window of the latest outcomes, not a lifetime tally (#149):
/// this many entries, and nothing older than `OUTCOME_WINDOW` is scored.
pub(super) const MAX_OUTCOMES: usize = 48;
pub(super) const OUTCOME_WINDOW: u64 = 12_000;
/// A window whose newest outcome is older than this is stale: the fight may have moved on.
pub(super) const OUTCOME_STALE: u64 = 6_000;
/// Why the bearing picker chose as it did (#149), in typed terms the diagnostic reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BearingReason {
/// The legacy fixed-share picker (the comparison runner's "current" mode).
FixedShare,
/// Too few outcomes in the window to trust a best sector: explore more.
FewObservations,
/// The window's newest outcome is old: explore more.
StaleResults,
/// The public picture's shape changed since the outcomes were learned: explore more.
ConditionsChanged,
/// Enough fresh outcomes under unchanged conditions: exploit the best sector.
Exploiting,
}
impl BearingReason {
pub fn name(self) -> &'static str {
match self {
Self::FixedShare => "fixed-share",
Self::FewObservations => "few-observations",
Self::StaleResults => "stale-results",
Self::ConditionsChanged => "conditions-changed",
Self::Exploiting => "exploiting",
}
}
}
/// The bearing picker's last decision, for the diagnostic (#149).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BearingReport {
pub sector: usize,
pub reason: BearingReason,
/// Outcomes scored (the window, not the lifetime tally).
pub observations: usize,
/// The best sector's window score.
pub score: f64,
/// The exploration share this decision used.
pub explore: f64,
}
impl Default for BearingReport {
fn default() -> Self {
Self { sector: 0, reason: BearingReason::FewObservations, observations: 0, score: 0.5, explore: 0.6 }
}
}
#[derive(Default)]
pub(super) struct Intel {
/// Shot down and got through, by approach sector, over every raid (the lifetime tally the
/// legacy picker scores; the window below is what the candidate forgets and reasons about).
pub kills: [u32; SECTORS],
pub hits: [u32; SECTORS],
/// The last observation of each unit the enemy knows of, by id. One entry per unit:
/// a newer observation replaces the older, so no log ever needs rescanning (#122).
contacts: BTreeMap<u32, Contact>,
/// The small window of recent raid outcomes the bearing picker scores (#149).
outcomes: VecDeque<Learned>,
/// The public picture's shape when the last outcome was learned: a change is a reason to
/// explore, never a read of the hidden force (#149).
conditions: u64,
}
impl Intel {
/// What the enemy's memory holds, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::{btree_bytes, vecdeque_bytes};
btree_bytes(self.contacts.len(), std::mem::size_of::<u32>() + std::mem::size_of::<Contact>())
+ vecdeque_bytes(&self.outcomes)
}
/// The picture as a save writes it, and back: the contacts (one per unit) and the sector scores.
pub(super) fn contacts(&self) -> &BTreeMap<u32, Contact> {
&self.contacts
}
pub(super) fn sectors(&self) -> ([u32; SECTORS], [u32; SECTORS]) {
(self.kills, self.hits)
}
pub(super) fn outcomes(&self) -> &VecDeque<Learned> {
&self.outcomes
}
pub(super) fn restore(contacts: Vec<Contact>, kills: [u32; SECTORS], hits: [u32; SECTORS], outcomes: Vec<Learned>) -> Self {
Self {
kills,
hits,
contacts: contacts.into_iter().map(|c| (c.id, c)).collect(),
outcomes: outcomes.into_iter().take(MAX_OUTCOMES).collect(),
conditions: 0,
}
}
/// One outcome into the window, bounded: the oldest goes first (#149).
pub(super) fn learn(&mut self, sector: usize, killed: bool, now: u64, conditions: u64) {
self.outcomes.push_back(Learned { sector: (sector % SECTORS) as u8, tick: now, killed });
while self.outcomes.len() > MAX_OUTCOMES {
self.outcomes.pop_front();
}
self.conditions = conditions;
}
/// The one writer of contacts: what was seen of `s`, at its place, this moment.
pub(super) fn observe(&mut self, s: &Sam, now: u64, seen: Seen) {
self.note(s.id, s.kind, s.pos, s.alive(), now, seen);
}
pub(super) fn note(&mut self, id: u32, kind: SamKind, at: DVec3, alive: bool, now: u64, seen: Seen) {
let c = self.contacts.entry(id).or_insert(Contact { id, kind, at, tick: now, seen, emission: None, destroyed: None, launches: 0 });
// The newest observation wins; a fresh look at a live unit clears an old wreck call.
c.kind = kind;
c.at = at;
c.tick = now;
c.seen = seen;
if seen == Seen::Emission {
c.emission = Some(now);
}
if seen == Seen::Launch {
c.launches = c.launches.saturating_add(1);
}
if alive {
c.destroyed = None;
}
}
/// Battle damage assessment: the enemy's own munition went down by a unit it knows of
/// and its last moments showed the unit's fate (truth read at this instant only).
pub(super) fn outcome(&mut self, id: u32, alive: bool, at: DVec3, now: u64) {
let Some(c) = self.contacts.get_mut(&id) else { return };
if alive {
c.at = at;
c.tick = now;
c.destroyed = None;
} else {
c.destroyed = Some(now);
}
}
/// Drops the contacts no observation has refreshed for `CONTACT_TTL`: silence is forgetting.
pub(super) fn expire(&mut self, now: u64) {
self.contacts.retain(|_, c| c.age(now) < CONTACT_TTL);
}
}
impl DroneKind {
/// It navigates by satellite: EW throws it off.
pub fn jammable(self) -> bool {
matches!(self, DroneKind::Shahed | DroneKind::Geran3 | DroneKind::Gerbera | DroneKind::Kh101 | DroneKind::Kalibr)
}
}
/// The sector of a bearing (radians).
pub fn sector(bearing: f64) -> usize {
((bearing.rem_euclid(TAU) / TAU) * SECTORS as f64) as usize % SECTORS
}
impl Sim {
/// Switches every EW station on or off; one cooling down after overheating stays off.
/// Returns how many are now on, and how many are still too hot.
pub fn set_ew(&mut self, on: bool) -> (u32, u32) {
let (mut n, mut hot) = (0, 0);
for s in self.sams.iter_mut().filter(|s| s.kind == SamKind::Ew && s.alive()) {
if on && s.ew_lock {
hot += 1;
continue;
}
s.ew_on = on && !s.moving();
n += u32::from(s.ew_on);
}
(n, hot)
}
pub fn ew_active(&self) -> bool {
self.sams.iter().any(|s| s.ew_on)
}
/// The stations' heat, and their jamming.
pub(super) fn step_ew(&mut self, out: &mut Out) {
let now = self.tick;
let mut on: Vec<DVec3> = Vec::new();
for s in self.sams.iter_mut().filter(|s| s.kind == SamKind::Ew) {
if !s.alive() || s.moving() {
s.ew_on = false;
}
if s.ew_on {
s.heat += HEAT;
if s.heat >= 1.0 {
s.heat = 1.0;
s.ew_on = false;
s.ew_lock = true;
out.messages.push("РЭБ: передатчик перегрет, выключен".into());
out.sound("minecraft:block.fire.extinguish", s.pos, 2.0, 0.7);
}
} else {
s.heat = (s.heat - COOL).max(0.0);
if s.ew_lock && s.heat < READY {
s.ew_lock = false;
}
}
if s.ew_on {
let top = s.pos + DVec3::Y * 2.6 * s.kind.spec().scale;
on.push(s.pos);
if now % 3 == 0 {
out.particles("minecraft:electric_spark", top, 0.6, DVec3::ZERO, 0.2, 3);
}
if now % 40 == 0 {
out.sound("minecraft:block.beacon.ambient", top, 2.0, 1.4);
}
// A transmitter on the air: the enemy finds it.
if now % 20 == 0 {
self.intel.observe(s, now, Seen::Jamming);
}
}
}
if on.is_empty() {
return;
}
for d in self.drones.iter_mut().filter(|d| d.alive() && d.kind.jammable()) {
let Some(k) = on.iter().map(|p| 1.0 - horizontal(d.pos - *p).length() / EW_RADIUS).reduce(f64::max) else { continue };
if k <= 0.0 {
continue;
}
// Its fix wanders: the aim drifts, the route is lost.
d.route.clear();
d.target += DVec3::new(self.rng.s(), 0.0, self.rng.s()) * (1.2 * k);
d.jammed = true;
}
}
/// What the enemy's raids learned: their drones' fates by sector, into the lifetime tally
/// and the small recent window the bearing picker scores (#149).
pub(super) fn learn(&mut self, sector: usize, killed: bool) {
if killed {
self.intel.kills[sector % SECTORS] += 1;
} else {
self.intel.hits[sector % SECTORS] += 1;
}
let conditions = self.picture_fingerprint();
self.intel.learn(sector, killed, self.tick, conditions);
}
/// The public picture's shape (#149): how many live hints of each category the enemy holds.
/// A fingerprint of beliefs only — no health, magazine, switch or true place is read.
pub(super) fn picture_fingerprint(&self) -> u64 {
let now = self.tick;
let mut h: u64 = 0xCBF2_9CE4_8422_2325;
let mut mix = |v: u64| h = (h ^ v).wrapping_mul(0x0000_0100_0000_01B3);
let mut cats = [0u32; 6];
for c in self.intel.contacts.values().filter(|c| c.live(now)) {
cats[recon::Category::of(c.kind) as usize] += 1;
}
for m in self.recon.marks.values().filter(|m| m.live(now)) {
cats[m.category as usize] += 1;
}
for n in cats {
mix(u64::from(n));
}
h
}
/// The bearing a smart raid comes from (#149). The candidate scores a small window of the
/// latest outcomes, forgets the old ones, and adapts its exploration share to what the
/// window can support — few observations, a stale result or changed public conditions each
/// named as a typed reason. The legacy mode keeps the lifetime tally and the fixed share.
pub(super) fn best_bearing(&mut self) -> f64 {
let now = self.tick;
let (pick, report) = if self.smart_legacy {
let score = |i: usize| {
let (k, h) = (self.intel.kills[i] as f64, self.intel.hits[i] as f64);
(h + 1.0) / (k + h + 2.0)
};
let best = (0..SECTORS).max_by(|&a, &b| score(a).total_cmp(&score(b))).unwrap_or(0);
// Unknown sectors are worth a look too.
let pick = if self.rng.chance(0.3) { (self.rng.f() * SECTORS as f64) as usize } else { best };
let observations = self.intel.kills.iter().chain(self.intel.hits.iter()).map(|n| *n as usize).sum();
(pick, BearingReport { sector: pick, reason: BearingReason::FixedShare, observations, score: score(best), explore: 0.3 })
} else {
let window: Vec<&Learned> = self.intel.outcomes.iter().filter(|o| now.saturating_sub(o.tick) <= OUTCOME_WINDOW).collect();
let total = window.len();
let newest = window.iter().map(|o| o.tick).max().unwrap_or(0);
let conditions = self.picture_fingerprint();
let (reason, explore) = if total < 6 {
(BearingReason::FewObservations, 0.6)
} else if now.saturating_sub(newest) > OUTCOME_STALE {
(BearingReason::StaleResults, 0.5)
} else if conditions != self.intel.conditions {
(BearingReason::ConditionsChanged, 0.45)
} else {
(BearingReason::Exploiting, 0.15)
};
let score = |i: usize| {
let k = window.iter().filter(|o| o.sector as usize == i && o.killed).count() as f64;
let h = window.iter().filter(|o| o.sector as usize == i && !o.killed).count() as f64;
(h + 1.0) / (k + h + 2.0)
};
let best = (0..SECTORS).max_by(|&a, &b| score(a).total_cmp(&score(b))).unwrap_or(0);
let pick = if self.rng.chance(explore) { (self.rng.f() * SECTORS as f64) as usize } else { best };
(pick, BearingReport { sector: pick, reason, observations: total, score: score(best), explore })
};
self.bearing = report;
(pick as f64 + 0.5 + self.rng.s() * 0.4) / SECTORS as f64 * TAU
}
/// The enemy's live picture of the defences at this moment: the contacts a decision may
/// rest on, newest first (ties by id, newest id first — the order the old revelation log
/// produced, kept so the planner's picks stay as they were; deterministic either way).
/// What a unit does while unobserved changes nothing here; only a new observation can (#127).
pub(super) fn picture_of_defences(&self) -> Vec<Contact> {
let now = self.tick;
let mut out: Vec<Contact> = self.intel.contacts.values().copied().filter(|c| c.live(now)).collect();
out.sort_by(|a, b| b.tick.cmp(&a.tick).then(b.id.cmp(&a.id)));
out
}
/// The knowledge this moment holds, as one snapshot for a whole decision (#146): the tick,
/// the contacts and the recon marks, read once and never re-read per kind or per job.
pub(super) fn knowledge_now(&self) -> KnowledgeSnapshot {
KnowledgeSnapshot { tick: self.tick, contacts: self.picture_of_defences(), marks: self.recon.leads(self.tick) }
}
/// The bounded refresh of a raid's unreleased portion (#149): a recon flight is out, and the
/// plan's own picks may be re-aimed once when a report arrives. The deadline is absolute — no
/// report, no delay: the launches keep their times either way.
pub(super) fn step_refresh(&mut self, out: &mut Out) {
let Some(r) = self.refresh.take() else { return };
if self.tick > r.deadline {
return;
}
if self.recon.reports <= r.reports {
self.refresh = Some(r);
return;
}
// A report arrived: one fresh snapshot, one bounded pass over the drones still waiting
// to launch. Only the plan's own picks are re-aimed, once, within the switch cap.
let knowledge = self.knowledge_now();
let obs = knowledge.observations();
let known = Arc::new(knowledge);
let relief = self.known_relief.clone();
let now = self.tick;
let mut per: HashMap<u32, usize> = HashMap::new();
let mut assigned = 0usize;
let mut changed = 0u32;
let mut job_next = self.job_next;
let mut diversions_left = self.diversions_left;
let mut jobs: Vec<RouteJob> = Vec::new();
for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart && d.kind.spec().class != Class::Ballistic && matches!(d.intent, Intent::Plan | Intent::Sead)) {
if assigned >= ASSIGN_PER_TICK || d.aim.switches >= SWITCH_CAP
|| d.kind.spec().decoy || (d.aim.unit == 0 && diversions_left == 0)
{
continue;
}
let Some(o) = obs.iter().find(|o| {
o.confidence(now) >= Confidence::Probable
&& (o.kind.is_some() || observe::fits(d.kind, o.category))
&& o.id != d.aim.unit
&& per.get(&o.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT
}) else {
continue;
};
*per.entry(o.id).or_insert(0) += 1;
assigned += 1;
changed += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = o.at + d.err;
d.intent = Intent::Refresh;
d.aim = d.aim.replaced(o.id, now, o.confidence(now));
if Self::route_plannable(d) {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Refresh, Arc::clone(&known), relief.clone()));
job_next += 1;
} else {
d.route.clear();
}
}
self.job_next = job_next;
self.diversions_left = diversions_left;
for job in jobs {
self.queue_route(job);
}
if changed > 0 {
self.refresh_applied = self.refresh_applied.saturating_add(changed);
out.messages.push(format!("Разведка противника: донесение изменило план налёта ({changed} целей)"));
}
}
/// Whether the picture holds a live contact for this unit: what the old revelation log
/// answered at a scan, now one map lookup. A public belief, never the unit's truth.
pub 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))
}
/// During a smart raid: its drones not yet launched go for what just gave itself away (a jamming station
/// first, then systems that fired), and drones whose system target is gone pick another. Routes for the
/// new aims are worked out over the following ticks, as the planner's share allows (#127).
pub(super) fn adapt(&mut self) {
if self.tick % 40 == 0 {
self.adapt_targets();
}
self.replan_retargets();
}
/// The adaptive tick: chooses the new aims and leaves a route job for each drone that needs one. The
/// old route stays until a new one is ready: a drone is never left with no way round the defences.
///
/// Every aim carries its [`Intent`] and the [`Aim`] bookkeeping that throttles changes: assignments
/// are spread over adaptive ticks and contacts, a fresh disclosure may replace an aim only after
/// `SWITCH_HOLD` and `SWITCH_CAP`, and only when it is worth a new route. A replacement of an aim
/// the picture killed is a distinct, lower-priority decision.
fn adapt_targets(&mut self) {
self.intel.expire(self.tick);
self.recon.expire(self.tick);
// One knowledge version for every aim and job this adaptive tick chooses (#146).
let knowledge = Arc::new(self.knowledge_now());
let picture = &knowledge.contacts;
let leads = &knowledge.marks;
// The candidate picks from the one merged hint list (#149); the legacy mode keeps the
// two separate lists and their old scales.
let obs = if self.smart_legacy { Vec::new() } else { knowledge.observations() };
if picture.is_empty() && leads.is_empty() {
return;
}
// Every job of this adaptive tick plans over the same relief version, even if another smart
// plan finishes before the job gets its budget (#127).
let relief = self.known_relief.clone();
let now = self.tick;
// Job ids are taken from the simulation's counter: a job keeps its id when it is replaced in
// place, and the save writes it back (#127).
let mut job_next = self.job_next;
let mut diversions_left = self.diversions_left;
// The drones sent at a new target: a route job each, to be worked out as the planner's budget allows.
let mut jobs: Vec<RouteJob> = Vec::new();
let mut n = 0usize;
let mut assigned = 0usize;
let mut per_contact: HashMap<u32, usize> = HashMap::new();
for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart && d.kind.spec().class != Class::Ballistic) {
let hunter = matches!(d.kind, DroneKind::Lancet | DroneKind::Kh22 | DroneKind::Zircon);
let eligible = hunter || (d.kind == DroneKind::Shahed && n % 4 == 0);
n += 1;
if !eligible || (d.aim.unit == 0 && diversions_left == 0) {
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).
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 {
continue;
}
*per_contact.entry(c.id).or_insert(0) += 1;
assigned += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = c.at + d.err;
d.intent = Intent::React;
d.aim = d.aim.replaced(c.id, now, c.confidence(now));
if Self::route_plannable(d) {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&knowledge), relief.clone()));
job_next += 1;
} else {
d.route.clear();
}
continue;
}
// Not sent at a unit yet: it may be given one, a bounded number a tick and per
// contact, so a mass retarget does not replace every route in one tick (#127).
if assigned >= ASSIGN_PER_TICK {
continue;
}
// The candidate picks from the one merged hint list (#149): a matched mark is not a
// second target, and both channels rank on the same public scale. The legacy mode
// keeps the two separate lists and their old scales.
let (at, unit, confidence) = if self.smart_legacy {
let exact = Self::fresh_target(&picture, &per_contact, d.kind, n);
let mark = Self::fresh_recon_target(&leads, &per_contact);
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,
}
} else {
match Self::fresh_observation(&obs, &per_contact, d.kind, n) {
Some(o) => (o.at, o.id, o.confidence(now)),
None => continue,
}
};
*per_contact.entry(unit).or_insert(0) += 1;
assigned += 1;
diversions_left -= u32::from(d.aim.unit == 0);
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, 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(&knowledge), relief.clone()));
job_next += 1;
} else {
// Nothing will be replanned for it: its old route leads to the old aim, so it goes straight.
d.route.clear();
}
}
// In flight: the aim is kept only while the picture says it is live. A unit watched dying,
// or forgotten after its contact aged out mid-flight, is replaced by the nearest live contact
// it can still turn onto — or, past the switch cap, the drone keeps its course. A unit merely
// moved is still aimed where seen.
for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart && d.kind.spec().class != Class::Ballistic) {
if d.aim.unit == 0 && diversions_left == 0 {
continue;
}
let aim = d.target - d.err;
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;
}
let plannable = Self::route_plannable(d);
// A replacement is not a disclosure reaction: the aim is dead, so the hold does not apply,
// but the cap and the tick's assignment budget do — a drone whose aim keeps dying stops
// chasing the picture, and a tick that killed many aims does not replace them all at once.
if d.aim.switches >= SWITCH_CAP || assigned >= ASSIGN_PER_TICK {
continue;
}
// The candidate replaces from the one merged hint list, best public rank first and
// nearest among equals (#149); the legacy mode keeps the two lists and their scales.
let next = if self.smart_legacy {
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)
.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,
});
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,
}
} else {
obs.iter()
.filter(|o| !plannable || Self::can_turn_to(d, o.at))
.filter(|o| per_contact.get(&o.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
.map(|o| (o.at.distance(d.pos), o.id, o.at, o.confidence(now), o.rank(now)))
.min_by(|a, b| b.4.cmp(&a.4).then(a.0.total_cmp(&b.0)))
.map(|(d, id, at, c, _)| (d, id, at, c))
};
if let Some((_, unit, at, confidence)) = next {
*per_contact.entry(unit).or_insert(0) += 1;
assigned += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = at + d.err;
d.intent = Intent::Replace;
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(&knowledge), relief.clone()));
job_next += 1;
} else {
d.route.clear();
}
}
}
self.job_next = job_next;
self.diversions_left = diversions_left;
for job in jobs {
self.queue_route(job);
}
}
/// The contact the drone is aimed at now: the live one whose observed place is its aim.
fn aimed_contact(picture: &[Contact], aim: DVec3) -> Option<Contact> {
picture.iter().copied().find(|c| c.at.distance(aim) < 6.0)
}
/// The contact a drone not yet sent at a unit should be given: a station that gave itself away
/// (a jammer, a radar that emitted, a system that fired) before anything else, then the rest of
/// the picture, round-robin so a mass retarget spreads over what is known (#127).
fn fresh_target(picture: &[Contact], per_contact: &HashMap<u32, usize>, kind: DroneKind, n: usize) -> Option<Contact> {
let free = |c: &&Contact| per_contact.get(&c.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT;
// A station transmitting is the loudest disclosure: the raid turns on it first, as it always did.
let jammers: Vec<&Contact> = picture.iter().filter(|c| c.kind == SamKind::Ew).filter(free).collect();
if let Some(c) = jammers.get(n % jammers.len().max(1)) {
return Some(**c);
}
// The hunters also take anything else that showed itself; the rest fall back to the picture.
let disclosed = |c: &&Contact| matches!(c.seen, Seen::Jamming | Seen::Emission | Seen::Launch);
let hunters = matches!(kind, DroneKind::Lancet | DroneKind::Kh22 | DroneKind::Zircon);
if hunters {
let shown: Vec<&Contact> = picture.iter().filter(disclosed).filter(free).collect();
if let Some(c) = shown.get(n % shown.len().max(1)) {
return Some(**c);
}
}
let all: Vec<&Contact> = picture.iter().filter(free).collect();
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)
}
/// The hint a drone not yet sent at a unit should be given (#149): one merged list, one
/// public scale. A transmitting jammer is the loudest disclosure, then (for the hunters)
/// anything that showed itself, then a round-robin over what fits — a disclosure contact
/// always fits, a recon mark only when the small policy says its category suits the kind.
fn fresh_observation(obs: &[Observation], per_contact: &HashMap<u32, usize>, kind: DroneKind, n: usize) -> Option<Observation> {
let free = |o: &&Observation| per_contact.get(&o.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT;
let jammers: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Ew && o.channel == recon::Source::Jamming).filter(free).collect();
if let Some(o) = jammers.get(n % jammers.len().max(1)) {
return Some(**o);
}
let hunters = matches!(kind, DroneKind::Lancet | DroneKind::Kh22 | DroneKind::Zircon);
if hunters {
let shown: Vec<&Observation> = obs.iter().filter(|o| o.channel != recon::Source::Flyby).filter(free).collect();
if let Some(o) = shown.get(n % shown.len().max(1)) {
return Some(**o);
}
}
let fit: Vec<&Observation> = obs.iter().filter(|o| o.kind.is_some() || observe::fits(kind, o.category)).filter(free).collect();
fit.get(n % fit.len().max(1)).map(|o| **o)
}
/// 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
/// route, so a marginal candidate is not taken.
fn switch_candidate(picture: &[Contact], current: Contact, d: &Drone, now: u64) -> Option<Contact> {
if d.aim.switches >= SWITCH_CAP || now.saturating_sub(d.aim.since) < SWITCH_HOLD {
return None;
}
let held = d.aim.confidence;
picture
.iter()
.filter(|c| c.id != current.id)
// Only something that has shown itself since this aim was chosen is a reason to switch.
.filter(|c| c.tick > d.aim.since)
.filter(|c| c.confidence(now) >= Confidence::Probable)
.filter(|c| match held {
Some(h) => c.confidence(now) > h || c.at.distance(d.pos) + SWITCH_GAIN < current.at.distance(d.pos),
None => true,
})
.min_by(|a, b| a.at.distance(d.pos).total_cmp(&b.at.distance(d.pos)))
.copied()
}
/// A kind whose route the replan works out: a Lancet's strike on a unit and the ballistic missiles go
/// straight on purpose, as in the raid's own plan.
fn route_plannable(d: &Drone) -> bool {
let spec = d.kind.spec();
d.smart && spec.ballistic.is_none() && !spec.decoy && d.kind != DroneKind::Lancet
}
/// Whether a drone can turn onto `at` from where it is. A slow missile with a close target behind
/// would only circle it: it finishes the approach it is on instead of turning to another unit (#127).
fn can_turn_to(d: &Drone, at: DVec3) -> bool {
let spec = d.kind.spec();
let radius = (spec.speed / spec.turn.max(0.01)).max(24.0);
let to = horizontal(at - d.pos);
if to.length() >= radius * 2.0 {
return true;
}
let heading = horizontal(d.vel).normalize_or_zero();
heading == DVec3::ZERO || heading.dot(to.normalize_or_zero()) > 0.0
}
/// Adds a job, replacing an older one for the same drone in place: a drone retargeted again before its
/// route was ready must not grow the queue or be planned for an aim it no longer has (#127). The queue
/// is bounded: past `JOBS_MAX` the lowest priority (then the oldest) job makes room, and a job that is
/// not worth more than what is queued is refused outright — the drone keeps its old route.
fn queue_route(&mut self, job: RouteJob) {
if let Some(i) = self.retargets.iter().position(|j| j.drone == job.drone) {
if self.retargets[i].version <= job.version {
self.retargets[i] = job;
}
return;
}
if self.retargets.len() >= JOBS_MAX {
let worst = self
.retargets
.iter()
.enumerate()
.min_by_key(|(i, j)| (j.priority(), *i))
.map(|(i, _)| i);
match worst {
Some(i) if self.retargets[i].priority() < job.priority() => {
self.retargets.remove(i);
}
_ => return,
}
}
self.retargets.push_back(job);
}
/// Drops the jobs a restored save can no longer stand behind (#127): a drone gone or dead, an aim
/// that has since changed, a unit the picture watched die or forgot, a duplicate for the same drone,
/// or a version older than `JOB_TTL` — the picture has moved on. Returns how many were cancelled.
pub(super) fn prune_air(&mut self) -> u32 {
let now = self.tick;
let mut seen: HashMap<u32, u64> = HashMap::new();
let mut cancelled = 0u32;
let mut kept: VecDeque<RouteJob> = VecDeque::with_capacity(self.retargets.len());
while let Some(job) = self.retargets.pop_front() {
let fresh = now.saturating_sub(job.version) <= JOB_TTL;
let newer = seen.get(&job.drone).is_none_or(|v| job.version >= *v);
let live = self.job_live(&job);
if fresh && newer && live {
seen.insert(job.drone, job.version);
kept.push_back(job);
} else {
cancelled += 1;
// A job dropped for staleness or as a duplicate leaves a route that still leads to the
// drone's own aim, so it is kept; one whose aim has changed leaves a route to nowhere,
// and that goes.
if let Some(d) = self.drone_of_mut(job.drone) && d.alive() && d.target != job.aim {
d.route.clear();
}
}
}
self.retargets = kept;
cancelled
}
/// The drone a job is for: waiting in the queue or already flying.
fn drone_of(&self, id: u32) -> Option<&Drone> {
self.queue.iter().find(|(_, d)| d.id == id).map(|(_, d)| d).or_else(|| self.drones.iter().find(|d| d.id == id))
}
fn drone_of_mut(&mut self, id: u32) -> Option<&mut Drone> {
if let Some(i) = self.queue.iter().position(|(_, d)| d.id == id) {
return Some(&mut self.queue[i].1);
}
self.drones.iter_mut().find(|d| d.id == id)
}
/// Whether a job still says what its drone is doing. A dead drone or an aim changed again
/// cancels it; so does a unit the picture watched die or forgot: the enemy no longer plans
/// a route to a target it does not believe in. A unit destroyed unobserved cancels nothing —
/// the picture still believes in it (#127).
fn job_live(&self, job: &RouteJob) -> bool {
let Some(d) = self.drone_of(job.drone) else { return false };
if !d.alive() || d.target != job.aim {
return false;
}
job.unit == 0 || self.known_live(job.unit)
}
/// The land this job's knowledge version knew, sampled on `grid` (NaN outside it). It reads the job's
/// own snapshot: a later smart plan replacing `Sim::known_relief` must not change a pending job (#127).
fn retarget_relief(job: &RouteJob, grid: &raid::Grid) -> Option<Vec<f32>> {
job.relief.as_deref()?.sampled_on(grid)
}
/// Works the retarget queue: one grid and one set of prices cover the jobs, and the work is the
/// planner's share for a tick. The queue is a bounded priority queue — the plan's own objectives first,
/// then SEAD, then reactions to disclosures, then replacements; FIFO within a priority. A job the budget
/// cannot reach stays queued for the next tick, and its drone keeps the old route (or, if it had none,
/// flies straight for a while — never for ever).
fn replan_retargets(&mut self) {
if self.retargets.is_empty() {
return;
}
let mut jobs: Vec<RouteJob> = std::mem::take(&mut self.retargets).into_iter().filter(|job| {
if self.job_live(job) {
return true;
}
if let Some(d) = self.drone_of_mut(job.drone) && d.alive() {
// No new route will come from this job: the old route is a fallback, not a plan.
d.route.clear();
}
false
}).collect();
if jobs.is_empty() {
return;
}
// Stable: jobs of one priority keep the order they were queued in.
jobs.sort_by_key(|j| std::cmp::Reverse(j.priority()));
self.retargets = jobs.into_iter().collect();
let jobs: Vec<RouteJob> = std::mem::take(&mut self.retargets).into();
// One grid over all their starts and goals, with room round them to go by.
let (mut lo, mut hi) = (DVec3::splat(f64::INFINITY), DVec3::splat(f64::NEG_INFINITY));
for job in &jobs {
let Some(d) = self.drone_of(job.drone) else { continue };
for p in [d.pos, job.aim] {
lo = lo.min(p);
hi = hi.max(p);
}
}
let span = (hi.x - lo.x).max(hi.z - lo.z) / 2.0 + 450.0;
let cell = raid::CELL.max(2.0 * span / raid::CELLS as f64);
let centre = (lo + hi) / 2.0;
let grid = raid::Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 };
// Jobs may carry different knowledge versions (their own known units and relief); keep the
// sampled relief, prices and routes per version, so jobs of one adaptive tick share caches and
// jobs of another do not (#127).
let mut reliefs: HashMap<Option<usize>, Option<Vec<f32>>> = HashMap::new();
let mut prices: HashMap<(DroneKind, KnowledgeVersion), Vec<f32>> = HashMap::new();
let mut routes: HashMap<(DroneKind, KnowledgeVersion, (i32, i32), (i32, i32)), Vec<DVec3>> = HashMap::new();
let mut work = 0usize;
let mut kept: Vec<RouteJob> = Vec::with_capacity(jobs.len());
let mut i = 0usize;
while i < jobs.len() {
if work >= raid::WORK_PER_TICK {
kept.extend(jobs[i..].iter().cloned());
break;
}
let job = jobs[i].clone();
if !self.job_live(&job) {
i += 1;
continue;
}
let Some(d) = self.drone_of(job.drone) else {
i += 1;
continue;
};
let (pos, kind) = (d.pos, d.kind);
let version = KnowledgeVersion {
tick: job.version,
known: Arc::as_ptr(&job.known) as usize,
relief: job.relief.as_ref().map(|r| Arc::as_ptr(r) as usize),
};
let land = reliefs.entry(version.relief).or_insert_with(|| Self::retarget_relief(&job, &grid));
let land = land.as_deref();
let key = (kind, version, grid.index(pos), grid.index(job.aim));
let route = match routes.get(&key) {
Some(r) => r.clone(),
None => {
if !prices.contains_key(&(kind, version)) {
let (p, cost) = self.price_grid_known(&grid, kind, land, &job.known);
work += cost;
prices.insert((kind, version), p);
}
// Land this job's version did not know is not free: every unknown cell costs more
// than the open ground, so a route keeps to what the plan mapped out (#127).
let unknown_land;
let heights = match land {
Some(h) => h,
None => {
unknown_land = vec![f32::NAN; (grid.size * grid.size) as usize];
&unknown_land
}
};
let relief = raid::Relief {
heights,
slope: (kind.climb_pitch().tan() * 0.5) as f32,
floor: (job.aim.y + kind.spec().clearance) as f32,
unknown: UNKNOWN_LAND,
};
let (r, cost) = raid::plan_route_on(&grid, &prices[&(kind, version)], Some(&relief), pos, job.aim);
work += cost;
routes.insert(key, r.clone());
r
}
};
if let Some(d) = self.drone_of_mut(job.drone) {
d.route = route;
}
i += 1;
}
self.retargets = kept.into_iter().collect();
}
/// The route jobs still waiting (#127; diagnostics).
pub fn retargets_len(&self) -> usize {
self.retargets.len()
}
/// The drones with a route job still waiting (tests and diagnostics).
#[cfg(test)]
pub(super) fn retarget_ids(&self) -> Vec<u32> {
self.retargets.iter().map(|j| j.drone).collect()
}
/// The relief a pending job carries (tests and diagnostics).
#[cfg(test)]
pub(super) fn pending_relief(&self, id: u32) -> Option<&KnownRelief> {
self.retargets.iter().find(|j| j.drone == id)?.relief.as_deref()
}
}
/// One contact as the diagnostic reports it: the observation, its age and confidence, and the
/// threat the planner would price from it — the belief, not the truth (#127).
#[derive(Clone, Debug, PartialEq)]
pub struct ContactReport {
pub id: u32,
/// The type identified at the observation.
pub kind: SamKind,
/// Where it was last observed.
pub at: DVec3,
/// What the last observation showed: "launch", "emission" or "jamming".
pub seen: &'static str,
/// Ticks since the last observation.
pub age: u64,
pub confidence: Confidence,
/// Whether the picture counts it as a live unit (unexpired, not watched dead).
pub live: bool,
/// When its destruction was observed, if it was.
pub observed_destroyed: Option<u64>,
/// Launches of this unit the picture watched. The magazine behind them is never observed.
pub launches: u16,
/// The belief the threat model prices by: that its own radar works.
pub own_sensor: bool,
/// Whether a live radar contact stands within data-link range of its observed place.
pub donor_in_link: bool,
/// What the planner makes of it, in words.
pub threat: &'static str,
/// Drones aimed at this contact now (whatever the reason).
pub aimed_by: u32,
/// Route jobs still being worked out for this contact.
pub pending_jobs: u32,
}
/// Why one drone is aimed where it is (#127): the reason, the unit, and the throttle's state.
#[derive(Clone, Debug, PartialEq)]
pub struct AimReport {
pub drone: u32,
/// 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,
/// The tick the aim was chosen at.
pub since: u64,
/// How many times the aim has been changed since the plan chose it.
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,
/// and the knowledge version it will be planned over.
#[derive(Clone, Debug, PartialEq)]
pub struct PendingReport {
pub job: u32,
pub drone: u32,
pub unit: u32,
pub at: DVec3,
/// The adaptive tick whose picture chose the aim.
pub version: u64,
/// Higher goes first (see `Intent`).
pub priority: u8,
pub intent: &'static str,
/// Whether the land of this job's version is known at all.
pub relief_known: bool,
/// Why it is still queued, in words.
pub reason: &'static str,
}
/// One merged public hint as the diagnostic reports it (#149): the one scale the planner ranks
/// and prices by, and whether a second channel agreed by public features (a belief, not a fact).
#[derive(Clone, Debug, PartialEq)]
pub struct ObservationReport {
pub id: u32,
pub at: DVec3,
pub radius: f64,
/// "flyby", "emission", "jamming" or "launch".
pub channel: &'static str,
pub age: u64,
pub confidence: Confidence,
pub category: &'static str,
pub role: Option<&'static str>,
/// The identified type of a disclosure contact; `None` for a recon mark's area.
pub kind: Option<&'static str>,
pub quality: &'static str,
/// A second public hint matched by area and category. Never a hidden truth.
pub matched: bool,
pub rank: u8,
}
/// The enemy's whole picture at one tick: what it knows and what it assumes, structured for
/// diagnostics (#127). No truth anywhere in it — a unit the picture got wrong is reported wrong.
#[derive(Clone, Debug, PartialEq)]
pub struct EnemyPictureReport {
pub now: u64,
pub contacts: Vec<ContactReport>,
/// Every smart drone's aim and why, for the plan a player's raid faces.
pub aims: Vec<AimReport>,
/// The route jobs still waiting.
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>,
/// The one merged hint list the candidate planner ranks and prices by (#149).
pub observations: Vec<ObservationReport>,
/// The bearing picker's last decision and its typed reason (#149).
pub bearing: BearingReport,
/// Whether a bounded refresh of the unreleased portion is still waiting for a report (#149).
pub refresh_waiting: bool,
/// Aims the refresh has re-chosen so far (#149).
pub refresh_applied: u32,
}
impl Sim {
/// The structured picture: observation, confidence and priced threat per contact, the aims
/// every smart drone carries and why, and the pending route jobs with their reason (#127).
pub fn enemy_picture(&self) -> EnemyPictureReport {
let now = self.tick;
let live: Vec<Contact> = self.picture_of_defences();
let aimed_at = |unit: u32| -> u32 {
self.queue
.iter()
.map(|(_, d)| d)
.chain(self.drones.iter())
.filter(|d| d.alive() && d.smart && d.aim.unit == unit && unit != 0)
.count() as u32
};
let pending_at = |unit: u32| -> u32 { self.retargets.iter().filter(|j| j.unit == unit && unit != 0).count() as u32 };
let contacts = self
.intel
.contacts
.values()
.map(|c| {
let donor = live.iter().any(|d| d.kind == SamKind::Radar && d.id != c.id && d.at.distance(c.at) <= sight::LINK);
ContactReport {
id: c.id,
kind: c.kind,
at: c.at,
seen: c.seen.name(),
age: c.age(now),
confidence: c.confidence(now),
live: c.live(now),
observed_destroyed: c.destroyed,
launches: c.launches,
own_sensor: c.believes_own_sensor(now),
donor_in_link: donor,
threat: Self::threat_text(c, now, donor),
aimed_by: aimed_at(c.id),
pending_jobs: pending_at(c.id),
}
})
.collect();
let aims = self
.queue
.iter()
.map(|(_, d)| d)
.chain(self.drones.iter())
.filter(|d| d.alive() && d.smart)
.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
.retargets
.iter()
.map(|j| PendingReport {
job: j.id,
drone: j.drone,
unit: j.unit,
at: j.aim,
version: j.version,
priority: j.priority(),
intent: j.intent.name(),
relief_known: j.relief.is_some(),
reason: if now.saturating_sub(j.version) > JOB_TTL {
"stale: the picture that chose the aim has moved on"
} else if j.relief.is_none() {
"waiting for the planner's share; the land is unknown and costs accordingly"
} else {
"waiting for the planner's share of this tick"
},
})
.collect();
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();
let observations = self
.knowledge_now()
.observations()
.into_iter()
.map(|o| ObservationReport {
id: o.id,
at: o.at,
radius: o.radius,
channel: o.channel.name(),
age: o.age(now),
confidence: o.confidence(now),
category: o.category.name(),
role: o.role.map(|r| r.key()),
kind: o.kind.map(|k| k.spec().key),
quality: o.quality.name(),
matched: o.matched,
rank: o.rank(now),
})
.collect();
EnemyPictureReport {
now,
contacts,
aims,
pending,
work_per_tick: raid::WORK_PER_TICK,
recon,
recon_sorties,
observations,
bearing: self.bearing,
refresh_waiting: self.refresh.is_some(),
refresh_applied: self.refresh_applied,
}
}
/// What the planner makes of a contact, in words for the diagnostic (#127).
fn threat_text(c: &Contact, now: u64, donor: bool) -> &'static str {
if !c.live(now) {
return "not priced: forgotten with age or watched dead";
}
let spec = c.kind.spec();
if spec.missile.is_none() && spec.gun.is_none() {
return "not armed: a jamming or support station, priced only for satellite-nav drones";
}
match (c.believes_own_sensor(now), donor) {
(true, true) => "missiles on its own sensor, reaching further on the linked radar; guns on its own sensor",
(true, false) => "missiles and guns on its own sensor",
(false, true) => "no own sensor believed: it fires on the linked radar's tracks",
(false, false) => "believed blind: no own sensor and no linked radar in reach",
}
}
}
#[cfg(test)]
mod picture_tests {
use super::*;
use super::super::{battery::SamMode, raid::Grid};
fn grid() -> Grid {
Grid { min: DVec3::new(-480.0, 0.0, -480.0), cell: 16.0, size: 60 }
}
/// A small force the picture knows about: an emitting patriot, a fixed radar, a jammer.
fn watched_force(sim: &mut Sim) -> Vec<u32> {
let mut ids = Vec::new();
for (kind, at, seen) in [
(SamKind::Patriot, DVec3::new(-120.0, 70.0, 0.0), Seen::Emission),
(SamKind::Radar, DVec3::new(0.0, 70.0, 0.0), Seen::Emission),
(SamKind::Ew, DVec3::new(120.0, 70.0, 0.0), Seen::Jamming),
] {
let id = sim.id();
let sam = Sam::new(id, kind, at, 0.0);
sim.intel.observe(&sam, 0, seen);
sim.sams.push(sam);
ids.push(id);
}
ids
}
// #127: what a unit does while unobserved — moves, switches off, re-roles, re-modes, spends
// its magazine, takes damage, dies — changes neither the picture nor anything priced or
// decided from it. Only a new observation can.
#[test]
fn hidden_changes_do_not_move_the_picture_or_its_decisions() {
let mut base = Sim::new(17);
let ids = watched_force(&mut base);
let mut changed = Sim::new(17);
let _ = watched_force(&mut changed);
base.tick = 100;
changed.tick = 100;
let grid = grid();
let snapshot = |sim: &Sim| {
let (prices, cost) = sim.price_grid(&grid, DroneKind::Kh101);
(sim.picture_of_defences(), prices, cost, sim.enemy_picture())
};
let before = snapshot(&base);
// Every hidden change at once: moves, silence, roles emptied, launcher-only mode,
// an empty magazine, damage, and one unit destroyed where nothing could watch.
changed.sams[0].pos = DVec3::new(-500.0, 70.0, 400.0);
changed.sams[1].radar_on = false;
changed.sams[1].radar_role = super::super::battery::RadarRole::Search;
changed.sams[2].roles = 0;
changed.sams[0].set_mode(SamMode::LauncherOnly);
changed.sams[0].missiles = 0;
changed.sams[0].health = 0.3;
changed.sams[1].health = 0.0;
// ...and an EW station's heat, transmitter lock and switch are its own energy, not a disclosure.
changed.sams[2].heat = 1.0;
changed.sams[2].ew_lock = true;
changed.sams[2].ew_on = false;
let after = snapshot(&changed);
assert_eq!(before, after, "a hidden change moved the enemy's picture");
// The adaptive tick decides the same aims on both.
for (sim, id) in [(&mut base, ids[0]), (&mut changed, ids[0])] {
let _ = id;
let from = DVec3::new(0.0, 120.0, -900.0);
let mut d = sim.make_drone(DroneKind::Kh22, from, DVec3::Z, DVec3::new(0.0, 70.0, 900.0));
d.smart = true;
sim.queue.push((0, d));
sim.adapt();
}
let aims = |sim: &Sim| sim.queue.iter().map(|(_, d)| d.target).collect::<Vec<_>>();
assert_eq!(aims(&base), aims(&changed), "the same picture chose different aims");
assert_eq!(base.retarget_ids(), changed.retarget_ids());
// The structured intent is part of the decision: the same picture chooses the same reason,
// the same unit and the same throttle state (#127).
let intent = |sim: &Sim| sim.queue.iter().map(|(_, d)| (d.intent, d.aim.unit, d.aim.since, d.aim.switches, d.aim.confidence)).collect::<Vec<_>>();
assert_eq!(intent(&base), intent(&changed), "a hidden change moved an intent");
let jobs = |sim: &Sim| sim.retargets.iter().map(|j| (j.id, j.drone, j.unit, j.version, j.priority(), j.intent)).collect::<Vec<_>>();
assert_eq!(jobs(&base), jobs(&changed), "a hidden change moved a route job");
}
// #127: the report explains each contact's part in the plan — how many drones aim at it, how many
// routes are still being worked out for it, and why a pending job waits — in plain English, since
// the core carries no player-facing text.
#[test]
fn the_report_explains_aims_and_pending_jobs_in_english() {
let mut sim = Sim::new(97);
watched_force(&mut sim);
for i in 0..6 {
let mut d = sim.make_drone(DroneKind::Kh22, DVec3::new(-900.0, 120.0, -400.0 + i as f64 * 80.0), DVec3::X, DVec3::new(900.0, 70.0, 0.0));
d.smart = true;
sim.queue.push((0, d));
}
sim.tick = 40;
sim.adapt();
let report = sim.enemy_picture();
assert!(!report.aims.is_empty(), "the report has no aims");
assert!(report.aims.iter().all(|a| matches!(a.intent, "react" | "plan" | "sead" | "replace")));
let aimed = report.contacts.iter().find(|c| c.aimed_by > 0).expect("no contact is aimed at");
assert!(aimed.pending_jobs > 0, "the aim of a pending route is not reported");
assert_eq!(report.pending.len(), report.contacts.iter().map(|c| c.pending_jobs).sum::<u32>() as usize);
let p = &report.pending[0];
assert!(!p.reason.is_empty() && p.priority <= 3);
assert_eq!(report.work_per_tick, super::super::raid::WORK_PER_TICK);
// No player-facing Russian in the core's diagnostics: every reported word is ASCII.
assert!(aimed.threat.is_ascii() && p.reason.is_ascii() && p.intent.is_ascii());
assert!(report.contacts.iter().all(|c| c.seen.is_ascii() && c.threat.is_ascii()));
}
// #127: a new disclosure is what updates the picture. The moved patriot is re-fixed at its
// new place: the picture, the prices and the adaptive aims follow the observation.
#[test]
fn a_new_observation_is_what_updates_the_picture() {
let mut sim = Sim::new(19);
let ids = watched_force(&mut sim);
sim.tick = 100;
let grid = grid();
let (before, _) = sim.price_grid(&grid, DroneKind::Kh101);
// A hidden move changes nothing...
sim.sams[0].pos = DVec3::new(-120.0, 70.0, 360.0);
let (mid, _) = sim.price_grid(&grid, DroneKind::Kh101);
assert_eq!(before, mid, "a hidden move changed the prices");
// ...until something discloses the unit again.
sim.intel.observe(&sim.sams[0], 200, Seen::Emission);
let picture = sim.picture_of_defences();
let c = picture.iter().find(|c| c.id == ids[0]).unwrap();
assert_eq!(c.at, DVec3::new(-120.0, 70.0, 360.0), "the new observation is not the one kept");
assert_eq!(c.tick, 200);
let (after, _) = sim.price_grid(&grid, DroneKind::Kh101);
assert_ne!(before, after, "the prices never noticed the re-observation");
}
// #127: a launcher-only S400 seen firing without its emissions ever fixed fights on the
// network in the picture: blind without a donor, dangerous out to the donor's reach with one.
#[test]
fn launcher_only_is_blind_in_the_picture_without_a_donor() {
let mut sim = Sim::new(5);
let id = sim.id();
let mut sam = Sam::new(id, SamKind::S400, DVec3::new(0.0, 70.0, 0.0), 0.0);
assert!(sam.set_mode(SamMode::LauncherOnly));
sim.intel.observe(&sam, 0, Seen::Launch);
sim.sams.push(sam);
let grid = grid();
let (prices, _) = sim.price_grid(&grid, DroneKind::Kh101);
assert!(prices.iter().all(|p| *p == 1.0), "a launcher believed blind priced a threat");
let report = sim.enemy_picture();
let c = report.contacts.iter().find(|c| c.id == id).unwrap();
assert!(!c.own_sensor && !c.donor_in_link, "the report disagrees with the blindness");
// A radar contact within data-link range of the observed place feeds it. The radar's
// actual role is not observable: the picture assumes any live radar contact feeds the
// network, and the report says so.
let id = sim.id();
let mut radar = Sam::new(id, SamKind::Radar, DVec3::new(300.0, 70.0, 0.0), 0.0);
radar.set_radar_role(super::super::battery::RadarRole::Search); // truth: cannot authorize
sim.intel.observe(&radar, 0, Seen::Emission);
sim.sams.push(radar);
let (prices, _) = sim.price_grid(&grid, DroneKind::Kh101);
assert!(prices.iter().any(|p| *p > 1.0), "a launcher with a linked radar priced no threat");
let report = sim.enemy_picture();
let c = report.contacts.iter().find(|c| c.kind == SamKind::S400).unwrap();
assert!(c.donor_in_link && !c.own_sensor, "the report does not name the network");
// The link breaking unobserved changes nothing in the picture: the radar's death is a
// secret until something watches it. Watched, the launcher goes blind again.
sim.sams.iter_mut().find(|s| s.kind == SamKind::Radar).unwrap().health = 0.0;
let (prices, _) = sim.price_grid(&grid, DroneKind::Kh101);
assert!(prices.iter().any(|p| *p > 1.0), "an unobserved link break changed the picture");
let radar_id = sim.sams.iter().find(|s| s.kind == SamKind::Radar).unwrap().id;
sim.intel.outcome(radar_id, false, DVec3::new(300.0, 70.0, 0.0), 50);
let (prices, _) = sim.price_grid(&grid, DroneKind::Kh101);
assert!(prices.iter().all(|p| *p == 1.0), "the watched donor died and the launcher stayed dangerous");
}
// #127: destruction is knowledge only when watched. A unit dying unseen keeps living in the
// picture and in the prices; the enemy's own munition watching the kill takes it out, and a
// fresh look at a live unit (a repair) brings it back.
#[test]
fn destruction_moves_the_picture_only_when_watched() {
let mut sim = Sim::new(23);
let ids = watched_force(&mut sim);
sim.tick = 100;
let grid = grid();
// Killed where nothing of the enemy's is watching: the picture never learns.
sim.sams[0].health = 0.0;
assert!(sim.picture_of_defences().iter().any(|c| c.id == ids[0]), "an unobserved kill removed the contact");
let (prices, _) = sim.price_grid(&grid, DroneKind::Kh101);
assert!(prices.iter().any(|p| *p > 1.0), "an unobserved kill changed the prices");
// The wreck watched by a strike: out of the picture and the prices...
sim.intel.outcome(ids[0], false, sim.sams[0].pos, 150);
assert!(!sim.known_live(ids[0]));
assert!(sim.picture_of_defences().iter().all(|c| c.id != ids[0]));
let (prices, _) = sim.price_grid(&grid, DroneKind::Kh101);
// The same force without the patriot: the watched death prices exactly as if it had
// never been seen (the jammer's cells stay: the jammer lives in the picture).
let mut without = Sim::new(23);
let kept = watched_force(&mut without);
without.intel.contacts.remove(&kept[0]);
let (expect, _) = without.price_grid(&grid, DroneKind::Kh101);
assert_eq!(prices, expect, "the watched-dead unit was still priced");
// ...and a fresh look at the rebuilt unit restores it.
sim.sams[0].health = 1.0;
sim.intel.observe(&sim.sams[0], 200, Seen::Emission);
assert!(sim.known_live(ids[0]) && sim.picture_of_defences().iter().find(|c| c.id == ids[0]).unwrap().tick == 200);
}
// #127: confidence is age alone. The bands gate what SEAD trusts (checked in raid.rs);
// here the picture and the report carry it.
#[test]
fn confidence_is_a_function_of_age_alone() {
let mut sim = Sim::new(29);
let ids = watched_force(&mut sim);
for (tick, want) in [(0, Confidence::Confirmed), (600, Confidence::Confirmed), (601, Confidence::Probable), (3000, Confidence::Probable), (3001, Confidence::Doubtful)] {
sim.tick = tick;
let c = sim.picture_of_defences().iter().find(|c| c.id == ids[0]).unwrap().confidence(tick);
assert_eq!(c, want, "tick {tick}");
let report = sim.enemy_picture();
let c = report.contacts.iter().find(|c| c.id == ids[0]).unwrap();
assert_eq!(c.confidence, want);
assert_eq!(c.age, tick);
}
sim.tick = ew::CONTACT_TTL - 1;
assert!(sim.known_live(ids[0]), "a contact dies before its TTL");
sim.tick = ew::CONTACT_TTL;
assert!(!sim.known_live(ids[0]), "a contact outlived its TTL");
sim.tick = ew::CONTACT_TTL + 2;
sim.adapt();
assert!(sim.picture_of_defences().is_empty(), "expired contacts were not pruned");
}
// #127: the structured report separates what was seen from what is believed, in English.
#[test]
fn enemy_picture_report_describes_observation_and_belief() {
let mut sim = Sim::new(31);
let ids = watched_force(&mut sim);
let id = sim.id();
let mut launcher = Sam::new(id, SamKind::S400, DVec3::new(0.0, 70.0, -3000.0), 0.0);
launcher.set_mode(SamMode::LauncherOnly);
sim.intel.observe(&launcher, 0, Seen::Launch);
sim.sams.push(launcher);
sim.tick = 40;
let report = sim.enemy_picture();
assert_eq!(report.contacts.len(), 4);
let by_id = |report: &EnemyPictureReport, id: u32| report.contacts.iter().find(|c| c.id == id).unwrap().clone();
let ew_c = by_id(&report, ids[2]);
assert_eq!(ew_c.seen, "jamming");
assert_eq!(ew_c.confidence, Confidence::Confirmed);
assert!(ew_c.live && ew_c.threat.contains("jamming"), "{}", ew_c.threat);
let sam_c = by_id(&report, id);
assert_eq!(sam_c.seen, "launch");
assert!(!sam_c.own_sensor, "a launch without emission fixes read as an own sensor");
assert!(sam_c.threat.contains("blind"), "{}", sam_c.threat);
let pat = by_id(&report, ids[0]);
assert!(pat.own_sensor && pat.seen == "emission");
assert!(pat.donor_in_link, "the radar contact should read as the patriot's network");
}
}
#[cfg(test)]
mod outcome_tests {
use super::*;
// #127: the battle-damage channel end to end. A drone the picture knows the target of flies
// to a unit that cannot shoot back (a radar); its impact watches the unit die, and the
// picture — not the truth — is what learns it. An identical loss nobody watches stays a
// live contact.
#[test]
fn an_impact_watches_the_kill_and_updates_only_the_picture() {
let mut sim = Sim::new(37);
let at = DVec3::new(0.0, 70.0, 0.0);
let id = sim.id();
let sam = Sam::new(id, SamKind::Radar, at, 0.0);
sim.intel.observe(&sam, 0, Seen::Launch);
sim.sams.push(sam);
// Low and level, so the impact sweeps the hull instead of diving into the ground early.
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 71.0, -200.0), DVec3::Z, at);
let mut ground = Ground::default();
let mut out = Out::default();
let mut seen_dead = None;
for now in 1..1200 {
sim.tick = now;
sim.step(&mut ground, None, &mut out);
seen_dead = sim.intel.contacts.get(&id).and_then(|c| c.destroyed);
if seen_dead.is_some() && !sim.drones.iter().any(|d| d.alive()) {
break;
}
}
let contact = sim.intel.contacts.get(&id).expect("the contact is forgotten while fresh");
assert!(!sim.sams[0].alive(), "the setup: the impact must kill the unit");
assert_eq!(seen_dead, contact.destroyed);
assert!(contact.destroyed.is_some(), "the impact watched the kill and the picture learned nothing");
assert!(!sim.known_live(id));
assert_eq!(sim.picture_of_defences(), Vec::new(), "a watched-dead unit stayed a target");
// The same loss, unwatched: the drone dies far from the unit and the contact lives on.
let mut other = Sim::new(37);
let id2 = other.id();
let sam = Sam::new(id2, SamKind::Radar, at, 0.0);
other.intel.observe(&sam, 0, Seen::Launch);
other.sams.push(sam);
other.add_drone(DroneKind::Shahed, DVec3::new(0.0, 80.0, -600.0), DVec3::Z, at);
// The drone is shot down far short of the aim: nothing watches the unit's fate.
other.drones[0].pos = DVec3::new(0.0, 80.0, -400.0);
let _ = other.shoot_down(0, 0, None, &Ground::default(), &mut Out::default());
let mut ground = Ground::default();
let mut out = Out::default();
for now in 1..1200 {
other.tick = now;
other.step(&mut ground, None, &mut out);
if !other.drones.iter().any(|d| d.alive()) {
break;
}
}
assert!(other.intel.contacts.get(&id2).unwrap().destroyed.is_none(), "an unwatched fate changed the picture");
assert!(other.known_live(id2));
}
}
#[cfg(test)]
mod intent_tests {
use super::*;
use super::super::raid::Grid;
use std::collections::HashMap;
/// A unit the picture knows of, placed and observed once.
fn watch(sim: &mut Sim, kind: SamKind, at: DVec3, tick: u64, seen: Seen) -> u32 {
let id = sim.id();
let sam = Sam::new(id, kind, at, 0.0);
sim.intel.observe(&sam, tick, seen);
sim.sams.push(sam);
id
}
fn smart_drone(sim: &mut Sim, kind: DroneKind, from: DVec3, aim: DVec3) -> u32 {
let mut d = sim.make_drone(kind, from, DVec3::X, aim);
d.smart = true;
let id = d.id;
sim.queue.push((0, d));
id
}
fn goal_unit(sim: &Sim, id: u32) -> u32 {
sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)).find(|d| d.id == id).unwrap().aim.unit
}
// #127: the plan records *why* a drone is aimed where it is. A radar strike is planned SEAD;
// everything else the plan chose is its own objective, never a random re-pick.
#[test]
fn the_plan_records_sead_separately_from_its_objective() {
let mut sim = Sim::new(41);
let radar = watch(&mut sim, SamKind::Radar, DVec3::new(0.0, 70.0, 0.0), 0, Seen::Emission);
let order = raid::RaidOrder {
kinds: vec![(DroneKind::Kh22, 8), (DroneKind::Shahed, 4)],
approach: raid::Approach::Sector,
dist: 1200.0,
aim: raid::Aim::Smart,
};
let objects = [DVec3::new(0.0, 70.0, 300.0)];
let mut out = Out::default();
sim.order_raid(&order, &objects, &mut out);
let intents = sim.planned_intents();
assert_eq!(intents.len(), 12, "the plan did not hold every drone");
let sead = intents.iter().filter(|i| i.1 == Intent::Sead).count();
assert!(sead > 0, "no SEAD job was recorded for the observed radar");
assert!(intents.iter().filter(|i| i.1 == Intent::Plan).count() > 0, "the plan's own objective was not recorded");
assert!(intents.iter().all(|i| matches!(i.1, Intent::Sead | Intent::Plan)));
// Every SEAD job goes for the observed radar; the planner's own picks may also aim at it,
// but they are recorded as its objective, not as SEAD.
assert!(sim.planned_aims().iter().filter(|(_, i)| *i == Intent::Sead).all(|(unit, _)| *unit == radar));
}
// #127: a mass retarget is spread over adaptive ticks and contacts: one tick assigns a bounded
// number of new aims, and a single contact does not draw the whole force.
#[test]
fn assignments_are_throttled_per_tick_and_per_contact() {
let mut sim = Sim::new(43);
for k in 0..6 {
watch(&mut sim, SamKind::S400, DVec3::new(-600.0 + k as f64 * 240.0, 70.0, -200.0), 0, Seen::Emission);
}
for i in 0..40 {
let from = DVec3::new(-1800.0, 120.0, -900.0 + i as f64 * 40.0);
smart_drone(&mut sim, DroneKind::Kh22, from, DVec3::new(1800.0, 70.0, 1800.0));
}
sim.tick = 40;
sim.adapt();
let assigned: Vec<(u32, Intent, u64, u16)> = sim
.queue
.iter()
.map(|(_, d)| d)
.filter(|d| d.aim.unit != 0)
.map(|d| (d.aim.unit, d.intent, d.aim.since, d.aim.switches))
.collect();
assert_eq!(assigned.len(), ASSIGN_PER_TICK, "the first adaptive tick did not assign its bounded share");
let mut per: HashMap<u32, usize> = HashMap::new();
for (unit, intent, since, switches) in &assigned {
*per.entry(*unit).or_insert(0) += 1;
assert_eq!(*intent, Intent::React, "a reaction to a disclosure was recorded as something else");
assert!(*switches == 0 && *since == 40);
}
assert!(per.values().all(|n| *n <= ASSIGN_PER_CONTACT), "one contact drew more than {ASSIGN_PER_CONTACT} drones: {per:?}");
assert!(sim.retarget_ids().len() <= ASSIGN_PER_TICK);
sim.tick = 80;
sim.adapt();
let now = sim.queue.iter().filter(|(_, d)| d.aim.unit != 0).count();
assert!(now > assigned.len(), "the next adaptive tick assigned nobody");
assert_eq!(now, 32, "the second adaptive tick did not assign its bounded share");
// No drone's aim repeats a unit twice in the queue: an assignment is per drone.
let mut drones: Vec<u32> = sim.queue.iter().map(|(_, d)| d.id).collect();
drones.sort_unstable();
drones.dedup();
assert_eq!(drones.len(), 40);
}
// #127: a fresh disclosure replaces an aim only after the hold and within the cap, and only when
// it is clearly better placed — a switch throws the route away and costs a new one.
#[test]
fn a_fresh_disclosure_switches_an_aim_only_after_the_hold() {
let mut sim = Sim::new(47);
let far = watch(&mut sim, SamKind::Patriot, DVec3::new(400.0, 70.0, 400.0), 0, Seen::Emission);
let near = watch(&mut sim, SamKind::Ew, DVec3::new(-520.0, 70.0, -520.0), 0, Seen::Jamming);
let mut d = sim.make_drone(DroneKind::Kh22, DVec3::new(-600.0, 120.0, -600.0), DVec3::X, DVec3::new(400.0, 70.0, 400.0));
d.smart = true;
let at = sim.intel.contacts()[&far].at;
d.target = at + d.err;
d.intent = Intent::Plan;
d.aim = Aim::unit(far, 0, Confidence::Confirmed);
let id = d.id;
sim.queue.push((0, d));
// The jammer shows itself again later: a fresh disclosure.
sim.intel.note(near, SamKind::Ew, sim.intel.contacts()[&near].at, true, 100, Seen::Jamming);
sim.tick = 120;
sim.adapt_targets();
assert_eq!(goal_unit(&sim, id), far, "the aim was switched before the hold elapsed");
sim.tick = 160;
sim.adapt_targets();
assert_eq!(goal_unit(&sim, id), near, "a clearly better placed fresh disclosure did not switch the aim");
let d = sim.queue.iter().map(|(_, d)| d).find(|x| x.id == id).unwrap();
assert_eq!((d.intent, d.aim.switches), (Intent::React, 1), "the switch was not recorded as a reaction");
// The cap holds: a drone that has switched its fill keeps the aim it has.
let d = sim.queue.iter_mut().map(|(_, d)| d).find(|x| x.id == id).unwrap();
d.aim.switches = SWITCH_CAP;
let before = d.target;
sim.intel.note(far, SamKind::S400, DVec3::new(-640.0, 70.0, -640.0), true, 300, Seen::Launch);
sim.tick = 400;
sim.adapt_targets();
assert_eq!(sim.queue.iter().map(|(_, d)| d).find(|x| x.id == id).unwrap().target, before, "a drone past the switch cap was turned again");
}
// #127: an aim the picture watched die is replaced by the nearest live contact — a distinct,
// lower-priority decision than a disclosure reaction.
#[test]
fn a_watched_kill_replaces_the_aim_and_queues_a_lower_priority_route() {
let mut sim = Sim::new(53);
let dead = watch(&mut sim, SamKind::S400, DVec3::new(0.0, 70.0, 0.0), 0, Seen::Emission);
let alive = watch(&mut sim, SamKind::S400, DVec3::new(300.0, 70.0, 300.0), 0, Seen::Emission);
let mut d = sim.make_drone(DroneKind::Kh22, DVec3::new(-600.0, 120.0, -600.0), DVec3::X, DVec3::new(0.0, 70.0, 0.0));
d.smart = true;
d.target = sim.intel.contacts()[&dead].at + d.err;
d.aim = Aim::unit(dead, 0, Confidence::Confirmed);
let id = d.id;
sim.drones.push(d);
// The enemy's own munition watched it die: the picture stops believing in it.
sim.intel.outcome(dead, false, DVec3::new(0.0, 70.0, 0.0), 40);
sim.tick = 40;
sim.adapt_targets();
let d = sim.drones.iter().find(|x| x.id == id).unwrap();
assert_eq!(d.aim.unit, alive, "the dead aim was not replaced by the nearest live contact");
assert_eq!(d.intent, Intent::Replace);
assert_eq!(d.aim.switches, 1);
let pending = sim.pending_intents();
assert!(pending.iter().any(|(_, i)| *i == Intent::Replace), "the replacement has no route job");
}
// #127: a unit that fires is observed to fire, and the picture counts the launches it watched. The
// magazine behind them is never in the picture: a hidden empty one changes nothing.
#[test]
fn launched_rounds_are_observed_but_the_magazine_is_not() {
let mut sim = Sim::new(59);
let id = watch(&mut sim, SamKind::Patriot, DVec3::new(0.0, 70.0, 0.0), 10, Seen::Launch);
sim.intel.note(id, SamKind::Patriot, DVec3::new(0.0, 70.0, 0.0), true, 20, Seen::Launch);
sim.tick = 20;
assert_eq!(sim.intel.contacts()[&id].launches, 2, "observed launches are not counted");
let report = sim.enemy_picture();
assert_eq!(report.contacts.iter().find(|c| c.id == id).unwrap().launches, 2);
let grid = Grid { min: DVec3::new(-480.0, 0.0, -480.0), cell: 16.0, size: 60 };
let before = sim.price_grid(&grid, DroneKind::Kh101);
// The magazine is empty and the launcher split from its radar: hidden changes.
let sam = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
sam.missiles = 0;
sam.bursts = 0;
sam.set_mode(super::super::battery::SamMode::LauncherOnly);
sim.sams.iter_mut().find(|s| s.id == id).unwrap().radar_on = false;
assert_eq!(before, sim.price_grid(&grid, DroneKind::Kh101), "a hidden magazine changed the prices");
assert_eq!(sim.enemy_picture().contacts.iter().find(|c| c.id == id).unwrap().launches, 2);
}
// #127: land the job's knowledge version did not map is not free. Given the same grid, the route
// with unknown cells priced keeps to the mapped land where the free-unknown one cuts across.
#[test]
fn unknown_land_is_not_free_in_a_replanned_route() {
let size = 80;
let grid = Grid { min: DVec3::new(-640.0, 0.0, -640.0), cell: 16.0, size };
// The plan mapped the left half; under it the land is high, so the mapped way costs altitude.
let mut heights = vec![f32::NAN; (size * size) as usize];
for i in 0..size / 2 {
for j in 0..size {
heights[(i * size + j) as usize] = 400.0;
}
}
let prices = vec![1.0f32; (size * size) as usize];
let from = DVec3::new(-520.0, 120.0, -520.0);
let to = DVec3::new(-40.0, 120.0, 520.0);
let plan = |unknown: f32| {
let relief = raid::Relief { heights: &heights, slope: 1.0, floor: 70.0, unknown };
let (route, _) = raid::plan_route_on(&grid, &prices, Some(&relief), from, to);
route
};
let unknown_cells = |route: &[DVec3]| {
route.iter().filter(|p| { let (i, j) = grid.index(**p); heights[(i * size + j) as usize].is_nan() }).count()
};
let free = plan(0.0);
let priced = plan(UNKNOWN_LAND);
assert!(unknown_cells(&free) > 0, "the test's free-unknown route never left the mapped land");
assert!(unknown_cells(&priced) < unknown_cells(&free), "priced unknown land did not keep the route to what was mapped");
assert_eq!(priced.last().unwrap(), &to);
}
// #127: the queue is bounded, and a job that is not worth more than what is queued does not
// displace anything.
#[test]
fn the_route_queue_is_bounded_and_refuses_a_worthless_job() {
let mut sim = Sim::new(61);
for i in 0..JOBS_MAX {
let mut d = sim.make_drone(DroneKind::Kh22, DVec3::new(i as f64, 100.0, 0.0), DVec3::X, DVec3::new(1000.0, 70.0, 0.0));
d.smart = true;
let id = d.id;
sim.drones.push(d);
sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 0.0), 0, 1, Arc::new(KnowledgeSnapshot::empty(1)), None));
}
assert_eq!(sim.retargets.len(), JOBS_MAX);
// A replacement is worth less than a plan's objective: the queue refuses it.
let mut d = sim.make_drone(DroneKind::Kh22, DVec3::new(0.0, 100.0, 50.0), DVec3::X, DVec3::new(1000.0, 70.0, 50.0));
d.smart = true;
let id = d.id;
sim.drones.push(d);
sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 50.0), 0, 2, Arc::new(KnowledgeSnapshot::empty(2)), None).with_intent(Intent::Replace));
assert_eq!(sim.retargets.len(), JOBS_MAX, "a worthless job grew the queue");
// Nothing queued is a replacement: a replacement is the lowest priority and does displace one.
sim.retargets.iter_mut().for_each(|j| j.intent = Intent::Replace);
let mut d = sim.make_drone(DroneKind::Kh22, DVec3::new(0.0, 100.0, 60.0), DVec3::X, DVec3::new(1000.0, 70.0, 60.0));
d.smart = true;
let id = d.id;
sim.drones.push(d);
sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 60.0), 0, 2, Arc::new(KnowledgeSnapshot::empty(2)), None).with_intent(Intent::Plan));
assert_eq!(sim.retargets.len(), JOBS_MAX, "the bound was broken");
assert!(sim.retargets.back().is_some_and(|j| j.drone == id && j.intent == Intent::Plan), "the plan's job did not make room");
}
// #127: the same seed makes the same intents, aims and jobs; the throttle and the priority order
// never make it seed-dependent in a way that differs between two runs of one seed.
#[test]
fn the_same_seed_chose_the_same_intents_and_jobs() {
let build = |seed: u64| {
let mut sim = Sim::new(seed);
for k in 0..5 {
watch(&mut sim, SamKind::S400, DVec3::new(-500.0 + k as f64 * 250.0, 70.0, 0.0), 0, Seen::Emission);
}
for i in 0..24 {
smart_drone(&mut sim, DroneKind::Kh22, DVec3::new(-1600.0, 110.0, -500.0 + i as f64 * 40.0), DVec3::new(1600.0, 70.0, 1600.0));
}
sim.tick = 40;
sim.adapt();
let aims: Vec<_> = sim.queue.iter().map(|(_, d)| (d.id, d.intent, d.aim.unit, d.aim.since, d.aim.switches)).collect();
let jobs: Vec<_> = sim.retargets.iter().map(|j| (j.id, j.drone, j.unit, j.version, j.priority())).collect();
(aims, jobs)
};
let a = build(67);
let b = build(67);
assert_eq!(a, b, "the same seed produced different intents or jobs");
assert!(!a.1.is_empty(), "the test no longer leaves jobs pending");
}
}