Fix raid gameplay, finite ammunition and truck routing

Check launch terrain, reserve ballistic targets for marked objectives, tune in-game reach and fallback fire, and support bounded terrain work on supply routes.

Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
2026-11-25 18:53:17 +03:00
parent 61c4fa5cee
commit aa842d8a1f
18 changed files with 606 additions and 257 deletions
+22 -19
View File
@@ -69,18 +69,17 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает то
«Баллистика», «Гиперзвук», «Орешник с прикрытием», «Подавление ПВО»), откуда (один сектор, два, со всех сторон,
волнами по типам), дальность старта, цели и **ПУСК**. Цели:
- *только объекты* — всё летит по отмеченным объектам (или по игроку, если их нет);
- *объекты и ПВО* — треть ударных средств бьёт по случайным комплексам;
- *объекты и ПВО* — часть ударных аппаратов бьёт по случайным комплексам. Баллистика летит по отмеченным объектам;
- *умный противник* — планировщик использует наблюдённые контакты и последние известные позиции комплексов: ведёт дроны и крылатые ракеты
маршрутами в обход зон поражения, низко, за рельефом и через мёртвые зоны; «Герберы» прилетают на 15 с раньше,
чтобы оттянуть ракеты; «Ланцеты» идут по Гепардам и Панцирям, Х-22/Циркон и часть баллистики — по дальнобойным
комплексам; на наблюдённые РЛС дальнего обнаружения выделяются 2–3 быстрых ударника (Х-22, Циркон, Искандер, Кинжал, затем Х-101,
Герань-3, Ланцет, Шахед; не больше четверти налёта); всё остальное стартует со сдвигом так, чтобы прилететь одновременно.
чтобы оттянуть ракеты. На технику вместе с наблюдёнными РЛС выделяется до четверти большого налёта.
Баллистика и остальная ударная группа идут по отмеченным объектам. В режиме волн группы прибывают с интервалами.
После налёта приходит отчёт: сколько сбито и прорвалось, ракет ПВО потрачено, комплексов потеряно, урон объектам.
**Обнаружение.** РЛС видит цель не дальше, чем позволяют:
- её размер: дальность растёт как корень четвёртой степени из ЭПР — Х-101 и Ланцет видно примерно вдвое ближе, чем Х-22;
- радиогоризонт: низколетящую цель видно поздно (Шахед на 25 м — с ~250 м, баллистику — издалека);
- радиогоризонт: низколетящие цели обнаруживаются ближе, чем цели на большой высоте;
- рельеф и лес: за холмом цель не видна (каждый комплекс строит свой горизонт по 48 лучам; рельеф известен в
прогруженных чанках);
- вблизи (24 м) видно всё.
@@ -107,10 +106,13 @@ P1-SUN также использует чужие данные. Пушкам (Г
не заменяет обязательное собственное сопровождение. Выключение не стирает старые сведения противника:
он продолжает использовать последнюю наблюдённую позицию, а пуски и РЭБ могут снова раскрыть технику.
**Логистика.** Пока нет ни одного склада, магазины пополняются сами, как раньше. Как только поставлен склад,
боекомплект считается: комплекс без ракет пишет «ЖДЁТ БК»; в 60 м от склада он перезаряжается прямо с него, а
**Логистика.** Боекомплект конечный с момента размещения техники. Комплекс с пустым боекомплектом показывает
«ЖДЁТ БК». В 60 блоках от склада он перезаряжается прямо с него, а
дальние обслуживают **ТЗМ**: заправляются на складе (2 перезарядки), сами едут к ждущим комплексам, ближайшим
первым, и возвращаются. Запас склада — 30 перезарядок, он виден в сводке. Склад и ТЗМ детонируют всем грузом.
первым, и возвращаются. ТЗМ ищет проезд с любой стороны получателя. Если объезда нет, машина может
уложить короткий мост или пандус из булыжника и расчистить до двух слоёв мягкого грунта. Строительство
требует разрешения на команды изменения мира. Запас склада — 30 перезарядок, он виден в сводке.
Склад и ТЗМ детонируют всем грузом.
Ударная **RM48U у С-400** — отдельный условный игровой боеприпас, который делит четыре ячейки
с ракетами ПВО. `/airdef ground-stock <склад> <количество>` задаёт конечный начальный запас
@@ -135,8 +137,9 @@ sandbox-сценария, `/airdef ground-load <С-400>` загружает од
**Умный противник учится.** Он запоминает, откуда его налёты сбивали, а откуда они прорывались, и следующий
налёт ведёт с лучшего направления; помнит комплексы, выдавшие себя пуском, и станции РЭБ, и во время налёта
перенацеливает ещё не взлетевшие Ланцеты и Шахеды на них; если цель-комплекс уничтожен, дроны идут к
следующему известному. Маршруты к новым целям достраиваются по бюджету планировщика в следующих тиках:
может перенацелить часть ещё не взлетевших аппаратов. Удары по технике занимают до четверти большого
налёта. Баллистика на всех этапах сохраняет отмеченный объект. Если цель-комплекс уничтожена, выделенные
на удар по технике аппараты могут выбрать другой известный комплекс. Маршруты к новым целям достраиваются по бюджету планировщика в следующих тиках:
необработанное задание не теряется, старый безопасный участок остаётся до готовности нового, а дрон без
маршрута летит прямо только до ближайшего бюджета. Дроны под обстрелом прижимаются к земле.
@@ -298,19 +301,19 @@ HUD не выводится. Простые пресеты налёта фазу
| ПВО | Вооружение | Дальность |
|---|---|---|
| Patriot | 4 × PAC-3, пусковая разворачивается на цель | 10–450 |
| Гепард | 2 × 35 мм, башня и стволы со слежением и упреждением, 160 очередей | 135 (слежение с 195) |
| Панцирь-С1 | 12 × 57Э6 и 2 × 30 мм; модуль поворачивается, пакеты и стволы поднимаются | ракеты 25–225, пушки 90 |
| С-400 | 4 × 48Н6, вертикальный холодный старт, РЛС обзора на прицепе | 30–720 |
| С-500 | 2 × 77Н6, холодный старт, самые быстрые ракеты | 40–1050 |
| Patriot | 4 × PAC-3, пусковая разворачивается на цель | 10–950 |
| Гепард | 2 × 35 мм, башня и стволы со слежением и упреждением, 160 очередей | 180 (слежение с 260) |
| Панцирь-С1 | 12 × 57Э6 и 2 × 30 мм; модуль поворачивается, пакеты и стволы поднимаются | ракеты 25–330, пушки 125 |
| С-400 | 4 × 48Н6, вертикальный холодный старт, РЛС обзора на прицепе | 30–1300 |
| С-500 | 2 × 77Н6, холодный старт, самые быстрые ракеты | 40–1850 |
| IRIS-T SLM | 8 ракет, вертикальный пуск, быстрые и манёвренные | 15–600 |
| NASAMS | 6 × AMRAAM, наводимая пусковая на прицепе | 10–450 |
| Бук-М2 | 4 × 9М317 на направляющих, башня с РЛС подсвета | 20–675 |
| Тор-М2 | 8 × 9М338 вертикально из башни, быстрая реакция против дронов | 8–240 |
| Тор-М2 | 8 × 9М338 вертикально из башни, быстрая реакция против дронов | 8–350 |
| P1-SUN | 8 дронов-перехватчиков против Шахедов и Герань; своей РЛС нет — стреляет по данным сети | 5–675 |
Обслуживающая техника (тоже пультами или `/airdef deploy <ключ>`): **РЛС дальнего обнаружения** (`radar`,
видит на 2,5 км с высокой мачты, хуже прячутся за рельефом), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`),
базовая дальность обзора 3800 блоков до поправок на класс цели, высоту и рельеф), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`),
**станция РЭБ** (`ew`), **прожектор** (`light`), **оптический пост** (`optical`: пассивно уточняет широкий класс
контакта по прямой видимости и передаёт уточнение в класс уже известного сетевого трека — без своего трека,
свежести и права на пуск; не излучает и не ведёт огневой трек). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
@@ -330,8 +333,8 @@ HUD не выводится. Простые пресеты налёта фазу
нарастает плавно, но холодного выброса нет; электрический P1-SUN не получает ракетную струю.
**Последний шанс** (`/airdef lastchance on|off`, по умолчанию вкл). Комплекс стреляет и по классу целей вне своих ролей
(С-400, С-500 и Patriot по умолчанию не бьют дроны), если цель долетит до своей точки меньше чем за 10 с и на ней ещё нет
ничьего перехватчика. Комплексу с пустыми ролями (огонь запрещён) это не касается. `/airdef why` пишет «последний шанс».
(С-400, С-500 и Patriot по умолчанию не бьют дроны), если цель долетит до своей точки меньше чем за 6 с, на ней ещё нет
ничьего перехватчика и готовый комплекс меньшей дальности не успевает её обстрелять. Комплексу с пустыми ролями (огонь запрещён) это не касается. `/airdef why` пишет «последний шанс».
**Дальний пуск по РЛС.** С-400, С-500 и Patriot могут стрелять дальше своей дальности (до 1,6×) по цели, которую держит
свежим треком РЛС дальнего обнаружения в радиусе связи: не чаще раза в 15 с, при не менее чем половине боезапаса, только по
+12
View File
@@ -50,6 +50,7 @@ const MAX_RECON_SORTIES: usize = recon::SORTIES_MAX * 2;
pub struct AirSave {
tick: u64,
job_next: u32,
diversions_left: u32,
kills: [u32; ew::SECTORS],
hits: [u32; ew::SECTORS],
/// The bearing memory's small window of recent outcomes (#149).
@@ -217,6 +218,7 @@ impl Sim {
^ (self.intel.contacts().len() as u64) << 36
^ (self.job_next as u64) << 48
^ self.recon.mark().rotate_left(12)
^ u64::from(self.diversions_left).rotate_left(18)
}
/// The air section of the state text: `None` when there is nothing to keep (an empty sky and no
@@ -249,6 +251,7 @@ impl Sim {
// temporary `String` per item and re-copied the whole growing head, so a full relief grid cost
// O(n²) bytes and a heavy autosave ran out of fuel.
let mut head = format!("air {VERSION} {} {} 0 0 0 {} {}\n", self.tick, self.job_next, contacts.len(), reliefs.len());
writeln!(head, "airdiversions {}", self.diversions_left).unwrap();
head.push_str("airintel");
for v in kills.iter().chain(hits.iter()) {
write!(head, " {v}").unwrap();
@@ -490,6 +493,7 @@ impl Sim {
let n_reliefs = l.count(8, "версии рельефа", MAX_RELIEFS)?;
// Every line of the section, and nothing else: a truncated or foreign line is refused.
let mut intel: Option<[u32; ew::SECTORS * 2]> = None;
let mut diversions_left = None;
let mut outcomes: Vec<ew::Learned> = Vec::new();
let mut global: Option<usize> = None;
let mut reliefs: Vec<Option<std::sync::Arc<ew::KnownRelief>>> = vec![None; n_reliefs];
@@ -513,6 +517,12 @@ impl Sim {
}
let l = Line { n: *n, word, w: w.clone() };
match word {
"airdiversions" => {
if w.len() != 2 || diversions_left.is_some() {
return Err(l.bad("перенацеливание", "нужен один счётчик на сохранение"));
}
diversions_left = Some(l.int(1, "остаток перенацеливаний", 0, i64::from(u32::MAX))? as u32);
}
"airintel" => {
if w.len() != 1 + ew::SECTORS * 2 {
return Err(l.bad("счётчики секторов", &format!("нужны {} чисел", ew::SECTORS * 2)));
@@ -864,6 +874,7 @@ impl Sim {
Ok(Some(AirSave {
tick,
job_next,
diversions_left: diversions_left.unwrap_or(0),
kills,
hits,
outcomes,
@@ -881,6 +892,7 @@ impl Sim {
/// job whose drone, aim or unit no longer stands is dropped — a restored job is never a ghost.
/// The live air state is replaced, never merged: what the sky held before the load goes.
pub fn restore_air(&mut self, save: AirSave) -> u32 {
self.diversions_left = save.diversions_left;
self.tick = save.tick;
// New jobs must not reuse an id a restored job already holds.
let highest = save.jobs.iter().map(|j| j.id).max().unwrap_or(0);
+18 -5
View File
@@ -792,9 +792,12 @@ impl Sim {
let mut assigned = 0usize;
let mut changed = 0u32;
let mut job_next = self.job_next;
let mut diversions_left = self.diversions_left;
let mut jobs: Vec<RouteJob> = Vec::new();
for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart && matches!(d.intent, Intent::Plan | Intent::Sead)) {
if assigned >= ASSIGN_PER_TICK || d.aim.switches >= SWITCH_CAP {
for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart && d.kind.spec().class != Class::Ballistic && matches!(d.intent, Intent::Plan | Intent::Sead)) {
if assigned >= ASSIGN_PER_TICK || d.aim.switches >= SWITCH_CAP
|| d.kind.spec().decoy || (d.aim.unit == 0 && diversions_left == 0)
{
continue;
}
let Some(o) = obs.iter().find(|o| {
@@ -808,6 +811,7 @@ impl Sim {
*per.entry(o.id).or_insert(0) += 1;
assigned += 1;
changed += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = o.at + d.err;
d.intent = Intent::Refresh;
d.aim = d.aim.replaced(o.id, now, o.confidence(now));
@@ -819,6 +823,7 @@ impl Sim {
}
}
self.job_next = job_next;
self.diversions_left = diversions_left;
for job in jobs {
self.queue_route(job);
}
@@ -874,16 +879,17 @@ impl Sim {
// Job ids are taken from the simulation's counter: a job keeps its id when it is replaced in
// place, and the save writes it back (#127).
let mut job_next = self.job_next;
let mut diversions_left = self.diversions_left;
// The drones sent at a new target: a route job each, to be worked out as the planner's budget allows.
let mut jobs: Vec<RouteJob> = Vec::new();
let mut n = 0usize;
let mut assigned = 0usize;
let mut per_contact: HashMap<u32, usize> = HashMap::new();
for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart) {
for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart && d.kind.spec().class != Class::Ballistic) {
let hunter = matches!(d.kind, DroneKind::Lancet | DroneKind::Kh22 | DroneKind::Zircon);
let eligible = hunter || (d.kind == DroneKind::Shahed && n % 4 == 0);
n += 1;
if !eligible {
if !eligible || (d.aim.unit == 0 && diversions_left == 0) {
continue;
}
// A recon mark is an area, not a unit: it is kept while the mark lives. A
@@ -904,6 +910,7 @@ impl Sim {
}
*per_contact.entry(c.id).or_insert(0) += 1;
assigned += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = c.at + d.err;
d.intent = Intent::React;
d.aim = d.aim.replaced(c.id, now, c.confidence(now));
@@ -947,6 +954,7 @@ impl Sim {
};
*per_contact.entry(unit).or_insert(0) += 1;
assigned += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = at + d.err;
d.intent = Intent::React;
// A first assignment is not a switch: the aim's clock starts here, the count is kept.
@@ -963,7 +971,10 @@ impl Sim {
// or forgotten after its contact aged out mid-flight, is replaced by the nearest live contact
// it can still turn onto — or, past the switch cap, the drone keeps its course. A unit merely
// moved is still aimed where seen.
for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart) {
for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart && d.kind.spec().class != Class::Ballistic) {
if d.aim.unit == 0 && diversions_left == 0 {
continue;
}
let aim = d.target - d.err;
let aim_gone = if recon::is_mark(d.aim.unit) {
!self.recon.live(d.aim.unit, self.tick)
@@ -1022,6 +1033,7 @@ impl Sim {
if let Some((_, unit, at, confidence)) = next {
*per_contact.entry(unit).or_insert(0) += 1;
assigned += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = at + d.err;
d.intent = Intent::Replace;
d.aim = d.aim.replaced(unit, now, confidence);
@@ -1034,6 +1046,7 @@ impl Sim {
}
}
self.job_next = job_next;
self.diversions_left = diversions_left;
for job in jobs {
self.queue_route(job);
}
+12 -31
View File
@@ -1,17 +1,7 @@
//! Logistics: once a depot stands, magazines are no longer refilled from
//! nowhere. A system out of missiles waits; one within reach of a depot
//! reloads from its stock; the reload trucks fill up at a depot and drive
//! reloads to the systems that wait, nearest first, and back.
//! Empty magazines are replenished from finite depot stock, either directly or via a truck.
use super::*;
impl Sim {
/// Whether ammunition is counted: a depot was set up (without one, magazines refill as
/// before). A destroyed depot still counts: losing the last one leaves the systems short,
/// not supplied from nowhere again.
pub fn logistics(&self) -> bool {
self.sams.iter().any(|s| s.kind == SamKind::Depot)
}
/// Prepare one explicitly typed round at a nearby living depot. Any displaced air round is retained there.
pub fn load_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
@@ -84,12 +74,6 @@ impl Sim {
/// Reloads from depots near the systems, and the trucks' rounds.
pub(super) fn step_supply(&mut self, out: &mut Out) {
if !self.logistics() {
for s in &mut self.sams {
s.empty = false;
}
return;
}
let now = self.tick;
// Systems by a depot reload from it.
for i in 0..self.sams.len() {
@@ -139,8 +123,7 @@ impl Sim {
if let Some((id, to)) = target {
self.sams[t].job = Some(id);
if at.distance(to) > HANDOVER {
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
self.order_move_near(t, to + side, 3.5);
self.order_move_near(t, to, HANDOVER - 0.75);
} else if let Some(j) = self.sams.iter().position(|s| s.id == id) {
if self.sams[t].return_cargo {
self.sams[j].ground_stock += 1;
@@ -217,8 +200,7 @@ impl Sim {
self.sams[t].job = None;
} else {
let to = self.sams[j].pos;
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
self.order_move_near(t, to + side, 3.5);
self.order_move_near(t, to, HANDOVER - 0.75);
continue;
}
} else { self.sams[t].job = None; }
@@ -231,15 +213,16 @@ impl Sim {
}.map(|s| (s.id, s.pos));
if let Some((id, to)) = next {
self.sams[t].job = Some(id);
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
if to.distance(at) > HANDOVER { self.order_move_near(t, to + side, 3.5); }
if to.distance(at) > HANDOVER { self.order_move_near(t, to, HANDOVER - 0.75); }
}
continue;
}
// Where it was going: hand over, or load up.
if let Some(job) = truck.job
&& let Some(j) = self.sams.iter().position(|s| s.id == job)
{
if let Some(job) = truck.job {
let Some(j) = self.sams.iter().position(|s| s.id == job && s.alive()) else {
self.sams[t].job = None;
continue;
};
if self.sams[j].pos.distance(at) <= HANDOVER {
if self.sams[j].kind == SamKind::Depot {
let take = TRUCK_LOAD.saturating_sub(self.sams[t].cargo).min(self.sams[j].cargo);
@@ -251,11 +234,10 @@ impl Sim {
self.reload_now(j, out);
}
self.sams[t].job = None;
} else if self.sams[j].alive() && (self.sams[j].empty || self.sams[j].kind == SamKind::Depot) {
} else if self.sams[j].empty || self.sams[j].kind == SamKind::Depot {
// Stopped short of it (it drove off meanwhile): on to where it stands now.
let to = self.sams[j].pos;
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
self.order_move_near(t, to + side, 3.5);
self.order_move_near(t, to, HANDOVER - 0.75);
continue;
} else {
self.sams[t].job = None;
@@ -286,9 +268,8 @@ impl Sim {
if let Some((id, to)) = next {
self.sams[t].job = Some(id);
// Stop beside it, not on it.
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
if to.distance(at) > HANDOVER {
self.order_move_near(t, to + side, 3.5);
self.order_move_near(t, to, HANDOVER - 0.75);
}
}
}
+24 -26
View File
@@ -1174,7 +1174,7 @@ pub enum SamState {
Packing,
Moving,
Deploying,
/// Out of missiles, waiting for a reload truck (logistics on: a depot stands).
/// Out of missiles, waiting for a resupply.
Waiting,
}
@@ -1290,7 +1290,7 @@ pub struct Sam {
pub cargo: u32,
/// A reload truck's job: the system it is driving to, or a depot.
job: Option<u32>,
/// Out of ammunition, waiting for a reload (logistics on).
/// Out of ammunition, waiting for a resupply.
pub empty: bool,
/// An EW station: jamming, and its transmitter's heat (0 cold, 1 forced off).
pub ew_on: bool,
@@ -1488,6 +1488,8 @@ pub struct Sim {
horizons: HashMap<u32, sight::Horizon>,
/// Blasts to come: (tick, where, TNT, small) — a magazine cooking off.
later: Vec<(u64, DVec3, u32, bool)>,
/// New unit targets the current raid may adopt after planning.
diversions_left: u32,
/// A planned raid's drones waiting for their launch tick.
pub queue: Vec<(u64, Drone)>,
/// The raid's launch sites and their jobs (#100).
@@ -1593,6 +1595,7 @@ impl Sim {
far_shots: true,
horizons: HashMap::new(),
later: Vec::new(),
diversions_left: u32::MAX,
queue: Vec::new(),
sites: sites::Sites::default(),
strikes: strike::Strikes::new(),
@@ -2052,7 +2055,7 @@ impl Sim {
let safe = if need.is_finite() { need + 2.0 } else { d.target.y + spec.clearance };
let mut height = base.max(safe).max(d.nav.dive + 1.0);
// Blind: it does not come down over land nobody has told of; it holds the height it has.
if d.nav.blind && d.low && to_target > 300.0 {
if d.nav.blind && (d.low || d.pos.y >= raid::VANILLA_BUILD_CEILING) && to_target > 300.0 {
height = height.max(d.pos.y);
}
let full = climb.pitch.tan();
@@ -2430,7 +2433,6 @@ impl Sim {
}
return;
}
let logistics = self.logistics();
// Drones by id (none come or go while the systems act), and how many systems have each as their
// missile target and as their gun target: counted once, then kept up to date as targets change.
let drone_at: HashMap<u32, usize> = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect();
@@ -2514,23 +2516,31 @@ impl Sim {
let radars: Vec<&Sam> = if me.mode == battery::SamMode::LauncherOnly || (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 d = drone(tr).filter(|_| open(tr.id))?;
why::basis(me, load, tr, d, now, claimed(d), k, opts, cued(tr.id), role_in_reach)
.filter(|b| *b != why::Basis::LastChance || self.last_chance_for(me, tr.class, d, claimed(d)))
};
// 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()));
let keep = had_target.filter(|t| !stuck && tracks.iter().any(|tr| {
tr.id == *t && basis(tr, 1.1, false).is_some_and(|b| b != why::Basis::LastChance)
}));
keep.or_else(|| {
let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(tr, 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| free(tr) && !shy(tr.id) && basis(tr, 1.0, role_in_reach).is_some())
.filter_map(|tr| drone(tr).map(|d| (tr, 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)
.filter(|tr| free(tr) && !shy(tr.id))
.filter_map(|tr| {
let b = basis(tr, if had_target == Some(tr.id) { 1.1 } else { 1.0 }, role_in_reach)?;
let d = drone(tr)?;
Some((b != why::Basis::LastChance, d.threat_at(pos, tr.est(now)), d.id))
})
.max_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)))
.map(|(_, _, id)| id)
})
});
// Guns: the nearest, spread over the targets the other guns and missiles aren't on.
@@ -2596,12 +2606,8 @@ impl Sim {
// combined system's crew would), not only once both are spent.
let spent = (spec.missile.is_some() && sam.missiles == 0 && sam.part(Part::Launcher) > 0.0 && sam.cells() > sam.ground_rounds) || (spec.gun.is_some() && sam.bursts == 0);
if spent && sam.reloading == 0 && !sam.empty {
if logistics {
sam.empty = true;
ammo_waits += 1;
} else {
sam.reloading = sam.reload_time()
}
sam.empty = true;
ammo_waits += 1;
}
sam.state = if sam.reloading > 0 {
SamState::Reload
@@ -2680,12 +2686,8 @@ impl Sim {
sam.flash = 2;
sam.recoil = 1.0;
if sam.bursts == 0 && sam.missiles == 0 {
if logistics {
sam.empty = true;
ammo_waits += 1;
} else {
sam.reloading = sam.reload_time()
}
sam.empty = true;
ammo_waits += 1;
}
let (_, rot) = sam.mount();
let s = spec.scale;
@@ -2781,12 +2783,8 @@ impl Sim {
sam.fired += 1;
sam.cooldown = load.interval;
if sam.missiles == 0 && (spec.gun.is_none() || sam.bursts == 0) {
if logistics {
sam.empty = true;
ammo_waits += 1;
} else {
sam.reloading = sam.reload_time()
}
}
}
}
+47 -32
View File
@@ -35,10 +35,29 @@ impl Sam {
}
}
fn finish_move(sam: &mut Sam, routes: &mut route::Routes, index: usize, now: u64, why: Option<route::Why>, out: &mut Out) {
if let Some(why) = why {
let report = sam.job.take().is_none_or(|job| {
routes.unreachable.insert((sam.id, job), now + route::UNREACHABLE_FOR).is_none()
});
if report {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), index + 1, why.text()));
}
}
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
}
impl Sim {
/// Orders unit `i` to drive to `to`. False for one that can't (a depot, a wreck, failed running gear).
pub fn order_move(&mut self, i: usize, to: DVec3) -> bool {
self.order_move_near(i, to, 0.0)
if !self.order_move_near(i, to, 0.0) {
return false;
}
self.sams[i].job = None;
true
}
/// The same, where arriving within `slack` blocks of `to` will do (a truck stops beside its job).
@@ -97,45 +116,45 @@ impl Sim {
sam.dest = None;
}
let Some(to) = sam.dest else {
routes.map.remove(&sam.id);
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
finish_move(sam, routes, n, now, None, out);
continue;
};
let route = routes.map.entry(sam.id).or_insert_with(|| route::Route::new(sam.pos, to, 0.0, sam.kind, now));
let (go, last) = match route.drive(ground, now, sam.pos, share) {
route::Drive::Wait(why) => {
if route.waited(now) > 40 && !route.told {
if sam.job.is_none() && route.waited(now) > 40 && !route.told {
route.told = true;
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text()));
}
continue;
}
route::Drive::Fail(why) => {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text()));
// A truck leaves that job alone for a while, and takes another.
if let Some(job) = sam.job.take() {
routes.unreachable.insert((sam.id, job), now + route::UNREACHABLE_FOR);
if why == route::Why::NoWay && route.approach_works() {
continue;
}
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
if matches!(why, route::Why::NoWay | route::Why::Stuck)
&& route.try_works(ground, sam.pos, now, out)
{
continue;
}
finish_move(sam, routes, n, now, Some(why), out);
continue;
}
route::Drive::Go(p, last) => (p, last),
};
let flat = horizontal(go - sam.pos);
if last && flat.length() < SPEED * 2.0 {
let partial = route.partial;
sam.pos = DVec3::new(go.x, sam.pos.y, go.z);
sam.dest = None;
routes.map.remove(&sam.id);
if partial {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::Partial.text()));
}
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
let why = if route.work_approach() {
if route.try_works(ground, sam.pos, now, out) {
continue;
}
Some(route::Why::NoWay)
} else {
// A partial route already made measurable progress. A delivery
// continues from here when the next stretch of terrain is ready.
(route.partial && sam.job.is_none()).then_some(route::Why::Partial)
};
finish_move(sam, routes, n, now, why, out);
out.sound("minecraft:block.piston.contract", sam.pos, 2.0, 0.6);
continue;
}
@@ -143,17 +162,17 @@ impl Sim {
sam.heading = slew(sam.heading, heading_of(flat), 0.06);
let ahead = DQuat::from_rotation_y(sam.heading) * DVec3::NEG_Z;
let turning = angle_diff(sam.heading, heading_of(flat)).abs();
if sam.kind == SamKind::Tzm && turning > 0.45 {
sam.yaw = sam.heading;
continue;
}
let step = SPEED * sam.drive_speed() * (1.0 - turning / std::f64::consts::PI).max(0.2);
let next = sam.pos + ahead * step;
// The column and chassis clearance ahead: a wall, low ceiling or a change after planning
// turns the vehicle back to the planner. Unknown voxels remain a wait, never a drive.
let Some(y) = ground.at(next, now) else {
if route.wait_ahead() {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::NoMap.text()));
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
finish_move(sam, routes, n, now, Some(route::Why::NoMap), out);
}
continue;
};
@@ -161,11 +180,7 @@ impl Sim {
route::Clearance::Clear => {}
route::Clearance::Pending => {
if route.wait_ahead() {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::NoMap.text()));
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
finish_move(sam, routes, n, now, Some(route::Why::NoMap), out);
}
continue;
}
+118 -58
View File
@@ -282,9 +282,52 @@ impl PartialOrd for Open {
}
}
/// Ticks an air start waits for the land under it to be told of.
/// Ticks a scheduled launch waits for the local terrain before using a high entry.
const AIR_START_WAIT: u32 = 120;
/// The build ceiling of the vanilla terrain supported by AirDef.
pub(super) const VANILLA_BUILD_CEILING: f64 = 320.0;
fn unit_strike_limit(total: u32) -> u32 {
(total / 4).max(1).min(total.saturating_sub(1))
}
fn ballistic_velocity(from: DVec3, aim: DVec3, speed: f64) -> DVec3 {
let flat = horizontal(aim - from);
let time = (flat.length() / speed).max(30.0);
flat / time + DVec3::Y * ((aim.y - from.y + 0.5 * GRAVITY * time * time) / time)
}
/// Sample the actual launch column and the first stretch ahead at block resolution.
fn launch_floor(ground: &mut Ground, d: &Drone, offmap: bool) -> (f64, bool) {
let spec = d.kind.spec();
let ballistic = spec.ballistic.is_some();
let heading = horizontal(d.vel).normalize_or(DVec3::NEG_Z);
let climb = d.kind.climb();
let mut floor = d.pos.y;
let mut pending = false;
for blocks in 0..=if ballistic { 8 } else { 24 } {
let dist = f64::from(blocks);
let p = d.pos + heading * dist;
let x = p.x.floor() as i32;
let z = p.z.floor() as i32;
if let Some(Some(height)) = ground.column(x, z, 384) {
let clear = if ballistic { 10.0 } else if offmap { spec.clearance } else { 2.0 };
let rise = if ballistic {
let t = dist / horizontal(d.vel).length().max(0.1);
(d.vel.y * t - 0.5 * GRAVITY * t * t).max(0.0)
} else {
climb.gain(dist)
};
floor = floor.max(height + clear - rise);
} else {
ground.want_chunk((x >> 4, z >> 4));
pending = true;
}
}
(floor, pending)
}
impl Sim {
/// Orders a raid on `objects` (at least one point). A smart raid is planned over the next ticks
/// (each route found in full, a few a tick) and launched when its plan is ready.
@@ -321,6 +364,7 @@ impl Sim {
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, picture, leads) } else { Vec::new() };
let mut diversions_left = unit_strike_limit(total).saturating_sub(radar_jobs.iter().flatten().count() as u32);
let mut index = 0usize;
for (group, &(kind, count)) in order.kinds.iter().enumerate() {
let spec = kind.spec();
@@ -336,8 +380,12 @@ impl Sim {
index += 1;
let (target, at_sam) = match job {
Some((at, id)) => (at, Some(id)),
None => self.choose_target(kind, object, order.aim, &picture, &leads),
None if smart && diversions_left == 0 => (object, None),
None => self.choose_target(kind, object, order.aim, picture, leads),
};
if smart && job.is_none() && at_sam.is_some() {
diversions_left -= 1;
}
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 };
@@ -473,10 +521,7 @@ impl Sim {
from.y = floor;
d.pos.y = floor;
if spec.ballistic.is_some() {
let aimed = aim + d.err;
let flat = horizontal(aimed - from);
let time = (flat.length() / spec.speed).max(30.0);
d.vel = flat / time + DVec3::Y * ((aimed.y - from.y + 0.5 * GRAVITY * time * time) / time);
d.vel = ballistic_velocity(from, d.target, spec.speed);
}
}
}
@@ -523,6 +568,7 @@ impl Sim {
// Timing: smart raids arrive at once; others leave at once (a moment apart).
let now = self.tick;
let arrive = plan.done.iter().map(|(_, t, e, g, _)| t + e - g).fold(0.0, f64::max);
let unit_strikes = plan.done.iter().filter(|(d, ..)| d.aim.unit != 0).count() as u32;
for (mut d, time, early, gap, site) in plan.done {
d.smart = plan.smart;
let wait = if plan.smart { arrive - (early - gap) - time } else { gap + self.rng.f() * 40.0 };
@@ -543,6 +589,7 @@ impl Sim {
if plan.smart && !self.smart_legacy && !self.recon.sorties.is_empty() {
self.refresh = Some(ew::Refresh { deadline: self.tick + ew::REFRESH_WINDOW, reports: self.recon.reports });
}
self.diversions_left = unit_strike_limit(plan.total).saturating_sub(unit_strikes);
self.wave = Some(WaveStats {
kills: self.kills,
hits: self.hits,
@@ -591,10 +638,7 @@ impl Sim {
let err = self.aim_error(kind);
let target = target + err;
let (vel, flight) = if spec.ballistic.is_some() {
let flat = horizontal(target - from);
let time = (flat.length() / spec.speed).max(30.0);
let up = (target.y - from.y + 0.5 * GRAVITY * time * time) / time;
(flat / time + DVec3::Y * up, Flight::Ballistic)
(ballistic_velocity(from, target, spec.speed), Flight::Ballistic)
} else {
(dir.normalize_or(DVec3::NEG_Z) * spec.speed, Flight::Cruise)
};
@@ -663,12 +707,12 @@ impl Sim {
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];
const RANK: [DroneKind; 6] =
[DroneKind::Kh22, DroneKind::Zircon, 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);
let cap = unit_strike_limit(flat.len() as u32) as usize;
for (n, &(_, i)) in ranked.iter().take((radars.len() * want).min(cap)).enumerate() {
let radar = radars[n % radars.len()];
jobs[i] = Some((radar.1, radar.0));
@@ -681,7 +725,7 @@ impl Sim {
/// unit is the last observation — the place seen then, the type identified then — never where
/// the unit actually is or what it has become since.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact], leads: &[recon::Mark]) -> (DVec3, Option<u32>) {
if (picture.is_empty() && leads.is_empty()) || kind.spec().decoy || aim == Aim::Objects {
if kind.spec().class == Class::Ballistic || kind.spec().decoy || aim == Aim::Objects || (picture.is_empty() && leads.is_empty()) {
return (object, None);
}
let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> {
@@ -707,13 +751,12 @@ impl Sim {
return (at, Some(id));
}
}
let guns: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Gun || o.kind.is_some_and(|k| k.armed() && k.range() <= 300.0)).collect();
let guns: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Gun || o.kind.is_some_and(|k| k.armed() && k.range() <= 350.0)).collect();
let long: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Radar || o.kind.is_some_and(|k| k.range() >= 450.0)).collect();
let all: Vec<&Observation> = obs.iter().collect();
let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick_o(&guns, r).or_else(|| pick_o(&all, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick_o(&long, r),
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick_o(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick_o(&all, r),
_ => None,
};
@@ -737,13 +780,12 @@ 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<ew::Contact> = picture.iter().copied().filter(|c| c.kind.armed() && c.kind.range() <= 300.0).collect();
let guns: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind.armed() && c.kind.range() <= 350.0).collect();
let long: Vec<ew::Contact> =
picture.iter().copied().filter(|c| c.kind.range() >= 450.0 || c.kind == SamKind::Radar).collect();
let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick(&guns, r).or_else(|| pick(picture, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick(&long, r),
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r),
_ => None,
};
@@ -897,10 +939,7 @@ impl Sim {
(prices, cost)
}
/// Ticks an air start waits for the land under it to be told of.
const AIR_START_WAIT: u32 = 120;
/// A planned raid's drones take off when their time comes.
/// A planned raid's drones take off when their time comes.
pub(super) fn release_queue(&mut self, ground: &mut Ground, out: &mut Out) {
let now = self.tick;
if self.queue.iter().all(|q| q.0 > now) {
@@ -912,25 +951,24 @@ const AIR_START_WAIT: u32 = 120;
for (t, mut d) in go {
// A site's job leaves its site one at a time, from its stock; a destroyed or empty site cancels it.
let from_site = self.sites.site_of(d.id);
// An air start (an off-map site's drone) was planned over land nobody had read. It waits (a second or
// two) for the land under it to be known, and begins above it if that is higher than the start: else it
// is born inside a hill and crashes at once.
let air = from_site.is_some_and(|id| self.sites.list.iter().any(|s| s.id == id && s.offmap));
if air {
let clear = if d.kind.spec().ballistic.is_some() { 10.0 } else { d.kind.spec().clearance };
match ground.at(d.pos, now) {
None if d.age < AIR_START_WAIT => {
// The game has no chunk there: it is asked to load the ones round the start (and kept a while).
let c = ((d.pos.x.floor() as i32) >> 4, (d.pos.z.floor() as i32) >> 4);
for (dx, dz) in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] {
ground.want_chunk((c.0 + dx, c.1 + dz));
}
d.age += 1;
self.queue.push((t, d));
continue;
}
Some(g) if d.pos.y < g + clear => d.pos.y = g + clear,
_ => {}
if let Some(site) = from_site.and_then(|id| self.sites.get(id)).filter(|s| s.alive && s.stock > 0) {
if site.next_free > now {
self.queue.push((t, d));
continue;
}
let (floor, pending) = launch_floor(ground, &d, site.offmap);
if site.offmap && pending && d.age < AIR_START_WAIT {
d.age += 1;
self.queue.push((t, d));
continue;
}
d.pos.y = if site.offmap && pending {
floor.max(VANILLA_BUILD_CEILING + 10.0 + d.kind.spec().clearance)
} else {
floor
};
if d.flight == Flight::Ballistic {
d.vel = ballistic_velocity(d.pos, d.target, d.kind.spec().speed);
}
d.age = 0;
}
@@ -939,11 +977,7 @@ const AIR_START_WAIT: u32 = 120;
self.scout_launch(d.id, site, d.kind, d.pos);
}
match slot {
// Free: not a site's job. Air: an off-map site's drone, already in flight position.
sites::Slot::Free => {}
// The air start was planned over land nobody had read; if it is read by now and the land there is
// higher than the start, it begins above it (else it is born inside a hill and crashes at once).
sites::Slot::Air => {}
sites::Slot::Free | sites::Slot::Air => {}
sites::Slot::Busy => {
self.queue.push((t, d));
continue;
@@ -953,14 +987,6 @@ const AIR_START_WAIT: u32 = 120;
continue;
}
sites::Slot::Go => {
// On a slope the pad's side or the muzzle's far end can stand in the land that rises there: the
// drone leaves from above the land at its own column, not from inside the hill.
if let Some(g) = ground.at(d.pos, now)
&& d.pos.y < g + 1.5
&& g < d.pos.y + 40.0
{
d.pos.y = g + 1.5;
}
let dir = d.vel.normalize_or_zero();
out.sound(d.kind.launch_sound(), d.pos, 1.0, 1.0);
out.particles("minecraft:flame", d.pos - dir * 1.5, 0.15, -dir * 0.1, 0.02, 4);
@@ -1050,9 +1076,7 @@ const AIR_START_WAIT: u32 = 120;
it.from = from;
it.d.pos = from;
if spec.ballistic.is_some() {
let flat = horizontal(it.d.target - from);
let time = (flat.length() / spec.speed).max(30.0);
it.d.vel = flat / time + DVec3::Y * ((it.d.target.y - from.y + 0.5 * GRAVITY * time * time) / time);
it.d.vel = ballistic_velocity(from, it.d.target, spec.speed);
} else {
let pitch = site.class.pitch();
let dir = horizontal(it.d.target - from).normalize_or(site.inward());
@@ -1143,7 +1167,6 @@ fn recon_pick(kind: DroneKind, leads: &[recon::Mark], r: f64) -> Option<recon::M
let fits = |c: C| match kind {
DroneKind::Lancet => matches!(c, C::Gun | C::Launcher | C::Ew),
DroneKind::Kh22 | DroneKind::Zircon => matches!(c, C::Radar | C::Launcher | C::Ew),
DroneKind::Iskander | DroneKind::Kinzhal => matches!(c, C::Radar | C::Launcher),
DroneKind::Shahed | DroneKind::Geran3 => matches!(c, C::Radar | C::Launcher | C::Gun | C::Ew),
_ => false,
};
@@ -1201,6 +1224,43 @@ mod tests {
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 smart_waves_reserve_ballistics_and_the_bulk_of_the_raid_for_marked_objects() {
let mut sim = Sim::new(32);
let object = DVec3::new(0.0, 70.0, 0.0);
let kinds = [(DroneKind::Kinzhal, 2), (DroneKind::Iskander, 2), (DroneKind::Oreshnik, 1),
(DroneKind::Kh22, 10), (DroneKind::Shahed, 25)];
for (i, kind) in [SamKind::Radar, SamKind::Pantsir, SamKind::Radar, SamKind::Gepard].into_iter().enumerate() {
let id = sim.id();
let sam = Sam::new(id, kind, DVec3::new(100.0 * i as f64 + 50.0, 70.0, 0.0), 0.0);
sim.intel.observe(&sam, sim.tick, ew::Seen::Emission);
sim.sams.push(sam);
}
let order = RaidOrder { kinds: kinds.to_vec(), approach: Approach::Waves, dist: 400.0, aim: Aim::Smart };
let mut out = Out::default();
sim.order_raid(&order, &[object], &mut out);
let items = &sim.plan.as_ref().unwrap().items;
let ballistic: Vec<_> = items.iter().filter(|item| item.d.kind.spec().class == Class::Ballistic).collect();
assert_eq!(ballistic.len(), 5);
assert!(ballistic.iter().all(|item| item.d.aim.unit == 0 && item.aim.distance(object) < 6.0));
let attacks_on_units = items.iter().filter(|item| item.d.aim.unit != 0).count();
assert!((1..=10).contains(&attacks_on_units), "{attacks_on_units}");
}
#[test]
fn the_launch_floor_checks_the_near_slope_between_coarse_terrain_samples() {
let mut sim = Sim::new(2);
let d = sim.make_drone(DroneKind::Shahed, DVec3::new(0.5, 86.0, 0.5), DVec3::X, DVec3::new(400.0, 64.0, 0.5));
let mut ground = Ground::default();
let unattained = launch_floor(&mut ground, &d, true);
assert!(unattained.1);
let land = Land(|x, _| if x == 5 { 160 } else { 64 });
serve(&mut ground, &land, 1);
let (floor, pending) = launch_floor(&mut ground, &d, true);
assert!(!pending);
assert!(floor > 160.0, "{floor}");
}
#[test]
fn sead_uses_only_unexpired_observations_at_the_last_known_position() {
let mut sim = Sim::new(121);
+177 -4
View File
@@ -171,6 +171,10 @@ pub(super) struct Route {
near: ((i32, i32), f64),
expanded: usize,
goal_checked: bool,
truck: bool,
work_approach: bool,
work_wait: u32,
works: u8,
phase: Phase,
pts: Vec<DVec3>,
next: usize,
@@ -206,6 +210,10 @@ impl Route {
near: ((0, 0), f64::MAX),
expanded: 0,
goal_checked: slack > 0.0,
truck: kind == SamKind::Tzm && slack > 0.0,
work_approach: false,
work_wait: 0,
works: 0,
phase: Phase::Search,
pts: Vec::new(),
next: 0,
@@ -231,7 +239,12 @@ impl Route {
horizontal(self.centre(c) - self.dest).length()
}
fn is_goal(&self, c: (i32, i32)) -> bool {
if self.slack > 0.0 { self.to_goal(c) <= self.slack } else { c == self.cell_of(self.dest) }
if self.slack == 0.0 {
return c == self.cell_of(self.dest);
}
let Some(info) = self.cells.get(&c) else { return false };
let p = self.centre(c);
DVec3::new(p.x, f64::from(info.h), p.z).distance(self.dest) <= self.slack
}
/// Searches afresh from `pos`, keeping the cells found bad.
@@ -252,6 +265,8 @@ impl Route {
self.expanded = 0;
self.near = (self.start, f64::MAX);
self.partial = false;
self.work_approach = false;
self.work_wait = 0;
self.cells.insert(self.start, Info { h: pos.y as f32, ok: true });
self.g.insert(self.start, 0.0);
let h = self.heur(self.start);
@@ -311,10 +326,18 @@ impl Route {
let Some(column) = ground.column(x, z, 1024) else { pending = true; continue };
let Some(h) = column else { return Clearance::Blocked };
let dh = h - base;
if dh > STEP_UP || dh < -STEP_DOWN {
let up = if self.truck { 2.0 } else { STEP_UP };
if dh > up || dh < -STEP_DOWN {
return Clearance::Blocked;
}
let top = DVec3::new(f64::from(x) + 0.5, h + 0.05, f64::from(z) + 0.5);
if self.truck && dx == 0 && dz == 0 {
match ground.world.sweep(top, top - DVec3::Y * 0.55, false, now) {
world::Sweep::Hit { .. } => {}
world::Sweep::Clear => return Clearance::Blocked,
_ => { pending = true; continue; }
}
}
match ground.world.sweep(top, top + DVec3::Y * self.chassis.height, false, now) {
world::Sweep::Clear => {}
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => pending = true,
@@ -542,13 +565,117 @@ impl Route {
if self.phase == Phase::Search {
return Drive::Wait(Why::Map);
}
let reach = f64::from(self.cell) * 0.7;
let reach = if self.truck { 0.65 } else { f64::from(self.cell) * 0.7 };
while self.next + 1 < self.pts.len() && horizontal(self.pts[self.next] - pos).length() < reach {
self.next += 1;
}
Drive::Go(self.pts[self.next], self.next + 1 >= self.pts.len())
}
/// Let an automatic delivery approach the nearest reachable spot before trying local roadwork.
pub(super) fn approach_works(&mut self) -> bool {
if !self.truck || self.works >= 2 || self.near.0 == self.start
|| self.to_goal(self.start) - self.near.1 < f64::from(self.cell)
{
return false;
}
self.failed = None;
self.finish(self.near.0, true);
self.work_approach = true;
true
}
pub(super) fn work_approach(&self) -> bool {
self.work_approach
}
/// Make a short local crossing only after route search or motion finds a blockage.
/// Returns true while waiting for terrain data or after requesting the edits.
pub(super) fn try_works(&mut self, ground: &mut Ground, pos: DVec3, now: u64, out: &mut Out) -> bool {
if !self.truck || self.works >= 2 || self.work_wait >= 60 {
return false;
}
self.work_wait += 1;
let direction = horizontal(self.dest - pos);
let (dx, dz) = if direction.x.abs() >= direction.z.abs() {
(if direction.x >= 0.0 { 1 } else { -1 }, 0)
} else {
(0, if direction.z >= 0.0 { 1 } else { -1 })
};
let coord = |row: i32, side: i32| (
pos.x.floor() as i32 + dx * row + dz * side,
pos.z.floor() as i32 + dz * row + dx * side,
);
let width = self.chassis.radius.ceil() as i32;
let start = pos.y.round() as i32;
let (ex, ez) = coord(10, 0);
let Some(Some(end)) = ground.column(ex, ez, 1024) else {
ground.want_chunk((ex >> 4, ez >> 4));
return true;
};
let end = end.round() as i32;
if (end - start).abs() > 2 || !(-63..=320).contains(&start) || !(-63..=320).contains(&end) {
return false;
}
let mut commands = Vec::new();
for row in 1..=10 {
let level = start + ((end - start) as f64 * f64::from(row) / 10.0).round() as i32;
let mut deck = false;
for side in -width..=width {
let (x, z) = coord(row, side);
let Some(Some(top)) = ground.column(x, z, 1024) else {
ground.want_chunk((x >> 4, z >> 4));
return true;
};
let top = top.round() as i32;
if top > level + 2 {
return false;
}
let p = DVec3::new(f64::from(x) + 0.5, f64::from(level), f64::from(z) + 0.5);
match ground.world.sweep(p + DVec3::Y * 0.25, p - DVec3::Y * 0.25, false, now) {
world::Sweep::Hit { .. } if top >= level => {}
world::Sweep::Hit { .. } | world::Sweep::Clear => deck = true,
_ => return true,
}
if top > level {
// Only shallow natural cover is cleared. Vanilla fills preserve other materials.
for block in ["short_grass", "fern", "snow", "dirt", "grass_block", "sand", "gravel"] {
commands.push(format!("fill {x} {level} {z} {x} {} {z} minecraft:air replace minecraft:{block}", top - 1));
}
}
}
if deck {
let (ax, az) = coord(row, -width);
let (bx, bz) = coord(row, width);
let y = level - 1;
for block in ["air", "water"] {
commands.push(format!("fill {ax} {y} {az} {bx} {y} {bz} minecraft:cobblestone replace minecraft:{block}"));
}
}
}
if commands.is_empty() || out.commands.len() + commands.len() > 192 {
return false;
}
out.commands.extend(commands);
let centre = pos + DVec3::new(f64::from(dx * 5), 0.0, f64::from(dz * 5));
ground.forget(centre, 9);
let (cx, cz) = (centre.x.floor() as i32, centre.z.floor() as i32);
let mut chunks = Vec::new();
for x in (cx - 9).div_euclid(16)..=(cx + 9).div_euclid(16) {
for z in (cz - 9).div_euclid(16)..=(cz + 9).div_euclid(16) {
chunks.push((x, z));
}
}
ground.world.columns_changed(&chunks);
self.works += 1;
self.replans = 0;
self.failed = None;
self.bad.clear();
self.cells.clear();
self.restart(pos);
true
}
pub(super) fn searching(&self) -> bool {
self.phase == Phase::Search && self.failed.is_none()
}
@@ -634,7 +761,53 @@ mod tests {
ground.world.serve(src, sections, now);
}
/// Drives a Patriot from the origin to `to` over land of the given heights (water: a height over a lower floor).
#[test]
fn a_supply_truck_builds_a_bridge_then_crosses_it() {
struct Creek(HashSet<(i32, i32)>);
impl world::WorldSource for Creek {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
let floor = if (16..20).contains(&x) && !self.0.contains(&(x, z)) { 60 } else { 64 };
Some(y < floor)
}
}
let mut creek = Creek(HashSet::new());
let mut sim = Sim::new(5);
let from = DVec3::new(0.5, 64.0, 0.5);
let to = DVec3::new(80.5, 64.0, 0.5);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Tzm, from, 0.0));
sim.sams[0].job = Some(999);
assert!(sim.order_move_near(0, to, HANDOVER - 0.75));
let mut ground = Ground::default();
let mut out = Out::default();
for _ in 0..2000 {
sim.tick += 1;
let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, 64)).collect();
ground.answer(columns, sim.tick);
let sections = ground.world.take_wanted(sim.tick);
ground.world.serve(&creek, sections, sim.tick);
sim.step_moves(&mut ground, &mut out);
for command in out.commands.drain(..) {
let words: Vec<&str> = command.split_whitespace().collect();
if words[7] == "minecraft:cobblestone" && words[9] == "minecraft:water" {
let [ax, ay, az, bx, by, bz] = std::array::from_fn(|i| words[i + 1].parse::<i32>().unwrap());
assert_eq!((ay, by), (63, 63));
for x in ax.min(bx)..=ax.max(bx) {
for z in az.min(bz)..=az.max(bz) {
if (16..20).contains(&x) { creek.0.insert((x, z)); }
}
}
}
}
if !sim.sams[0].moving() { break; }
}
assert!(!creek.0.is_empty(), "the truck built no bridge");
assert!(sim.sams[0].pos.distance(to) <= HANDOVER, "{:?} {:?}", sim.sams[0].pos, out.messages);
assert!(out.messages.is_empty(), "{:?}", out.messages);
}
/// Drives a Patriot from the origin to `to` over land of the given heights.
fn march_kind<H: Fn(i32, i32) -> i32, B: Fn(i32, i32) -> i32>(kind: SamKind, height: H, floor: B, to: DVec3, ticks: u32) -> (Sim, Out, u32) {
let src = Src { height, floor };
let mut sim = Sim::new(3);
+10 -6
View File
@@ -22,6 +22,8 @@ use super::*;
/// Rays round a radar, and blocks between the land's samples along them.
const RAYS: usize = 48;
const STEP: f64 = 16.0;
/// The longest profiles use wider intervals to retain the same height-cache footprint.
const MAX_RAY_STEPS: f64 = 160.0;
/// How far units share their tracks (the network's data links).
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`.
@@ -33,8 +35,8 @@ pub const FIRE_QUALITY: u8 = 50;
pub(super) const GUN_PICK_AGE: u64 = 40;
/// A track older than this is shown as a forecast.
pub const FORECAST_AGE: u64 = 20;
/// Radio horizon: `HORIZON * (√mast + √height)` blocks.
pub(super) const HORIZON: f64 = 35.0;
/// The game's radio horizon: `HORIZON * (√mast + √height)` blocks.
pub(super) const HORIZON: f64 = 95.0;
/// Anything this near is seen (and heard), whatever hides it.
pub(super) const NEAR: f64 = 24.0;
@@ -43,11 +45,13 @@ pub(super) struct Horizon {
pub(super) rays: Vec<Vec<f32>>,
antenna: DVec3,
reach: f64,
step: f64,
}
impl Horizon {
fn build(antenna: DVec3, reach: f64, ground: &mut Ground, now: u64) -> Self {
let steps = (reach / STEP).ceil() as usize + 1;
let step = STEP.max(reach / MAX_RAY_STEPS);
let steps = (reach / step).ceil() as usize + 1;
let rays = (0..RAYS)
.map(|r| {
let a = r as f64 / RAYS as f64 * TAU;
@@ -55,7 +59,7 @@ impl Horizon {
let mut top = f32::NEG_INFINITY;
(1..=steps)
.map(|k| {
let d = k as f64 * STEP;
let d = k as f64 * step;
// Unknown land (not loaded, not answered yet) hides nothing.
if let Some(g) = ground.at(antenna + dir * d, now) {
top = top.max(((g - antenna.y) / d) as f32);
@@ -65,7 +69,7 @@ impl Horizon {
.collect()
})
.collect();
Self { rays, antenna, reach }
Self { rays, antenna, reach, step }
}
fn matches(&self, sam: &Sam) -> bool {
@@ -75,7 +79,7 @@ impl Horizon {
pub(super) fn hides(&self, antenna: DVec3, p: DVec3) -> bool {
let rel = p - antenna;
let flat = (rel.x * rel.x + rel.z * rel.z).sqrt();
let k = (flat / STEP) as usize;
let k = (flat / self.step) as usize;
if k == 0 {
return false;
}
+3 -3
View File
@@ -304,7 +304,7 @@ const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec {
eject_drag: 0.0,
pk: 0.9,
fuse: 4.0,
life: 240,
life: 360,
scale: 1.0,
flame: 1.0,
rear: 28.0,
@@ -344,7 +344,7 @@ const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec {
eject_drag: 0.07,
pk: 0.9,
fuse: 5.0,
life: 300,
life: 390,
scale: 1.5,
flame: 1.4,
rear: 30.0,
@@ -364,7 +364,7 @@ const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec {
eject_drag: 0.07,
pk: 0.95,
fuse: 6.0,
life: 320,
life: 430,
scale: 1.7,
flame: 1.6,
rear: 32.0,
+5 -3
View File
@@ -1189,7 +1189,8 @@ mod tests {
assert!(sim.queue.is_empty(), "the jobs are cancelled");
assert!(sim.launched < 14 && sim.launched >= before, "launched {}", sim.launched);
assert!(out.messages.iter().any(|m| m.contains("уничтожена") && m.contains("отменено")), "{:?}", out.messages);
assert!(sim.strikes.wrecks.len() == 1 && sim.fires.list.len() == 1, "a wreck and a fire");
assert_eq!(sim.strikes.wrecks.len(), 1);
assert!(sim.fires.list.iter().any(|fire| horizontal(fire.at - site.pos).length() <= TUNE.hit_r), "a fire at the destroyed site");
assert!(!sim.blasts.is_empty() || sim.tick > 0);
assert!(matches!(sim.strikes.get(id).unwrap().state, SiteState::Destroyed(_)));
assert!(sim.order_test_strike(id, player, &mut out).is_err(), "destroyed already");
@@ -1493,12 +1494,13 @@ mod tests {
k.est = Some(Estimate { pos: DVec2::new(0.0, 700.0), radius: 20.0, fix: true, bearing: 3.14, bearing_err: 0.01, origin: DVec2::ZERO });
sim.order_test_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
out.messages.clear();
let wrecks = sim.fires.list.len();
run(&mut sim, &mut ground, &mut out, 500);
assert!(out.messages.iter().any(|m| m.contains("за пределами") && m.contains("прекратились")), "{:?}", out.messages);
assert!(sim.queue.is_empty() && !sim.sites.get(id).unwrap().alive);
// Nothing drawn: no wreck, no fire, no blast of its own.
assert_eq!((sim.strikes.wrecks.len(), sim.fires.list.len()), (0, wrecks));
let site = sim.sites.get(id).unwrap();
assert!(sim.strikes.wrecks.is_empty());
assert!(sim.fires.list.iter().all(|fire| horizontal(fire.at - site.pos).length() > TUNE.hit_r));
}
#[test]
+14 -14
View File
@@ -8,7 +8,7 @@ const NAMED_TUBE_PIVOT: DVec3 = DVec3::new(0.0, -0.5, 1.5);
const UNIT_SPEC_PATRIOT: SamSpec = SamSpec {
name: "Patriot",
key: "patriot",
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 450.0, interval: 16 }),
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 950.0, interval: 16 }),
gun: None,
reload: 220,
scale: 1.3,
@@ -26,7 +26,7 @@ const UNIT_SPEC_PATRIOT: SamSpec = SamSpec {
mount: (0.69, 1.2),
pivot: DVec3::new(0.0, -0.5, 1.375),
muzzle: Muzzle::Patriot,
sensor: 585.0,
sensor: 1350.0,
mast: 5.0,
};
@@ -34,7 +34,7 @@ const UNIT_SPEC_GEPARD: SamSpec = SamSpec {
name: "Гепард",
key: "gepard",
missile: None,
gun: Some(GunSpec { range: 135.0, track: 195.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
gun: Some(GunSpec { range: 180.0, track: 260.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
reload: 160,
scale: 1.25,
rest_pitch: 0.0,
@@ -51,15 +51,15 @@ const UNIT_SPEC_GEPARD: SamSpec = SamSpec {
mount: (1.55, 0.25),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 255.0,
sensor: 335.0,
mast: 3.0,
};
const UNIT_SPEC_PANTSIR: SamSpec = SamSpec {
name: "Панцирь-С1",
key: "pantsir",
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) }),
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 330.0, interval: 14 }),
gun: Some(GunSpec { range: 125.0, track: 185.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
reload: 280,
scale: 1.3,
rest_pitch: 0.0,
@@ -76,14 +76,14 @@ const UNIT_SPEC_PANTSIR: SamSpec = SamSpec {
mount: (1.35, 0.69),
pivot: DVec3::ZERO,
muzzle: Muzzle::Pantsir,
sensor: 292.0,
sensor: 450.0,
mast: 4.0,
};
const UNIT_SPEC_S400: SamSpec = SamSpec {
name: "С-400",
key: "s400",
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 720.0, interval: 20 }),
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 1300.0, interval: 20 }),
gun: None,
reload: 420,
scale: 1.5,
@@ -101,14 +101,14 @@ const UNIT_SPEC_S400: SamSpec = SamSpec {
mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 2, 7.0),
sensor: 936.0,
sensor: 1750.0,
mast: 5.0,
};
const UNIT_SPEC_S500: SamSpec = SamSpec {
name: "С-500",
key: "s500",
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1050.0, interval: 20 }),
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1850.0, interval: 20 }),
gun: None,
reload: 520,
scale: 1.6,
@@ -126,7 +126,7 @@ const UNIT_SPEC_S500: SamSpec = SamSpec {
mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 1, 9.5),
sensor: 1365.0,
sensor: 2450.0,
mast: 5.0,
};
@@ -208,7 +208,7 @@ const UNIT_SPEC_BUK: SamSpec = SamSpec {
const UNIT_SPEC_TOR: SamSpec = SamSpec {
name: "Тор-М2",
key: "tor",
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 240.0, interval: 8 }),
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 350.0, interval: 8 }),
gun: None,
reload: 300,
scale: 1.3,
@@ -226,7 +226,7 @@ const UNIT_SPEC_TOR: SamSpec = SamSpec {
mount: (1.5, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::Cells,
sensor: 315.0,
sensor: 475.0,
mast: 3.5,
};
@@ -276,7 +276,7 @@ const UNIT_SPEC_RADAR: SamSpec = SamSpec {
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 2550.0,
sensor: 3800.0,
mast: 16.0,
};
+99 -9
View File
@@ -79,7 +79,7 @@ pub(super) const SHY_TICKS: u64 = 120;
/// 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).
pub(super) const LAST_CHANCE_TICKS: f64 = 200.0;
pub(super) const LAST_CHANCE_TICKS: f64 = 120.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
@@ -327,6 +327,54 @@ 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)
}
/// A shorter-range role weapon with a usable track and time to engage.
fn has_role_cover(&self, fallback: &Sam, d: &Drone) -> bool {
let now = self.tick;
let lead = (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
|| sam.kind.range() >= reach
{
return false;
}
let Some(track) = sam.track(d.id) else { return false };
if track.class.class().is_none() || !allowed(sam.roles, track, now, d)
|| sam.doctrine.area_blocks(sam.pos, track, now) != 0
{
return false;
}
let at = track.est(now);
let soon = at + track.vel * 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
});
gun || spec.missile.as_ref().is_some_and(|load| {
let authority = if sam.mode == battery::SamMode::LauncherOnly {
self.sams.iter().any(|radar| radar_cue(sam, &[radar], d.id, now))
} else {
track.own_authorizes(now)
};
sam.missiles > 0 && f64::from(sam.cooldown) <= lead && sam.part(Part::Launcher) > 0.0
&& 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))
&& authority
})
})
}
/// The saturation audit: every armed system against every alive drone, attributed to the first
/// ground that stops the shot. Reads the tracks' estimates and provenance, never the target's
/// own class or velocity (#133).
@@ -372,7 +420,7 @@ impl Sim {
}
let est = tr.class;
let free = claimed(d, &missile_on, sam.target);
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, d, free);
let chance = blocks & ROLE != 0 && self.last_chance_for(sam, est, d, free);
if blocks & ROLE != 0 && !chance {
a.role += 1;
continue;
@@ -606,7 +654,7 @@ impl Sim {
.filter(|d| {
d.alive()
&& (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles))
|| last_chance(self.last_chance, sam.roles, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target)))
|| self.last_chance_for(sam, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target)))
})
.max_by(|a, b| {
let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, now) == 0);
@@ -639,7 +687,7 @@ impl Sim {
let est = tr.class;
let blocks = target_blocks(sam.roles, Some(tr), now, t);
let claimed_now = claimed(t, &missile_on, sam.target);
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, t, claimed_now);
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));
}
@@ -837,7 +885,6 @@ impl Sim {
v.push(battle_check(self.battle_reason(index)));
return v;
}
let logistics = self.logistics();
let (missile_on, guns_on) = engagement_counts(&self.sams);
let alive = self.drones.iter().filter(|d| d.alive()).count();
let now = self.tick;
@@ -881,7 +928,7 @@ impl Sim {
// Of what the system's picture holds: a track of its roles' classes (or not yet
// classified), or a known out-of-role one about to hit (the last chance) — never
// the target's own class (#133).
.filter(|d| d.alive() && (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles)) || last_chance(self.last_chance, sam.roles, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target))))
.filter(|d| d.alive() && (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles)) || self.last_chance_for(sam, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target))))
.max_by(|a, b| {
// What the doctrine lets the system shoot at comes first; then the most threatening.
let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, self.tick) == 0);
@@ -917,7 +964,7 @@ impl Sim {
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 && last_chance(self.last_chance, sam.roles, est, t, first_claim);
let chance = blocks & ROLE != 0 && self.last_chance_for(sam, est, t, first_claim);
let role_text = if blocks & ROLE == 0 {
match est {
ClassEst::Unknown => "роль: тип не определён — цель ведётся по общим правилам, классовые ограничения не применяются".to_string(),
@@ -1004,7 +1051,7 @@ impl Sim {
let supply = if sam.reloading > 0 {
format!("перезарядка, ещё {:.1} с", sam.reloading as f64 / 20.0)
} else if sam.empty {
if logistics { "пуст, ждёт машину-заряжающую (ТЗМ) со склада".into() } else { "пуст".into() }
"пуст, ждёт пополнения со склада или ТЗМ".into()
} else {
"боезапас есть".into()
};
@@ -1195,6 +1242,46 @@ mod tests {
sim.sams[0].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: now, own_tick: now, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false });
}
#[test]
fn last_chance_leaves_a_drone_for_a_ready_short_range_battery() {
let (mut sim, _, _, _) = setup(SamKind::S500);
sim.tick = 100;
shahed_at(&mut sim, 45.0);
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
let id = sim.id();
let mut gun = Sam::new(id, SamKind::Gepard, DVec3::new(5.0, 70.0, 0.0), 0.0);
gun.tracks.push(Track { source: id, ..sim.sams[0].tracks[0] });
sim.sams.push(gun);
let chance = |s: &Sim| s.last_chance_for(&s.sams[0], ClassEst::Firm(Class::Drone), &s.drones[0], 0);
assert!(!chance(&sim));
sim.sams[1].bursts = 0;
assert!(chance(&sim), "an empty gun may not block the fallback shot");
sim.sams[1].bursts = 20;
sim.sams[1].pos.x = 500.0;
assert!(chance(&sim), "a gun outside engagement range may not block the fallback shot");
}
#[test]
fn an_empty_s400_stays_empty_until_external_stock_pays_for_a_reload() {
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
sim.sams[0].missiles = 0;
for _ in 0..900 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
assert_eq!((sim.sams[0].missiles, sim.sams[0].reloading), (0, 0));
assert!(sim.sams[0].empty);
let id = sim.id();
let mut depot = Sam::new(id, SamKind::Depot, DVec3::new(10.0, 70.0, 0.0), 0.0);
depot.cargo = 1;
sim.sams.push(depot);
for _ in 0..450 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
assert_eq!((sim.sams[0].missiles, sim.sams[1].cargo), (4, 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.
@@ -1558,7 +1645,10 @@ mod tests {
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, -300.0), DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
let target = sim.drones[0].id;
let now = 1;
sim.sams[0].tracks.push(seeded_track(target, radar, 0, battery::Measure::Search, now));
sim.sams[0].tracks.push(Track {
class: ClassEst::Firm(Class::Cruise),
..seeded_track(target, radar, 0, battery::Measure::Search, now)
});
assert_eq!(sim.battle_reason(0).expect("a reason").kind, BattleKind::AwaitingTrack);
// Каналы заняты: the supporting radar has the contact but both tracked-contact channels
+6 -14
View File
@@ -1016,11 +1016,9 @@ frames = 10
[[step]]
command = "airdef stats"
# Baseline re-measured after the #145 fix (engine 2bcce64): the embedded-cue flood of #134 is
# removed, restoring the intercepts. The pre-#133 522 used the target's true velocity, which the
# measurement-only contract (#133) forbids; ~325 is the restored range. See
# docs/measurements/issue-145-intercept-regression.json for the A/B decomposition.
expect.feedback = "В воздухе: 184, ракет: 4, ПВО: 64, сбито: 325, поражений: 2011, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 4672 секций (219 КБ), запросов 13570, неизвестно 0, лучей 335118 (ударов 8088, неизв. 158), клеток 2162018; взрывы в блоках: 2041 (подтверждено 0, без перемен 148, нет чанка 1754), чужих ответов 0"
# Finite-ammunition checkpoint after extending the game ranges. With no depot,
# the two waves exhaust the initial stock. The previous baseline used free reloads.
expect.feedback = "В воздухе: 184, ракет: 0, ПВО: 64, сбито: 135, поражений: 2161, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 4881 секций (228 КБ), запросов 12163, неизвестно 0, лучей 303646 (ударов 1226, неизв. 135), клеток 1944815; взрывы в блоках: 2176 (подтверждено 0, без перемен 88, нет чанка 1946), чужих ответов 0"
# The Windows #122 path: a Smart order through the UI launch function (`airdef raid`
# is the wave screen's ПУСК button handler) with a fat intel log and EW up — twice.
@@ -1067,12 +1065,6 @@ frames = 100
[[step]]
command = "airdef stats"
# Re-measured on the shipped engine 8e711f969 with #146 (one knowledge snapshot per Smart order)
# integrated: the two late Smart raids plan over the versioned picture, so their outcome and world
# queries differ from the #145 agent's pre-#146 measurement (385/2472 on engine 2bcce64). The
# tick-2102 checkpoint above is unaffected by #146 and matches on both engines.
# Re-measured again on engine acfb379aa (the DLSS temporal-stability pin): the late Smart raids'
# outcome shifted with the engine's host answers (417/2463, 7 in the air); the tick-2102 checkpoint
# is unchanged. The ground-oom memory bounds (agent/ground-oom) produce this exact same string —
# they do not move this fight.
expect.feedback = "В воздухе: 7, ракет: 0, ПВО: 68, сбито: 417, поражений: 2463, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 8527 секций (399 КБ), запросов 19444, неизвестно 0, лучей 413900 (ударов 11127, неизв. 1084), клеток 3197805; взрывы в блоках: 2501 (подтверждено 0, без перемен 194, нет чанка 2305), чужих ответов 0"
# The two late Smart raids also run with finite stock. At this point the
# launchers still have no supply depot.
expect.feedback = "В воздухе: 24, ракет: 0, ПВО: 68, сбито: 143, поражений: 2688, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 7307 секций (342 КБ), запросов 16768, неизвестно 0, лучей 400901 (ударов 2567, неизв. 971), клеток 3894960; взрывы в блоках: 2783 (подтверждено 0, без перемен 145, нет чанка 2638), чужих ответов 0"
+10 -3
View File
@@ -96,17 +96,17 @@ struct Run {
fn run() -> Run {
// Six raids 1500 ticks apart: the sky clears between them, so recordings close and the
// kept replays pile up (the journal's and the poses' budgets are per recording).
run_with(&[(3, 12, Aim::Objects), (1503, 12, Aim::Objects), (3003, 12, Aim::Objects), (4503, 12, Aim::Objects), (6003, 12, Aim::Objects), (7503, 12, Aim::Objects), (1203, 10, Aim::Smart)], TICKS)
run_with(&[(3, 12, Aim::Objects), (1503, 12, Aim::Objects), (3003, 12, Aim::Objects), (4503, 12, Aim::Objects), (6003, 12, Aim::Objects), (7503, 12, Aim::Objects), (1203, 10, Aim::Smart)], TICKS, false)
}
/// The extreme continuous load: waves overlap, the sky never clears, one recording runs long
/// and the flight tracks reach their points budget (the thinning), with over a thousand objects
/// airborne at once — well past the crash's >200.
fn run_extreme() -> Run {
run_with(&[(3, 40, Aim::Objects), (103, 40, Aim::Objects), (203, 40, Aim::Objects), (1003, 40, Aim::Objects), (2003, 40, Aim::Objects), (3003, 40, Aim::Objects), (4003, 40, Aim::Objects), (5003, 40, Aim::Objects)], 8000)
run_with(&[(3, 40, Aim::Objects), (103, 40, Aim::Objects), (203, 40, Aim::Objects), (1003, 40, Aim::Objects), (2003, 40, Aim::Objects), (3003, 40, Aim::Objects), (4003, 40, Aim::Objects), (5003, 40, Aim::Objects)], 8000, true)
}
fn run_with(waves: &[(u64, u32, Aim)], ticks: u64) -> Run {
fn run_with(waves: &[(u64, u32, Aim)], ticks: u64, sustained_supply: bool) -> Run {
let mut sim = Sim::new(SEED);
let mut ground = Ground::default();
let mut out = Out::default();
@@ -118,6 +118,13 @@ fn run_with(waves: &[(u64, u32, Aim)], ticks: u64) -> Run {
for now in 1..=ticks {
if now == 3 {
deploy(&mut sim);
if sustained_supply {
// Sustained fire needs physical stock under finite ammunition rules.
for _ in 0..3 {
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Depot, DEPLOY_AT, 0.0));
}
}
}
for &(at, count, aim) in waves {
if now == at {
+11 -12
View File
@@ -124,35 +124,34 @@ fn run_to(ticks: u64) -> Sim {
sim
}
/// The restored checkpoint, measured on this native replica with the #145 fix in place. The WASM
/// budget fixture measures 325 intercepts / 2011 hits at the same tick on the same fix; the replica
/// replays the same fight but answers render rays with the host tracer one tick later, and the
/// combat is chaotic, so its counters sit a few apart (314 / 2022). Both are deterministic; the
/// WASM run is the authoritative fuel/perf measurement, this one the fast fight-and-audit guard.
const REPLICA_KILLS: u32 = 314;
const REPLICA_HITS: u32 = 2022;
/// No depot is deployed in this fixture. Both waves spend the initial ammunition;
/// the checkpoint records the combat outcome with finite magazines and the extended ranges.
const REPLICA_KILLS: u32 = 144;
const REPLICA_HITS: u32 = 2152;
const REPLICA_AIRBORNE: usize = 184;
const REPLICA_FIRED: u32 = 355;
#[test]
fn checkpoint_replica_holds_the_restored_intercept_count() {
fn checkpoint_replica_matches_the_finite_ammunition_baseline() {
let sim = run_to(CHECKPOINT);
let airborne = sim.drones.iter().filter(|d| d.alive()).count();
let fired: u32 = sim.sams.iter().map(|s| s.fired).sum();
eprintln!(
"checkpoint tick {}: airborne {airborne}, missiles {}, kills {}, hits {}, fired {}",
sim.tick,
sim.missiles.len(),
sim.kills,
sim.hits,
sim.sams.iter().map(|s| s.fired).sum::<u32>()
fired
);
eprintln!("tally: {}", sim.tally.text());
eprintln!("audit: {}", sim.launch_audit().text());
assert_eq!(airborne, REPLICA_AIRBORNE, "the sky at the checkpoint");
assert_eq!(sim.kills, REPLICA_KILLS, "intercepts at the checkpoint (deterministic replica baseline)");
assert_eq!(sim.hits, REPLICA_HITS, "hits at the checkpoint");
// The regression guard: the #134 embedded-cue flood dropped this replica to 247 intercepts
// (the WASM run to 243). Restored, it must stay well above that broken count.
assert!(sim.kills >= 300, "the intercept count fell back toward the #145 regression: {}", sim.kills);
assert_eq!(fired, REPLICA_FIRED, "launches at the checkpoint");
assert!(sim.sams.iter().all(|s| s.fired <= s.kind.missile_magazine().unwrap_or(0)),
"a battery fired more than its initial load with no depot");
}
#[test]
+17 -17
View File
@@ -298,7 +298,7 @@
"kind": "Patriot",
"key": "patriot",
"name": "Patriot",
"missile": {"kind": "Pac3", "magazine": 4, "min": 10.0, "max": 450.0, "interval": 16},
"missile": {"kind": "Pac3", "magazine": 4, "min": 10.0, "max": 950.0, "interval": 16},
"gun": null,
"reload": 220,
"scale": 1.3,
@@ -316,7 +316,7 @@
"mount": [0.69, 1.2],
"pivot": [0.0, -0.5, 1.375],
"muzzle": {"type": "patriot"},
"sensor": 585.0,
"sensor": 1350.0,
"mast": 5.0
},
{
@@ -324,7 +324,7 @@
"key": "gepard",
"name": "Гепард",
"missile": null,
"gun": {"range": 135.0, "track": 195.0, "p": 0.3, "bursts": 160, "shell": 10.0, "slew": [0.22, 0.16]},
"gun": {"range": 180.0, "track": 260.0, "p": 0.3, "bursts": 160, "shell": 10.0, "slew": [0.22, 0.16]},
"reload": 160,
"scale": 1.25,
"rest_pitch": 0.0,
@@ -341,15 +341,15 @@
"mount": [1.55, 0.25],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"},
"sensor": 255.0,
"sensor": 335.0,
"mast": 3.0
},
{
"kind": "Pantsir",
"key": "pantsir",
"name": "Панцирь-С1",
"missile": {"kind": "M57e6", "magazine": 12, "min": 25.0, "max": 225.0, "interval": 14},
"gun": {"range": 90.0, "track": 135.0, "p": 0.25, "bursts": 140, "shell": 9.0, "slew": [0.25, 0.18]},
"missile": {"kind": "M57e6", "magazine": 12, "min": 25.0, "max": 330.0, "interval": 14},
"gun": {"range": 125.0, "track": 185.0, "p": 0.25, "bursts": 140, "shell": 9.0, "slew": [0.25, 0.18]},
"reload": 280,
"scale": 1.3,
"rest_pitch": 0.0,
@@ -366,14 +366,14 @@
"mount": [1.35, 0.69],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "pantsir"},
"sensor": 292.0,
"sensor": 450.0,
"mast": 4.0
},
{
"kind": "S400",
"key": "s400",
"name": "С-400",
"missile": {"kind": "M48n6", "magazine": 4, "min": 30.0, "max": 720.0, "interval": 20},
"missile": {"kind": "M48n6", "magazine": 4, "min": 30.0, "max": 1300.0, "interval": 20},
"gun": null,
"reload": 420,
"scale": 1.5,
@@ -391,14 +391,14 @@
"mount": [0.7, 1.45],
"pivot": {"ref": "tube_pivot"},
"muzzle": {"type": "grid", "cols": 2, "rows": 2, "size": 7.0},
"sensor": 936.0,
"sensor": 1750.0,
"mast": 5.0
},
{
"kind": "S500",
"key": "s500",
"name": "С-500",
"missile": {"kind": "M77n6", "magazine": 2, "min": 40.0, "max": 1050.0, "interval": 20},
"missile": {"kind": "M77n6", "magazine": 2, "min": 40.0, "max": 1850.0, "interval": 20},
"gun": null,
"reload": 520,
"scale": 1.6,
@@ -416,7 +416,7 @@
"mount": [0.7, 1.45],
"pivot": {"ref": "tube_pivot"},
"muzzle": {"type": "grid", "cols": 2, "rows": 1, "size": 9.5},
"sensor": 1365.0,
"sensor": 2450.0,
"mast": 5.0
},
{
@@ -498,7 +498,7 @@
"kind": "Tor",
"key": "tor",
"name": "Тор-М2",
"missile": {"kind": "M9m338", "magazine": 8, "min": 8.0, "max": 240.0, "interval": 8},
"missile": {"kind": "M9m338", "magazine": 8, "min": 8.0, "max": 350.0, "interval": 8},
"gun": null,
"reload": 300,
"scale": 1.3,
@@ -516,7 +516,7 @@
"mount": [1.5, 0.0],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "cells"},
"sensor": 315.0,
"sensor": 475.0,
"mast": 3.5
},
{
@@ -566,7 +566,7 @@
"mount": [0.0, 0.0],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"},
"sensor": 2550.0,
"sensor": 3800.0,
"mast": 16.0
},
{
@@ -708,7 +708,7 @@
"eject_drag": 0.0,
"pk": 0.9,
"fuse": 4.0,
"life": 240,
"life": 360,
"scale": 1.0,
"flame": 1.0,
"rear": 28.0,
@@ -748,7 +748,7 @@
"eject_drag": 0.07,
"pk": 0.9,
"fuse": 5.0,
"life": 300,
"life": 390,
"scale": 1.5,
"flame": 1.4,
"rear": 30.0,
@@ -768,7 +768,7 @@
"eject_drag": 0.07,
"pk": 0.95,
"fuse": 6.0,
"life": 320,
"life": 430,
"scale": 1.7,
"flame": 1.6,
"rear": 32.0,
+1 -1
View File
@@ -714,7 +714,7 @@ def test_wasm():
BUDGET_SCENARIO = "tests/budgets/wasm_flat_budget.toml"
BUDGET_ASSERTED_SHA256 = "5313a882621cd833ecd5945c0d46b88cdce47388db210beb8dc9a4912efa3329"
BUDGET_ASSERTED_SHA256 = "9122cdac879f7db79fe10de3d0bef4646e3d7391e3716f6f46c0c19c07564634"
def fuel_measurements(output):