Keep heavy AirDef batteries available for confirmed missile threats

This commit is contained in:
2026-12-02 18:52:41 +03:00
parent 20fdb23b39
commit f6303fe4d4
15 changed files with 273 additions and 82 deletions
+153 -33
View File
@@ -13,6 +13,7 @@ pub(super) const ROLE: u8 = 2;
pub(super) const UNSEEN: u8 = 4;
/// Its track is older than a launcher fires on.
pub(super) const STALE: u8 = 8;
const CLASS_PENDING: u8 = 16;
/// Why a drone is not a candidate for a system at all. The role is checked against the track's
/// *estimated* class, never the target's own (#133): an unidentified track is not blocked — the
@@ -32,6 +33,15 @@ pub(super) fn allowed(roles: u8, track: &Track, now: u64, d: &Drone) -> bool {
target_blocks(roles, Some(track), now, d) == 0
}
fn firing_blocks(sam: &Sam, track: Option<&Track>, now: u64, d: &Drone) -> u8 {
let blocks = target_blocks(sam.roles, track, now, d);
if blocks & ROLE == 0 && sam.specializes_in_missiles() && track.is_some_and(|t| !matches!(t.class, ClassEst::Firm(_))) {
blocks | CLASS_PENDING
} else {
blocks
}
}
pub(super) const TOO_CLOSE: u8 = 1;
pub(super) const TOO_FAR: u8 = 2;
@@ -75,14 +85,26 @@ pub(super) const SHY_TICKS: u64 = 120;
// ---------------------------------------------------------------- the grounds to launch on
/// Last chance (`/airdef lastchance`): a track of a *known* class the system does not engage that
/// is about to hit, with nobody's interceptor on it, is shot at anyway; a system told to hold fire
/// (no roles) keeps to it. An unidentified track is no last-chance case: it is already a candidate
/// under the general rules (#133).
/// A known, out-of-role contact may receive an emergency shot if it is closing on its game aim.
pub(super) const LAST_CHANCE_TICKS: f64 = 120.0;
const SPECIALIST_LAST_CHANCE_TICKS: f64 = 80.0;
pub(super) fn last_chance(on: bool, roles: u8, class: ClassEst, d: &Drone, claimed: u32) -> bool {
on && roles != 0 && !class.in_roles(roles) && claimed == 0 && arrival(d) < LAST_CHANCE_TICKS
fn closing_arrival(d: &Drone) -> f64 {
let to_aim = d.target - d.pos;
let distance = to_aim.length();
let closing = d.vel.dot(to_aim.normalize_or_zero());
if closing > 0.1 { distance / closing } else { f64::INFINITY }
}
fn last_chance(on: bool, sam: &Sam, class: ClassEst, d: &Drone, claimed: u32) -> bool {
if !on || sam.roles == 0 || class.class().is_none() || class.in_roles(sam.roles) || claimed > 0 {
return false;
}
if sam.specializes_in_missiles() {
matches!(class, ClassEst::Firm(_)) && sam.missiles > sam.last_chance_reserve() && closing_arrival(d) < SPECIALIST_LAST_CHANCE_TICKS
} else {
arrival(d) < LAST_CHANCE_TICKS
}
}
/// The big radar's cue (heavy systems only): they may fire out to `FAR_K` × max at a target the radar holds.
@@ -137,6 +159,33 @@ pub(super) enum Basis {
FarShot,
}
impl Sam {
/// Heavy launchers with a role mask that excludes ordinary drones conserve their rounds.
pub(super) fn specializes_in_missiles(&self) -> bool {
matches!(self.kind, SamKind::S400 | SamKind::S500) && self.roles & Class::Drone.bit() == 0
}
fn last_chance_reserve(&self) -> u32 {
let air_capacity = self.cells().saturating_sub(self.ground_rounds);
air_capacity.div_ceil(2).max(self.doctrine.reserve)
}
pub(super) fn shot_priority(&self, class: ClassEst, basis: Basis) -> u8 {
if basis == Basis::LastChance {
return 0;
}
if !self.specializes_in_missiles() {
return 1;
}
match class.class() {
Some(Class::Ballistic) => 4,
Some(Class::Supersonic) => 3,
Some(Class::Cruise) => 2,
_ => 1,
}
}
}
/// What is switched on beyond the roles (the sim's settings).
#[derive(Clone, Copy)]
pub(super) struct Opts {
@@ -160,7 +209,7 @@ pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Dro
} else if !own && !cued {
return None;
}
let blocks = target_blocks(sam.roles, Some(track), now, d);
let blocks = firing_blocks(sam, Some(track), now, d);
if blocks & !ROLE != 0 {
return None;
}
@@ -179,7 +228,7 @@ pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Dro
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, track.est(now)) == 0;
return (far && far_blocks(opts.far_shots, sam, load, cued, role_in_reach) == 0).then_some(Basis::FarShot);
}
(reach == 0 && (own || sam.mode == battery::SamMode::LauncherOnly) && last_chance(opts.last_chance, sam.roles, est, d, claimed)).then_some(Basis::LastChance)
(reach == 0 && (own || sam.mode == battery::SamMode::LauncherOnly) && last_chance(opts.last_chance, sam, est, d, claimed)).then_some(Basis::LastChance)
}
/// The kill chance of an interceptor that met its target `dist` from the launcher whose reach is `max`:
@@ -328,13 +377,18 @@ impl LaunchAudit {
impl Sim {
pub(super) fn last_chance_for(&self, sam: &Sam, class: ClassEst, d: &Drone, claimed: u32) -> bool {
last_chance(self.last_chance, sam.roles, class, d, claimed) && !self.has_role_cover(sam, d)
last_chance(self.last_chance, sam, class, d, claimed) && !self.has_role_cover(sam, class, d)
}
/// A shorter-range role weapon with a usable track and time to engage.
fn has_role_cover(&self, fallback: &Sam, d: &Drone) -> bool {
fn has_role_cover(&self, fallback: &Sam, class: ClassEst, d: &Drone) -> bool {
let now = self.tick;
let lead = (arrival(d) - 20.0).clamp(0.0, 40.0);
let specialist = fallback.specializes_in_missiles();
let lead = if specialist {
(closing_arrival(d) - 20.0).clamp(0.0, 60.0)
} else {
(arrival(d) - 20.0).clamp(0.0, 40.0)
};
let reach = fallback.kind.range();
self.sams.iter().any(|sam| {
if sam.id == fallback.id || !sam.alive() || sam.moving() || sam.reloading > 0
@@ -343,20 +397,33 @@ impl Sim {
return false;
}
let Some(track) = sam.track(d.id) else { return false };
if track.class.class().is_none() || !allowed(sam.roles, track, now, d)
let estimate = if specialist && !matches!(track.class, ClassEst::Firm(_)) {
class
} else {
track.class
};
if estimate.class().is_none() {
return false;
}
if !estimate.in_roles(sam.roles) || track.age(now) > sight::MISSILE_AGE
|| sam.doctrine.area_blocks(sam.pos, track, now) != 0
{
return false;
}
let at = track.est(now);
let soon = at + track.vel * lead;
let closest = |to: DVec3, ready: u32| {
let speed_sq = track.vel.length_squared();
let nearest = if speed_sq > 1e-6 { (to - at).dot(track.vel) / speed_sq } else { 0.0 };
at + track.vel * nearest.clamp(f64::from(ready).min(lead), lead)
};
let available = |target: Option<u32>| target.is_none_or(|id| id == d.id);
let spec = sam.kind.spec();
let gun = spec.gun.as_ref().is_some_and(|gun| {
let mount = sam.mount().0;
sam.gun_up() && sam.bursts > 0 && f64::from(sam.gun_cooldown) <= lead
&& available(sam.gun_target) && track.own_within(now, sight::GUN_PICK_AGE)
&& at.distance(mount).min(soon.distance(mount)) < gun.range
&& closest(mount, sam.gun_cooldown).distance(mount) < gun.range
});
gun || spec.missile.as_ref().is_some_and(|load| {
let authority = if sam.mode == battery::SamMode::LauncherOnly {
@@ -365,11 +432,12 @@ impl Sim {
track.own_authorizes(now)
};
sam.missiles > 0 && f64::from(sam.cooldown) <= lead && sam.part(Part::Launcher) > 0.0
&& (!sam.specializes_in_missiles() || matches!(track.class, ClassEst::Firm(_)))
&& available(sam.target) && !sam.preparing.is_some_and(|p| p.ground)
&& sam.terrain_verdict(d.id, now).is_none_or(|v| v == 0)
&& sam.doctrine.reserve_blocks(sam.missiles, d, track.class) == 0
&& (in_reach(load.min, load.max, 1.0, sam.pos, at)
|| in_reach(load.min, load.max, 1.0, sam.pos, soon))
&& sam.doctrine.reserve_blocks(sam.missiles, d, estimate) == 0
&& closest(sam.pos, sam.cooldown).distance(sam.pos) < load.max
&& (at + track.vel * f64::from(sam.cooldown)).distance(sam.pos).max(soon.distance(sam.pos)) >= load.min
&& authority
})
})
@@ -406,7 +474,7 @@ impl Sim {
a.no_track += 1;
continue;
};
let blocks = target_blocks(sam.roles, Some(tr), now, d);
let blocks = firing_blocks(sam, Some(tr), now, d);
if blocks & STALE != 0 {
a.stale += 1;
continue;
@@ -421,7 +489,7 @@ impl Sim {
let est = tr.class;
let free = claimed(d, &missile_on, sam.target);
let chance = blocks & ROLE != 0 && self.last_chance_for(sam, est, d, free);
if blocks & ROLE != 0 && !chance {
if blocks & CLASS_PENDING != 0 || (blocks & ROLE != 0 && !chance) {
a.role += 1;
continue;
}
@@ -556,6 +624,7 @@ pub enum BattleBlock {
NoWeapon,
NoTarget,
NoTrack,
ClassPending,
OutOfRoles,
OutOfReach,
Claimed,
@@ -685,8 +754,11 @@ impl Sim {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoTrack), Some(t.id), mark));
};
let est = tr.class;
let blocks = target_blocks(sam.roles, Some(tr), now, t);
let blocks = firing_blocks(sam, Some(tr), now, t);
let claimed_now = claimed(t, &missile_on, sam.target);
if blocks & CLASS_PENDING != 0 {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::ClassPending), Some(t.id), mark));
}
let chance = blocks & ROLE != 0 && self.last_chance_for(sam, est, t, claimed_now);
if blocks & ROLE != 0 && !chance {
return Some(reason(BattleKind::Blocked, Some(if sam.roles == 0 { BattleBlock::Hold } else { BattleBlock::OutOfRoles }), Some(t.id), mark));
@@ -703,7 +775,7 @@ impl Sim {
let role_in_reach = spec.missile.as_ref().is_some_and(|load| {
self.drones.iter().any(|o| {
sam.track(o.id).is_some_and(|other| {
allowed(sam.roles, other, now, o)
firing_blocks(sam, Some(other), now, o) == 0
&& in_reach(load.min, load.max, 1.0, sam.pos, other.est(now))
&& doc.area_blocks(sam.pos, other, now) | doc.reserve_blocks(sam.missiles, o, other.class) == 0
&& claimed(o, &missile_on, sam.target) < doc.needed(o, other.class)
@@ -959,13 +1031,15 @@ impl Sim {
format!("цель: {} {}, {}", track.map_or_else(|| ClassEst::Unknown.name(), |tr| tr.class.name()), if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)),
));
let est = track.map_or(ClassEst::Unknown, |tr| tr.class);
let blocks = target_blocks(sam.roles, track, now, t);
let blocks = firing_blocks(sam, track, now, t);
// Where the system believes the target is: its track's forecast (the true place only when it has no track).
let est_at = track.map_or(t.pos, |tr| tr.est(now));
let evel = track.map_or(t.vel, |tr| tr.vel);
let first_claim = claimed(t, &missile_on, sam.target);
let chance = blocks & ROLE != 0 && self.last_chance_for(sam, est, t, first_claim);
let role_text = if blocks & ROLE == 0 {
let role_text = if blocks & CLASS_PENDING != 0 {
"роль: комплекс ждёт подтверждения класса цели".to_string()
} else if blocks & ROLE == 0 {
match est {
ClassEst::Unknown => "роль: тип не определён — цель ведётся по общим правилам, классовые ограничения не применяются".to_string(),
_ => format!("роль: {} в ролях [{}]", est.name(), roles_text(sam.roles)),
@@ -975,14 +1049,24 @@ impl Sim {
"последний шанс: {} не в ролях [{}], но до цели {:.0} с, перехватчиков на ней нет",
est.name(),
roles_text(sam.roles),
arrival(t) / 20.0
if sam.specializes_in_missiles() { closing_arrival(t) } else { arrival(t) } / 20.0
)
} else if sam.roles == 0 {
"роль: система не ведёт огонь (роли не заданы) — цель не выбирается".to_string()
} else {
format!("роль: {} не в ролях [{}]", est.name(), roles_text(sam.roles))
};
v.push(check(blocks & ROLE == 0 || chance, role_text));
v.push(check(blocks & (CLASS_PENDING | ROLE) == 0 || chance, role_text));
if self.last_chance && sam.roles != 0 && sam.specializes_in_missiles()
&& blocks & (CLASS_PENDING | ROLE) == ROLE
{
let reserve = sam.last_chance_reserve();
if sam.missiles <= reserve {
v.push(check(false, format!("последний шанс: сохранён резерв для основных целей ({}/{reserve})", sam.missiles)));
} else if self.has_role_cover(sam, est, t) {
v.push(check(false, "последний шанс: цель прикрывает комплекс ближнего действия".to_string()));
}
}
// The doctrine: which of its settings let the shot through or stopped it. The last chance is past them.
let doc = &sam.doctrine;
let area = track.map_or(0, |tr| doc.area_blocks(sam.pos, tr, now));
@@ -1068,7 +1152,7 @@ impl Sim {
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
let cued = radar_cue(sam, &radars, t.id, now);
let role_in_reach = self.drones.iter().any(|o| {
sam.track(o.id).is_some_and(|tr| allowed(sam.roles, tr, now, o) && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o, tr.class) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o, tr.class))
sam.track(o.id).is_some_and(|tr| firing_blocks(sam, Some(tr), now, o) == 0 && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o, tr.class) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o, tr.class))
});
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0;
let far_ok = far && track.is_some_and(|tr| basis(sam, load, tr, t, now, 0, 1.0, Opts { last_chance: self.last_chance, far_shots: self.far_shots }, cued, role_in_reach) == Some(Basis::FarShot));
@@ -1291,7 +1375,7 @@ mod tests {
// Classified as a drone by the picture: the roles block it, the last chance is what fires.
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
let at = until_fired(&mut sim, &mut ground, &land, &mut out, 140).expect("the S-400 never fired on a Shahed about to hit");
assert!(at < LAST_CHANCE_TICKS, "fired with {at:.0} ticks to go");
assert!(at < SPECIALIST_LAST_CHANCE_TICKS, "fired with {at:.0} ticks to go");
// The diagnostic names why: first the role block, then the last chance.
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
shahed_at(&mut sim, 100.0);
@@ -1326,6 +1410,37 @@ mod tests {
assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс")));
}
#[test]
fn specialist_last_chance_protects_reserve_and_rejects_receding_targets() {
for kind in [SamKind::S400, SamKind::S500] {
let (mut sim, _, _, _) = setup(kind);
shahed_at(&mut sim, 45.0);
let class = ClassEst::Firm(Class::Drone);
assert!(sim.last_chance_for(&sim.sams[0], class, &sim.drones[0], 0));
sim.drones[0].vel = -sim.drones[0].vel;
assert!(!sim.last_chance_for(&sim.sams[0], class, &sim.drones[0], 0));
sim.drones[0].vel = -sim.drones[0].vel;
sim.sams[0].missiles = sim.sams[0].last_chance_reserve();
assert!(!sim.last_chance_for(&sim.sams[0], class, &sim.drones[0], 0));
}
}
#[test]
fn a_ballistic_track_preempts_the_s400s_held_cruise_target() {
let (mut sim, mut ground, _, mut out) = setup(SamKind::S400);
sim.tick = 100;
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 100.0, -180.0), DVec3::Z, DVec3::ZERO);
seed_classified(&mut sim, ClassEst::Firm(Class::Cruise));
sim.sams[0].target = Some(sim.drones[0].id);
sim.add_drone(DroneKind::Kinzhal, DVec3::new(0.0, 100.0, -400.0), DVec3::Z, DVec3::ZERO);
let cruise = sim.sams[0].tracks[0];
let ballistic = &sim.drones[1];
let id = ballistic.id;
sim.sams[0].tracks.push(Track { id, pos: ballistic.pos, vel: ballistic.vel, class: ClassEst::Firm(Class::Ballistic), ..cruise });
sim.step_sams(&mut ground, &mut out);
assert_eq!(sim.sams[0].target, Some(id));
}
#[test]
fn last_chance_is_off_when_switched_off_and_with_no_roles() {
for (off, roles) in [(true, 30u8), (false, 0u8)] {
@@ -1396,12 +1511,10 @@ mod tests {
}
#[test]
fn roles_read_the_estimate_an_unidentified_track_is_not_blocked() {
// #133: the role filter reads the track's estimated class, never the target's own. While
// the contact is unidentified the S-400 (its roles exclude drones) keeps it as a candidate
// under the general rules — the explicit policy, named in why; once the estimate firms as
// a drone, the block applies and why names that instead.
assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0, "the S-400 does not engage drones");
fn specialists_require_confirmed_class_but_explicit_drone_roles_restore_normal_fire() {
for kind in [SamKind::S400, SamKind::S500] {
assert_eq!(kind.spec().roles & (Class::Drone.bit() | Class::Jet.bit()), 0);
}
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
sim.last_chance = false;
shahed_at(&mut sim, 60.0);
@@ -1417,8 +1530,13 @@ mod tests {
}
saw_open = true;
assert_eq!(why::target_blocks(roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "an unidentified contact must not be role-blocked");
assert_eq!(why::firing_blocks(&sim.sams[0], Some(&t), sim.tick, &sim.drones[0]), why::CLASS_PENDING);
let w = sim.why(0);
assert!(w.iter().any(|c| c.legacy_text().contains("по общим правилам")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
assert!(w.iter().any(|c| c.legacy_text().contains("ждёт подтверждения класса")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
sim.sams[0].roles |= Class::Drone.bit();
assert_eq!(why::firing_blocks(&sim.sams[0], Some(&t), sim.tick, &sim.drones[0]), 0);
let w = sim.why(0);
assert!(w.iter().any(|c| c.legacy_text().contains("по общим правилам")));
break;
}
assert!(saw_open, "the contact was never seen unidentified");
@@ -1439,6 +1557,8 @@ mod tests {
assert_ne!(why::target_blocks(sim.sams[0].roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "a classified out-of-role contact must be blocked");
let w = sim.why(0);
assert!(w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
sim.sams[0].roles |= Class::Drone.bit();
assert_eq!(why::firing_blocks(&sim.sams[0], Some(&t), sim.tick, &sim.drones[0]), 0, "the explicit drone role enables an ordinary shot");
// Holding fire (no roles at all): nothing is a candidate, the unidentified either.
let d = sim.drones[0].clone();
let unknown = Track { id: d.id, class: ClassEst::Unknown, pos: d.pos, vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: battery::Measure::Search, quality: 40, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 1, locked: false };