Playtest fixes: smoke by engine, searchlights, far launch sites that load their chunks, air defence balance, last chance and radar-cued shots, radars in smart raids, echo, Windows release build from a tag
build / mod (push) Successful in 4m4s
release / windows (push) Successful in 23m13s

Smoke: one rule by engine, no heat on trails, no trail on P1-SUN. Searchlights: two lamps a target, off with an empty sky. Halos fade before their reach and their sum is limited. Launch sites load chunks through the server thread, go off-map as a last resort, and reach 4000 blocks. Air defence: ranges x1.5, shots grow with urgency, claims released, /airdef lastchance, long shots on a big radar's tracks. Build: rust-toolchain.toml, airdef.py check, generator manifest and --check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 23:44:14 +03:00
parent 5003376e70
commit ccc3e20902
67 changed files with 4573 additions and 328 deletions
+297
View File
@@ -0,0 +1,297 @@
//! Balance measurements: a whole raid on flat land, flown headlessly against a cluster of systems.
//! The `#[ignore]`d tests print tables (`cargo test --release balance -- --ignored --nocapture`);
//! the others assert the cheap invariants. The tables are what the air defence's tuning is judged by.
use super::sites::testland::{Land, serve};
use super::*;
/// The ten armed kinds in the order a cluster takes them (long-range heavy ones spread evenly).
const MIX: [SamKind; 10] = [
SamKind::Patriot,
SamKind::IrisT,
SamKind::S400,
SamKind::Pantsir,
SamKind::Nasams,
SamKind::Tor,
SamKind::S500,
SamKind::Buk,
SamKind::Gepard,
SamKind::P1sun,
];
/// What one drone went through, for saying why it got through.
#[derive(Default, Clone)]
struct Hist {
kind: Option<DroneKind>,
/// Ticks any system held a track of it.
seen: u32,
/// Ticks some loaded launcher with the class in its roles had it in range (`cover`), and held its track too (`reach`).
cover: u32,
reach: u32,
/// Distinct interceptors sent at it.
shots: std::collections::HashSet<u32>,
dead: bool,
last: (DVec3, DVec3),
/// Ticks to the aim when first covered, first tracked by a covering launcher, first shot at.
ttg: (f64, f64, f64),
}
#[derive(Default, Debug, Clone)]
pub(super) struct Result {
pub launched: u32,
pub kills: u32,
pub leaked: u32,
pub missiles: u32,
pub ticks: u64,
/// Leaks by cause.
pub unseen: u32,
pub no_cover: u32,
pub untracked: u32,
pub hits: u32,
pub crashes: u32,
pub unshot: u32,
pub missed: u32,
/// Missiles fired by the heavy systems (S-400, S-500, Patriot).
pub heavy: u32,
pub by_kind: Vec<(DroneKind, u32, u32)>,
pub tally: String,
}
pub(super) struct Setup {
pub systems: usize,
pub smart: bool,
pub seed: u64,
pub size: u32,
pub radars: usize,
pub objects: usize,
/// Called on the sim before the raid (a test sets its switches).
pub tweak: fn(&mut Sim),
}
impl Setup {
pub fn new(systems: usize, smart: bool, seed: u64) -> Self {
Setup { systems, smart, seed, size: 36, radars: (systems / 10).max(1), objects: 36, tweak: |_| {} }
}
}
/// The cluster: `objects` in a grid, systems of the mix scattered round them, radars among them.
pub(super) fn cluster(sim: &mut Sim, s: &Setup) {
let mut rng = Rng::new(s.seed.wrapping_mul(977) + 5);
let side = (s.objects as f64).sqrt().ceil() as usize;
for k in 0..s.objects {
let p = DVec3::new(((k % side) as f64 - side as f64 / 2.0) * 70.0, 70.0, ((k / side) as f64 - side as f64 / 2.0) * 70.0);
sim.targets.push(p);
sim.target_health.push(100.0);
}
let objects = sim.targets.clone();
for i in 0..s.systems {
let at = objects[(rng.f() * objects.len() as f64) as usize % objects.len()];
let a = rng.f() * TAU;
let r = 30.0 + rng.f() * 110.0;
let id = sim.id();
sim.sams.push(Sam::new(id, MIX[i % MIX.len()], at + DVec3::new(a.sin() * r, 0.0, a.cos() * r), rng.f() * TAU));
}
for _ in 0..s.radars {
let a = rng.f() * TAU;
let r = rng.f() * 220.0;
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Radar, DVec3::new(a.sin() * r, 70.0, a.cos() * r), 0.0));
}
}
/// Flies one raid to its end and counts.
pub(super) fn fly(s: &Setup) -> Result {
let mut sim = Sim::new(s.seed);
cluster(&mut sim, s);
(s.tweak)(&mut sim);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..200 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
let mut order = crate::wave::WaveConfig::mix(s.size, 500.0);
// The Oreshnik's blocks are a raid of their own; this measures the ordinary mass raid.
order.kinds.retain(|k| k.0 != DroneKind::Oreshnik);
if s.smart {
order.aim = raid::Aim::Smart;
order.approach = raid::Approach::AllSides;
}
let targets = sim.targets.clone();
let fired0: u32 = sim.sams.iter().map(|m| m.fired).sum();
sim.order_raid(&order, &targets, &mut out);
let mut hist: HashMap<u32, Hist> = HashMap::new();
let mut result = Result::default();
let start = sim.tick;
let mut gone_unkilled: Vec<Hist> = Vec::new();
for _ in 0..9000 {
serve(&mut ground, &land, sim.tick);
out = Out::default();
sim.step(&mut ground, None, &mut out);
let now = sim.tick;
for d in &sim.drones {
let h = hist.entry(d.id).or_default();
h.kind = Some(d.kind);
h.last = (d.pos, d.target);
if !d.alive() {
h.dead = true;
continue;
}
if sim.sams.iter().any(|m| m.seen.contains(&d.id)) {
h.seen += 1;
}
let class = d.kind.spec().class.bit();
let covers = |m: &&Sam| {
m.alive() && m.roles & class != 0 && m.missiles > 0 && m.kind.spec().missile.as_ref().is_some_and(|l| (l.min..l.max).contains(&m.pos.distance(d.pos)))
};
let ttg = why::arrival(d);
if h.cover == 0 && sim.sams.iter().filter(covers).next().is_some() {
h.ttg.0 = ttg;
}
if h.reach == 0 && sim.sams.iter().filter(covers).any(|m| m.seen.contains(&d.id)) {
h.ttg.1 = ttg;
}
h.cover += u32::from(sim.sams.iter().filter(covers).next().is_some());
h.reach += u32::from(sim.sams.iter().filter(covers).any(|m| m.seen.contains(&d.id)));
}
for m in &sim.missiles {
if let Some(h) = hist.get_mut(&m.target) {
if h.shots.is_empty() {
h.ttg.2 = h.last.0.distance(h.last.1) / h.kind.map_or(1.0, |k| k.spec().speed);
}
h.shots.insert(m.id);
}
}
// Drones gone from the sky that were never brought down arrived (or crashed).
let here: std::collections::HashSet<u32> = sim.drones.iter().map(|d| d.id).collect();
let queued: std::collections::HashSet<u32> = sim.queue.iter().map(|q| q.1.id).collect();
let vanished: Vec<u32> = hist.iter().filter(|(id, h)| !here.contains(id) && !queued.contains(id) && !h.dead && h.kind.is_some()).map(|(id, _)| *id).collect();
for id in vanished {
if let Some(h) = hist.remove(&id) {
// Gone from the sky near its aim: arrived. (A kill that detonates or breaks up removes the drone too.)
let k = h.kind.unwrap();
if !k.spec().decoy && h.last.0.distance(h.last.1) < 2.0 * k.spec().speed + 12.0 {
if std::env::var("LEAKS").is_ok() {
eprintln!(" leak {k:?} seen {} cover {} reach {} shots {} ttg cover/track/shot {:.0}/{:.0}/{:.0}", h.seen, h.cover, h.reach, h.shots.len(), h.ttg.0, h.ttg.1, h.ttg.2);
}
gone_unkilled.push(h);
}
}
}
// Dead ones that have landed are forgotten.
hist.retain(|id, h| !(h.dead && !here.contains(id)));
if now - start > 300 && sim.queue.is_empty() && !sim.planning() && !sim.drones.iter().any(|d| d.alive()) && sim.missiles.is_empty() {
break;
}
}
result.ticks = sim.tick - start;
result.launched = sim.launched;
result.kills = sim.kills;
result.missiles = sim.sams.iter().map(|m| m.fired).sum::<u32>() - fired0;
result.heavy = sim.sams.iter().filter(|m| matches!(m.kind, SamKind::S400 | SamKind::S500 | SamKind::Patriot)).map(|m| m.fired).sum();
result.hits = sim.hits;
result.crashes = sim.crashes;
result.leaked = sim.hits;
let mut kinds: HashMap<DroneKind, (u32, u32)> = HashMap::new();
for h in &gone_unkilled {
let k = h.kind.unwrap();
kinds.entry(k).or_default().0 += 1;
if h.seen == 0 {
result.unseen += 1;
} else if h.cover == 0 {
result.no_cover += 1;
} else if h.reach == 0 {
result.untracked += 1;
} else if h.shots.is_empty() {
result.unshot += 1;
} else {
result.missed += 1;
}
}
result.by_kind = kinds.into_iter().map(|(k, v)| (k, v.0, v.1)).collect();
result.by_kind.sort_by_key(|k| k.0 as u8);
result.tally = sim.tally.text();
result
}
pub(super) fn table(title: &str, smart: bool, size: u32, systems: &[usize], seeds: &[u64], tweak: fn(&mut Sim)) -> Vec<(usize, f64)> {
let mut means = Vec::new();
eprintln!("== {title} ({} raid)", if smart { "smart" } else { "mix" });
eprintln!("{:>4} {:>4} {:>5} {:>5} {:>5} {:>6} {:>6} | leaks: unseen nocover untrk unshot missed hits crash", "sams", "seed", "sent", "kills", "leak", "missil", "heavy");
for &n in systems {
let (mut total, mut missiles, mut heavy, mut clean) = (0, 0, 0, 0);
for &seed in seeds {
let mut s = Setup::new(n, smart, seed);
s.tweak = tweak;
s.size = size;
let r = fly(&s);
total += r.leaked;
clean += u32::from(r.leaked == 0);
missiles += r.missiles;
heavy += r.heavy;
if std::env::var("ROWS").is_ok() { eprintln!("{n:>4} {seed:>4} {:>5} {:>5} {:>5} {:>6} {:>6} | {:>12} {:>7} {:>5} {:>6} {:>6} {:>4} {:>5} {:?}", r.launched, r.kills, r.leaked, r.missiles, r.heavy, r.unseen, r.no_cover, r.untracked, r.unshot, r.missed, r.hits, r.crashes, r.by_kind.iter().map(|k| format!("{:?}:{}", k.0, k.1)).collect::<Vec<_>>()); }
if seed == seeds[0] && std::env::var("ROWS").is_ok() {
eprintln!(" tally: {}", r.tally);
}
}
let mean = total as f64 / seeds.len() as f64;
let k = seeds.len() as f64;
eprintln!("{n:>4} mean leaks {mean:.1} (clean seeds {clean}/{}), missiles {:.0}, of them heavy {:.0}", seeds.len(), missiles as f64 / k, heavy as f64 / k);
means.push((n, mean));
}
means
}
#[test]
#[ignore]
fn raid_table() {
for smart in [false, true] {
table("current", smart, 36, &[20, 50, 150], &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], |_| {});
}
}
/// A raid of 80 (about 100 drones): 20 systems clearly lose, 150 hold (a loose bound, one seed).
#[test]
fn a_small_cluster_loses_and_a_big_one_holds() {
let mut s = Setup::new(20, false, 2);
s.size = 80;
let small = fly(&s);
let mut s = Setup::new(150, false, 2);
s.size = 80;
let big = fly(&s);
eprintln!("20 systems: {small:?}\n150 systems: {big:?}");
assert!(small.launched >= 80, "the raid was not launched: {small:?}");
assert!(small.leaked >= 10, "20 systems should clearly lose, leaked {}", small.leaked);
assert!(big.leaked <= 5, "150 systems leaked {}", big.leaked);
}
/// What each of the new rules adds, one at a time (the raid of 36 and a heavier one of 80).
#[test]
#[ignore]
fn rules_one_by_one() {
for size in [36, 80] {
for smart in [false, true] {
table(&format!("size {size}: roles only"), smart, size, &[20, 50, 150], &[1, 2, 3, 4, 5, 6], |s| {
s.last_chance = false;
s.far_shots = false;
});
table(&format!("size {size}: + last chance"), smart, size, &[20, 50, 150], &[1, 2, 3, 4, 5, 6], |s| s.far_shots = false);
table(&format!("size {size}: + last chance + long shots"), smart, size, &[20, 50, 150], &[1, 2, 3, 4, 5, 6], |_| {});
}
}
}
/// One raid in detail, for hunting a leak: `LEAKS=1 cargo test --release one_raid -- --ignored --nocapture`.
#[test]
#[ignore]
fn one_raid() {
let n: usize = std::env::var("SAMS").ok().and_then(|v| v.parse().ok()).unwrap_or(150);
let smart = std::env::var("SMART").is_ok();
let size: u32 = std::env::var("SIZE").ok().and_then(|v| v.parse().ok()).unwrap_or(36);
for seed in 1..=12 {
let mut s = Setup::new(n, smart, seed);
s.size = size;
let r = fly(&s);
eprintln!("seed {seed}: sent {} kills {} leaked {} missiles {} ticks {}", r.launched, r.kills, r.leaked, r.missiles, r.ticks);
}
}
+15 -1
View File
@@ -15,6 +15,8 @@ pub const BEAM_INNER: f64 = 0.03;
pub const BEAM_OUTER: f64 = 0.075;
/// A target is lit once the axis is this close to it (inside the cone's soft edge).
const LIT_ANGLE: f64 = 0.05;
/// Most lamps on one target.
const MAX_LAMPS: u32 = 2;
/// Ticks between casts of the beam's axis against the land.
const CAST_EVERY: u64 = 4;
/// Guns' hits at night on an unlit target.
@@ -75,6 +77,10 @@ impl Sim {
self.flares = keep;
// What the network tracks, for the searchlights.
let tracked: Vec<u32> = self.sams.iter().flat_map(|s| s.seen.iter().copied()).collect();
// A lamp holds a target only while fewer than two others do; the sky is swept only while
// something flies in it.
let mut held: HashMap<u32, u32> = HashMap::new();
let anything = self.drones.iter().any(|d| d.alive());
let gun_targets: Vec<u32> = self.sams.iter().filter_map(|s| s.gun_target).collect();
for i in 0..self.sams.len() {
if self.sams[i].kind != SamKind::Light || !self.sams[i].alive() || self.sams[i].moving() {
@@ -93,12 +99,20 @@ impl Sim {
let target = self
.drones
.iter()
.filter(|d| d.alive() && tracked.contains(&d.id) && d.pos.distance(pos) < BEAM)
.filter(|d| d.alive() && tracked.contains(&d.id) && d.pos.distance(pos) < BEAM && held.get(&d.id).copied().unwrap_or(0) < MAX_LAMPS)
.min_by(|a, b| {
let key = |d: &Drone| d.pos.distance(pos) * if gun_targets.contains(&d.id) { 0.3 } else { 1.0 };
key(a).total_cmp(&key(b))
})
.map(|d| (d.id, d.pos));
if let Some((t, _)) = target {
*held.entry(t).or_insert(0) += 1;
} else if !anything {
let sam = &mut self.sams[i];
sam.target = None;
sam.beam_on = false;
continue;
}
let sam = &mut self.sams[i];
let (head, _) = sam.mount();
let (want_yaw, want_pitch, reach) = match target {
+131 -13
View File
@@ -26,6 +26,8 @@ mod units;
mod why;
pub mod world;
#[cfg(test)]
mod balance;
#[cfg(test)]
mod regress;
#[cfg(test)]
mod sensor_tests;
@@ -229,6 +231,13 @@ pub struct Ground {
known: HashMap<(i32, i32), (i32, u64)>,
wanted: Vec<(i32, i32)>,
asked: std::collections::HashSet<(i32, i32)>,
/// Columns whose chunk the game is loading (it answered `PENDING`), and the tick it said so: not asked
/// again for a few ticks.
loading: HashMap<(i32, i32), u64>,
/// Chunks the search wants loaded (`render.load-chunks`), taken every tick.
chunks: Vec<(i32, i32)>,
/// The game has answered "loading" at least once: it loads chunks on request (a server doesn't).
pub loads: bool,
/// The tick of the last full clean-up (a big cache would otherwise be scanned on every answer).
swept: u64,
/// The tick of the last answer round: what the heights' ages are measured against.
@@ -237,6 +246,14 @@ pub struct Ground {
pub world: world::WorldCache,
}
/// What `render.ground` answers (`i32::MIN`) for a column whose chunk it is loading for the mod.
pub const PENDING: i32 = i32::MIN;
/// Ticks before a column that was loading is asked about again.
const LOAD_RECHECK: u64 = 6;
/// The chunks asked to load at once (the game holds 64).
const CHUNKS_MAX: usize = 48;
/// Ticks a strike drone may fly before it is lost: a Shahed at 0.6 blocks a tick needs 6700 for 4000 blocks.
const MAX_FLIGHT: u32 = 24_000;
/// The `when` of a height reported changed: due to be asked again.
const STALE: u64 = u64::MAX;
/// Ticks after which a land height used by the flights' look-ahead is asked again (#64), changes told of or not.
@@ -272,8 +289,17 @@ impl Ground {
pub fn answer(&mut self, answers: Vec<(i32, i32, i32)>, now: u64) {
self.now = now;
for (x, z, y) in answers {
if y == PENDING {
self.loading.insert((x, z), now);
self.loads = true;
continue;
}
self.loading.remove(&(x, z));
self.known.insert((x, z), (y, now));
}
if self.loading.len() > 4096 {
self.loading.retain(|_, t| now.saturating_sub(*t) < 400);
}
self.age_heights();
if self.known.len() > 300_000 && now.saturating_sub(self.swept) >= SWEEP_EVERY {
self.swept = now;
@@ -318,6 +344,25 @@ impl Ground {
fn due(&self, when: u64) -> bool {
when == STALE || self.now.saturating_sub(when) > HEIGHT_TTL
}
/// Asks the game to load the chunk (chunk x, z) for a while, if there is room; whether it did.
pub fn want_chunk(&mut self, c: (i32, i32)) -> bool {
if self.chunks.contains(&c) {
return true;
}
if self.chunks.len() >= CHUNKS_MAX {
return false;
}
self.chunks.push(c);
true
}
/// How many chunks are wanted so far this tick.
pub fn chunks_wanted(&self) -> usize {
self.chunks.len()
}
/// The chunks to ask the game to load this tick.
pub fn take_chunks(&mut self) -> Vec<(i32, i32)> {
std::mem::take(&mut self.chunks)
}
pub fn take_wanted(&mut self) -> Vec<(i32, i32)> {
self.asked.clear();
std::mem::take(&mut self.wanted)
@@ -524,6 +569,13 @@ pub struct DroneSpec {
pub ballistic: Option<f64>,
}
impl DroneSpec {
/// Its size, for how thick its smoke is.
pub fn trail_scale(&self) -> f32 {
self.scale as f32
}
}
impl DroneKind {
pub const ALL: [DroneKind; 13] = [
DroneKind::Shahed,
@@ -924,6 +976,11 @@ struct MissileSpec {
}
impl MissileKind {
/// How thick its motor smoke is (its size); `None` for an electric one.
pub fn trail_scale(self) -> Option<f32> {
let s = self.spec();
(s.flame > 0.0).then_some(s.scale as f32)
}
/// The sound of its launch.
pub fn launch_sound(self) -> &'static str {
match self {
@@ -1199,6 +1256,11 @@ pub struct Sam {
pub bursts: u32,
cooldown: u32,
gun_cooldown: u32,
/// Ticks until the system may take another long shot on a big radar's cue (`why::basis`).
far_cooldown: u32,
/// Ticks it has held its present missile target without launching, and a target it gave up (id, until when).
held: u32,
shy: Option<(u32, u64)>,
pub reloading: u32,
/// What its missiles are after, and what its guns track.
pub target: Option<u32>,
@@ -1270,6 +1332,9 @@ impl Sam {
bursts: spec.gun.as_ref().map_or(0, |g| g.bursts),
cooldown: 40,
gun_cooldown: 0,
far_cooldown: 0,
held: 0,
shy: None,
reloading: 0,
target: None,
gun_target: None,
@@ -1432,6 +1497,10 @@ pub struct Sim {
pub shader: bool,
/// Air defence holds fire.
pub hold: bool,
/// Last chance (`/airdef lastchance`): a system fires at a class outside its roles when it is about to hit.
pub last_chance: bool,
/// The heavy systems take long shots on the big radar's cue (a switch for the balance tests).
pub far_shots: bool,
/// What the land hides round each system's radar, by system id.
horizons: HashMap<u32, sight::Horizon>,
/// Blasts to come: (tick, where, TNT, small) — a magazine cooking off.
@@ -1505,6 +1574,8 @@ impl Sim {
truth: false,
shader: false,
hold: false,
last_chance: true,
far_shots: true,
horizons: HashMap::new(),
later: Vec::new(),
queue: Vec::new(),
@@ -1907,7 +1978,7 @@ impl Sim {
}
let at_target = d.pos.distance(d.target) < speed.max(1.5);
let in_ground = sweep.hit().is_some() || ground.ground_hit(below, d.pos, 0.2, &sweep, now);
if at_target || in_ground || d.age > 8000 {
if at_target || in_ground || d.age > MAX_FLIGHT {
boom.push((d.pos, spec.warhead, spec.decoy));
// Into the land or a building short of its aim: a crash, not a hit.
if in_ground && d.pos.distance(d.target) >= speed.max(1.5) + 3.0 {
@@ -1929,7 +2000,7 @@ impl Sim {
let back = d.pos - d.vel.normalize_or_zero() * 1.5 * spec.scale;
match spec.engine {
Engine::Prop(..) => {
if d.age % 2 == 0 {
if d.age % 10 == 0 {
out.particles("minecraft:smoke", back, 0.05, DVec3::ZERO, 0.01, 1);
}
}
@@ -2241,6 +2312,7 @@ impl Sim {
let sam = &mut self.sams[i];
sam.cooldown = sam.cooldown.saturating_sub(1);
sam.gun_cooldown = sam.gun_cooldown.saturating_sub(1);
sam.far_cooldown = sam.far_cooldown.saturating_sub(1);
sam.flash = sam.flash.saturating_sub(1);
sam.recoil *= 0.6;
if sam.radar_up() {
@@ -2288,17 +2360,30 @@ impl Sim {
let drone = |tr: &Track| drone_at.get(&tr.id).map(|&k| &self.drones[k]);
let claimed = |d: &Drone| why::claimed(d, &missile_on, had_target);
let needed = why::needed;
let opts = why::Opts { last_chance: self.last_chance, far_shots: self.far_shots };
let target = spec.missile.as_ref().map(|load| {
let ok = |tr: &Track, k: f64| {
drone(tr).is_some_and(|d| why::allowed(roles, tr, now, d) && open(tr.id) && why::in_reach(load.min, load.max, k, pos, tr.est(now)))
// A launcher with nothing to fire (reloading, empty, failed) claims no target: others take it.
if me.missiles == 0 || me.reloading > 0 || me.part(Part::Launcher) <= 0.0 {
return None;
}
let radars: Vec<&Sam> = if me.kind.far_shooter() && opts.far_shots { self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect() } else { Vec::new() };
let cued = |id: u32| !radars.is_empty() && why::radar_cue(me, &radars, id, now);
let basis = |tr: &Track, k: f64, role_in_reach: bool| {
drone(tr).filter(|_| open(tr.id)).and_then(|d| why::basis(me, load, tr, d, now, claimed(d), k, opts, cued(tr.id), role_in_reach))
};
let keep = had_target.filter(|t| tracks.iter().any(|tr| tr.id == *t && ok(tr, 1.1)));
// A target held too long without a launch (the mount can't lay on it, the land) is let go,
// and not taken again for a while: another system gets it.
let shy = |id: u32| me.shy.is_some_and(|(s, until)| s == id && until > now);
let stuck = me.held > why::HOLD_MAX;
let keep = had_target.filter(|t| !stuck && tracks.iter().any(|tr| tr.id == *t && basis(tr, 1.1, false).is_some()));
keep.or_else(|| {
let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(d));
// Long shots only while nothing of the system's roles is in its normal reach.
let role_in_reach = !radars.is_empty() && tracks.iter().any(|tr| free(tr) && basis(tr, 1.0, true) == Some(why::Basis::Role));
tracks
.iter()
.filter(|tr| ok(tr, 1.0))
.filter(|tr| free(tr) && !shy(tr.id) && basis(tr, 1.0, role_in_reach).is_some())
.filter_map(|tr| drone(tr).map(|d| (tr, d)))
.filter(|(_, d)| claimed(d) < needed(d))
.max_by(|a, b| a.1.threat_at(pos, a.0.est(now)).total_cmp(&b.1.threat_at(pos, b.0.est(now))))
.map(|(_, d)| d.id)
})
@@ -2330,7 +2415,16 @@ impl Sim {
tracks_lost += 1;
}
retarget(&mut missile_on, had_target, target);
self.sams[i].target = target;
let sam = &mut self.sams[i];
if target.is_some() && target == had_target {
sam.held += 1;
} else {
if let (Some(h), true) = (had_target, sam.held > why::HOLD_MAX) {
sam.shy = Some((h, now + why::SHY_TICKS));
}
sam.held = 0;
}
sam.target = target;
}
if let Some(gun_target) = gun_target {
retarget(&mut guns_on, had_gun, gun_target);
@@ -2364,8 +2458,24 @@ impl Sim {
} else {
SamState::Search
};
// Back to the rest position, under the drive's limits like any other turn.
sam.aim_towards(sam.heading, Some(spec.rest_pitch));
// Nothing to fire at: the mount watches the nearest track of its classes (a reaction a turn
// shorter), else it goes back to the rest position, under the drive's limits like any other turn.
let (mount, _) = sam.mount();
let watch = sam
.tracks
.iter()
.filter(|tr| tr.age(now) <= sight::MISSILE_AGE && drone_at.get(&tr.id).is_some_and(|&k| roles & self.drones[k].kind.spec().class.bit() != 0 && self.drones[k].alive()))
.min_by(|a, b| a.est(now).distance(mount).total_cmp(&b.est(now).distance(mount)))
.map(|tr| why::aim_wants(mount, tr.est(now), tr.vel, spec.gun.as_ref().map_or(5.0, |g| g.shell)));
match (watch, spec.family) {
(Some((_, yaw, pitch)), Family::Trainable) => {
let _ = pitch;
sam.aim_towards(yaw, None)
}
(Some((_, yaw, _)), Family::Vertical) if matches!(spec.muzzle, Muzzle::Cells) => sam.aim_towards(yaw, None),
(Some((_, yaw, pitch)), Family::Gun | Family::Turret) => sam.aim_towards(yaw, Some(pitch)),
_ => sam.aim_towards(sam.heading, Some(spec.rest_pitch)),
}
continue;
};
let (mount, _) = sam.mount();
@@ -2496,6 +2606,10 @@ impl Sim {
retarget(&mut missile_on, Some(mt), None);
sam.target = None;
} else if ready && aligned {
// Past its normal reach: a long shot, and the next waits.
if sam.kind.far_shooter() && t.is_some_and(|t| t.distance(sam.pos) >= load.max) {
sam.far_cooldown = why::FAR_COOLDOWN;
}
launches.push((load.kind, muzzle, dir, mt, sam.id));
// Its missile is on it from now, so the systems after this one this tick see
// the target taken; this one's next launch looks for another.
@@ -2546,8 +2660,10 @@ impl Sim {
out.sound(event, muzzle, 1.0, 1.0);
} else {
out.particles("minecraft:flash", muzzle, 0.0, DVec3::ZERO, 0.0, 1);
out.particles("minecraft:cloud", muzzle - dir * 2.0, 1.4, DVec3::new(0.0, 0.02, 0.0), 0.06, 70);
out.particles("minecraft:campfire_cosy_smoke", muzzle - dir * 3.0, 1.2, DVec3::ZERO, 0.02, 20);
if spec.flame > 0.0 {
out.particles("minecraft:cloud", muzzle - dir * 2.0, 1.4, DVec3::new(0.0, 0.02, 0.0), 0.06, 70);
out.particles("minecraft:campfire_cosy_smoke", muzzle - dir * 3.0, 1.2, DVec3::ZERO, 0.02, 20);
}
let event = if kind == MissileKind::M57e6 { "airdef:launch.pantsir" } else { "airdef:launch.patriot" };
out.sound(event, muzzle, 1.0, 0.95 + self.vis.f() as f32 * 0.1);
}
@@ -2573,6 +2689,8 @@ impl Sim {
let (mut missed, mut expired, mut orphaned) = (0u32, 0u32, 0u32);
let (mut blocked, mut scrubbed) = (0u32, 0u32);
let sams_fit: HashMap<u32, f64> = self.sams.iter().map(|s| (s.id, 1.0 - 0.3 * (1.0 - s.health.clamp(0.0, 1.0)))).collect();
// Where each launcher stands and how far its missiles reach: a hit past that is less likely (`why::reach_fit`).
let launchers: HashMap<u32, (DVec3, f64)> = self.sams.iter().filter_map(|s| Some((s.id, (s.pos, s.kind.spec().missile.as_ref()?.max)))).collect();
// The data link (#66): the track the firing system holds of each missile's target, if it is up.
let links: HashMap<(u32, u32), Track> = self
.missiles
@@ -2680,7 +2798,7 @@ impl Sim {
if (rel0 + delta * k).length() < spec.fuse && world.map(|w| w.0).or(waiting).is_none_or(|w| k <= w) {
// A target faster than the interceptor is hard to hit.
let ratio = (spec.speed / t.vel.length().max(0.1)).min(1.0).powf(1.5);
let fit = sams_fit.get(&m.sam).copied().unwrap_or(1.0);
let fit = sams_fit.get(&m.sam).copied().unwrap_or(1.0) * launchers.get(&m.sam).map_or(1.0, |(at, max)| why::reach_fit(*max, at.distance(m.pos)));
let kill = self.rng.chance(spec.pk * fit * ratio / t.kind.spec().stealth.sqrt());
missed += u32::from(!kill);
done.push((m.id, Some(t.id), kill, m.sam));
+138 -50
View File
@@ -87,6 +87,8 @@ pub(super) struct Plan {
wants: Vec<sites::Want>,
sited: bool,
site_wait: u32,
/// The player has been told the enemy is still preparing.
said: bool,
smart: bool,
approach: Approach,
total: u32,
@@ -115,6 +117,9 @@ pub(super) struct WaveStats {
pub(super) const CELL: f64 = 16.0;
pub(super) const CELLS: i32 = 140;
/// The planner's work a tick (cells priced and opened): a raid takes a few ticks to plan, never a long one.
/// The longest a drone of a raid that arrives together waits to take off (ticks): a Shahed at 0.6 blocks a tick
/// takes 6700 of them to fly 4000 blocks, and the fastest missile must wait for it.
const LONGEST_WAIT: f64 = 12_000.0;
pub(super) const WORK_PER_TICK: usize = 40_000;
/// The planner's grid over a raid: its corner, its cells' size and how many a side.
@@ -258,6 +263,9 @@ impl Sim {
let cell = CELL.max(2.0 * span / CELLS as f64);
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) } else { Vec::new() };
let mut index = 0usize;
for (group, &(kind, count)) in order.kinds.iter().enumerate() {
let spec = kind.spec();
for _ in 0..count {
@@ -268,7 +276,12 @@ impl Sim {
};
let a = sides[side];
let object = objects[(self.rng.f() * objects.len() as f64) as usize % objects.len()];
let (target, at_sam) = self.choose_target(kind, object, order.aim);
let job = radar_jobs.get(index).copied().flatten();
index += 1;
let (target, at_sam) = match job {
Some((at, id)) => (at, Some(id)),
None => self.choose_target(kind, object, order.aim),
};
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;
let height = if spec.ballistic.is_some() { 10.0 } else if spec.cruise > 0.0 { spec.cruise } else { 25.0 };
@@ -298,6 +311,7 @@ impl Sim {
wants,
sited: false,
site_wait: 0,
said: false,
smart,
approach: order.approach,
total,
@@ -356,7 +370,8 @@ impl Sim {
}
});
plan.waited += 1;
if plan.unanswered.is_empty() || plan.waited >= 40 {
// The game answers 512 columns a tick: a big grid (a long range) gets the time its cells take.
if plan.unanswered.is_empty() || plan.waited >= 40 + (n * n) as u32 / 300 {
plan.mapped = true;
} else {
self.plan = Some(plan);
@@ -437,7 +452,7 @@ impl Sim {
if site != 0 {
self.sites.job(d.id, site);
}
self.queue.push((now + wait.clamp(0.0, 2400.0) as u64, d));
self.queue.push((now + wait.clamp(0.0, LONGEST_WAIT) as u64, d));
}
self.wave = Some(WaveStats {
kills: self.kills,
@@ -497,6 +512,31 @@ impl Sim {
}
}
/// The strikes a smart raid sends at the radars (they emit, so the enemy knows them whether or not they
/// fired): for the drones of `kinds` in order, the radar's 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)]) -> Vec<Option<(DVec3, u32)>> {
let mut radars: Vec<&Sam> = self.sams.iter().filter(|s| s.alive() && s.kind == SamKind::Radar).collect();
radars.sort_by_key(|s| s.id);
let flat: Vec<DroneKind> = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect();
let mut jobs = vec![None; flat.len()];
if radars.is_empty() {
return jobs;
}
// Fast ones first (a stable sort keeps the raid's order among equals).
const RANK: [DroneKind; 8] =
[DroneKind::Kh22, DroneKind::Zircon, DroneKind::Iskander, DroneKind::Kinzhal, DroneKind::Kh101, DroneKind::Geran3, DroneKind::Lancet, DroneKind::Shahed];
let mut ranked: Vec<(usize, usize)> = flat.iter().enumerate().filter_map(|(i, k)| Some((RANK.iter().position(|r| r == k)?, i))).collect();
ranked.sort_by_key(|r| r.0);
let want = if flat.len() >= 24 { 3 } else { 2 };
let cap = (flat.len() / 4).max(1);
for (n, &(_, i)) in ranked.iter().take((radars.len() * want).min(cap)).enumerate() {
let radar = radars[n % radars.len()];
jobs[i] = Some((radar.pos, radar.id));
}
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) -> (DVec3, Option<u32>) {
@@ -525,9 +565,9 @@ impl Sim {
}
// 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() <= 200.0).collect();
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() >= 300.0 || s.kind == SamKind::Radar).collect();
alive.iter().copied().filter(|s| s.kind.range() >= 450.0 || s.kind == SamKind::Radar).collect();
let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick(&guns, r).or_else(|| pick(&alive, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick(&long, r),
@@ -621,7 +661,8 @@ impl Sim {
for (t, d) in go {
// A site's job leaves its site one at a time, from its stock; a destroyed or empty site cancels it.
match self.site_slot(d.id) {
sites::Slot::Free => {}
// Free: not a site's job. Air: an off-map site's drone, already in flight position.
sites::Slot::Free | sites::Slot::Air => {}
sites::Slot::Busy => {
self.queue.push((t, d));
continue;
@@ -645,9 +686,8 @@ impl Sim {
}
}
/// Looks for the raid's launch sites. Returns whether they are settled (placed, or given up: drones whose
/// side has no suitable ground go to another side's site, or are cancelled with a message; a raid left with
/// nothing is cancelled whole).
/// Looks for the raid's launch sites. Returns whether they are settled (placed, or off the map: a side with
/// no suitable ground still launches, from the air at the ordered range; nothing is cancelled).
fn settle_sites(&mut self, plan: &mut Plan, ground: &mut Ground, out: &mut Out) -> bool {
plan.site_wait += 1;
let mut keep: Vec<DVec3> = self.sams.iter().filter(|s| s.alive()).map(|s| s.pos).collect();
@@ -655,43 +695,15 @@ impl Sim {
keep.push(plan.centre);
let last = plan.site_wait >= sites::SEARCH_TICKS;
if !sites::search(&mut plan.wants, ground, plan.centre, &keep, self.tick, last) {
// The game loads the land of the places looked at; the player hears the enemy is preparing.
if !plan.said && plan.site_wait >= 40 {
plan.said = true;
out.messages.push("Противник готовит налёт: ищет площадки, местность подгружается".into());
}
return false;
}
use sites::Search;
// A side that found nothing hands its drones to a site of the same class and range on another side.
let mut moved = 0;
let mut dropped = 0;
let found: Vec<usize> = (0..plan.wants.len()).filter(|&i| plan.wants[i].state == Search::Found).collect();
let mut keep_items = Vec::new();
for mut it in std::mem::take(&mut plan.items) {
let w = &plan.wants[it.want];
if w.state != Search::Found {
let (class, range) = (w.class, w.ordered);
let near = |x: &sites::Want| x.class == class && (x.ordered - range).abs() < range * 0.35 + 30.0;
match found.iter().copied().find(|&i| near(&plan.wants[i])) {
Some(i) => {
it.want = i;
moved += 1;
}
None => {
dropped += 1;
continue;
}
}
}
keep_items.push(it);
}
plan.items = keep_items;
if moved + dropped > 0 {
out.messages.push(format!(
"Нет пригодной земли для части площадок: {moved} целей ушли с другой стороны, {dropped} отменено"
));
}
plan.total -= dropped;
if plan.items.is_empty() {
out.messages.push("Налёт отменён: нет пригодной известной земли для пусковых площадок".into());
return false;
}
// A side that found nothing is not given up (no raid is cancelled for it): its site is off the map.
// The pads, and the sites themselves; the old raid's sites go unless they still have jobs to fly.
let queued: Vec<u32> = self.queue.iter().map(|q| q.1.id).collect();
self.sites.retire(&queued);
@@ -703,12 +715,18 @@ impl Sim {
plan.wants[it.want].jobs += 1;
}
let mut shortened = false;
for w in plan.wants.iter_mut().filter(|w| w.state == Search::Found && w.jobs > 0) {
let mut pos = w.found.unwrap_or_default();
for w in plan.wants.iter_mut().filter(|w| w.jobs > 0) {
let offmap = w.state != Search::Found;
let mut pos = if offmap {
// At the ordered range over the raid's centre height: nothing stands there.
plan.centre + DVec3::new(w.bearing.sin(), 0.0, w.bearing.cos()) * w.ordered
} else {
w.found.unwrap_or_default()
};
if w.water {
pos.y += sites::DECK;
}
shortened |= w.range < w.ordered - if w.class == sites::SiteClass::Battery { 1.0 } else { 75.0 };
shortened |= !offmap && w.range < w.ordered - if w.class == sites::SiteClass::Battery { 1.0 } else { 75.0 };
w.site = self.sites.add(sites::LaunchSite {
id: 0,
side: w.side as u8,
@@ -716,12 +734,13 @@ impl Sim {
bearing: w.bearing,
class: w.class,
pos,
range: w.range,
range: if offmap { w.ordered } else { w.range },
water: w.water,
stock: w.jobs,
planned: w.jobs,
alive: true,
next_free: 0,
offmap,
});
}
if shortened {
@@ -731,6 +750,11 @@ impl Sim {
for it in plan.items.iter_mut() {
let w = &plan.wants[it.want];
let Some(site) = self.sites.get(w.site) else { continue };
// Off the map: it starts where the plan put it, cruising.
if site.offmap {
it.d.sector = site.sector;
continue;
}
let from = site.muzzle(it.pad);
let spec = it.d.kind.spec();
it.from = from;
@@ -746,9 +770,16 @@ impl Sim {
}
it.d.sector = site.sector;
}
let n = self.sites.list.iter().filter(|s| plan.wants.iter().any(|w| w.site == s.id)).count();
let barges = self.sites.list.iter().filter(|s| s.water && plan.wants.iter().any(|w| w.site == s.id)).count();
out.messages.push(format!("Пусковые площадки противника: {n}{}", if barges > 0 { format!(" (на баржах: {barges})") } else { String::new() }));
let mine = |s: &&sites::LaunchSite| plan.wants.iter().any(|w| w.site == s.id);
let n = self.sites.list.iter().filter(mine).filter(|s| !s.offmap).count();
let off = self.sites.list.iter().filter(mine).filter(|s| s.offmap).count();
let barges = self.sites.list.iter().filter(mine).filter(|s| s.water).count();
if n > 0 {
out.messages.push(format!("Пусковые площадки противника: {n}{}", if barges > 0 { format!(" (на баржах: {barges})") } else { String::new() }));
}
if off > 0 {
out.messages.push(format!("Площадок за пределами загруженной карты: {off}: оттуда пуск без площадки, с высоты полёта"));
}
// Where they are is the enemy's secret, unless the sandbox's true picture is on.
if self.truth {
for site in self.sites.list.iter().filter(|s| plan.wants.iter().any(|w| w.site == s.id)) {
@@ -848,6 +879,63 @@ mod tests {
eprintln!("4000 ticks in {:?}, kills {} hits {}", t.elapsed(), sim.kills, sim.hits);
assert!(sim.queue.is_empty() && !sim.drones.iter().any(|d| d.alive()), "the raid never ended");
}
/// How many of the live and queued drones are aimed at each point (the drone's own aim: its target less its navigation error).
fn aimed_at(sim: &Sim, p: DVec3) -> Vec<DroneKind> {
sim.drones.iter().chain(sim.queue.iter().map(|q| &q.1)).filter(|d| d.alive() && (d.target - d.err).distance(p) < 6.0).map(|d| d.kind).collect()
}
#[test]
fn a_smart_raid_goes_for_every_radar_and_the_enemys_adapting_does_not_turn_it_away() {
let mut sim = Sim::new(21);
let mut radars = Vec::new();
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));
radars.push((id, p));
}
let ew = sim.id();
sim.sams.push(Sam::new(ew, SamKind::Ew, DVec3::new(0.0, 70.0, 0.0), 0.0));
sim.targets.push(DVec3::new(0.0, 70.0, 0.0));
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 mut order = crate::wave::WaveConfig::mix(36, 500.0);
order.aim = Aim::Smart;
order.approach = Approach::AllSides;
let total: u32 = order.kinds.iter().map(|k| k.1).sum();
sim.order_raid(&order, &sim.targets.clone(), &mut out);
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
let check = |sim: &Sim, when: &str| {
let mut all = 0;
for (i, (_, p)) in radars.iter().enumerate() {
let kinds = aimed_at(sim, *p);
all += kinds.len();
assert!(kinds.len() >= 2, "{when}: radar {i} has only {kinds:?} aimed at it");
}
all
};
let planned = check(&sim, "planned");
assert!(planned as u32 <= total / 4 + 6, "{planned} of {total} at the radars (the EW station and the rest may add a few)");
// 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));
for _ in 0..160 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
check(&sim, "after adapting");
}
#[test]
fn systems_ready_together_send_one_missile_at_a_drone() {
let mut sim = Sim::new(3);
+2
View File
@@ -234,6 +234,8 @@ fn armed_strike_on_a_system_destroys_it_at_once() {
let mut destroyed = 0;
for seed in 1..=40 {
let mut sim = Sim::new(seed);
// The strike itself is under test: the Patriot does not shoot the Lancet down on a last chance.
sim.last_chance = false;
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Patriot, centre, 0.0));
let mut ground = Ground::default();
+1 -1
View File
@@ -20,7 +20,7 @@ use super::*;
const RAYS: usize = 48;
const STEP: f64 = 16.0;
/// How far units share their tracks (the network's data links).
pub(super) const LINK: f64 = 1500.0;
pub(super) const LINK: f64 = 2250.0;
/// A launcher fires on a track no older than this (ticks); a gun needs its own radar's, newer than `GUN_AGE`.
pub(super) const MISSILE_AGE: u64 = 120;
pub(super) const GUN_AGE: u64 = 3;
+217 -23
View File
@@ -2,16 +2,23 @@
//! looks for suitable ground on each side (only land the game has told of: flat, open to the sky, clear in
//! front, away from the defence), and sets up a site there: a ramp for the drones, a launcher vehicle for the
//! cruise missiles, a battery for the ballistic ones (at their own range). The raid's drones are jobs of the
//! sites: each one leaves its site, one at a time, from the stock the site holds. Ground nobody has told of is
//! never suitable, and nothing is force-loaded: a side without suitable ground waits for the game's answers
//! for a few seconds, and is then given up with a message.
//! sites: each one leaves its site, one at a time, from the stock the site holds.
//!
//! The land beyond the render distance is not there until the game loads it, so the search asks for the chunks
//! of the places it is looking at (`render.load-chunks`, API 22: a few, never a ring; the game generates or reads
//! them on its workers and keeps them some seconds) and waits for them: a column the game is loading is neither
//! land nor sea, it is pending. Where nothing can be loaded (a server) or nothing suitable is found within
//! `SEARCH_TICKS`, the raid is never cancelled for it: the side's site is *off the map* (`offmap`): no kit is drawn,
//! nothing can be destroyed, and its drones start in the air at the ordered range, cruising over whatever is there.
use super::*;
/// The most candidate places tried for one site, and how long (ticks) a raid waits for the game's answers.
pub const MAX_TRIES: usize = 90;
pub const SEARCH_TICKS: u32 = 300;
pub const SEARCH_TICKS: u32 = 400;
/// Candidates asked about ahead of the one being waited for.
const PREFETCH: usize = 3;
/// Prefetched candidates ask for their chunks only while fewer than this many are wanted.
const PREFETCH_CHUNKS: usize = 24;
/// The footprint's samples (offsets in blocks), the most the ground may differ over it, and how far from
/// the defence and the objects a site must be.
const FOOTPRINT: [(f64, f64); 9] = [(0.0, 0.0), (8.0, 0.0), (-8.0, 0.0), (0.0, 8.0), (0.0, -8.0), (6.0, 6.0), (6.0, -6.0), (-6.0, 6.0), (-6.0, -6.0)];
@@ -123,6 +130,9 @@ pub struct LaunchSite {
pub planned: u32,
pub alive: bool,
pub next_free: u64,
/// Off the map: no land to stand on was found (or none can be loaded), so there is no kit; the drones
/// start in the air at `pos`'s range.
pub offmap: bool,
}
impl LaunchSite {
@@ -161,6 +171,8 @@ pub(super) enum Slot {
/// Not a site's job (a manual launch, an old save): off it goes.
Free,
Go,
/// An off-map site's drone: it starts in the air, without a launch.
Air,
/// The site launched a moment ago.
Busy,
/// The site is gone or empty: the job is cancelled.
@@ -215,8 +227,9 @@ impl Sites {
}
s.stock -= 1;
s.next_free = now + s.class.cadence();
let air = s.offmap;
self.jobs.swap_remove(j);
Slot::Go
if air { Slot::Air } else { Slot::Go }
}
}
@@ -260,6 +273,13 @@ pub(super) struct Want {
pub site: u32,
}
impl Want {
/// Whether the search has nothing to show for it: the site is off the map.
pub fn offmap(&self) -> bool {
self.state == Search::Failed
}
}
/// The want of this side, class and range, made if there is none yet.
pub(super) fn want_index(wants: &mut Vec<Want>, centre: DVec3, side: usize, bearing: f64, class: SiteClass, range: f64, lo: f64) -> usize {
if let Some(i) = wants.iter().position(|w| w.side == side && w.class == class && (w.range - range).abs() < 1.0) {
@@ -269,16 +289,19 @@ pub(super) fn want_index(wants: &mut Vec<Want>, centre: DVec3, side: usize, bear
let lat = DVec3::new(bearing.cos(), 0.0, -bearing.sin());
// In order: known land at the ordered range (round it for most, the ordered range for a ballistic battery),
// known land nearer in steps, then a barge on open water at the ordered range, then on water nearer.
// A long range retreats in steps of at most 100 blocks and tries wider rings, not a few huge gaps.
let near = |from: f64| -> Vec<f64> {
let min = if class == SiteClass::Battery { lo.min(from).max(80.0) } else { (from * 0.3).max(80.0) };
let min = if class == SiteClass::Battery { lo.min(from).max(80.0) } else { (from * 0.3).max(80.0).max(from - 600.0) };
(1..=6).map(|i| from - (from - min) * f64::from(i) / 6.0).collect()
};
let wide = (range / 500.0).clamp(1.0, 3.0);
let round: Vec<f64> = if class == SiteClass::Battery {
vec![range]
} else {
[0.0, 24.0, -24.0, 48.0, -48.0, 72.0, -72.0].iter().map(|d| (range + d).max(KEEP_OUT)).collect()
[0.0, 24.0, -24.0, 48.0, -48.0, 72.0, -72.0].iter().map(|d| (range + d * wide).max(KEEP_OUT)).collect()
};
let laterals: &[f64] = &[0.0, 20.0, -20.0];
// A battery may stand where another site of the side does (its range is its own): wider to the sides.
let laterals: &[f64] = if class == SiteClass::Battery { &[0.0, 20.0, -20.0, 60.0, -60.0] } else { &[0.0, 20.0, -20.0] };
let mut cands = Vec::new();
for water in [false, true] {
for r in round.iter().copied().chain(near(range)) {
@@ -300,9 +323,25 @@ enum Verdict {
Good(DVec3, bool),
}
/// The chunks a site at `p` needs: its footprint and the way ahead, up to 14 blocks.
fn chunks_of(p: DVec3, inward: DVec3) -> Vec<(i32, i32)> {
let mut out: Vec<(i32, i32)> = Vec::with_capacity(6);
for (dx, dz) in FOOTPRINT {
for k in [0.0, 14.0] {
let c = (((p.x + dx + inward.x * k).floor() as i32) >> 4, ((p.z + dz + inward.z * k).floor() as i32) >> 4);
if !out.contains(&c) {
out.push(c);
}
}
}
out
}
/// Whether a site fits at `p` (x, z): every sample of its footprint is land the game told of and within
/// `FLAT` blocks of the others, the sky above is open, the way ahead is clear, and nothing of the defence is near.
fn judge(ground: &mut Ground, p: DVec3, inward: DVec3, keep: &[DVec3], now: u64) -> Verdict {
/// A column or chunk the game is still loading makes it `Pending`, and the chunks are asked for (unless this is
/// a look ahead at a later candidate, `ahead`, and many are wanted already).
fn judge(ground: &mut Ground, p: DVec3, inward: DVec3, keep: &[DVec3], now: u64, ahead: bool) -> Verdict {
if p.x.abs() > 29_000_000.0 || p.z.abs() > 29_000_000.0 || keep.iter().any(|k| horizontal(*k - p).length() < KEEP_OUT) {
return Verdict::Bad;
}
@@ -318,6 +357,22 @@ fn judge(ground: &mut Ground, p: DVec3, inward: DVec3, keep: &[DVec3], now: u64)
}
}
}
// The way ahead must be loaded too before it is swept (an unknown stretch is answered "no chunk" and kept
// for a while): a column in the middle of each chunk it needs says so.
let chunks = chunks_of(p, inward);
if !pending {
for &(cx, cz) in &chunks {
pending |= ground.column(cx * 16 + 8, cz * 16 + 8, 256).is_none();
}
}
if pending {
if !ahead || ground.chunks_wanted() < PREFETCH_CHUNKS {
for c in chunks {
ground.want_chunk(c);
}
}
return Verdict::Pending;
}
if pending {
return Verdict::Pending;
}
@@ -334,7 +389,9 @@ fn judge(ground: &mut Ground, p: DVec3, inward: DVec3, keep: &[DVec3], now: u64)
match ground.world.sweep(c + DVec3::Y * 0.5, c - DVec3::Y * 0.5, false, now) {
world::Sweep::Hit { .. } => solid += 1,
world::Sweep::Clear => {}
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => return Verdict::Pending,
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => {
return Verdict::Pending;
}
world::Sweep::Unknown { .. } => return Verdict::Bad,
}
}
@@ -346,7 +403,9 @@ fn judge(ground: &mut Ground, p: DVec3, inward: DVec3, keep: &[DVec3], now: u64)
for s in [up, ahead] {
match s {
world::Sweep::Clear => {}
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => return Verdict::Pending,
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => {
return Verdict::Pending;
}
world::Sweep::Unknown { .. } | world::Sweep::Hit { .. } => return Verdict::Bad,
}
}
@@ -373,7 +432,7 @@ pub(super) fn search(wants: &mut [Want], ground: &mut Ground, centre: DVec3, kee
break;
}
let (cand, water) = w.cands[w.cursor];
match judge(ground, cand, inward, &keep, now) {
match judge(ground, cand, inward, &keep, now, false) {
Verdict::Bad => w.cursor += 1,
// Land when land was asked for, a barge when water was.
Verdict::Good(_, got) if got != water => w.cursor += 1,
@@ -387,7 +446,7 @@ pub(super) fn search(wants: &mut [Want], ground: &mut Ground, centre: DVec3, kee
Verdict::Pending => {
for k in 1..=PREFETCH {
if let Some(&(c, _)) = w.cands.get(w.cursor + k) {
let _ = judge(ground, c, inward, &keep, now);
let _ = judge(ground, c, inward, &keep, now, true);
}
}
if last {
@@ -414,7 +473,8 @@ impl Sim {
/// Takes site `id` out of play (destroyed): its stock is gone and its queued jobs are cancelled. Returns how
/// many. (The counter-strike, #101, uses this.)
pub fn destroy_site(&mut self, id: u32) -> u32 {
let Some(s) = self.sites.list.iter_mut().find(|s| s.id == id) else { return 0 };
// An off-map site is nowhere to be found: nothing to destroy.
let Some(s) = self.sites.list.iter_mut().find(|s| s.id == id && !s.offmap) else { return 0 };
s.alive = false;
s.stock = 0;
let ids: Vec<u32> = self.sites.jobs.iter().filter(|j| j.1 == id).map(|j| j.0).collect();
@@ -431,7 +491,7 @@ impl Sim {
/// Draws every site's kit: a ramp or launcher per pad in use, turned to the way the launches go.
pub(super) fn draw_sites(&self, out: &mut Out) {
for s in self.sites.list.iter().filter(|s| s.alive) {
for s in self.sites.list.iter().filter(|s| s.alive && !s.offmap) {
let rot = DQuat::from_rotation_y(heading_of(s.inward()));
let sc = s.class.scale();
if s.water {
@@ -651,6 +711,7 @@ mod tests {
planned: 5,
alive: true,
next_free: 0,
offmap: false,
});
for i in 0..5 {
let site = sim.sites.get(id).unwrap().clone();
@@ -689,9 +750,16 @@ mod tests {
assert_eq!(sim.launched as usize + n, 14);
}
/// Runs the sim `ticks` without the game answering anything, and counts what left.
fn run_blind(sim: &mut Sim, out: &mut Out, ground: &mut Ground, ticks: u32) {
for _ in 0..ticks {
sim.step(ground, None, out);
}
}
#[test]
fn no_suitable_ground_means_a_clear_refusal() {
// Never answered: unknown ground is not suitable, and nothing is launched.
fn no_suitable_ground_means_the_raid_launches_off_the_map() {
// Never answered: unknown ground is not suitable, but nothing is cancelled: every side starts off the map.
let (mut ground, mut out) = (Ground::default(), Out::default());
let mut sim = Sim::new(3);
sim.order_raid(&order(Approach::TwoSectors, 300.0), &[DVec3::new(0.0, 70.0, 0.0)], &mut out);
@@ -701,20 +769,146 @@ mod tests {
n += 1;
assert!(n <= SEARCH_TICKS + 5, "a raid waits for ever");
}
assert!(sim.queue.is_empty() && sim.sites.list.is_empty());
assert!(out.messages.iter().any(|m| m.contains("площад")), "{:?}", out.messages);
assert!(!sim.drones.iter().any(|d| d.alive()));
// A cliff face everywhere (too steep to stand on) is refused as well, and a sea (no land) too.
assert_eq!(sim.queue.len() + sim.launched as usize, 14);
assert!(!sim.sites.list.is_empty() && sim.sites.list.iter().all(|s| s.offmap), "{:?}", sim.sites.list);
let said: Vec<_> = out.messages.iter().filter(|m| m.contains("за пределами")).collect();
assert_eq!(said.len(), 1, "{:?}", out.messages);
assert!(!out.messages.iter().any(|m| m.contains("отмен")), "{:?}", out.messages);
run_blind(&mut sim, &mut out, &mut ground, 400);
assert_eq!(sim.launched, 14, "{:?}", out.messages);
assert!(sim.queue.is_empty());
// No kit, and nothing to destroy.
let mut o2 = Out::default();
sim.draw_sites(&mut o2);
assert!(o2.models.is_empty());
let id = sim.sites.list[0].id;
assert_eq!(sim.destroy_site(id), 0);
// A cliff face everywhere (too steep to stand on) and a sea (no land) launch off the map as well.
for steep in [true, false] {
let land = Land(move |x, _| if steep { x * 4 } else { -100 });
let (mut ground, mut out) = (Ground::default(), Out::default());
let mut sim = Sim::new(3);
plan(&mut sim, &mut ground, &land, &order(Approach::Sector, 300.0), &mut out);
assert!(sim.queue.is_empty() && sim.sites.list.is_empty(), "steep {steep}");
assert!(out.messages.iter().any(|m| m.contains("площад")));
assert!(!sim.sites.list.is_empty() && sim.sites.list.iter().all(|s| s.offmap), "steep {steep}");
assert_eq!(sim.queue.len() + sim.launched as usize, 14, "steep {steep}");
assert!(!out.messages.iter().any(|m| m.contains("отмен")), "{:?}", out.messages);
}
}
/// Chunks that load on request: a column of a chunk asked for answers `PENDING` until `delay` ticks
/// after the first request, and a chunk never asked for is not there (-64).
struct Lazy {
height: i32,
delay: u64,
asked: std::cell::RefCell<HashMap<(i32, i32), u64>>,
most: usize,
}
impl Lazy {
fn loaded(&self, c: (i32, i32), now: u64) -> Option<bool> {
self.asked.borrow().get(&c).map(|&t| now >= t + self.delay)
}
fn tick(&mut self, ground: &mut Ground, now: u64) {
let chunks = ground.take_chunks();
self.most = self.most.max(chunks.len());
for c in chunks {
self.asked.borrow_mut().entry(c).or_insert(now);
}
let cols = ground
.take_wanted()
.into_iter()
.map(|(x, z)| {
let y = match self.loaded((x >> 4, z >> 4), now) {
Some(true) => self.height,
Some(false) => PENDING,
None => -64,
};
(x, z, y)
})
.collect();
ground.answer(cols, now);
let secs = ground.world.take_wanted(now);
let view = Seen { lazy: self, now };
ground.world.serve(&view, secs, now);
}
}
struct Seen<'a> {
lazy: &'a Lazy,
now: u64,
}
impl world::WorldSource for Seen<'_> {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
self.lazy.loaded((x >> 4, z >> 4), self.now).filter(|&l| l).map(|_| y < self.lazy.height)
}
}
#[test]
fn a_column_pending_for_chunk_load_waits_then_finds_a_site() {
let (mut ground, mut out) = (Ground::default(), Out::default());
let mut lazy = Lazy { height: 64, delay: 50, asked: Default::default(), most: 0 };
let mut sim = Sim::new(21);
sim.order_raid(&order(Approach::TwoSectors, 1500.0), &[DVec3::new(0.0, 70.0, 0.0)], &mut out);
let mut n = 0;
while sim.planning() {
lazy.tick(&mut ground, sim.tick);
sim.step(&mut ground, None, &mut out);
n += 1;
assert!(n < SEARCH_TICKS + 5, "never settled");
}
assert!(n > 50, "settled in {n} ticks, before any chunk could be there");
assert!(sim.sites.list.iter().all(|s| !s.offmap), "{:?} {:?}", sim.sites.list, out.messages);
assert!(!sim.sites.list.is_empty());
assert!(lazy.most <= 48 && lazy.most > 0, "{} chunks wanted at once", lazy.most);
assert!(out.messages.iter().any(|m| m.contains("готовит")), "{:?}", out.messages);
assert!(!out.messages.iter().any(|m| m.contains("отмен") || m.contains("за пределами")), "{:?}", out.messages);
// Far ones stand where the raid was ordered (1500 out), not nearer.
assert!(sim.sites.list.iter().any(|s| s.range > 1400.0), "{:?}", sim.sites.list.iter().map(|s| s.range).collect::<Vec<_>>());
}
#[test]
fn a_game_that_never_loads_gets_the_same_launch_off_the_map() {
// The game answers "no chunk" (-64) for what was not asked about, and never loads what was (a server).
let (mut ground, mut out) = (Ground::default(), Out::default());
let mut sim = Sim::new(5);
sim.order_raid(&order(Approach::Sector, 2500.0), &[DVec3::new(0.0, 70.0, 0.0)], &mut out);
let mut n = 0;
while sim.planning() {
let _ = ground.take_chunks();
let cols = ground.take_wanted().into_iter().map(|(x, z)| (x, z, -64)).collect();
ground.answer(cols, sim.tick);
sim.step(&mut ground, None, &mut out);
n += 1;
assert!(n < SEARCH_TICKS + 5);
}
assert!(sim.sites.list.iter().all(|s| s.offmap));
assert_eq!(sim.queue.len() + sim.launched as usize, 14);
// Where they start: at the ordered range, not at the player.
assert!(sim.queue.iter().all(|q| horizontal(q.1.pos - DVec3::new(0.0, 70.0, 0.0)).length() > 2400.0));
}
#[test]
fn a_raid_ordered_4000_out_reaches_its_target() {
let (land, mut ground, mut out) = (flat(), Ground::default(), Out::default());
let mut sim = Sim::new(9);
let o = RaidOrder { kinds: vec![(DroneKind::Shahed, 2), (DroneKind::Kh101, 1), (DroneKind::Iskander, 1)], approach: Approach::Sector, dist: 4000.0, aim: Aim::Objects };
let target = DVec3::new(0.0, 70.0, 0.0);
sim.order_raid(&o, &[target], &mut out);
let mut closest = [f64::MAX; 4];
for _ in 0..16_000 {
step(&mut sim, &mut ground, &land, &mut out);
for d in sim.drones.iter().filter(|d| d.alive()) {
let k = match d.kind {
DroneKind::Shahed => 0,
DroneKind::Kh101 => 1,
_ => 2,
};
closest[k] = closest[k].min(horizontal(d.pos - target).length());
}
}
assert_eq!(sim.launched, 4, "{:?}", out.messages);
assert!(closest.iter().take(3).all(|&c| c < 120.0), "closest approaches {closest:?}");
assert!(sim.drones.iter().all(|d| !d.alive()), "still flying");
}
/// Land inside a radius of the origin (surface 64), open water outside it (surface 63 over a floor at 50):
/// the game's height over water is the surface, and the blocks under it are not solid.
struct Island(f64);
+3 -1
View File
@@ -79,7 +79,9 @@ impl Ground {
Some((y > -64).then_some(f64::from(y)))
}
None => {
if self.wanted.len() < cap && self.asked.insert((x, z)) {
// A chunk the game is loading is asked about again in a few ticks, not every one.
let loading = self.loading.get(&(x, z)).is_some_and(|&t| self.now.saturating_sub(t) < LOAD_RECHECK);
if !loading && self.wanted.len() < cap && self.asked.insert((x, z)) {
self.wanted.push((x, z));
}
None
+21 -21
View File
@@ -192,7 +192,7 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "Patriot",
key: "patriot",
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 300.0, interval: 16 }),
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 450.0, interval: 16 }),
gun: None,
reload: 220,
scale: 1.3,
@@ -208,7 +208,7 @@ impl SamKind {
mount: (0.69, 1.2),
pivot: DVec3::new(0.0, -0.5, 1.375),
muzzle: Muzzle::Patriot,
sensor: 390.0,
sensor: 585.0,
mast: 5.0,
};
&S
@@ -218,7 +218,7 @@ impl SamKind {
name: "Гепард",
key: "gepard",
missile: None,
gun: Some(GunSpec { range: 90.0, track: 130.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
gun: Some(GunSpec { range: 135.0, track: 195.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
reload: 160,
scale: 1.25,
rest_pitch: 0.0,
@@ -234,7 +234,7 @@ impl SamKind {
mount: (1.55, 0.25),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 170.0,
sensor: 255.0,
mast: 3.0,
};
&S
@@ -243,8 +243,8 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "Панцирь-С1",
key: "pantsir",
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 150.0, interval: 14 }),
gun: Some(GunSpec { range: 60.0, track: 90.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 225.0, interval: 14 }),
gun: Some(GunSpec { range: 90.0, track: 135.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
reload: 280,
scale: 1.3,
rest_pitch: 0.0,
@@ -260,7 +260,7 @@ impl SamKind {
mount: (1.35, 0.69),
pivot: DVec3::ZERO,
muzzle: Muzzle::Pantsir,
sensor: 195.0,
sensor: 292.0,
mast: 4.0,
};
&S
@@ -269,7 +269,7 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "С-400",
key: "s400",
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 480.0, interval: 20 }),
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 720.0, interval: 20 }),
gun: None,
reload: 420,
scale: 1.5,
@@ -286,7 +286,7 @@ impl SamKind {
mount: (0.7, 1.45),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 2, 7.0),
sensor: 624.0,
sensor: 936.0,
mast: 5.0,
};
&S
@@ -295,7 +295,7 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "С-500",
key: "s500",
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 4, min: 40.0, max: 700.0, interval: 20 }),
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 4, min: 40.0, max: 1050.0, interval: 20 }),
gun: None,
reload: 520,
scale: 1.6,
@@ -312,7 +312,7 @@ impl SamKind {
mount: (0.7, 1.45),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 1, 9.5),
sensor: 910.0,
sensor: 1365.0,
mast: 5.0,
};
&S
@@ -321,7 +321,7 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "IRIS-T SLM",
key: "irist",
missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 400.0, interval: 10 }),
missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }),
gun: None,
reload: 300,
scale: 1.4,
@@ -338,7 +338,7 @@ impl SamKind {
mount: (0.7, 1.45),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(4, 2, 4.0),
sensor: 520.0,
sensor: 780.0,
mast: 5.0,
};
&S
@@ -347,7 +347,7 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "NASAMS",
key: "nasams",
missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 300.0, interval: 14 }),
missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }),
gun: None,
reload: 260,
scale: 1.3,
@@ -364,7 +364,7 @@ impl SamKind {
mount: (0.62, 0.4),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(3, 2, 4.0),
sensor: 390.0,
sensor: 585.0,
mast: 5.0,
};
&S
@@ -373,7 +373,7 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "Бук-М2",
key: "buk",
missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 450.0, interval: 18 }),
missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }),
gun: None,
reload: 400,
scale: 1.4,
@@ -389,7 +389,7 @@ impl SamKind {
mount: (1.55, 0.2),
pivot: DVec3::ZERO,
muzzle: Muzzle::Rails(&[-9.0, -3.0, 13.0, 19.0]),
sensor: 585.0,
sensor: 878.0,
mast: 4.0,
};
&S
@@ -398,7 +398,7 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "Тор-М2",
key: "tor",
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 160.0, interval: 8 }),
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 240.0, interval: 8 }),
gun: None,
reload: 300,
scale: 1.3,
@@ -409,7 +409,7 @@ impl SamKind {
mount: (1.5, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::Cells,
sensor: 210.0,
sensor: 315.0,
mast: 3.5,
};
&S
@@ -418,7 +418,7 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "P1-SUN",
key: "p1sun",
missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 450.0, interval: 12 }),
missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }),
gun: None,
reload: 240,
scale: 1.1,
@@ -454,7 +454,7 @@ impl SamKind {
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 1700.0,
sensor: 2550.0,
mast: 16.0,
};
&S
+322 -19
View File
@@ -45,9 +45,115 @@ pub(super) fn claimed(d: &Drone, missile_on: &HashMap<u32, u32>, had_target: Opt
d.engaged + on
}
/// Ballistic missiles get a pair; anything else one.
/// Ticks until the target reaches its aim at its present speed.
pub(super) fn arrival(d: &Drone) -> f64 {
d.pos.distance(d.target) / d.vel.length().max(0.1)
}
/// Shoot-look-shoot that grows with urgency: ballistic missiles get a pair, anything else one; a target
/// this close to its aim (ticks) has one more interceptor allowed on it at once, closer still another, and in the last seconds a fourth.
pub(super) const URGENT: f64 = 240.0;
pub(super) const DESPERATE: f64 = 110.0;
pub(super) const FINAL: f64 = 60.0;
pub(super) fn needed(d: &Drone) -> u32 {
if d.kind.spec().class == Class::Ballistic { 2 } else { 1 }
let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 };
let t = arrival(d);
base + u32::from(t < URGENT) + u32::from(t < DESPERATE) + u32::from(t < FINAL)
}
/// Ticks a launcher may hold a target without launching before it lets go, and how long it then keeps away from it.
pub(super) const HOLD_MAX: u32 = 24;
pub(super) const SHY_TICKS: u64 = 120;
// ---------------------------------------------------------------- the grounds to launch on
/// Last chance (`/airdef lastchance`): a target of a 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.
pub(super) const LAST_CHANCE_TICKS: f64 = 200.0;
pub(super) fn last_chance(on: bool, roles: u8, d: &Drone, claimed: u32) -> bool {
on && roles != 0 && roles & d.kind.spec().class.bit() == 0 && claimed == 0 && 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.
pub(super) const FAR_K: f64 = 1.6;
/// Ticks between one system's long shots; the share of the magazine it keeps for them; the radar track's age.
pub(super) const FAR_COOLDOWN: u32 = 300;
pub(super) const FAR_RADAR_AGE: u64 = 150;
impl SamKind {
/// Whether the kind takes long shots on a big radar's data.
pub(super) fn far_shooter(self) -> bool {
matches!(self, SamKind::S400 | SamKind::S500 | SamKind::Patriot)
}
}
/// A live big radar in data-link reach of `sam` that measured `id` recently.
pub(super) fn radar_cue(sam: &Sam, radars: &[&Sam], id: u32, now: u64) -> bool {
radars.iter().any(|r| {
r.alive()
&& !r.moving()
&& r.radar_up()
&& r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range())
&& r.track(id).is_some_and(|t| t.own_tick > 0 && t.age(now) <= FAR_RADAR_AGE)
})
}
/// The ground beyond `max`: a long shot is allowed (the system, its launcher and magazine, the flag, a cue).
pub(super) fn far_blocks(on: bool, sam: &Sam, load: &units::MissileLoad, cued: bool, in_reach_of_any: bool) -> u8 {
(if on && sam.kind.far_shooter() { 0 } else { FAR_OFF })
| (if cued { 0 } else { FAR_NO_CUE })
| (if sam.far_cooldown == 0 { 0 } else { FAR_WAIT })
| (if sam.missiles * 2 >= load.magazine { 0 } else { FAR_LOW })
| (if in_reach_of_any { FAR_BUSY } else { 0 })
}
pub(super) const FAR_OFF: u8 = 1;
pub(super) const FAR_NO_CUE: u8 = 2;
pub(super) const FAR_WAIT: u8 = 4;
pub(super) const FAR_LOW: u8 = 8;
pub(super) const FAR_BUSY: u8 = 16;
/// Why a system may launch at a target: its role, the last chance, or a long shot on the radar's cue.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Basis {
Role,
LastChance,
FarShot,
}
/// What is switched on beyond the roles (the sim's settings).
#[derive(Clone, Copy)]
pub(super) struct Opts {
pub last_chance: bool,
pub far_shots: bool,
}
/// Whether, and on what basis, `sam` may launch at `d` on `track`: `k` stretches the reach (a held target
/// may stray); `claimed` is the interceptors others have on it; `cued` that a big radar holds it; and
/// `role_in_reach` that the system has a target of its roles in range anyway (no long shots then).
#[allow(clippy::too_many_arguments)]
pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Drone, now: u64, claimed: u32, k: f64, opts: Opts, cued: bool, role_in_reach: bool) -> Option<Basis> {
let blocks = target_blocks(sam.roles, Some(track), now, d);
if blocks & !ROLE != 0 {
return None;
}
let est = track.est(now);
let reach = reach_blocks(load.min, load.max, k, sam.pos, est);
if blocks & ROLE == 0 {
if reach == 0 {
return Some(Basis::Role);
}
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 0;
return (far && far_blocks(opts.far_shots, sam, load, cued, role_in_reach) == 0).then_some(Basis::FarShot);
}
(reach == 0 && last_chance(opts.last_chance, sam.roles, d, claimed)).then_some(Basis::LastChance)
}
/// The kill chance of an interceptor that met its target `dist` from the launcher whose reach is `max`:
/// whole up to `max`, falling linearly to half at `FAR_K` × max.
pub(super) fn reach_fit(max: f64, dist: f64) -> f64 {
1.0 - 0.5 * ((dist - max) / (max * (FAR_K - 1.0))).clamp(0.0, 1.0)
}
/// A gun's candidates: measured by the system's own radar a moment ago and within the gun's tracking range
@@ -209,7 +315,7 @@ impl Sim {
let subject = sam.target.or(sam.gun_target).and_then(drone_at).or_else(|| {
self.drones
.iter()
.filter(|d| d.alive() && sam.roles & d.kind.spec().class.bit() != 0)
.filter(|d| d.alive() && (sam.roles & d.kind.spec().class.bit() != 0 || last_chance(self.last_chance, sam.roles, d, claimed(d, &missile_on, sam.target))))
.max_by(|a, b| a.threat(sam.pos).total_cmp(&b.threat(sam.pos)))
});
let Some(t) = subject else {
@@ -227,10 +333,21 @@ impl Sim {
// Where the system believes the target is: its track's forecast (the true place only when it has no track).
let est = track.map_or(t.pos, |tr| tr.est(now));
let evel = track.map_or(t.vel, |tr| tr.vel);
v.push(check(
blocks & ROLE == 0,
format!("роль: {} {} [{}]", t.kind.spec().class.name(), if blocks & ROLE == 0 { "в ролях" } else { "не в ролях" }, roles_text(sam.roles)),
));
let first_claim = claimed(t, &missile_on, sam.target);
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, t, first_claim);
let role_text = if blocks & ROLE == 0 {
format!("роль: {} в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles))
} else if chance {
format!(
"последний шанс: {} не в ролях [{}], но до цели {:.0} с, перехватчиков на ней нет",
t.kind.spec().class.name(),
roles_text(sam.roles),
arrival(t) / 20.0
)
} else {
format!("роль: {} не в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles))
};
v.push(check(blocks & ROLE == 0 || chance, role_text));
let detect = match (track, sam.own.contains(&t.id)) {
(Some(tr), own) => {
let kind = if own { "своей РЛС" } else { "по сети (стволы не стреляют)" };
@@ -277,17 +394,31 @@ impl Sim {
let mut fires = false;
if let Some(load) = &spec.missile {
let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est);
v.push(check(
reach == 0,
format!(
"ракеты: дальность {}–{}, цель на {}{}",
crate::panel::distance(load.min),
crate::panel::distance(load.max),
crate::panel::distance(dist),
if reach & TOO_CLOSE != 0 { " — слишком близко" } else if reach & TOO_FAR != 0 { " — слишком далеко" } else { "" }
),
));
let free = claimed(t, &missile_on, sam.target);
// Beyond the normal reach, a heavy system may fire on a big radar's cue.
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
let cued = sam.kind.far_shooter() && 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)) && claimed(o, &missile_on, sam.target) < needed(o))
});
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 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));
if far {
let fb = far_blocks(self.far_shots, sam, load, cued, role_in_reach);
let mut no = Vec::new();
for (bit, name) in [
(FAR_OFF, "не для этого комплекса"),
(FAR_NO_CUE, "нет свежего трека большой РЛС"),
(FAR_WAIT, "дальний пуск уже был недавно"),
(FAR_LOW, "меньше половины боезапаса"),
(FAR_BUSY, "есть цель в обычной дальности"),
] {
if fb & bit != 0 {
no.push(name);
}
}
v.push(check(far_ok, if far_ok { format!("дальний пуск по РЛС: цель на {} дальше обычных {}", crate::panel::distance(dist), crate::panel::distance(load.max)) } else { format!("дальний пуск по РЛС не разрешён: {}", no.join(", ")) }));
}
let free = first_claim;
let need = needed(t);
v.push(check(free < need, format!("цель занята перехватчиками: {free} из {need}{}", if free < need { "" } else { " — другие уже на ней" })));
let mb = missile_blocks(sam);
@@ -320,7 +451,8 @@ impl Sim {
},
));
}
fires |= reach == 0 && free < need && mb == 0 && aligned && blocks == 0 && land == 0;
let grounds = blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && (reach == 0 || far_ok);
fires |= grounds && free < need && mb == 0 && aligned && land == 0;
}
if let Some(gun) = &spec.gun {
let on_it = guns_on.get(&t.id).copied().unwrap_or(0) - u32::from(sam.gun_target == Some(t.id));
@@ -379,4 +511,175 @@ mod tests {
sim.sams[0].roles = 0xFF;
assert!(sim.why(0).iter().any(|c| c.text.starts_with("роль")));
}
use super::sites::testland::{Land, serve};
fn setup(kind: SamKind) -> (Sim, Ground, Land<fn(i32, i32) -> i32>, Out) {
let mut sim = Sim::new(5);
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(0.0, 70.0, 0.0), 0.0));
(sim, Ground::default(), Land(|_, _| 64), Out::default())
}
/// Steps `ticks` or until something is fired; returns the drone's ticks to its aim at the first launch.
fn until_fired(sim: &mut Sim, ground: &mut Ground, land: &Land<fn(i32, i32) -> i32>, out: &mut Out, ticks: u32) -> Option<f64> {
for _ in 0..ticks {
serve(ground, land, sim.tick);
sim.step(ground, None, out);
if sim.sams[0].fired > 0 {
return sim.drones.first().map(arrival);
}
}
None
}
/// A Shahed `blocks` short of its aim, which is `80` out from the system, coming in along z.
fn shahed_at(sim: &mut Sim, blocks: f64) {
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -80.0 - blocks), DVec3::Z, DVec3::new(0.0, 70.0, -80.0));
}
#[test]
fn last_chance_fires_at_a_class_out_of_roles_only_when_it_is_about_to_hit() {
// The S-400 does not engage drones by default.
assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0);
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
shahed_at(&mut sim, 60.0);
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");
// The diagnostic names why: the last chance.
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
shahed_at(&mut sim, 100.0);
for _ in 0..30 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
let w = sim.why(0);
assert!(w.iter().any(|c| c.ok && c.text.starts_with("последний шанс")), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
}
#[test]
fn last_chance_waits_for_a_target_far_from_its_aim() {
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
// In plain view 120 blocks off, but flying away from its aim, 480 blocks (800 ticks) ahead.
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -120.0), DVec3::NEG_Z, DVec3::new(0.0, 70.0, -600.0));
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a Shahed far from its aim");
let w = sim.why(0);
// Still named as the role block it was: no target of its classes.
assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.text.contains("нет целей классов")), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
assert!(!w.iter().any(|c| c.text.starts_with("последний шанс")));
}
#[test]
fn last_chance_is_off_when_switched_off_and_with_no_roles() {
for (off, roles) in [(true, 30u8), (false, 0u8)] {
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
sim.last_chance = !off;
sim.sams[0].roles = roles;
shahed_at(&mut sim, 60.0);
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 140).is_none(), "fired with last chance off={off}, roles {roles}");
}
}
#[test]
fn last_chance_leaves_a_target_that_already_has_an_interceptor_on_it() {
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
shahed_at(&mut sim, 60.0);
// Another system's interceptor is on it.
let id = sim.drones[0].id;
sim.drones[0].engaged = 1;
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 40).is_none(), "fired at {id} that is claimed");
}
/// A Kh101 `dist` from the origin on the far side, at height, coming in along z; a radar beside the system.
fn far_setup(radar: bool, dist: f64) -> (Sim, Ground, Land<fn(i32, i32) -> i32>, Out) {
let (mut sim, ground, land, out) = setup(SamKind::S400);
if radar {
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Radar, DVec3::new(40.0, 70.0, 0.0), 0.0));
}
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, -dist), DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
(sim, ground, land, out)
}
/// The radar's measurement of every live drone, fresh this tick (as if its beam had just passed).
fn radar_sees(sim: &mut Sim) {
let now = sim.tick;
let tracks: Vec<Track> = sim
.drones
.iter()
.filter(|d| d.alive())
.map(|d| Track { id: d.id, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false })
.collect();
for r in sim.sams.iter_mut().filter(|s| s.kind == SamKind::Radar) {
for t in &tracks {
r.tracks.retain(|o| o.id != t.id);
r.tracks.push(*t);
}
}
}
fn fire_far(sim: &mut Sim, ground: &mut Ground, land: &Land<fn(i32, i32) -> i32>, out: &mut Out, ticks: u32) -> u32 {
for _ in 0..ticks {
radar_sees(sim);
serve(ground, land, sim.tick);
sim.step(ground, None, out);
}
sim.sams[0].fired
}
#[test]
fn heavy_systems_shoot_far_on_a_radars_cue_but_not_without_one() {
let max = SamKind::S400.spec().missile.as_ref().unwrap().max;
let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4);
assert!(fire_far(&mut sim, &mut ground, &land, &mut out, 80) >= 1, "no long shot at 1.4 x max with a radar");
let w = sim.why(0);
assert!(w.iter().any(|c| c.text.starts_with("дальний пуск по РЛС")), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
// No radar, no shot (the system's own radar may well see it: that is not a cue).
let (mut sim, mut ground, land, mut out) = far_setup(false, max * 1.4);
assert_eq!(fire_far(&mut sim, &mut ground, &land, &mut out, 80), 0, "a long shot with no radar");
// And a kind that is not a heavy one never does.
let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4);
sim.far_shots = false;
assert_eq!(fire_far(&mut sim, &mut ground, &land, &mut out, 80), 0, "a long shot with them switched off");
}
#[test]
fn a_long_shot_waits_out_its_cooldown_and_for_nothing_closer() {
let max = SamKind::S400.spec().missile.as_ref().unwrap().max;
// Two far targets: one long shot, the second waits its 300 ticks.
let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4);
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, max * 1.4), DVec3::NEG_Z, DVec3::new(0.0, 70.0, 0.0));
assert_eq!(fire_far(&mut sim, &mut ground, &land, &mut out, 70), 1, "not exactly one long shot in the cooldown");
// A closer target in normal reach: the far one is not fired at while it stands.
let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4);
let far = sim.drones[0].id;
sim.add_drone(DroneKind::Kh101, DVec3::new(300.0, 120.0, 0.0), DVec3::NEG_X, DVec3::new(0.0, 70.0, 0.0));
for _ in 0..40 {
radar_sees(&mut sim);
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
assert!(!sim.missiles.iter().any(|m| m.target == far), "a long shot while a closer target was in reach");
}
assert!(sim.sams[0].fired > 0, "the closer target was not fired at");
}
#[test]
fn the_kill_chance_falls_to_half_at_the_far_end() {
assert_eq!(reach_fit(100.0, 80.0), 1.0);
assert_eq!(reach_fit(100.0, 100.0), 1.0);
assert!((reach_fit(100.0, 130.0) - 0.75).abs() < 1e-9);
assert!((reach_fit(100.0, 160.0) - 0.5).abs() < 1e-9);
assert!((reach_fit(100.0, 400.0) - 0.5).abs() < 1e-9);
}
#[test]
fn every_interceptor_lives_long_enough_to_fly_its_reach() {
// Life × top speed must cover the far end of a heavy system's reach with room to chase; the rest their plain reach.
for kind in SamKind::ARMED {
let Some(load) = kind.spec().missile.as_ref() else { continue };
let m = load.kind.spec();
let reach = load.max * if kind.far_shooter() { FAR_K } else { 1.0 };
assert!(m.life as f64 * m.speed > reach * 1.2, "{}: {} x {} does not cover {reach}", kind.name(), m.life, m.speed);
}
}
}