Give the enemy a last-observation picture and observed-capability pricing (#127)

This commit is contained in:
2026-11-06 17:58:17 +03:00
parent 0b645d77e9
commit 8fc10c07a1
14 changed files with 1189 additions and 188 deletions
+107 -112
View File
@@ -275,9 +275,9 @@ impl Sim {
}
let smart = order.aim == Aim::Smart;
// The planner's picture of the layout: one snapshot for the whole order. It is
// read-only while the plan is built, and recomputing it per drone made a big
// second order quadratic in the intel log and the force's size (#122).
let known = self.known_units();
// read-only while the plan is built, and taking it per drone made a big second order
// quadratic in the force's size (#122); a map of contacts makes it linear in them (#127).
let picture = self.picture_of_defences();
// A smart enemy comes from where its raids got through best.
let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU };
// The raid's sides (1, 2, or 4-5): its launch sites go there (#100).
@@ -290,7 +290,7 @@ impl Sim {
let grid = Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 };
let mut items = Vec::new();
// A smart raid goes for the radars too (a few strikers each); the others pick as they always did.
let radar_jobs = if smart { self.radar_strikes(&order.kinds, &known) } else { Vec::new() };
let radar_jobs = if smart { self.radar_strikes(&order.kinds, &picture) } else { Vec::new() };
let mut index = 0usize;
for (group, &(kind, count)) in order.kinds.iter().enumerate() {
let spec = kind.spec();
@@ -306,7 +306,7 @@ impl Sim {
index += 1;
let (target, at_sam) = match job {
Some((at, id)) => (at, Some(id)),
None => self.choose_target(kind, object, order.aim, &known),
None => self.choose_target(kind, object, order.aim, &picture),
};
let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0);
let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0;
@@ -547,9 +547,12 @@ impl Sim {
/// The strikes a smart raid sends at observed radars: for drones of `kinds` in order,
/// the last observed place and id for those that go for one. Each radar
/// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid.
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], known: &[(u32, DVec3)]) -> Vec<Option<(DVec3, u32)>> {
let mut radars: Vec<(u32, DVec3)> = known.iter().copied()
.filter(|(id, _)| self.sams.iter().any(|s| s.id == *id && s.alive() && s.kind == SamKind::Radar))
/// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile.
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact]) -> Vec<Option<(DVec3, u32)>> {
let mut radars: Vec<(u32, DVec3)> = picture
.iter()
.filter(|c| c.kind == SamKind::Radar && c.confidence(self.tick) >= ew::Confidence::Probable)
.map(|c| (c.id, c.at))
.collect();
radars.sort_by_key(|(id, _)| *id);
let flat: Vec<DroneKind> = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect();
@@ -571,48 +574,40 @@ impl Sim {
jobs
}
/// What a drone goes for: an object, or (by its kind and the raid's aim) a system. Returns the
/// point and the system's id.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, known: &[(u32, DVec3)]) -> (DVec3, Option<u32>) {
let alive: Vec<&Sam> = self.sams.iter().filter(|s| s.alive()).collect();
if alive.is_empty() || kind.spec().decoy || aim == Aim::Objects {
/// What a drone goes for: an object, or (by its kind and the raid's aim) a unit. Returns the
/// point and the unit's id. The planner has only the picture (#93, #127): what it knows of a
/// unit is the last observation — the place seen then, the type identified then — never where
/// the unit actually is or what it has become since.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact]) -> (DVec3, Option<u32>) {
if picture.is_empty() || kind.spec().decoy || aim == Aim::Objects {
return (object, None);
}
let pick = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
(!list.is_empty()).then(|| {
let s = list[(r * list.len() as f64) as usize % list.len()];
(s.pos, s.id)
})
let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> {
let c = list.get((r * list.len() as f64) as usize)?;
Some((c.at, c.id))
};
let r = self.rng.f();
let roll = self.rng.f();
if aim == Aim::ObjectsAndSams {
return if roll < 0.33 { pick(&alive, r).map_or((object, None), |(p, id)| (p, Some(id))) } else { (object, None) };
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
// station, a radar, a system that fired).
// The planner has only what the enemy knows (#93): the radars (they emit) and the units that gave
// themselves away; the rest of the player's layout is not in its hands.
let alive: Vec<&Sam> = alive.iter().copied().filter(|s| Self::enemy_knows(s, known)).collect();
let pick_known = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
let s = *list.get((r * list.len() as f64) as usize)?;
known.iter().find(|(id, _)| *id == s.id).map(|(_, pos)| (*pos, s.id))
};
let known_ew: Vec<&Sam> = alive.iter().copied().filter(|s| s.kind == SamKind::Ew).collect();
let known_ew: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind == SamKind::Ew).collect();
if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !known_ew.is_empty() && roll < 0.6 {
let s = known_ew[(r * known_ew.len() as f64) as usize % known_ew.len()];
return (known.iter().find(|(id, _)| *id == s.id).unwrap().1, Some(s.id));
let c = known_ew[(r * known_ew.len() as f64) as usize % known_ew.len()];
return (c.at, Some(c.id));
}
// Short-range systems (guns, Tor, P1-SUN) for the Lancets; long-range ones and the radars
// that feed them for the fast missiles.
let guns: Vec<&Sam> = alive.iter().copied().filter(|s| s.kind.armed() && s.kind.range() <= 300.0).collect();
let long: Vec<&Sam> =
alive.iter().copied().filter(|s| s.kind.range() >= 450.0 || s.kind == SamKind::Radar).collect();
let guns: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind.armed() && c.kind.range() <= 300.0).collect();
let long: Vec<ew::Contact> =
picture.iter().copied().filter(|c| c.kind.range() >= 450.0 || c.kind == SamKind::Radar).collect();
let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick_known(&guns, r).or_else(|| pick_known(&alive, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick_known(&long, r),
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick_known(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick_known(&alive, r),
DroneKind::Lancet if roll < 0.75 => pick(&guns, r).or_else(|| pick(picture, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick(&long, r),
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r),
_ => None,
};
choice.map_or((object, None), |(p, id)| (p, Some(id)))
@@ -625,52 +620,54 @@ impl Sim {
self.price_grid_on(grid, kind, None)
}
/// The same over known land: a cell's drone flies `height` over the land there, not over the system's feet,
/// so what a radar sees and what a hill hides follow the relief.
/// The same over the picture this moment holds: a smart plan's own prices are priced on the
/// picture the plan was ordered with (#127). Later observations change nothing here.
pub(super) fn price_grid_on(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>) -> (Vec<f32>, usize) {
let known_now = self.known_units();
self.price_grid_known(grid, kind, land, &known_now)
self.price_grid_known(grid, kind, land, &self.picture_of_defences())
}
/// The same over a picture of the enemy: a retarget is priced on the picture its target was chosen
/// from, so the jobs of one adaptive tick do not each see a different world (#127).
pub(super) fn price_grid_known(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, known_now: &[(u32, DVec3)]) -> (Vec<f32>, usize) {
/// The same over a picture of the defences: a retarget is priced on the picture its target was
/// chosen from, so the jobs of one adaptive tick do not each see a different world (#127). Every
/// capability read here is the contact's published kind and the contact's own observations —
/// never the unit's actual switch settings, damage, roles, link health or magazine.
pub(super) fn price_grid_known(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, picture: &[ew::Contact]) -> (Vec<f32>, usize) {
let mut cost = 0;
let spec = kind.spec();
let height = spec.clearance.max(6.0);
let n = grid.size;
let now = self.tick;
let mut prices = vec![1.0f32; (n * n) as usize];
// Known jamming stations: drones that navigate by satellite keep away.
if kind.jammable() {
for s in self.sams.iter().filter(|s| s.kind == SamKind::Ew && s.alive() && known_now.iter().any(|k| k.0 == s.id)) {
let pos = known_now.iter().find(|(id, _)| *id == s.id).unwrap().1;
let (ci, cj) = grid.index(pos);
let r = (EW_RADIUS / grid.cell).ceil() as i32;
for c in picture.iter().filter(|c| c.kind == SamKind::Ew) {
let (ci, cj) = grid.index(c.at);
let r = (ew::EW_RADIUS / 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) {
if horizontal(grid.centre((i, j), pos.y) - pos).length() < EW_RADIUS {
if horizontal(grid.centre((i, j), c.at.y) - c.at).length() < ew::EW_RADIUS {
prices[(i * n + j) as usize] += 12.0;
}
}
}
}
}
// Only the systems the enemy knows of are priced in (#93): a hidden one is flown into.
for s in self.sams.iter().filter(|s| s.alive() && s.roles & spec.class.bit() != 0 && Self::enemy_knows(s, &known_now)) {
let pos = known_now.iter().find(|(id, _)| *id == s.id).unwrap().1;
let sp = s.kind.spec();
// Only the systems the picture holds are priced in (#93): a hidden one is flown into.
for c in picture.iter().filter(|c| c.kind.spec().roles & spec.class.bit() != 0) {
let pos = c.at;
let sp = c.kind.spec();
let (lo, hi) = sp.missile.as_ref().map_or((0.0, 0.0), |m| (m.min, m.max));
let gun = sp.gun.as_ref().map_or(0.0, |g| g.range);
// A gun needs its own radar; a missile also flies on the tracks of any radar within data-link range.
let own = sight::reach(s, kind, height);
let net = self.sams.iter().filter_map(|r| {
let at = known_now.iter().find(|(id, _)| *id == r.id)?.1;
(r.id != s.id && at.distance(pos) <= sight::LINK).then(|| sight::reach(r, kind, height))
}).fold(0.0, f64::max);
// A gun needs its own radar; a missile also flies on the tracks of any radar the picture
// holds within data-link range of the unit's observed place. What those radars are set to
// (role, switch, damage) is not observable: a live contact of one is assumed to feed.
let own = if c.believes_own_sensor(now) { ew::published_reach(c.kind, kind, height) } else { 0.0 };
let net = picture
.iter()
.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);
let (hi, gun) = (hi.min(own.max(net)), gun.min(own));
let far = hi.max(gun);
let at = pos + (sight::antenna(s) - s.pos);
let horizon = (pos == s.pos).then(|| self.horizons.get(&s.id)).flatten();
// Only the cells round it.
let (ci, cj) = grid.index(pos);
let r = (far / grid.cell).ceil() as i32 + 1;
@@ -687,9 +684,6 @@ impl Sim {
if !(missile || d < gun) {
continue;
}
if horizon.is_some_and(|h| h.hides(at, p)) {
continue;
}
prices[(i * n + j) as usize] += if missile { 30.0 } else { 18.0 };
}
}
@@ -985,23 +979,27 @@ mod tests {
fn sead_uses_only_unexpired_observations_at_the_last_known_position() {
let mut sim = Sim::new(121);
let old = DVec3::new(100.0, 70.0, 200.0);
let mut radar = Sam::new(1, SamKind::Radar, old, 0.0);
radar.radar_on = false;
let radar = Sam::new(1, SamKind::Radar, old, 0.0);
sim.sams.push(radar);
let kinds = [(DroneKind::Kh22, 8)];
let none = Vec::new();
assert!(sim.radar_strikes(&kinds, &none).iter().all(Option::is_none));
sim.tick = 20;
sim.intel.revealed.push((1, old, sim.tick));
sim.intel.observe(&sim.sams[0], sim.tick, ew::Seen::Emission);
// The truth moving after the fix is not an observation: the strike goes to the seen place.
sim.sams[0].pos = DVec3::new(900.0, 70.0, 900.0);
sim.tick = 40;
let known = sim.known_units();
let jobs = sim.radar_strikes(&kinds, &known);
let picture = sim.picture_of_defences();
let jobs = sim.radar_strikes(&kinds, &picture);
assert_eq!(jobs.iter().flatten().count(), 2);
assert!(jobs.iter().flatten().all(|job| *job == (old, 1)));
// An old contact is not worth a strike either.
sim.tick = 3021;
let picture = sim.picture_of_defences();
assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none), "a doubtful contact was struck");
sim.tick = 6020;
let known = sim.known_units();
assert!(sim.radar_strikes(&kinds, &known).iter().all(Option::is_none));
let picture = sim.picture_of_defences();
assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none));
}
#[test]
@@ -1011,9 +1009,10 @@ mod tests {
for (i, at) in [(-300.0, -200.0), (250.0, -250.0), (50.0, 300.0)].into_iter().enumerate() {
let id = sim.id();
let p = DVec3::new(at.0, 70.0, at.1);
sim.sams.push(Sam::new(id, SamKind::Radar, p, i as f64));
let sam = Sam::new(id, SamKind::Radar, p, i as f64);
sim.intel.observe(&sam, sim.tick, ew::Seen::Emission);
sim.sams.push(sam);
radars.push((id, p));
sim.intel.revealed.push((id, p, sim.tick));
}
let ew = sim.id();
sim.sams.push(Sam::new(ew, SamKind::Ew, DVec3::new(0.0, 70.0, 0.0), 0.0));
@@ -1049,7 +1048,7 @@ mod tests {
// The first strikers are the fast ones.
assert!(radars.iter().any(|(_, p)| aimed_at(&sim, *p).iter().any(|k| matches!(k, DroneKind::Kh22 | DroneKind::Zircon | DroneKind::Iskander | DroneKind::Kinzhal))));
// The enemy has learnt of the jamming station and re-aims what it can: not these.
sim.intel.revealed.push((ew, DVec3::new(0.0, 70.0, 0.0), sim.tick));
sim.intel.observe(&sim.sams.iter().find(|s| s.id == ew).unwrap(), sim.tick, ew::Seen::Jamming);
for _ in 0..160 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
@@ -1057,50 +1056,45 @@ mod tests {
check(&sim, "after adapting");
}
/// The snapshot the planner works from must not depend on how it is computed:
/// the set-based pass is checked here against the former per-entry rescan, over
/// duplicates, the dead, the aged-out, ids the force never had, and ordering.
/// The picture the planner works from: one contact per unit, the newest observation
/// winning, the forgotten and the watched-dead out, the order deterministic — and it
/// never reads the force itself, so a contact of a unit that no longer exists stays
/// until its observations age out.
#[test]
fn known_units_matches_the_naive_reference_on_a_fat_log() {
fn picture_is_newest_per_unit_and_reads_no_truth() {
let mut sim = Sim::new(9);
let mut places = Vec::new();
let mut ids = Vec::new();
for (i, kind) in [SamKind::S400, SamKind::Ew, SamKind::Radar, SamKind::Tor, SamKind::Patriot].into_iter().enumerate() {
let id = sim.id();
let mut sam = Sam::new(id, kind, DVec3::new(i as f64 * 100.0, 70.0, -50.0), 0.0);
// The second system is dead: known only while it lived.
if i == 1 { sam.health = 0.0; }
sim.sams.push(sam);
places.push((id, DVec3::new(i as f64 * 100.0, 70.0, -50.0)));
sim.sams.push(Sam::new(id, kind, DVec3::new(i as f64 * 100.0, 70.0, -50.0), 0.0));
ids.push(id);
}
let naive = |sim: &Sim| {
let mut out: Vec<(u32, DVec3)> = Vec::new();
for &(id, at, observed) in sim.intel.revealed.iter().rev() {
if sim.tick.saturating_sub(observed) >= 6000 { continue; }
if !out.iter().any(|o| o.0 == id) && sim.sams.iter().any(|s| s.id == id && s.alive()) {
out.push((id, at));
}
}
out
};
sim.tick = 7000;
let dead = places[1].0;
let (a, b, c, d, e) = (places[0].0, places[1].0, places[2].0, places[3].0, places[4].0);
// A long log: repeated observations (newest wins), one dead system, one never-seen
// system, one id the force does not have, and an entry that aged out.
let (a, b, c, d, e) = (ids[0], ids[1], ids[2], ids[3], ids[4]);
// A long fight: repeated observations (newest wins), one unit watched dying, one
// never seen, one id the force does not have, and one observation that aged out.
for t in 0..200u64 {
sim.intel.revealed.push((a, DVec3::new(11.0, 70.0, t as f64), 1000 + t));
sim.intel.revealed.push((c, DVec3::new(13.0, 70.0, t as f64), 1000 + t));
if t % 7 == 0 { sim.intel.revealed.push((b, DVec3::new(12.0, 70.0, t as f64), 1000 + t)); }
if t % 11 == 0 { sim.intel.revealed.push((d, DVec3::new(14.0, 70.0, t as f64), 1000 + t)); }
if t % 13 == 0 { sim.intel.revealed.push((999_999, DVec3::new(1.0, 70.0, 0.0), 1000 + t)); }
sim.intel.observe(&sim.sams[0], 1000 + t, ew::Seen::Launch);
sim.intel.observe(&sim.sams[2], 1000 + t, ew::Seen::Emission);
if t % 7 == 0 { sim.intel.observe(&sim.sams[1], 1000 + t, ew::Seen::Jamming); }
if t % 11 == 0 { sim.intel.observe(&sim.sams[3], 1000 + t, ew::Seen::Launch); }
if t % 13 == 0 {
sim.intel.note(999_999, SamKind::Radar, DVec3::new(1.0, 70.0, 0.0), true, 1000 + t, ew::Seen::Emission);
}
}
sim.intel.revealed.push((e, DVec3::new(15.0, 70.0, 0.0), 2)); // aged out at tick 7000
let expected = naive(&sim);
assert_eq!(sim.known_units(), expected);
assert_eq!(expected.iter().map(|k| k.0).collect::<Vec<_>>(), vec![c, a, d]);
assert!(expected.iter().all(|k| k.0 != dead && k.0 != e && k.0 != 999_999));
// The newest observation's place is the one kept.
assert_eq!(expected.iter().find(|k| k.0 == a).unwrap().1, DVec3::new(11.0, 70.0, 199.0));
sim.intel.note(e, SamKind::Patriot, DVec3::new(15.0, 70.0, 0.0), true, 2, ew::Seen::Launch); // aged out at tick 7000
// The EW station is watched dying by a strike: observed, and so out of the targets.
sim.intel.outcome(b, false, sim.sams[1].pos, 1349);
let picture = sim.picture_of_defences();
let got: Vec<u32> = picture.iter().map(|c| c.id).collect();
// a and c were both seen last at tick 1199 (tie: the newer id first); d at 1198; the
// fake at 1195. The watched-dead b, the never-seen e and the aged-out are out.
assert_eq!(got, vec![c, a, d, 999_999]);
assert_eq!(picture[0].at, DVec3::new(200.0, 70.0, -50.0), "the observed place is the unit's own");
assert_eq!(picture[0].seen, ew::Seen::Emission);
assert_eq!(picture[1].kind, SamKind::S400);
assert!(picture.iter().all(|c| c.id != b && c.id != e));
assert_eq!(sim.picture_of_defences(), picture, "the picture is not deterministic");
}
/// The reported Windows stop (#122): the second big order from the UI path, with a fat
@@ -1116,11 +1110,12 @@ mod tests {
sim.sams.push(Sam::new(id, [SamKind::S400, SamKind::Patriot, SamKind::Nasams, SamKind::Pantsir][i % 4], DVec3::new((i % 8 * 40) as f64, 70.0, (i / 8 * 40) as f64), 0.0));
ids.push(id);
}
// A fought-off first raid leaves a long log: launches, emitting radars, stations.
// Its entries sit in the past of the sim clock, like real ones.
// A fought-off first raid leaves a long observation history: launches, emitting
// radars, stations. Its entries sit in the past of the sim clock, like real ones.
sim.tick = 4000;
for t in 0..3000u64 {
sim.intel.revealed.push((ids[(t as usize) % ids.len()], DVec3::new(10.0, 70.0, t as f64), 1001 + t));
let sam = &sim.sams[(t as usize) % ids.len()];
sim.intel.observe(sam, 1001 + t, if t % 3 == 0 { ew::Seen::Emission } else { ew::Seen::Launch });
}
sim.targets.push(DVec3::new(160.0, 70.0, 160.0));
sim.target_health.push(100.0);