From 32748b116c77e962fa90f3be59dd459cf0fa0d16 Mon Sep 17 00:00:00 2001 From: chexit Date: Sat, 21 Nov 2026 10:57:04 +0300 Subject: [PATCH] Smart v2 on top of #146: one public picture, mark prices, bounded refresh, bearing window (#149) Re-applied the genuinely new #149 features onto kimi-work, REUSING the already-integrated #146 infrastructure (KnowledgeSnapshot { tick, contacts, marks }, knowledge_now(), Plan.knowledge, RouteJob.known, versioned price_grid_known and restore). No #146 scaffolding is duplicated: one snapshot per order, prices over known.tick, versioned restore are kept exactly as they were. The only additive change to KnowledgeSnapshot is observations(). New #149 layer: - observe::Observation + observe::merge: Contact and Mark become one public hint, matched by public features only (area overlap + exact category); coarse Unknown/contradicting marks stay separate, the contact's kind/fix are never rewritten, recon.truth and real ids are not used. One Observation::rank scale replaces the two ranks in radar_strikes, choose_target and the adaptive picks (kimi-work's slice signatures kept). - price_grid_known prices marks: a trusted launcher/gun/jammer mark prices its published category envelope weighted by confidence (Confirmed x1, Probable x0.5); a radar mark feeds the network belief; a mark matched to a contact is priced once through the contact; a doubtful mark prices nothing. - Bounded refresh of the unreleased portion: ew::Refresh with absolute deadline REFRESH_WINDOW=600; step_refresh re-aims queued Plan/Sead drones once on a report (typed Intent::Refresh, SEAD priority) within SWITCH_CAP and assignment budgets; no report never delays a launch. - Bearing window: Intel.outcomes bounded VecDeque (48 entries, 12000-tick window); best_bearing adapts exploration share by typed BearingReason (few/stale/conditions-changed/exploiting); conditions are a fingerprint of the public picture, never hidden state. bearing_report() and bearing/refresh_*/observations fields in EnemyPictureReport. Legacy fixed share kept. - examples/smart_bench runner (simple/current/candidate, seeds 1/7/42, open/hills/config-change/ recon-lost, JSON+lines); Sim::smart_legacy reproduces current Smart; harness::run_with_hook. Light modes and bounded jobs unchanged; policy reads no health/charges/hidden switches/positions. Tests: smart_tests + observe::tests (metamorphic hidden-layout, public dedup, marks in prices, one version per order in both modes, bounded refresh fires-once/never-pauses, bearing window and reasons, durable window + Intent::Refresh). The relief-version regression fixture's wall is widened in z so it crosses any east-west route after the candidate's assignment-order change. cargo test passes: airdef-core 326 lib + 8 scenarios; airdef-mod 113 lib + core_boundary + 5 scenarios. Co-Authored-By: Kimi Code --- airdef-mod/examples/sim_run/harness.rs | 42 ++- airdef-mod/examples/smart_bench.rs | 187 +++++++++++ airdef-mod/src/recon_view.rs | 16 +- airdef-mod/src/sim/durable.rs | 42 ++- airdef-mod/src/sim/ew.rs | 432 +++++++++++++++++++++---- airdef-mod/src/sim/mod.rs | 32 +- airdef-mod/src/sim/observe.rs | 268 +++++++++++++++ airdef-mod/src/sim/raid.rs | 145 +++++++-- airdef-mod/src/sim/regress.rs | 4 +- airdef-mod/src/sim/smart_tests.rs | 312 ++++++++++++++++++ docs/CODEX-HANDOFF.md | 39 +++ 11 files changed, 1435 insertions(+), 84 deletions(-) create mode 100644 airdef-mod/examples/smart_bench.rs create mode 100644 airdef-mod/src/sim/observe.rs create mode 100644 airdef-mod/src/sim/smart_tests.rs diff --git a/airdef-mod/examples/sim_run/harness.rs b/airdef-mod/examples/sim_run/harness.rs index ef5d4f5..8eb4ba3 100644 --- a/airdef-mod/examples/sim_run/harness.rs +++ b/airdef-mod/examples/sim_run/harness.rs @@ -72,6 +72,9 @@ pub struct Scenario { pub ew: bool, /// Ticks a truck on a job may stand still before it counts as stuck. pub stuck_after: u64, + /// The smart enemy runs the legacy picks (#149's comparison runner): separate hint lists, + /// the lifetime bearing tally, no mark pricing and no refresh of the unreleased portion. + pub legacy: bool, } impl Scenario { @@ -87,6 +90,7 @@ impl Scenario { stop_at_end: true, ew: false, stuck_after: 600, + legacy: false, } } pub fn unit(&mut self, kind: SamKind, x: f64, z: f64) -> &mut Unit { @@ -138,6 +142,18 @@ pub struct Report { pub intents: String, /// The most aim switches one drone went through. pub switches_max: u16, + /// Smart drones seen over the run (#149's comparison). + pub smart_seen: u32, + /// The share of them whose last aim was a live public hint when last seen (#149). + pub useful_share: f64, + /// Distinct aim units over the smart drones seen, per drone (#149). + pub diversity: f64, + /// The share of smart drones switched twice or more (#149's jitter). + pub jittery_share: f64, + /// The bearing picker's last typed reason (#149). + pub bearing_reason: String, + /// Aims the bounded refresh re-chose (#149). + pub refresh_applied: u32, } /// The last intent every smart drone of the run was seen carrying, as `name:count`. @@ -146,7 +162,7 @@ fn intent_counts(seen: &HashMap) -> String { for name in seen.values() { *counts.entry(*name).or_insert(0usize) += 1; } - ["plan", "sead", "react", "replace"].iter().map(|k| format!("{k}:{}", counts.get(*k).copied().unwrap_or(0))).collect::>().join(",") + ["plan", "sead", "react", "replace", "refresh"].iter().map(|k| format!("{k}:{}", counts.get(*k).copied().unwrap_or(0))).collect::>().join(",") } fn finite(v: DVec3) -> bool { @@ -154,7 +170,14 @@ fn finite(v: DVec3) -> bool { } pub fn run(sc: &Scenario) -> Report { + run_with_hook(sc, &mut |_, _| {}) +} + +/// The same, with a hook called after every tick (#149's comparison runner): a scenario may +/// change the defence between waves or shoot a recon flight down before its report. +pub fn run_with_hook(sc: &Scenario, hook: &mut dyn FnMut(u64, &mut Sim)) -> Report { let mut sim = Sim::new(sc.seed); + sim.smart_legacy = sc.legacy; sim.damage = false; // explosions would change the land the height function describes for u in &sc.units { let id = sim.id(); @@ -183,6 +206,8 @@ pub fn run(sc: &Scenario) -> Report { let mut standing: HashMap = HashMap::new(); // drone id -> the last structured intent it carried (#127). let mut intents_seen: HashMap = HashMap::new(); + // drone id -> (last aim unit, whether the picture held it live then, switches) (#149). + let mut decisions: HashMap = HashMap::new(); let mut out = Out::default(); for now in 1..=sc.ticks { // Raids come in order: one is ordered once the previous one has been sent. @@ -205,6 +230,7 @@ pub fn run(sc: &Scenario) -> Report { ground.world.serve(&sc.terrain, sections, now); let dt = t.elapsed(); times.push(dt); + hook(now, &mut sim); if planning { r.planning += dt; r.planning_ticks += 1; @@ -220,6 +246,8 @@ pub fn run(sc: &Scenario) -> Report { for d in sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)) { if d.alive() && d.smart() { intents_seen.insert(d.id, d.intent().name()); + let unit = d.aim_unit(); + decisions.insert(d.id, (unit, unit != 0 && sim.known_live(unit), d.aim_switches())); } } // The air section a save would take, sampled when the sky is fullest (writing it every tick @@ -271,6 +299,18 @@ pub fn run(sc: &Scenario) -> Report { r.raids_ended = ended.iter().filter(|o| **o).count(); r.all_ended = r.raids_ended == sc.raids.len(); r.intents = intent_counts(&intents_seen); + r.smart_seen = decisions.len() as u32; + if !decisions.is_empty() { + let n = decisions.len() as f64; + r.useful_share = decisions.values().filter(|(_, live, _)| *live).count() as f64 / n; + let mut units: Vec = decisions.values().map(|(u, _, _)| *u).collect(); + units.sort_unstable(); + units.dedup(); + r.diversity = units.len() as f64 / n; + r.jittery_share = decisions.values().filter(|(_, _, s)| *s >= 2).count() as f64 / n; + } + r.bearing_reason = sim.bearing_report().reason.name().to_string(); + r.refresh_applied = sim.refresh_applied(); r.tick_total = times.iter().sum(); times.sort(); if !times.is_empty() { diff --git a/airdef-mod/examples/smart_bench.rs b/airdef-mod/examples/smart_bench.rs new file mode 100644 index 0000000..10a0f00 --- /dev/null +++ b/airdef-mod/examples/smart_bench.rs @@ -0,0 +1,187 @@ +//! Smart v2 comparison runner (#149): the simple mode, the current (legacy) Smart and the +//! candidate, on fixed seeds and one scenario set — open map, hills, a configuration changed +//! between waves, and a recon flight shot down before its report. +//! +//! It prints one JSON array of rows: the share of useful decisions (a smart drone whose last +//! aim was a live public hint), the diversity of aims, the reasons (intents) on the review, +//! the share of jittery drones (two switches or more), the bearing picker's typed reason, the +//! refresh count, and the CPU/worst-job figures. The goal is interesting counterplay and clear +//! mistakes, not a maximised hit count — read the reasons and the jitter beside the losses. +//! +//! cargo run --release --example smart_bench +#[path = "sim_run/harness.rs"] +mod harness; + +use airdef::sim::{Aim, Approach, DroneKind, Sam, SamKind, Sim}; +use glam::DVec3; +use harness::{Report, Scenario, Terrain}; + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + Simple, + Current, + Candidate, +} + +impl Mode { + fn name(self) -> &'static str { + match self { + Mode::Simple => "simple", + Mode::Current => "current", + Mode::Candidate => "candidate", + } + } + fn apply(self, sc: &mut Scenario) { + sc.legacy = self == Mode::Current; + let aim = match self { + Mode::Simple => Aim::ObjectsAndSams, + _ => Aim::Smart, + }; + for raid in &mut sc.raids { + raid.aim = aim; + } + } +} + +fn esc(s: &str) -> String { + s.chars().flat_map(|c| match c { + '"' => "\\\"".chars().collect::>(), + '\\' => "\\\\".chars().collect::>(), + c => vec![c], + }).collect() +} + +fn row(sc: &str, mode: Mode, r: &Report) -> String { + format!( + "{{\"scenario\":\"{}\",\"mode\":\"{}\",\"seed\":{},\"ticks\":{},\"all_ended\":{},\"launched\":{},\"kills\":{},\"hits\":{},\"fired\":{},\"sams_lost\":{},\"smart_seen\":{},\"useful_share\":{:.3},\"diversity\":{:.3},\"jittery_share\":{:.3},\"intents\":\"{}\",\"bearing_reason\":\"{}\",\"refresh_applied\":{},\"switches_max\":{},\"retargets_max\":{},\"tick_p95_ms\":{:.3},\"tick_max_ms\":{:.3},\"planning_ms\":{:.1},\"air_bytes\":{}}}", + esc(sc), + mode.name(), + r.seed, + r.ticks_run, + r.all_ended, + r.launched, + r.kills, + r.hits, + r.fired, + r.sams_lost, + r.smart_seen, + r.useful_share, + r.diversity, + r.jittery_share, + esc(&r.intents), + esc(&r.bearing_reason), + r.refresh_applied, + r.switches_max, + r.retargets_max, + r.tick_p95.as_secs_f64() * 1000.0, + r.tick_max.as_secs_f64() * 1000.0, + r.planning.as_secs_f64() * 1000.0, + r.air_bytes, + ) +} + +/// An open map: a ring of systems on flat land, one combined strike. +fn open() -> Scenario { + let mut sc = Scenario::new("open"); + sc.terrain = Terrain::Flat(70); + for i in 0..18 { + let a = i as f64 * 2.399_963; + let r = 120.0 + (i as f64 / 18.0) * 320.0; + let kind = [SamKind::Radar, SamKind::S400, SamKind::Pantsir, SamKind::Ew, SamKind::Tor][i % 5]; + sc.unit(kind, a.sin() * r, a.cos() * r).heading = a; + } + sc.raids.push(harness::RaidSpec { + kinds: vec![(DroneKind::Gerbera, 6), (DroneKind::Shahed, 10), (DroneKind::Kh101, 3), (DroneKind::Kh22, 2), (DroneKind::Lancet, 3)], + approach: Approach::AllSides, + aim: Aim::Smart, + dist: 500.0, + at: 1, + }); + sc.ticks = 20 * 60 * 6; + sc +} + +/// Hills: the standard big smart scenario's terrain and force. +fn hills() -> Scenario { + let mut sc = harness::big_smart(); + sc.name = "hills".into(); + sc.ticks = 20 * 60 * 6; + sc +} + +/// Two waves with the defence changed between them: a radar moves unobserved, the EW stations +/// switch on, and a fresh battery appears. The second wave's picture must earn what it knows. +fn config_change() -> Scenario { + let mut sc = open(); + sc.name = "config-change".into(); + sc.raids.push(harness::RaidSpec { + kinds: vec![(DroneKind::Shahed, 8), (DroneKind::Geran3, 4), (DroneKind::Kh22, 2), (DroneKind::Iskander, 2)], + approach: Approach::TwoSectors, + aim: Aim::Smart, + dist: 600.0, + at: 4200, + }); + sc.ticks = 20 * 60 * 10; + sc +} + +/// A recon flight shot down before its report: the strike must fly on the picture it had, and +/// the bounded refresh must never hold the raid waiting for a report that will not come. +fn recon_lost() -> Scenario { + let mut sc = open(); + sc.name = "recon-lost".into(); + sc.ticks = 20 * 60 * 6; + sc +} + +pub fn main() { + let seeds = [1u64, 7, 42]; + let scenarios: [(&str, fn() -> Scenario); 4] = [("open", open), ("hills", hills), ("config-change", config_change), ("recon-lost", recon_lost)]; + let modes = [Mode::Simple, Mode::Current, Mode::Candidate]; + let mut rows = Vec::new(); + for (name, make) in scenarios { + for mode in modes { + for &seed in &seeds { + let r = run(mode, name, make, seed); + rows.push(row(name, mode, &r)); + eprintln!("{name} {} seed {seed}: useful {:.2} diversity {:.2} jitter {:.2} kills {} hits {} reasons {} bearing {} refresh {}", mode.name(), r.useful_share, r.diversity, r.jittery_share, r.kills, r.hits, r.intents, r.bearing_reason, r.refresh_applied); + } + } + } + println!("[{}]", rows.join(",\n")); +} + +fn run(mode: Mode, name: &str, make: fn() -> Scenario, seed: u64) -> Report { + let mut sc = make(); + sc.seed = seed; + mode.apply(&mut sc); + match name { + "config-change" => { + let mut changed = false; + harness::run_with_hook(&sc, &mut |now, sim: &mut Sim| { + if !changed && now >= 3600 && !sim.planning() { + changed = true; + if let Some(radar) = sim.sams.iter_mut().find(|s| s.kind == SamKind::Radar) { + radar.pos += DVec3::new(300.0, 0.0, -200.0); + } + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::Pantsir, DVec3::new(-200.0, 70.0, 250.0), 0.0)); + sim.set_ew(true); + } + }) + } + "recon-lost" => { + let mut killed = false; + harness::run_with_hook(&sc, &mut |now, sim: &mut Sim| { + if !killed && now >= 120 { + let recon: Vec = sim.drones.iter().filter(|d| sim.is_recon_drone(d.id)).map(|d| d.id).collect(); + if !recon.is_empty() { + sim.drones.retain(|d| !recon.contains(&d.id)); + killed = true; + } + } + }) + } + _ => harness::run(&sc), + } +} diff --git a/airdef-mod/src/recon_view.rs b/airdef-mod/src/recon_view.rs index f47fbbf..53b3415 100644 --- a/airdef-mod/src/recon_view.rs +++ b/airdef-mod/src/recon_view.rs @@ -182,7 +182,7 @@ pub fn picture_lines(pic: &EnemyPictureReport) -> Vec { #[cfg(test)] mod tests { use super::*; - use crate::sim::{AimReport, Confidence, EnemyPictureReport, ReconReport, ReconSortieReport}; + use crate::sim::{AimReport, BearingReport, Confidence, EnemyPictureReport, ReconReport, ReconSortieReport}; use glam::DVec3; fn mark(id: u32, category: &'static str, role: Option<&'static str>, quality: &'static str, confidence: Confidence, age: u64) -> ReconReport { @@ -198,7 +198,19 @@ mod tests { } fn picture(recon: Vec, recon_sorties: Vec, aims: Vec) -> EnemyPictureReport { - EnemyPictureReport { now: 1000, contacts: Vec::new(), aims, pending: Vec::new(), work_per_tick: 4, recon, recon_sorties } + EnemyPictureReport { + now: 1000, + contacts: Vec::new(), + aims, + pending: Vec::new(), + work_per_tick: 4, + recon, + recon_sorties, + observations: Vec::new(), + bearing: BearingReport::default(), + refresh_waiting: false, + refresh_applied: 0, + } } // The reason names all three factors with the planner's own weights, and they sum to the priority. diff --git a/airdef-mod/src/sim/durable.rs b/airdef-mod/src/sim/durable.rs index e8b4d3b..33421c8 100644 --- a/airdef-mod/src/sim/durable.rs +++ b/airdef-mod/src/sim/durable.rs @@ -51,6 +51,8 @@ pub struct AirSave { job_next: u32, kills: [u32; ew::SECTORS], hits: [u32; ew::SECTORS], + /// The bearing memory's small window of recent outcomes (#149). + outcomes: Vec, contacts: Vec, drones: Vec, queue: Vec<(u64, Drone)>, @@ -247,6 +249,16 @@ impl Sim { head += &format!(" {v}"); } head += "\n"; + // The bearing window (#149): bounded, and optional — an older save without it loads with + // an empty window and the lifetime tally it does carry. + let outcomes: Vec<&ew::Learned> = self.intel.outcomes().iter().take(ew::MAX_OUTCOMES).collect(); + if !outcomes.is_empty() { + head += &format!("airlearn {}", outcomes.len()); + for o in &outcomes { + head += &format!(" {} {} {}", o.sector, o.tick, u8::from(o.killed)); + } + head += "\n"; + } head += &format!("airglobal {}\n", global.map_or_else(|| "-".into(), |t| t.to_string())); for (i, r) in reliefs.iter().enumerate() { let g = r.grid(); @@ -319,7 +331,7 @@ impl Sim { .zip(job_relief) .filter(|(j, _)| saved.contains(&j.drone) && (j.unit == 0 || units.contains(&j.unit))) .collect(); - if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() && self.recon.is_empty() { + if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() && self.recon.is_empty() && outcomes.is_empty() { return None; } let head = head.replacen( @@ -467,6 +479,7 @@ impl Sim { let n_reliefs = l.count(8, "версии рельефа", MAX_RELIEFS)?; // Every line of the section, and nothing else: a truncated or foreign line is refused. let mut intel: Option<[u32; ew::SECTORS * 2]> = None; + let mut outcomes: Vec = Vec::new(); let mut global: Option = None; let mut reliefs: Vec>> = vec![None; n_reliefs]; let mut contacts: BTreeMap = BTreeMap::new(); @@ -499,6 +512,21 @@ impl Sim { } intel = Some(v); } + "airlearn" => { + let n = l.count(1, "исходы", ew::MAX_OUTCOMES)?; + if w.len() != 2 + n * 3 { + return Err(l.bad("исходы", "нужны сектор, такт и исход каждого")); + } + if !outcomes.is_empty() { + return Err(l.bad("исходы", "окно записано дважды")); + } + for i in 0..n { + let sector = l.int(2 + i * 3, "сектор исхода", 0, ew::SECTORS as i64 - 1)? as u8; + let t = l.int(3 + i * 3, "такт исхода", 0, tick as i64)? as u64; + let killed = l.int(4 + i * 3, "исход", 0, 1)? == 1; + outcomes.push(ew::Learned { sector, tick: t, killed }); + } + } "airglobal" => { if w.len() != 2 { return Err(l.bad("рельеф", "нужна одна ссылка на версию рельефа")); @@ -602,7 +630,7 @@ impl Sim { let unit = l.int(6, "юнит", 0, 1 << 30)? as u32; let version = l.int(7, "версия знаний", 0, tick as i64)? as u64; let priority = l.int(8, "приоритет", 0, 9)? as u8; - let intent = intent_of(l.word(9, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react или replace"))?; + let intent = intent_of(l.word(9, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react, replace или refresh"))?; if priority != intent.priority() { return Err(l.bad("приоритет", "не совпадает с намерением")); } @@ -827,6 +855,7 @@ impl Sim { job_next, kills, hits, + outcomes, contacts: contacts.into_values().collect(), drones: drones.into_values().collect(), queue, @@ -845,7 +874,7 @@ impl Sim { // New jobs must not reuse an id a restored job already holds. let highest = save.jobs.iter().map(|j| j.id).max().unwrap_or(0); self.job_next = save.job_next.max(1).max(highest.saturating_add(1)); - self.intel = ew::Intel::restore(save.contacts.clone(), save.kills, save.hits); + self.intel = ew::Intel::restore(save.contacts.clone(), save.kills, save.hits, save.outcomes.clone()); self.known_relief = save.known_relief; self.drones = save.drones; self.queue = save.queue; @@ -889,7 +918,7 @@ fn parse_drone(l: &Line, first: usize) -> Result<(Drone, usize), String> { let vel = DVec3::new(l.num(first + 5, "скорость X")?, l.num(first + 6, "скорость Y")?, l.num(first + 7, "скорость Z")?); let target = DVec3::new(l.num(first + 8, "цель X")?, l.num(first + 9, "цель Y")?, l.num(first + 10, "цель Z")?); let flight = flight_of(l.word(first + 11, "полёт")?).ok_or_else(|| l.bad("полёт", "cruise, dive, ballistic или falling"))?; - let intent = intent_of(l.word(first + 12, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react или replace"))?; + let intent = intent_of(l.word(first + 12, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react, replace или refresh"))?; let unit = l.int(first + 13, "юнит намерения", 0, 1 << 30)? as u32; let since = l.int(first + 14, "такт выбора цели", 0, 1 << 40)? as u64; let switches = l.int(first + 15, "переключения", 0, u16::MAX as i64)? as u16; @@ -982,13 +1011,14 @@ mod durable_tests { let id = sim.id(); let at = DVec3::new(-400.0 + k as f64 * 400.0, 70.0, 0.0); let c = contact(id, kind, at, 10, if kind == SamKind::Ew { ew::Seen::Jamming } else { ew::Seen::Emission }, k as u16); - sim.intel = ew::Intel::restore([c].to_vec(), [0; ew::SECTORS], [0; ew::SECTORS]); + sim.intel = ew::Intel::restore([c].to_vec(), [0; ew::SECTORS], [0; ew::SECTORS], Vec::new()); ids.push(id); } sim.intel = ew::Intel::restore( ids.iter().enumerate().map(|(k, id)| contact(*id, [SamKind::S400, SamKind::Radar, SamKind::Ew][k], DVec3::new(-400.0 + k as f64 * 400.0, 70.0, 0.0), 10, ew::Seen::Emission, k as u16)).collect(), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], + Vec::new(), ); sim.tick = 120; sim.job_next = 7; @@ -1074,7 +1104,7 @@ mod durable_tests { let id = sim.id(); contacts.push(contact(id, SamKind::S400, DVec3::new(-560.0 + k as f64 * 160.0, 70.0, -320.0), 0, ew::Seen::Emission, 0)); } - sim.intel = ew::Intel::restore(contacts, [0; ew::SECTORS], [0; ew::SECTORS]); + sim.intel = ew::Intel::restore(contacts, [0; ew::SECTORS], [0; ew::SECTORS], Vec::new()); for i in 0..40 { let from = DVec3::new(-1800.0, 100.0, -800.0 + i as f64 * 40.0); let mut d = sim.make_drone(DroneKind::Kh22, from, DVec3::X, DVec3::new(1800.0, 70.0, 1800.0)); diff --git a/airdef-mod/src/sim/ew.rs b/airdef-mod/src/sim/ew.rs index 8b92bec..c22b818 100644 --- a/airdef-mod/src/sim/ew.rs +++ b/airdef-mod/src/sim/ew.rs @@ -45,6 +45,9 @@ pub enum Intent { /// 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 { @@ -54,6 +57,7 @@ impl Intent { Self::Sead => "sead", Self::React => "react", Self::Replace => "replace", + Self::Refresh => "refresh", } } /// The key a save writes and reads. @@ -61,14 +65,15 @@ impl Intent { self.name() } pub(super) fn from_key(key: &str) -> Option { - [Self::Plan, Self::Sead, Self::React, Self::Replace].into_iter().find(|i| i.key() == key) + [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 => 2, + Self::Sead | Self::Refresh => 2, Self::React => 1, Self::Replace => 0, } @@ -246,6 +251,16 @@ 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. @@ -386,11 +401,19 @@ pub(super) struct KnowledgeSnapshot { } impl KnowledgeSnapshot { + pub(super) fn new(tick: u64, contacts: Vec, marks: Vec) -> 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 { + observe::merge(&self.contacts, &self.marks, self.tick) + } } /// The radar reach the enemy's planners price by: the type's published figure, undamaged @@ -405,14 +428,81 @@ pub(super) fn published_reach(kind: SamKind, drone: DroneKind, height: f64) -> f 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. + /// 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, + /// The small window of recent raid outcomes the bearing picker scores (#149). + outcomes: VecDeque, + /// 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 { @@ -423,8 +513,26 @@ impl Intel { pub(super) fn sectors(&self) -> ([u32; SECTORS], [u32; SECTORS]) { (self.kills, self.hits) } - pub(super) fn restore(contacts: Vec, kills: [u32; SECTORS], hits: [u32; SECTORS]) -> Self { - Self { kills, hits, contacts: contacts.into_iter().map(|c| (c.id, c)).collect() } + pub(super) fn outcomes(&self) -> &VecDeque { + &self.outcomes + } + pub(super) fn restore(contacts: Vec, kills: [u32; SECTORS], hits: [u32; SECTORS], outcomes: Vec) -> 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. @@ -554,24 +662,77 @@ impl Sim { } } - /// What the enemy's raids learned: their drones' fates by sector. + /// 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 bearing a smart raid comes from: the sector its raids got through best, a little random. + /// 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 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 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 }) }; - 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 }; + self.bearing = report; (pick as f64 + 0.5 + self.rng.s() * 0.4) / SECTORS as f64 * TAU } @@ -592,9 +753,68 @@ impl Sim { 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 = HashMap::new(); + let mut assigned = 0usize; + let mut changed = 0u32; + let mut job_next = self.job_next; + let mut jobs: Vec = Vec::new(); + for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart && matches!(d.intent, Intent::Plan | Intent::Sead)) { + if assigned >= ASSIGN_PER_TICK || d.aim.switches >= SWITCH_CAP { + 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; + 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; + 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. - pub(super) fn known_live(&self, id: u32) -> bool { + /// 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); } @@ -625,6 +845,9 @@ impl Sim { 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; } @@ -681,23 +904,30 @@ impl Sim { if assigned >= ASSIGN_PER_TICK { continue; } - 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)) + // 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, } - (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; @@ -737,30 +967,41 @@ impl Sim { if d.aim.switches >= SWITCH_CAP || assigned >= ASSIGN_PER_TICK { continue; } - 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, - }); - 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, + // 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; @@ -832,6 +1073,27 @@ impl Sim { .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, kind: DroneKind, n: usize) -> Option { + 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 @@ -1193,6 +1455,27 @@ pub struct PendingReport { 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)] @@ -1209,6 +1492,14 @@ pub struct EnemyPictureReport { pub recon: Vec, /// The recon flights still out. pub recon_sorties: Vec, + /// The one merged hint list the candidate planner ranks and prices by (#149). + pub observations: Vec, + /// 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 { @@ -1326,7 +1617,38 @@ impl Sim { 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 } + 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). diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index e1d651f..e471464 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -25,10 +25,12 @@ pub mod record; mod sight; mod terrain; mod ew; +mod observe; mod optical; mod recon; mod durable; -pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport, ReconReport, ReconSortieReport}; +pub use ew::{AimReport, BearingReason, BearingReport, Confidence, ContactReport, EnemyPictureReport, Intent, ObservationReport, PendingReport, ReconReport, ReconSortieReport}; +pub use observe::Observation; pub use recon::{Category, Mark, Quality, Source, is_drone_id, priority_parts}; pub mod lights; mod logistics; @@ -45,6 +47,8 @@ mod balance; mod regress; #[cfg(test)] mod sensor_tests; +#[cfg(test)] +mod smart_tests; pub use ew::EW_RADIUS; pub use damage::{Comps, Part, PartState}; pub use sight::{AirPicture, Ident, LowSensor, Track, RIM_RAYS}; @@ -1494,6 +1498,16 @@ pub struct Sim { intel: ew::Intel, /// Reconnaissance flights and the partial picture they radioed home (#135). recon: recon::Recon, + /// The smart enemy runs the legacy picks (#149's comparison runner): the two separate hint + /// lists and their old scales, the lifetime bearing tally with its fixed share, no mark + /// pricing and no refresh of the unreleased portion. The light modes never read it. + pub smart_legacy: bool, + /// The bounded refresh of the last smart raid's unreleased portion (#149), while it waits. + refresh: Option, + /// Aims the refresh has re-chosen (#149; diagnostics). + refresh_applied: u32, + /// The bearing picker's last decision and its typed reason (#149). + bearing: ew::BearingReport, /// 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). @@ -1572,6 +1586,10 @@ impl Sim { tally: record::Tally::default(), intel: ew::Intel::default(), recon: recon::Recon::default(), + smart_legacy: false, + refresh: None, + refresh_applied: 0, + bearing: ew::BearingReport::default(), night: false, fires: fires::Fires::default(), day_time: None, @@ -1593,6 +1611,16 @@ impl Sim { self.next * PARTS } + /// The bearing picker's last decision and its typed reason (#149; diagnostics). + pub fn bearing_report(&self) -> ew::BearingReport { + self.bearing + } + + /// Aims the bounded refresh of the unreleased portion has re-chosen (#149; diagnostics). + pub fn refresh_applied(&self) -> u32 { + self.refresh_applied + } + /// What a system's camera follows: its guns' or missiles' target, else what its missiles in /// flight are after. pub fn watched(&self, sam: &Sam) -> Option<&Drone> { @@ -1685,6 +1713,7 @@ impl Sim { self.retargets.clear(); self.known_relief = None; self.recon.clear_sorties(); + self.refresh = None; self.wave = None; // Ammunition still to cook off, flares in the sky. self.later.clear(); @@ -1728,6 +1757,7 @@ impl Sim { self.tick += 1; self.plan_step(Some(&mut *ground), out); self.adapt(); + self.step_refresh(out); self.step_settling(ground); self.release_queue(ground, out); self.begin_recording_if_active(); diff --git a/airdef-mod/src/sim/observe.rs b/airdef-mod/src/sim/observe.rs new file mode 100644 index 0000000..a5851db --- /dev/null +++ b/airdef-mod/src/sim/observe.rs @@ -0,0 +1,268 @@ +//! The planner's one public observation (#149): a disclosure `Contact` and a recon `Mark` are +//! two channels hinting at the same game objects, on two different scales. This module projects +//! both into a single [`Observation`] — an area, a channel, an age, a confidence and the public +//! game features — and matches them by those public features alone: a mark whose area holds a +//! contact's fix and whose observed category agrees is the same hint, not a second target. +//! +//! A match is a belief, never a fact: it is made only on an exact public category agreement and +//! area overlap, it is flagged (`matched`), and it invents nothing — the contact keeps the kind +//! and place it was observed with, the mark only adds what it publicly saw (a refined radar role, +//! a fresher look). A coarse `Unknown` mark or a contradicting category is *not* matched: it stays +//! a separate hint. The observer's truth map and the units' real ids play no part here. +use super::*; + +/// A contact fix this far inside a mark's area (on top of its radius) reads as the same public +/// hint. The fix is exact, the area is coarse: the slack is the cell jitter a report carries. +const MATCH_SLACK: f64 = 8.0; + +/// One public hint about one game object, from either channel (#149). There is no health, +/// magazine, link, hidden switch or true place in it: `kind` is `Some` only for a disclosure +/// contact, whose type was identified at the observation; a mark carries its coarse category. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Observation { + /// The hint's public id: a contact's id, or a mark's synthetic one. Never a matched unit's truth. + pub id: u32, + /// The best public place: a contact's fix, or a mark's area centre. + pub at: DVec3, + /// 0 for an exact fix; the area's radius for a mark. + pub radius: f64, + /// The channel that showed it last: flyby, emission, jamming or launch. + pub channel: recon::Source, + /// The tick of the observation this hint rests on. + pub observed: u64, + pub category: recon::Category, + /// A radar's role, once a refined look told it. + pub role: Option, + /// The type identified at a disclosure observation; `None` for a recon mark. + pub kind: Option, + pub quality: recon::Quality, + /// A second public hint agreed by area and category. A belief for the diagnostic, not a fact. + pub matched: bool, +} + +impl Observation { + pub fn age(&self, now: u64) -> u64 { + now.saturating_sub(self.observed) + } + pub fn confidence(&self, now: u64) -> Confidence { + ew::confidence_for_age(self.age(now)) + } + /// An exact disclosure fix, rather than a coarse area. + pub fn exact(&self) -> bool { + self.radius == 0.0 + } + pub fn live(&self, now: u64) -> bool { + self.age(now) < ew::CONTACT_TTL + } + /// The one ranking scale both channels share (#149): the mark's priority parts (freshness, + /// quality, observed role) plus a small premium for being a fix rather than an area. + pub fn rank(&self, now: u64) -> u8 { + let (f, q, r) = recon::priority_parts(self.confidence(now), self.quality, self.category, self.role); + f * 4 + q * 3 + r + u8::from(self.exact()) * 3 + } +} + +/// The disclosure channel in the one scale the marks already use. +pub(super) fn channel_of(seen: ew::Seen) -> recon::Source { + match seen { + ew::Seen::Launch => recon::Source::Launch, + ew::Seen::Emission => recon::Source::Emission, + ew::Seen::Jamming => recon::Source::Jamming, + } +} + +/// Projects contacts and marks into one list of public hints, best first. A mark is matched to a +/// contact only by public features (area overlap and an exact category agreement); a matched mark +/// is consumed — the object is one hint, priced and assigned once. Unmatched marks stand as areas. +pub(super) fn merge(contacts: &[ew::Contact], marks: &[recon::Mark], now: u64) -> Vec { + let mut out: Vec = contacts + .iter() + .filter(|c| c.live(now)) + .map(|c| Observation { + id: c.id, + at: c.at, + radius: 0.0, + channel: channel_of(c.seen), + observed: c.tick, + category: recon::Category::of(c.kind), + role: None, + kind: Some(c.kind), + quality: recon::Quality::Refined, + matched: false, + }) + .collect(); + let mut areas = Vec::new(); + for m in marks.iter().filter(|m| m.live(now)) { + let hit = out.iter_mut().find(|o| { + o.kind.is_some() + && m.category != recon::Category::Unknown + && m.category == o.category + && (m.role.is_none() || o.category == recon::Category::Radar) + && horizontal(o.at - m.area).length() <= m.radius + MATCH_SLACK + }); + match hit { + Some(o) => { + // The match is public evidence, not truth: the fresher look and the refined role + // are what the mark itself saw; the contact's kind and fix are never rewritten. + o.matched = true; + if m.observed > o.observed { + o.observed = m.observed; + o.channel = m.source; + } + if o.category == recon::Category::Radar && m.role.is_some() { + o.role = m.role; + } + } + None => areas.push(Observation { + id: m.id, + at: m.area, + radius: m.radius, + channel: m.source, + observed: m.observed, + category: m.category, + role: m.role, + kind: None, + quality: m.quality, + matched: false, + }), + } + } + out.extend(areas); + out.sort_by(|a, b| b.rank(now).cmp(&a.rank(now)).then(b.observed.cmp(&a.observed)).then(a.id.cmp(&b.id))); + out +} + +/// The small game policy (#149): which observed categories a kind is worth turning onto. One +/// place for the fit both the plan's picks and the adaptive assignments read — no hidden state, +/// only the public category and the kind's published role. +pub(super) fn fits(kind: DroneKind, category: recon::Category) -> bool { + use recon::Category as C; + match kind { + DroneKind::Lancet => matches!(category, C::Gun | C::Launcher | C::Ew), + DroneKind::Kh22 | DroneKind::Zircon => matches!(category, C::Radar | C::Launcher | C::Ew), + DroneKind::Iskander | DroneKind::Kinzhal => matches!(category, C::Radar | C::Launcher), + DroneKind::Shahed | DroneKind::Geran3 => matches!(category, C::Radar | C::Launcher | C::Gun | C::Ew), + _ => false, + } +} + +/// The public worst-case envelope of a category: the furthest missile reach and gun range any +/// published kind of that category has, for this drone at this height. What a mark's area may +/// hold is priced by the catalog, never by a hidden unit's actual load (#149). +pub(super) fn category_envelope(category: recon::Category) -> (f64, f64, f64) { + let mut lo = f64::INFINITY; + let mut hi = 0.0f64; + let mut gun = 0.0f64; + for k in SamKind::ALL { + if recon::Category::of(k) != category { + continue; + } + let sp = k.spec(); + if let Some(m) = &sp.missile { + lo = lo.min(m.min); + hi = hi.max(m.max); + } + if let Some(g) = &sp.gun { + gun = gun.max(g.range); + } + } + (lo.min(hi), hi, gun) +} + +/// The published reach of the strongest radar kind, for a mark that only says "a radar is here". +pub(super) fn radar_envelope(drone: DroneKind, height: f64) -> f64 { + SamKind::ALL + .into_iter() + .filter(|k| recon::Category::of(*k) == recon::Category::Radar) + .map(|k| ew::published_reach(k, drone, height)) + .fold(0.0, f64::max) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn contact(id: u32, kind: SamKind, at: DVec3, tick: u64) -> ew::Contact { + ew::Contact { id, kind, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 } + } + + fn mark(id: u32, at: DVec3, category: recon::Category, observed: u64) -> recon::Mark { + recon::Mark { + id, + area: at, + radius: recon::COARSE_AREA, + category, + role: None, + source: recon::Source::Flyby, + observed, + reported: observed, + quality: recon::Quality::Coarse, + looks: 1, + } + } + + // #149: one object, two channels, one hint. A mark whose area holds the contact's fix and + // whose category agrees is matched and consumed — not a second target. The match reads only + // public features: two marks of different hidden truths but the same public area/category + // both fold into the one contact. + #[test] + fn a_matching_mark_is_one_hint_not_two() { + let at = DVec3::new(100.0, 70.0, 0.0); + let c = contact(16, SamKind::Radar, at, 100); + let m1 = mark(recon::ID_BASE + 1, at + DVec3::new(20.0, 0.0, 0.0), recon::Category::Radar, 120); + let m2 = mark(recon::ID_BASE + 2, at + DVec3::new(-30.0, 0.0, 10.0), recon::Category::Radar, 130); + let obs = merge(&[c], &[m1, m2], 200); + assert_eq!(obs.len(), 1, "the same public object stayed two hints"); + assert!(obs[0].matched && obs[0].exact() && obs[0].kind == Some(SamKind::Radar)); + assert_eq!(obs[0].observed, 130, "the fresher public look was not taken"); + assert_eq!(obs[0].id, 16, "the hint kept the mark's synthetic id over the contact's"); + } + + // #149: an unconfirmed match is not a fact. A coarse Unknown mark, a contradicting category, + // or an area that does not hold the fix stays a separate hint — nothing is merged on a guess. + #[test] + fn an_unconfirmed_match_stays_separate() { + let at = DVec3::new(100.0, 70.0, 0.0); + let c = contact(16, SamKind::Radar, at, 100); + let unknown = mark(recon::ID_BASE + 1, at, recon::Category::Unknown, 120); + let wrong = mark(recon::ID_BASE + 2, at, recon::Category::Launcher, 120); + let far = mark(recon::ID_BASE + 3, at + DVec3::new(400.0, 0.0, 0.0), recon::Category::Radar, 120); + let obs = merge(&[c], &[unknown, wrong, far], 200); + assert_eq!(obs.len(), 4, "a weak match was treated as a fact"); + assert!(obs.iter().filter(|o| o.kind.is_some()).all(|o| !o.matched)); + // A refined role is public only for a radar; a launcher mark never lends one. + let mut radar = mark(recon::ID_BASE + 4, at, recon::Category::Radar, 140); + radar.quality = recon::Quality::Refined; + radar.role = Some(battery::RadarRole::Engagement); + let obs = merge(&[c], &[radar], 200); + assert_eq!(obs.len(), 1); + assert_eq!(obs[0].role, Some(battery::RadarRole::Engagement)); + } + + // #149: one scale. A fresh confirmed fix outranks an old doubtful area; a refined big-role + // mark outranks a coarse modest one of the same age; the order never reads an id or a truth. + #[test] + fn the_rank_is_one_public_scale() { + let fresh = contact(16, SamKind::Radar, DVec3::ZERO, 190); + let old = mark(recon::ID_BASE + 1, DVec3::X * 500.0, recon::Category::Launcher, 0); + let obs = merge(&[fresh], &[old], 200); + assert_eq!(obs[0].id, 16, "a fresh fix did not lead an old area"); + let mut big = mark(recon::ID_BASE + 2, DVec3::X * 900.0, recon::Category::Radar, 190); + big.quality = recon::Quality::Refined; + big.role = Some(battery::RadarRole::Engagement); + let modest = mark(recon::ID_BASE + 3, DVec3::X * 1300.0, recon::Category::Radar, 190); + let obs = merge(&[], &[modest, big], 200); + assert_eq!(obs[0].id, big.id, "the bigger observed role did not lead"); + assert!(obs[0].rank(200) > obs[1].rank(200)); + } + + // #149: the policy fit is the public category, the same for the plan and the adaptive picks. + #[test] + fn the_fit_is_the_public_category() { + assert!(fits(DroneKind::Lancet, recon::Category::Gun)); + assert!(!fits(DroneKind::Lancet, recon::Category::Radar)); + assert!(fits(DroneKind::Kh22, recon::Category::Radar)); + assert!(!fits(DroneKind::Iskander, recon::Category::Gun)); + assert!(!fits(DroneKind::Gerbera, recon::Category::Launcher)); + } +} diff --git a/airdef-mod/src/sim/raid.rs b/airdef-mod/src/sim/raid.rs index 7ce5d90..3b7a70e 100644 --- a/airdef-mod/src/sim/raid.rs +++ b/airdef-mod/src/sim/raid.rs @@ -519,6 +519,13 @@ impl Sim { if plan.smart && !plan.heights.is_empty() { self.known_relief = Some(std::sync::Arc::new(ew::KnownRelief::new(plan.grid, std::mem::take(&mut plan.heights)))); } + // The bounded refresh moment for the unreleased portion (#149): a recon flight is still + // out, so a report may arrive while the drones wait to launch, and the plan's own picks + // may be re-aimed once on it. The deadline is absolute and the launches keep their times + // — no report never pauses the raid. + if plan.smart && !self.smart_legacy && !self.recon.sorties.is_empty() { + self.refresh = Some(ew::Refresh { deadline: self.tick + ew::REFRESH_WINDOW, reports: self.recon.reports }); + } self.wave = Some(WaveStats { kills: self.kills, hits: self.hits, @@ -604,24 +611,33 @@ 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], leads: &[recon::Mark]) -> Vec> { - // 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). Both lists are the - // order's own knowledge version, not a later picture (#146). + // Radars the picture trusts, best first. The candidate ranks the one merged hint list on + // the single public scale (#149): a mark matched to a contact is not a second radar. The + // legacy mode keeps the two chains and their old scales. The order is the observed role, + // freshness and quality -- never the id (#135). Both lists are the order's own knowledge + // version, not a later picture (#146). let now = self.tick; - let mut radars: Vec<(u8, u64, u32, DVec3)> = picture - .iter() - .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(leads.iter().copied().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(); + let mut radars: Vec<(u8, u64, u32, DVec3)> = if self.smart_legacy { + picture + .iter() + .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(leads.iter().copied().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() + } else { + observe::merge(picture, leads, now) + .into_iter() + .filter(|o| o.category == recon::Category::Radar && o.confidence(now) >= ew::Confidence::Probable) + .map(|o| (o.rank(now), o.observed, o.id, o.at)) + .collect() + }; radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2))); let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect(); let flat: Vec = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect(); @@ -660,7 +676,42 @@ impl Sim { if aim == Aim::ObjectsAndSams { return if roll < 0.33 { pick(picture, r).map_or((object, None), |(p, id)| (p, Some(id))) } else { (object, None) }; } - // Smart: each kind at what it is good against; what gave itself away first (a jamming + // The candidate picks from the one merged hint list (#149): a matched mark is not a + // second target, and the fit is the small public policy, not a per-kind guess. + if !self.smart_legacy { + let obs = observe::merge(picture, leads, self.tick); + let pick_o = |list: &[&Observation], r: f64| -> Option<(DVec3, u32)> { + let o = list.get((r * list.len() as f64) as usize)?; + Some((o.at, o.id)) + }; + let jammers: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Ew && o.channel == recon::Source::Jamming).collect(); + if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !jammers.is_empty() && roll < 0.6 { + if let Some((at, id)) = pick_o(&jammers, r) { + return (at, Some(id)); + } + } + let guns: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Gun || o.kind.is_some_and(|k| k.armed() && k.range() <= 300.0)).collect(); + let long: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Radar || o.kind.is_some_and(|k| k.range() >= 450.0)).collect(); + let all: Vec<&Observation> = obs.iter().collect(); + let choice = match kind { + DroneKind::Lancet if roll < 0.75 => pick_o(&guns, r).or_else(|| pick_o(&all, r)), + DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick_o(&long, r), + DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick_o(&long, r), + DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick_o(&all, r), + _ => None, + }; + if let Some((at, id)) = choice { + return (at, Some(id)); + } + // Nothing the kind's usual preference picked: an unmerged mark whose observed + // category fits is the next best reason to turn a strike off the object. + let fits: Vec<&Observation> = obs.iter().filter(|o| o.kind.is_none() && observe::fits(kind, o.category)).collect(); + if let Some((at, id)) = pick_o(&fits, r) { + return (at, Some(id)); + } + return (object, None); + } + // Legacy smart: each kind at what it is good against; what gave itself away first (a jamming // station, a radar, a system that fired). let known_ew: Vec = picture.iter().copied().filter(|c| c.kind == SamKind::Ew).collect(); if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !known_ew.is_empty() && roll < 0.6 { @@ -746,6 +797,17 @@ impl Sim { .filter(|d| d.kind == SamKind::Radar && d.id != c.id && d.at.distance(pos) <= sight::LINK) .map(|d| ew::published_reach(d.kind, kind, height)) .fold(0.0, f64::max); + // A trusted radar mark near the observed place feeds the network too (#149): the + // strongest published radar reach, since the mark does not name the kind. + let net = if self.smart_legacy { + net + } else { + knowledge.marks + .iter() + .filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable && m.area.distance(pos) <= sight::LINK) + .map(|_| observe::radar_envelope(kind, height)) + .fold(net, f64::max) + }; let (hi, gun) = (hi.min(own.max(net)), gun.min(own)); let far = hi.max(gun); // Only the cells round it. @@ -768,6 +830,53 @@ impl Sim { } } } + // The marks the contacts do not already stand for (#149): an area is priced by its public + // category's published envelope, weighted by the confidence the age alone gives. A mark + // matched to a contact is one hint and was priced through the contact above. + if !self.smart_legacy { + for o in knowledge.observations().into_iter().filter(|o| o.kind.is_none() && o.confidence(now) >= ew::Confidence::Probable) { + let scale: f32 = if o.confidence(now) == ew::Confidence::Confirmed { 1.0 } else { 0.5 }; + let pos = o.at; + match o.category { + recon::Category::Ew if kind.jammable() => { + let reach = ew::EW_RADIUS + o.radius; + let (ci, cj) = grid.index(pos); + let r = (reach / grid.cell).ceil() as i32; + for i in (ci - r).max(0)..=(ci + r).min(n - 1) { + for j in (cj - r).max(0)..=(cj + r).min(n - 1) { + cost += 1; + if horizontal(grid.centre((i, j), pos.y) - pos).length() < reach { + prices[(i * n + j) as usize] += 12.0 * scale; + } + } + } + } + recon::Category::Launcher | recon::Category::Gun => { + let (lo, hi, gun) = observe::category_envelope(o.category); + let far = hi.max(gun) + o.radius; + let (ci, cj) = grid.index(pos); + let r = (far / grid.cell).ceil() as i32 + 1; + for i in (ci - r).max(0)..=(ci + r).min(n - 1) { + for j in (cj - r).max(0)..=(cj + r).min(n - 1) { + cost += 1; + let ground = land.map(|l| l[(i * n + j) as usize]).filter(|g| g.is_finite()); + let p = grid.centre((i, j), ground.map_or(pos.y + height, |g| f64::from(g) + height)); + let d = horizontal(p - pos).length(); + if d > far { + continue; + } + let missile = (lo..hi).contains(&d); + if !(missile || d < gun) { + continue; + } + prices[(i * n + j) as usize] += (if missile { 30.0 } else { 18.0 }) * scale; + } + } + } + _ => {} + } + } + } (prices, cost) } diff --git a/airdef-mod/src/sim/regress.rs b/airdef-mod/src/sim/regress.rs index 258c54d..0d8b576 100644 --- a/airdef-mod/src/sim/regress.rs +++ b/airdef-mod/src/sim/regress.rs @@ -297,7 +297,9 @@ fn wall_relief() -> std::sync::Arc { for j in 0..g.size { let x = g.min.x + (f64::from(i) + 0.5) * g.cell; let z = g.min.z + (f64::from(j) + 0.5) * g.cell; - if (x + 1000.0).abs() < 80.0 && z.abs() < 420.0 { + // The wall spans every approach lane: whichever drone the adaptive tick leaves last, + // its east-west route crosses the ridge, so the two relief versions must differ (#149). + if (x + 1000.0).abs() < 80.0 && z.abs() < 2000.0 { h[(i * g.size + j) as usize] = 1000.0; } } diff --git a/airdef-mod/src/sim/smart_tests.rs b/airdef-mod/src/sim/smart_tests.rs new file mode 100644 index 0000000..5f9e6d2 --- /dev/null +++ b/airdef-mod/src/sim/smart_tests.rs @@ -0,0 +1,312 @@ +//! Smart v2 (#149): the merged public picture, one knowledge version per order, the bounded +//! refresh of the unreleased portion, and the bearing window — and the metamorphic guarantee +//! that a hidden permutation nothing observed changes no decision. +use super::*; +use super::sites::testland::{Land, serve}; + +fn grid() -> raid::Grid { + raid::Grid { min: DVec3::new(-800.0, 0.0, -800.0), cell: 16.0, size: 100 } +} + +fn mark(id: u32, at: DVec3, category: recon::Category, observed: u64) -> recon::Mark { + recon::Mark { + id, + area: at, + radius: recon::COARSE_AREA, + category, + role: None, + source: recon::Source::Flyby, + observed, + reported: observed, + quality: recon::Quality::Coarse, + looks: 1, + } +} + +fn contact(id: u32, kind: SamKind, at: DVec3, tick: u64) -> ew::Contact { + ew::Contact { id, kind, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 } +} + +fn order() -> RaidOrder { + RaidOrder { kinds: vec![(DroneKind::Shahed, 4), (DroneKind::Kh22, 2)], approach: Approach::Sector, dist: 900.0, aim: Aim::Smart } +} + +// #149: the metamorphic guarantee. Two worlds with the same seed and the same observed radar, +// whose hidden forces are a permutation of one another (kinds swapped between places), order +// the same recon flight, the same aims and intents, and the same prices — nothing unobserved +// leaks into a decision. +#[test] +fn a_hidden_permutation_changes_nothing_before_observation() { + let object = DVec3::new(0.0, 70.0, 0.0); + let build = |perm: bool| { + let mut sim = Sim::new(149); + let id = sim.id(); + let radar = Sam::new(id, SamKind::Radar, DVec3::new(150.0, 70.0, -80.0), 0.0); + sim.intel.observe(&radar, 0, ew::Seen::Emission); + sim.sams.push(radar); + let spots = [DVec3::new(-200.0, 70.0, 100.0), DVec3::new(300.0, 70.0, 200.0), DVec3::new(-50.0, 70.0, -300.0)]; + let kinds = if perm { [SamKind::Pantsir, SamKind::S400, SamKind::Tor] } else { [SamKind::S400, SamKind::Tor, SamKind::Pantsir] }; + for (k, p) in kinds.into_iter().zip(spots) { + let id = sim.id(); + sim.sams.push(Sam::new(id, k, p, 0.0)); + } + sim.targets.push(object); + sim.target_health.push(100.0); + let mut out = Out::default(); + sim.order_raid(&order(), &[object], &mut out); + let flight: Vec<_> = sim.recon.sorties.iter().map(|s| s.zones.iter().map(|z| (z.center, z.radius)).collect::>()).collect(); + let aims = sim.planned_aims(); + let intents = sim.planned_intents(); + let (prices, _) = sim.price_grid(&grid(), DroneKind::Kh101); + (flight, aims, intents, prices) + }; + assert_eq!(build(false), build(true), "a hidden permutation changed the flight, the plan or the prices"); +} + +// #149: the same guarantee after a look. Once a radar is observed, permuting only the units +// nothing saw changes neither the structured picture nor the prices. +#[test] +fn a_hidden_permutation_changes_nothing_after_observation() { + let build = |perm: bool| { + let mut sim = Sim::new(149); + let id = sim.id(); + let radar = Sam::new(id, SamKind::Radar, DVec3::new(150.0, 70.0, -80.0), 0.0); + sim.intel.observe(&radar, 0, ew::Seen::Emission); + sim.sams.push(radar); + let spots = [DVec3::new(-200.0, 70.0, 100.0), DVec3::new(300.0, 70.0, 200.0)]; + let kinds = if perm { [SamKind::S400, SamKind::Pantsir] } else { [SamKind::Pantsir, SamKind::S400] }; + for (k, p) in kinds.into_iter().zip(spots) { + let id = sim.id(); + sim.sams.push(Sam::new(id, k, p, 0.0)); + } + sim.tick = 100; + let (prices, _) = sim.price_grid(&grid(), DroneKind::Kh101); + (sim.enemy_picture(), prices) + }; + assert_eq!(build(false), build(true), "a hidden permutation moved the picture or the prices after a look"); +} + +// #149: price_grid_known accounts for marks. A fresh probable mark raises the cells its public +// category covers; a doubtful one prices nothing; a mark matched to a contact is priced once, +// exactly as the contact alone. The legacy mode prices contacts only. +#[test] +fn a_fresh_mark_prices_the_map_and_a_doubtful_one_does_not() { + let mut sim = Sim::new(149); + let g = grid(); + let m = mark(recon::ID_BASE + 1, DVec3::new(0.0, 70.0, 0.0), recon::Category::Launcher, 0); + let fresh = ew::KnowledgeSnapshot::new(100, Vec::new(), vec![m]); + let (prices, _) = sim.price_grid_known(&g, DroneKind::Kh101, None, &fresh); + assert!(prices.iter().any(|p| *p > 1.0), "a fresh launcher mark priced nothing"); + let old = ew::KnowledgeSnapshot::new(4000, Vec::new(), vec![m]); + let (prices, _) = sim.price_grid_known(&g, DroneKind::Kh101, None, &old); + assert!(prices.iter().all(|p| *p == 1.0), "a doubtful mark was priced"); + // Merged into a contact of the same public category: one hint, priced once. + let c = contact(16, SamKind::S400, m.area, 100); + let merged = ew::KnowledgeSnapshot::new(100, vec![c], vec![m]); + let only = ew::KnowledgeSnapshot::new(100, vec![c], Vec::new()); + assert_eq!( + sim.price_grid_known(&g, DroneKind::Kh101, None, &merged).0, + sim.price_grid_known(&g, DroneKind::Kh101, None, &only).0, + "a matched mark was priced twice" + ); + // The legacy mode does not price marks at all. + sim.smart_legacy = true; + let (prices, _) = sim.price_grid_known(&g, DroneKind::Kh101, None, &fresh); + assert!(prices.iter().all(|p| *p == 1.0), "the legacy mode priced a mark"); +} + +// #146/#149: one order prices every kind over the snapshot its targets were chosen from. A +// contact disclosed while the plan is still being worked out changes neither mode's routes: +// the #146 versioning is preserved for the candidate and the legacy picker alike. +#[test] +fn one_order_prices_every_kind_over_its_own_snapshot() { + let object = DVec3::new(0.0, 70.0, 300.0); + let build = |legacy: bool, disclose: bool| { + let mut sim = Sim::new(149); + sim.smart_legacy = legacy; + let id = sim.id(); + let radar = Sam::new(id, SamKind::Radar, DVec3::new(600.0, 70.0, -600.0), 0.0); + sim.intel.observe(&radar, 0, ew::Seen::Emission); + sim.sams.push(radar); + sim.targets.push(object); + sim.target_health.push(100.0); + let mut ground = Ground::default(); + let land = Land(|_, _| 64); + let mut out = Out::default(); + for _ in 0..20 { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + } + let order = RaidOrder { kinds: vec![(DroneKind::Kh101, 6), (DroneKind::Shahed, 8)], approach: Approach::Sector, dist: 600.0, aim: Aim::Smart }; + sim.order_raid(&order, &[object], &mut out); + if disclose { + // A jamming station gives itself away at the objective while the plan waits for its + // land: every satellite-nav kind prices it, so the live picture bends the routes. + let id = sim.id(); + let threat = Sam::new(id, SamKind::Ew, object, 0.0); + sim.intel.observe(&threat, sim.tick, ew::Seen::Jamming); + sim.sams.push(threat); + } + // Work the plan alone (no adaptive ticks): the queue's routes are the plan's own. + while sim.planning() { + serve(&mut ground, &land, sim.tick); + sim.tick += 1; + sim.plan_step(Some(&mut ground), &mut out); + } + sim.queue.iter().map(|(_, d)| (d.id, d.route.clone())).collect::>() + }; + assert_eq!(build(false, false), build(false, true), "the candidate mixed two knowledge versions in one order"); + assert_eq!(build(true, false), build(true, true), "the legacy mode lost the #146 one-version pricing"); +} + +// #149: a report arriving while the raid's drones still wait re-aims the plan's own picks once, +// on a fresh snapshot, within the switch cap — and then the refresh is spent. +#[test] +fn a_report_refreshes_the_unreleased_portion_once() { + let object = DVec3::new(0.0, 70.0, 0.0); + let mut sim = Sim::new(149); + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0), 0.0)); + sim.targets.push(object); + sim.target_health.push(100.0); + let mut ground = Ground::default(); + let land = Land(|_, _| 64); + let mut out = Out::default(); + for _ in 0..20 { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + } + sim.order_raid(&order(), &[object], &mut out); + // Force the first sortie's look so a report is pending, then finish the plan: the refresh + // moment is armed only because a report is actually on its way. + let s = sim.recon.sorties.first().expect("no recon sortie").clone(); + let d = sim.drones.iter_mut().find(|d| d.id == s.drone).expect("the sortie has no aircraft"); + d.pos = s.zones[s.next].center + DVec3::Y * 40.0; + sim.tick += 1; + sim.step_recon(&mut out); + let report_at = sim.recon.sorties.first().unwrap().report_at.expect("no pending report"); + while sim.planning() { + serve(&mut ground, &land, sim.tick); + sim.tick += 1; + sim.plan_step(Some(&mut ground), &mut out); + } + assert!(sim.refresh.is_some(), "a pending report did not arm the bounded refresh"); + // The report arrives: the mark is in the picture. + sim.tick = report_at; + sim.step_recon(&mut out); + assert!(sim.recon.reports > 0); + let m = *sim.recon.marks.values().next().expect("the report left no mark"); + // One drone is past the switch cap: it keeps its aim. + sim.queue[0].1.aim.switches = ew::SWITCH_CAP; + let capped = sim.queue[0].1.id; + sim.step_refresh(&mut out); + assert!(sim.refresh.is_none(), "the refresh was not spent"); + assert!(sim.refresh_applied > 0, "the report re-aimed nobody"); + assert!(sim.queue.iter().any(|(_, d)| d.intent == ew::Intent::Refresh && d.aim.unit == m.id), "no drone was refreshed onto the mark"); + assert!(sim.queue.iter().find(|(_, d)| d.id == capped).unwrap().1.intent != ew::Intent::Refresh, "a drone past the cap was refreshed"); + // Spent: a second call changes nothing. + let applied = sim.refresh_applied; + sim.step_refresh(&mut out); + assert_eq!(sim.refresh_applied, applied); +} + +// #149: no report never pauses the raid. Past the deadline the refresh is dropped and the +// launches keep the times the plan gave them. +#[test] +fn no_report_never_pauses_the_raid() { + let object = DVec3::new(0.0, 70.0, 0.0); + let mut sim = Sim::new(149); + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0), 0.0)); + sim.targets.push(object); + sim.target_health.push(100.0); + let mut ground = Ground::default(); + let land = Land(|_, _| 64); + let mut out = Out::default(); + for _ in 0..20 { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + } + sim.order_raid(&order(), &[object], &mut out); + let s = sim.recon.sorties.first().expect("no recon sortie").clone(); + let d = sim.drones.iter_mut().find(|d| d.id == s.drone).unwrap(); + d.pos = s.zones[s.next].center + DVec3::Y * 40.0; + sim.tick += 1; + sim.step_recon(&mut out); + while sim.planning() { + serve(&mut ground, &land, sim.tick); + sim.tick += 1; + sim.plan_step(Some(&mut ground), &mut out); + } + let deadline = sim.refresh.as_ref().expect("the refresh was not armed").deadline; + let times: Vec = sim.queue.iter().map(|(t, _)| *t).collect(); + // The report never arrives (the aircraft is lost); the deadline passes. + sim.drones.retain(|d| !recon::is_drone_id(d.id)); + sim.tick = deadline + 1; + sim.step_refresh(&mut out); + assert!(sim.refresh.is_none(), "the refresh outlived its deadline"); + assert_eq!(sim.refresh_applied, 0); + assert_eq!(sim.queue.iter().map(|(t, _)| *t).collect::>(), times, "a missing report delayed a launch"); +} + +// #149: the bearing window forgets, and names why it explores. Few observations, a stale +// result and changed public conditions are distinct typed reasons; the legacy mode keeps its +// fixed share. +#[test] +fn the_bearing_window_forgets_and_names_its_reason() { + let mut sim = Sim::new(149); + sim.tick = 100; + for _ in 0..8 { + sim.learn(3, false); + } + sim.best_bearing(); + let r = sim.bearing_report(); + assert_eq!(r.reason, ew::BearingReason::Exploiting); + assert_eq!(r.observations, 8); + sim.tick = 100 + ew::OUTCOME_STALE + 1; + sim.best_bearing(); + assert_eq!(sim.bearing_report().reason, ew::BearingReason::StaleResults); + sim.tick = 100 + ew::OUTCOME_WINDOW + 1; + sim.best_bearing(); + let r = sim.bearing_report(); + assert_eq!(r.reason, ew::BearingReason::FewObservations); + assert_eq!(r.observations, 0, "the window did not forget the old outcomes"); + + let mut sim = Sim::new(149); + sim.tick = 100; + for _ in 0..8 { + sim.learn(3, false); + } + let id = sim.id(); + let radar = Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0); + sim.intel.observe(&radar, 100, ew::Seen::Emission); + sim.sams.push(radar); + sim.best_bearing(); + assert_eq!(sim.bearing_report().reason, ew::BearingReason::ConditionsChanged); + sim.smart_legacy = true; + sim.best_bearing(); + assert_eq!(sim.bearing_report().reason, ew::BearingReason::FixedShare); +} + +// #149: the bearing window and a refresh intent are durable: a save writes them, a load reads +// them back, and an older save without the window loads with an empty one. +#[test] +fn the_bearing_window_and_a_refresh_intent_survive_a_save() { + let mut sim = Sim::new(149); + sim.tick = 500; + sim.learn(2, true); + sim.learn(5, false); + let mut d = sim.make_drone(DroneKind::Shahed, DVec3::new(-500.0, 120.0, 0.0), DVec3::X, DVec3::ZERO); + d.smart = true; + d.intent = ew::Intent::Refresh; + d.aim = ew::Aim::unit(recon::ID_BASE + 1, 500, Confidence::Confirmed); + sim.queue.push((600, d)); + let text = sim.air_text().expect("the window and the queue are durable"); + assert!(text.contains("airlearn"), "the bearing window was not written"); + assert!(text.contains("refresh"), "the refresh intent was not written"); + let mut back = Sim::new(1); + back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there")); + assert_eq!(back.intel.outcomes().len(), 2); + assert_eq!(back.queue[0].1.intent, ew::Intent::Refresh); + assert_eq!(back.queue[0].1.aim.unit, recon::ID_BASE + 1); +} diff --git a/docs/CODEX-HANDOFF.md b/docs/CODEX-HANDOFF.md index 4cfd245..7fc7ca5 100644 --- a/docs/CODEX-HANDOFF.md +++ b/docs/CODEX-HANDOFF.md @@ -642,6 +642,45 @@ kills 59→58, 59→58, 56→63; hits 7→7, 7→9, 8→3; потери ЗРК 3 появляется). Adapter: `the_air_section_of_a_save_is_written_and_read_by_the_adapter` (запись/чтение секции, замена не слияние, старый save без секции, сценарий без воздуха). +### #149: Smart v2 поверх #146 — единая разведкартина, цены отметок, ограниченный refresh, окно bearing + +Продолжение #127/#135 **поверх уже интегрированного #146** (`KnowledgeSnapshot { tick, contacts, marks }`, +`knowledge_now()`, `Plan.knowledge`, `RouteJob.known`, версионные `price_grid_known`/restore). Инфраструктура +#146 не дублируется и не меняется: один снимок на приказ, цены по `known.tick`, версионный restore — как есть. +Новое наслоение: + +- **Один публичный тип наблюдения** `sim::observe::Observation` (область/радиус, канал `recon::Source`, + возраст, уверенность, категория/роль/тип, качество, флаг `matched`). `observe::merge` сводит `Contact` и + `Mark` в один список **только по публичным признакам** (перекрытие области + точное совпадение категории); + coarse `Unknown` и противоречащая категория остаются отдельными подсказками, контакт не переписывает + тип/место, отметка добавляет лишь свежесть и refined-роль; `recon.truth` и реальные id не участвуют. + `KnowledgeSnapshot::observations()` (аддитивно) отдаёт этот список; одна шкала `Observation::rank` + заменила две разные в `radar_strikes`, `choose_target` и адаптивном выборе (сигнатуры kimi-work сохранены). +- **Цены отметок** в существующем `price_grid_known`: свежая (Probable/Confirmed) отметка launcher/gun/jammer + ценит клетки по published-огибающей категории (`observe::category_envelope`), взвешенной уверенностью + (Confirmed ×1, Probable ×0.5); radar-отметка кормит сетевую веру ПУ рядом (`observe::radar_envelope`); + совпавшая с контактом ценится один раз через контакт; doubtful не ценится. +- **Ограниченный refresh не выпущенной части**: пока разведчики в воздухе, при завершении плана взводится + `ew::Refresh { deadline, reports }` с абсолютным дедлайном `REFRESH_WINDOW=600`. `step_refresh` один раз, + при приходе донесения, перенацеливает queued-дроны с intent Plan/Sead на свежий снимок (typed + `Intent::Refresh`, приоритет SEAD) в пределах `SWITCH_CAP` и бюджетов. Нет донесения — пуски не задерживаются. +- **Окно bearing**: `Intel.outcomes` — bounded `VecDeque` (48 записей, окно 12000 тиков); + `best_bearing` кандидата скорит окно и адаптирует долю исследования по typed `BearingReason` + (few/stale/conditions-changed/exploiting); «условия» — fingerprint публичной картины, не скрытое состояние. + Legacy сохраняет пожизненные kills/hits и фиксированные 0.3 (`FixedShare`). Диагностика — + `Sim::bearing_report()`, поля `bearing/refresh_waiting/refresh_applied/observations` в `EnemyPictureReport`. +- **Сравнительный runner** `cargo run --release --example smart_bench`: simple / current (legacy) / candidate + на seed 1/7/42, сценарии open/hills/config-change/recon-lost; JSON и строки (полезные решения, разнообразие, + jitter ≥2 переключений, reasons/intents, bearing reason, refresh, CPU p95/max, worst jobs). + `Sim::smart_legacy` воспроизводит текущий Smart kimi-work (включая #146) для честного сравнения; + `harness::run_with_hook` меняет оборону между волнами и сбивает разведчика до донесения. Лёгкий режим и + bounded jobs не тронуты; policy не читает здоровье/заряды/скрытые переключатели/позиции мира. +- **Тесты** `sim::smart_tests` + `sim::observe::tests`: метаморфный hidden-layout до/после наблюдения, дедуп + по публичным признакам, отметки в ценах, одна версия на приказ (обе моды чтят #146), bounded refresh + (срабатывает один раз / не паузит), окно bearing и причины, durable окна (`airlearn`) и `Intent::Refresh`. + Регрессия relief-версий сохранена; стена в её фикстуре расширена по z, чтобы пересекать любой восток-запад + маршрут после смены порядка назначений кандидатом. + ## Что следующему агенту проверить в первую очередь 1. На Windows: обновление сабмодуля через `all`, сохранение/перезаход, рабочий цикл игры.