Add typed depot logistics visibility, auto-strike, 16-block reach, and web panel controls
build / mod (push) Failing after 15s
build / mod (push) Failing after 15s
This commit is contained in:
+112
-13
@@ -1,6 +1,6 @@
|
||||
//! Player-facing labels for battery configuration and status.
|
||||
use crate::sim::battery::{BatteryStatus, RadarProfile, SamMode};
|
||||
use crate::sim::{Sam, SamKind};
|
||||
use crate::sim::{AmmoKind, Sam, SamKind, SupplyStatus, SupplySummary};
|
||||
|
||||
/// One profile's functions in a line the player can read.
|
||||
pub fn radar_profile_line(profile: RadarProfile) -> String {
|
||||
@@ -49,14 +49,22 @@ pub fn sam_status(sam: &Sam, now: u64) -> String {
|
||||
return text + " " + &sam.state.name().to_lowercase();
|
||||
}
|
||||
match sam.kind {
|
||||
SamKind::Depot => return format!("{text}: {} перезарядок, RM48U {}, снятых ПВО {}", sam.cargo, sam.ground_stock, sam.air_48n6_stock),
|
||||
SamKind::Tzm => return format!(
|
||||
"{text}: на борту {}/2, RM48U {}, снятых ПВО {}{}",
|
||||
sam.cargo,
|
||||
sam.ground_stock,
|
||||
sam.air_48n6_stock,
|
||||
if sam.return_cargo { ", везёт RM48U на склад" } else if sam.job().is_some() { ", в пути" } else { "" }
|
||||
),
|
||||
SamKind::Depot => {
|
||||
let kinds = sam.ammo_stock.non_zero().count();
|
||||
return format!("{text}: {} БК ({} видов), RM48U {}, снятых ПВО {}", sam.ammo_stock.total(), kinds, sam.ground_stock, sam.air_48n6_stock);
|
||||
}
|
||||
SamKind::Tzm => {
|
||||
let carried: Vec<_> = sam.ammo_stock.non_zero().map(|(k, n)| format!("{}×{n}", k.short_name())).collect();
|
||||
let cargo_detail = if carried.is_empty() { String::new() } else { format!(" ({})", carried.join(", ")) };
|
||||
return format!(
|
||||
"{text}: на борту {}/{}{cargo_detail}, RM48U {}, снятых ПВО {}{}",
|
||||
sam.ammo_stock.total(),
|
||||
crate::sim::TRUCK_CAPACITY,
|
||||
sam.ground_stock,
|
||||
sam.air_48n6_stock,
|
||||
if sam.return_cargo { ", везёт RM48U на склад" } else if sam.job().is_some() { ", в пути" } else { "" }
|
||||
);
|
||||
}
|
||||
SamKind::Ew => {
|
||||
let state = if sam.ew_on { "ГЛУШИТ" } else if sam.ew_lock { "остывает" } else { "готова" };
|
||||
return format!("{text}: {state}, нагрев {:.0}%", sam.heat * 100.0);
|
||||
@@ -114,6 +122,72 @@ pub fn sam_status(sam: &Sam, now: u64) -> String {
|
||||
text
|
||||
}
|
||||
|
||||
/// Human-readable resupply / reload reason for one unit card or status command.
|
||||
pub fn supply_line(status: &SupplyStatus) -> String {
|
||||
match status {
|
||||
SupplyStatus::Reloading { ticks_left } => format!("Перезарядка: {} с", ticks_left.div_ceil(20)),
|
||||
SupplyStatus::TruckEnRoute { truck_num, eta_ticks, rm48u: true, returning: true, .. } => {
|
||||
format!("ТЗМ №{truck_num} едет забрать RM48U (~{} с)", eta_ticks.div_ceil(20))
|
||||
}
|
||||
SupplyStatus::TruckEnRoute { truck_num, eta_ticks, rm48u: true, returning: false, .. } => {
|
||||
format!("ТЗМ №{truck_num} везёт RM48U (~{} с)", eta_ticks.div_ceil(20))
|
||||
}
|
||||
SupplyStatus::TruckEnRoute { truck_num, eta_ticks, rm48u: false, .. } => {
|
||||
format!("ТЗМ №{truck_num} везёт БК (~{} с)", eta_ticks.div_ceil(20))
|
||||
}
|
||||
SupplyStatus::TruckFetching { truck_num, depot_num, eta_ticks, rm48u: true, .. } => {
|
||||
format!("ТЗМ №{truck_num} едет на склад №{depot_num} за RM48U (~{} с)", eta_ticks.div_ceil(20))
|
||||
}
|
||||
SupplyStatus::TruckFetching { truck_num, depot_num, eta_ticks, rm48u: false, .. } => {
|
||||
format!("ТЗМ №{truck_num} едет на склад №{depot_num} за БК (~{} с)", eta_ticks.div_ceil(20))
|
||||
}
|
||||
SupplyStatus::NoRm48uStock => "Ждёт RM48U: на складах и в ТЗМ нет ударных ракет".to_string(),
|
||||
SupplyStatus::OutOfStock { missing } => {
|
||||
let names: Vec<_> = missing.into_iter().flatten().map(|k| k.short_name()).collect();
|
||||
format!("Ждёт БК ({}): нет на складах и в ТЗМ", names.join(", "))
|
||||
}
|
||||
SupplyStatus::NoTruck { rm48u } => {
|
||||
format!("Ждёт {}: нет исправной ТЗМ", if *rm48u { "RM48U" } else { "БК" })
|
||||
}
|
||||
SupplyStatus::RouteBlocked { rm48u } => {
|
||||
format!("Ждёт {}: ТЗМ не может проехать", if *rm48u { "RM48U" } else { "БК" })
|
||||
}
|
||||
SupplyStatus::WaitingForTruck { rm48u: true, returning: true } => "Ожидает свободную ТЗМ для вывоза RM48U".to_string(),
|
||||
SupplyStatus::WaitingForTruck { rm48u: true, returning: false } => "Ожидает свободную ТЗМ для доставки RM48U".to_string(),
|
||||
SupplyStatus::WaitingForTruck { rm48u: false, .. } => "Ожидает свободную ТЗМ".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Multi-line aggregate summary of depot & truck stocks for `/airdef stocks`.
|
||||
pub fn stock_summary_lines(summary: &SupplySummary) -> Vec<String> {
|
||||
let mut lines = vec![
|
||||
format!(
|
||||
"Склады: {} · ТЗМ: {} (занято {}) · ждут БК: {}, RM48U: {}, перезарядка: {}",
|
||||
summary.depots_alive, summary.trucks_alive, summary.trucks_busy, summary.waiting_ammo, summary.waiting_rm48u, summary.reloading
|
||||
),
|
||||
format!(
|
||||
"RM48U: на складах {}, в ТЗМ {}, в ПУ {}",
|
||||
summary.rm48u_depot, summary.rm48u_truck, summary.rm48u_loaded
|
||||
),
|
||||
];
|
||||
let entries: Vec<String> = AmmoKind::ALL
|
||||
.into_iter()
|
||||
.filter_map(|k| {
|
||||
let d = summary.depot_ammo[k.index()];
|
||||
let t = summary.truck_ammo[k.index()];
|
||||
(d + t > 0).then(|| format!("{} {} ({}+{})", k.short_name(), d + t, d, t))
|
||||
})
|
||||
.collect();
|
||||
if entries.is_empty() {
|
||||
lines.push("БК ПВО на складах и в ТЗМ исчерпан".to_string());
|
||||
} else {
|
||||
for chunk in entries.chunks(3) {
|
||||
lines.push(chunk.join(" · "));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -150,15 +224,16 @@ mod tests {
|
||||
assert_eq!(sam_status(&radar, 0), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
|
||||
|
||||
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
|
||||
depot.cargo = 2;
|
||||
depot.clear_ammo();
|
||||
depot.set_ammo(crate::sim::AmmoKind::S400Missile, 2);
|
||||
depot.ground_stock = 3;
|
||||
depot.air_48n6_stock = 1;
|
||||
assert_eq!(sam_status(&depot, 0), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1");
|
||||
assert_eq!(sam_status(&depot, 0), "Склад боеприпасов: 2 БК (1 видов), RM48U 3, снятых ПВО 1");
|
||||
|
||||
let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0);
|
||||
tzm.cargo = 1;
|
||||
tzm.set_ammo(crate::sim::AmmoKind::TorMissile, 1);
|
||||
tzm.return_cargo = true;
|
||||
assert_eq!(sam_status(&tzm, 0), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад");
|
||||
assert_eq!(sam_status(&tzm, 0), "ТЗМ: на борту 1/2 (Тор×1), RM48U 0, снятых ПВО 0, везёт RM48U на склад");
|
||||
|
||||
let mut ew = Sam::new(7, SamKind::Ew, DVec3::ZERO, 0.0);
|
||||
ew.ew_on = true;
|
||||
@@ -210,4 +285,28 @@ mod tests {
|
||||
assert_eq!(status(BatteryStatus::Launcher { index: 3, kind: SamKind::S500, mode: SamMode::LauncherOnly, linked: false }), "№4 С-500: launcher, нет связанной РЛС сопровождения");
|
||||
assert_eq!(status(BatteryStatus::Launcher { index: 4, kind: SamKind::S400, mode: SamMode::Integrated, linked: false }), "№5 С-400: integrated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_supply_status_and_stock_summary() {
|
||||
assert_eq!(supply_line(&SupplyStatus::Reloading { ticks_left: 41 }), "Перезарядка: 3 с");
|
||||
assert_eq!(
|
||||
supply_line(&SupplyStatus::TruckEnRoute { truck_num: 2, truck_id: 9, eta_ticks: 100, rm48u: false, returning: false }),
|
||||
"ТЗМ №2 везёт БК (~5 с)"
|
||||
);
|
||||
assert_eq!(
|
||||
supply_line(&SupplyStatus::TruckFetching { truck_num: 1, truck_id: 8, depot_num: 3, eta_ticks: 240, rm48u: true }),
|
||||
"ТЗМ №1 едет на склад №3 за RM48U (~12 с)"
|
||||
);
|
||||
assert_eq!(
|
||||
supply_line(&SupplyStatus::OutOfStock { missing: [Some(AmmoKind::PantsirMissile), Some(AmmoKind::PantsirGun)] }),
|
||||
"Ждёт БК (Панцирь рак, Панцирь пуш): нет на складах и в ТЗМ"
|
||||
);
|
||||
let mut sum = SupplySummary { depots_alive: 1, trucks_alive: 1, trucks_busy: 1, waiting_ammo: 1, waiting_rm48u: 0, reloading: 0, rm48u_depot: 2, rm48u_truck: 1, rm48u_loaded: 1, ..Default::default() };
|
||||
sum.depot_ammo[AmmoKind::S400Missile.index()] = 4;
|
||||
sum.truck_ammo[AmmoKind::S400Missile.index()] = 1;
|
||||
let lines = stock_summary_lines(&sum);
|
||||
assert!(lines[0].contains("Склады: 1 · ТЗМ: 1 (занято 1)"));
|
||||
assert!(lines[1].contains("RM48U: на складах 2, в ТЗМ 1, в ПУ 1"));
|
||||
assert!(lines[2].contains("С-400 5 (4+1)"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ pub fn tree() -> Tree {
|
||||
Node::lit("chains").runs().then(Node::arg("батарея", Value::int_from(1)).runs()),
|
||||
Node::lit("raid").runs(),
|
||||
Node::lit("sites").runs(),
|
||||
Node::lit("stocks").runs(),
|
||||
Node::lit("ground-stock").then(Node::arg("склад", Value::int_from(1)).then(Node::arg("количество", Value::int_from(0)).runs())),
|
||||
Node::lit("ground-cancel").then(Node::arg("комплекс", Value::int_from(1)).runs()),
|
||||
Node::lit("ground-unload").then(Node::arg("комплекс", Value::int_from(1)).runs()),
|
||||
@@ -94,6 +95,7 @@ pub fn tree() -> Tree {
|
||||
Node::lit("shader").then(Node::arg("режим", Value::choice(["on", "off", "hd"])).runs()),
|
||||
toggle("hold"),
|
||||
toggle("lastchance"),
|
||||
toggle("autostrike"),
|
||||
Node::lit("roles").runs().then(
|
||||
Node::arg("комплекс", Value::choice(armed)).then(
|
||||
Node::arg(
|
||||
@@ -122,6 +124,11 @@ pub fn tree() -> Tree {
|
||||
Node::lit("launch").then(Node::arg("запрос", Value::word()).then(
|
||||
Node::arg("сессия", Value::word()).then(Node::arg("сценарий", Value::word()).runs())
|
||||
)),
|
||||
Node::lit("action").then(Node::arg("запрос", Value::word()).then(
|
||||
Node::arg("сессия", Value::word()).then(Node::arg("действие", Value::choice(["autostrike", "strike"])).then(
|
||||
Node::arg("значение", Value::word()).runs()
|
||||
))
|
||||
)),
|
||||
]),
|
||||
Node::lit("stats").runs(),
|
||||
])
|
||||
@@ -187,7 +194,7 @@ mod tests {
|
||||
"scenario delete a", "scenario village", "scenario village hard", "scenario village start",
|
||||
"breaches", "breaches 2", "why", "why 2", "why 2 source", "chains", "chains 2", "ew on", "ew off", "move 4", "target here", "targets clear",
|
||||
"sites", "strike 3", "battery", "battery 1 launcher", "battery 1 integrated", "radar 2 on", "radar 2 off", "radar 2 engagement", "radar 2 search", "deploy s400_launcher", "deploy s500_launcher", "deploy radar_search", "deploy radar_track", "deploy radar_height", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000",
|
||||
"wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off",
|
||||
"wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off", "autostrike on", "autostrike off",
|
||||
"roles all default", "doctrine", "doctrine 1 reserve 4", "doctrine all salvo eco", "doctrine 2 sector 90 45", "doctrine 2 sector off", "doctrine 1 guard 1,2", "doctrine 1 reset", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic",
|
||||
] {
|
||||
ok(line);
|
||||
@@ -259,11 +266,11 @@ mod tests {
|
||||
fn completion_offers_the_next_word_only() {
|
||||
let top = complete("", &[]);
|
||||
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
|
||||
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel", "chains"] {
|
||||
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "autostrike", "roles", "doctrine", "stats", "recon", "sites", "stocks", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel", "chains"] {
|
||||
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
|
||||
}
|
||||
assert!(top.contains(&"post".to_string()));
|
||||
assert_eq!(top.len(), 40);
|
||||
assert_eq!(top.len(), 42);
|
||||
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
|
||||
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
|
||||
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
|
||||
|
||||
@@ -44,6 +44,7 @@ pub struct Layout {
|
||||
pub targets: Vec<(DVec3, f64)>,
|
||||
pub damage: Option<bool>,
|
||||
pub last_chance: Option<bool>,
|
||||
pub auto_strike: Option<bool>,
|
||||
pub seed: Option<u64>,
|
||||
pub wave: Option<Vec<String>>,
|
||||
pub far: Option<bool>,
|
||||
@@ -55,6 +56,8 @@ pub struct Layout {
|
||||
pub roles: Vec<(SamKind, u8)>,
|
||||
/// Fire doctrines by the system's place in the file (#47).
|
||||
pub doctrines: Vec<(usize, sim::doctrine::Doctrine)>,
|
||||
/// Typed depot/TZM ammunition stocks by the unit's place in the file.
|
||||
pub stocks: Vec<(usize, sim::AmmoStock)>,
|
||||
/// Strike missiles in stock and ticks towards the next (#101).
|
||||
pub strikes: Option<(u32, u32)>,
|
||||
}
|
||||
@@ -190,6 +193,7 @@ impl Layout {
|
||||
}
|
||||
"damage" => out.damage = l.flag(1, "значение")?,
|
||||
"lastchance" => out.last_chance = l.flag(1, "значение")?,
|
||||
"autostrike" => out.auto_strike = l.flag(1, "значение")?,
|
||||
"strikes" => out.strikes = Some((l.need(1, "запас", 0.0, COUNT)? as u32, l.num(2, "до следующей", 0.0, COUNT)?.map_or(0, |v| v as u32))),
|
||||
"far" => out.far = l.flag(1, "значение")?,
|
||||
"acoustics" => out.acoustics = l.flag(1, "значение")?,
|
||||
@@ -213,6 +217,37 @@ impl Layout {
|
||||
let guards = (0..n).map(|k| l.xyz(7 + 3 * k, "охраняемый объект")).collect::<Result<Vec<_>, _>>()?;
|
||||
out.doctrines.push((at, sim::doctrine::Doctrine { guards, sector, reserve, salvo }));
|
||||
}
|
||||
"stock" => {
|
||||
let at = l.need(1, "склад или ТЗМ", 0.0, MAX_UNITS as f64)? as usize;
|
||||
let target = out.sams.get(at).ok_or_else(|| l.bad("склад или ТЗМ", "нет такой строки техники"))?;
|
||||
if !matches!(target.kind, SamKind::Depot | SamKind::Tzm) {
|
||||
return Err(l.bad("склад или ТЗМ", "боезапас склада поддерживается только для склада и ТЗМ"));
|
||||
}
|
||||
let mut stock = sim::AmmoStock::default();
|
||||
let mut seen = [false; sim::AmmoKind::COUNT];
|
||||
if l.w.get(2).is_none() {
|
||||
return Err(l.bad("состав", "строка оборвана"));
|
||||
}
|
||||
if l.w.get(2) != Some(&"-") {
|
||||
for item in &l.w[2..] {
|
||||
let (k, v) = item.split_once('=').ok_or_else(|| l.bad("состав", &format!("«{item}»: нужен вид=число")))?;
|
||||
let kind = sim::AmmoKind::from_key(k).ok_or_else(|| l.bad("состав", &format!("неизвестный вид БК «{k}»")))?;
|
||||
if seen[kind.index()] {
|
||||
return Err(l.bad("состав", &format!("повтор вида БК «{k}»")));
|
||||
}
|
||||
seen[kind.index()] = true;
|
||||
let count: f64 = v.parse().map_err(|_| l.bad("состав", &format!("«{v}» не число")))?;
|
||||
if !count.is_finite() || count < 0.0 || count > COUNT || count.fract() != 0.0 {
|
||||
return Err(l.bad("состав", &format!("недопустимое количество «{v}»")));
|
||||
}
|
||||
stock.set(kind, count as u32);
|
||||
}
|
||||
}
|
||||
if target.kind == SamKind::Tzm && stock.total() > sim::TRUCK_CAPACITY {
|
||||
return Err(l.bad("состав", &format!("груз ТЗМ больше {}", sim::TRUCK_CAPACITY)));
|
||||
}
|
||||
out.stocks.push((at, stock));
|
||||
}
|
||||
"roles" => {
|
||||
let kind = l.kind(1)?;
|
||||
out.roles.push((kind, l.need(2, "роли", 0.0, 255.0)? as u8));
|
||||
@@ -369,5 +404,24 @@ mod tests {
|
||||
assert!(crate::layout::Layout::parse("doctrine 0 eco 1 - - 2 1 2 3\n").is_err(), "guards cut short");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autostrike_and_typed_stocks_parse_and_validate() {
|
||||
let text = "sam depot 0 70 0 0\nsam tzm 10 70 0 0\nautostrike true\nstock 0 s400=3 pantsir_gun=4\nstock 1 tor=1\n";
|
||||
let l = Layout::parse(text).unwrap();
|
||||
assert_eq!(l.auto_strike, Some(true));
|
||||
assert_eq!(l.stocks.len(), 2);
|
||||
assert_eq!(l.stocks[0].1.get(sim::AmmoKind::S400Missile), 3);
|
||||
assert_eq!(l.stocks[0].1.get(sim::AmmoKind::PantsirGun), 4);
|
||||
assert_eq!(l.stocks[1].1.get(sim::AmmoKind::TorMissile), 1);
|
||||
|
||||
let empty = Layout::parse("sam depot 0 70 0 0\nstock 0 -\nautostrike false\n").unwrap();
|
||||
assert_eq!(empty.auto_strike, Some(false));
|
||||
assert!(empty.stocks[0].1.is_empty());
|
||||
|
||||
assert!(Layout::parse("sam s400 0 70 0 0\nstock 0 s400=1\n").is_err());
|
||||
assert!(Layout::parse("sam depot 0 70 0 0\nstock 0 unknown=1\n").is_err());
|
||||
assert!(Layout::parse("sam depot 0 70 0 0\nstock 0 s400=1 s400=2\n").is_err());
|
||||
assert!(Layout::parse("sam tzm 0 70 0 0\nstock 0 s400=3\n").is_err());
|
||||
assert!(Layout::parse("autostrike maybe\n").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
+170
-10
@@ -302,6 +302,7 @@ const BTN_REEL: u32 = 42;
|
||||
const BTN_FAR: u32 = 19;
|
||||
const BTN_ACOUSTICS: u32 = 20;
|
||||
const BTN_DLSS: u32 = 24;
|
||||
const BTN_AUTOSTRIKE: u32 = 25;
|
||||
const FLEET_ROWS: u32 = 4;
|
||||
const BTN_RESERVE: u32 = 50;
|
||||
const BTN_SALVO: u32 = 51;
|
||||
@@ -445,13 +446,26 @@ impl AirDef {
|
||||
Some(at) => {
|
||||
let d = view(&p);
|
||||
let heading = (-d.x).atan2(-d.z);
|
||||
if let Err(e) = self.place(kind, mode, role, at, heading) {
|
||||
say(&e);
|
||||
return;
|
||||
}
|
||||
let id = match self.place(kind, mode, role, at, heading) {
|
||||
Ok(id) => id,
|
||||
Err(e) => {
|
||||
say(&e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
out.sound("minecraft:block.anvil.place", at, 2.0, 0.7);
|
||||
let profile = if kind == SamKind::Radar { format!(", профиль {}", role.profile().id) } else { String::new() };
|
||||
say(&format!("{} развёрнут{profile}", kind.name()));
|
||||
let depot = if kind == SamKind::Depot {
|
||||
self.sim
|
||||
.sams
|
||||
.iter()
|
||||
.find(|s| s.id == id)
|
||||
.map(|s| format!(" (БК ПВО: {}, RM48U: {})", s.ammo_stock.total(), s.ground_stock))
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
say(&format!("{} развёрнут{profile}{depot}", kind.name()));
|
||||
}
|
||||
None => say("Наведитесь на землю, где поставить комплекс"),
|
||||
}
|
||||
@@ -1031,10 +1045,16 @@ impl AirDef {
|
||||
// left) and where it was driving, if anywhere.
|
||||
let dest = s.dest.filter(|_| !fresh).map_or("- - -".to_string(), |d| format!("{} {} {}", d.x, d.y, d.z));
|
||||
let new = Sam::new(0, s.kind, s.pos, s.heading);
|
||||
let depot_stock = if s.kind == SamKind::Depot && s.alive() { s.ammo_stock } else { new.ammo_stock };
|
||||
let (health, cargo, missiles, bursts, empty, reloading) = if fresh {
|
||||
(new.health, new.cargo, new.missiles.saturating_sub(s.ground_rounds), new.bursts, false, 0)
|
||||
let c = match s.kind {
|
||||
SamKind::Depot => depot_stock.total(),
|
||||
SamKind::Tzm => 0,
|
||||
_ => new.cargo,
|
||||
};
|
||||
(new.health, c, new.missiles.saturating_sub(s.ground_rounds), new.bursts, false, 0)
|
||||
} else {
|
||||
(s.health, s.cargo, s.missiles, s.bursts, s.empty, s.reloading)
|
||||
(s.health, s.ammo_stock.total().max(s.cargo), s.missiles, s.bursts, s.empty, s.reloading)
|
||||
};
|
||||
// The parts' states (sensor, mount, launcher, gun, tracks, comms) close the line; older saves lack them.
|
||||
let comps = if fresh { new.comps } else { s.comps };
|
||||
@@ -1063,6 +1083,7 @@ impl AirDef {
|
||||
}
|
||||
text += &format!("damage {}\n", self.sim.damage);
|
||||
text += &format!("lastchance {}\n", self.sim.last_chance);
|
||||
text += &format!("autostrike {}\n", self.sim.auto_strike);
|
||||
// A scenario to replay from the start begins with the full stock.
|
||||
let (stock, progress) = if fresh { (sim::strike::TUNE.stock, 0) } else { (self.sim.strikes.stock, self.sim.strikes.progress) };
|
||||
text += &format!("strikes {stock} {progress}\n");
|
||||
@@ -1079,6 +1100,19 @@ impl AirDef {
|
||||
for (i, s) in self.sim.sams.iter().enumerate().filter(|(_, s)| !s.doctrine.is_default()) {
|
||||
text += &format!("doctrine {i} {}\n", s.doctrine.save_text());
|
||||
}
|
||||
// Typed depot/TZM ammunition stocks by the unit's place in this file.
|
||||
for (i, s) in self.sim.sams.iter().enumerate().filter(|(_, s)| matches!(s.kind, SamKind::Depot | SamKind::Tzm)) {
|
||||
let stock = if fresh {
|
||||
if s.kind == SamKind::Depot && s.alive() {
|
||||
s.ammo_stock
|
||||
} else {
|
||||
Sam::new(0, s.kind, s.pos, s.heading).ammo_stock
|
||||
}
|
||||
} else {
|
||||
s.ammo_stock
|
||||
};
|
||||
text += &format!("stock {i} {}\n", stock.save_text());
|
||||
}
|
||||
// The enemy's air state, last: it names its own format version, so an older build (or an
|
||||
// older save) reads the layout and ignores it (#127).
|
||||
if (view || air) && !fresh && let Some(line) = self.village.and_then(|v| v.save(self.sim.tick, air)) {
|
||||
@@ -1172,6 +1206,7 @@ impl AirDef {
|
||||
/// Adds a checked layout to the scene: nothing here can fail.
|
||||
fn commit_layout(&mut self, layout: layout::Layout) {
|
||||
let base = self.sim.sams.len();
|
||||
let count = layout.sams.len();
|
||||
for r in layout.sams {
|
||||
let id = self.sim.id();
|
||||
let mut sam = Sam::new(id, r.kind, r.pos, r.heading);
|
||||
@@ -1190,6 +1225,7 @@ impl AirDef {
|
||||
sam.bursts = b.min(sam.bursts);
|
||||
sam.empty = empty;
|
||||
sam.reloading = reloading;
|
||||
sam.infer_reload_mask();
|
||||
}
|
||||
// The parts: absent in older saves, which load with every part whole.
|
||||
for (v, c) in sam.comps.0.iter_mut().zip(&r.comps) {
|
||||
@@ -1225,6 +1261,9 @@ impl AirDef {
|
||||
if let Some(l) = layout.last_chance {
|
||||
self.sim.last_chance = l;
|
||||
}
|
||||
if let Some(a) = layout.auto_strike {
|
||||
self.sim.auto_strike = a;
|
||||
}
|
||||
if let Some((stock, progress)) = layout.strikes {
|
||||
self.sim.strikes.restore(stock, progress);
|
||||
}
|
||||
@@ -1258,6 +1297,31 @@ impl AirDef {
|
||||
s.doctrine = d;
|
||||
}
|
||||
}
|
||||
let mut explicit_stock = vec![false; count];
|
||||
for (i, stock) in layout.stocks {
|
||||
if let Some(s) = self.sim.sams.get_mut(base + i) {
|
||||
s.ammo_stock = stock;
|
||||
s.sync_cargo();
|
||||
if i < explicit_stock.len() {
|
||||
explicit_stock[i] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (offset, has_explicit) in explicit_stock.into_iter().enumerate() {
|
||||
if has_explicit {
|
||||
continue;
|
||||
}
|
||||
if let Some(s) = self.sim.sams.get_mut(base + offset) {
|
||||
match s.kind {
|
||||
SamKind::Depot => {
|
||||
s.ammo_stock = sim::AmmoStock::from_legacy_cargo(s.cargo);
|
||||
s.sync_cargo();
|
||||
}
|
||||
SamKind::Tzm => s.clear_ammo(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn give(&self) {
|
||||
@@ -1304,13 +1368,16 @@ fn durable_mark(sim: &Sim) -> u64 {
|
||||
let at = s.dest.unwrap_or(s.pos);
|
||||
let place = (at.x * 10.0) as i64 as u64 ^ ((at.z * 10.0) as i64 as u64).rotate_left(21) ^ (if s.dest.is_some() { 0 } else { (s.heading * 100.0) as i64 as u64 }).rotate_left(42);
|
||||
let ammo = u64::from(s.missiles) | u64::from(s.bursts) << 16 | u64::from(s.cargo) << 32 | u64::from(s.empty) << 48 | u64::from(s.reloading > 0) << 49;
|
||||
let typed = u64::from(s.ground_rounds) ^ u64::from(s.ground_stock).rotate_left(17) ^ u64::from(s.air_48n6_stock).rotate_left(39) ^ u64::from(s.ground_request).rotate_left(55) ^ u64::from(s.ground_return).rotate_left(56) ^ u64::from(s.return_cargo).rotate_left(57);
|
||||
let typed_stock = s.ammo_stock.0.iter().fold(0u64, |a, &v| a.wrapping_mul(131).wrapping_add(u64::from(v)));
|
||||
let typed = u64::from(s.ground_rounds) ^ u64::from(s.ground_stock).rotate_left(17) ^ u64::from(s.air_48n6_stock).rotate_left(39) ^ u64::from(s.ground_request).rotate_left(55) ^ u64::from(s.auto_ground_request).rotate_left(58) ^ u64::from(s.ground_return).rotate_left(56) ^ u64::from(s.return_cargo).rotate_left(57) ^ typed_stock.rotate_left(7);
|
||||
let parts = s.comps.0.iter().fold(0u64, |a, v| a.wrapping_mul(131).wrapping_add((v * 100.0) as u64));
|
||||
((s.health * 1000.0) as u64).wrapping_mul(1_000_003) ^ place ^ ammo.rotate_left(7) ^ parts.rotate_left(13) ^ typed.rotate_left(29) ^ (s.mode as u64).rotate_left(3) ^ (s.radar_role as u64).rotate_left(11) ^ u64::from(s.spent_cells).rotate_left(19) ^ u64::from(s.radar_on).rotate_left(23)
|
||||
})
|
||||
.chain(sim.target_health.iter().map(|h| (h * 10.0) as u64))
|
||||
.fold(sim.sams.len() as u64, |a, h| a.wrapping_mul(31).wrapping_add(h))
|
||||
.wrapping_mul(31)
|
||||
.wrapping_add(u64::from(sim.auto_strike))
|
||||
.wrapping_mul(31)
|
||||
.wrapping_add(strikes)
|
||||
// The air state's shape (#127): a launch, a loss, a new or finished route job makes the
|
||||
// autosave take the raid as it stands, so a reload resumes it rather than an empty sky.
|
||||
@@ -1783,6 +1850,9 @@ impl AirDef {
|
||||
sam.set_mode(mode);
|
||||
sam.set_radar_role(role);
|
||||
if let Some(r) = self.sim.roles.get(&kind) { sam.roles = *r; }
|
||||
if kind == SamKind::Depot {
|
||||
self.sim.roll_depot_stock(&mut sam);
|
||||
}
|
||||
self.sim.sams.push(sam);
|
||||
self.sim.settle(id);
|
||||
self.dirty = true;
|
||||
@@ -1795,9 +1865,19 @@ impl AirDef {
|
||||
let d = view(&p);
|
||||
let flat = DVec3::new(d.x, 0.0, d.z).normalize_or(DVec3::NEG_Z);
|
||||
let at = DVec3::new(p.x, p.y, p.z) + flat * 8.0;
|
||||
self.place(kind, mode, role, at, (-flat.x).atan2(-flat.z))?;
|
||||
let id = self.place(kind, mode, role, at, (-flat.x).atan2(-flat.z))?;
|
||||
let profile = if kind == SamKind::Radar { format!(", профиль {}", role.profile().id) } else { String::new() };
|
||||
Ok(format!("{} развёрнут ({}, {}{profile})", kind.name(), mode.key(), role.key()))
|
||||
let depot = if kind == SamKind::Depot {
|
||||
self.sim
|
||||
.sams
|
||||
.iter()
|
||||
.find(|s| s.id == id)
|
||||
.map(|s| format!(", БК ПВО: {}, RM48U: {}", s.ammo_stock.total(), s.ground_stock))
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
Ok(format!("{} развёрнут ({}, {}{profile}{depot})", kind.name(), mode.key(), role.key()))
|
||||
}
|
||||
|
||||
fn open_menu(&mut self, page: Page) {
|
||||
@@ -1834,6 +1914,16 @@ impl AirDef {
|
||||
let indices = &indices[start..(start + post::PAGE_SIZE).min(indices.len())];
|
||||
self.post.shown = indices.iter().map(|&i| self.sim.sams[i].id).collect();
|
||||
widgets.push(Widget::Button(ButtonWidget { id: POST_FILTER, label: format!("Фильтр · {}", self.post.filter.label()) }));
|
||||
let sup = self.sim.supply_summary();
|
||||
let ammo_total: u32 = sup.depot_ammo.iter().sum::<u32>() + sup.truck_ammo.iter().sum::<u32>();
|
||||
widgets.push(Widget::Text(TextWidget {
|
||||
id: 0,
|
||||
text: format!(
|
||||
"Логистика · скл {} · ТЗМ {}/{} · БК {} · RM48U {} · ждут {}",
|
||||
sup.depots_alive, sup.trucks_busy, sup.trucks_alive, ammo_total, sup.rm48u_depot + sup.rm48u_truck, sup.waiting_ammo + sup.waiting_rm48u
|
||||
),
|
||||
color: 0,
|
||||
}));
|
||||
let rows = indices.iter().map(|&i| {
|
||||
let sam = &self.sim.sams[i];
|
||||
monitor::fit(post::row(sam, i, self.post.pinned == Some(sam.id)), 184.0)
|
||||
@@ -1866,6 +1956,9 @@ impl AirDef {
|
||||
let reason = self.sim.battle_reason(i);
|
||||
if matches!(page, Page::UnitChecks(_, _)) {
|
||||
let mut details = vec![battery_view::sam_status(sam, self.sim.tick)];
|
||||
if let Some(sup) = self.sim.supply_status(i) {
|
||||
details.push(format!("Снабжение · {}", battery_view::supply_line(&sup)));
|
||||
}
|
||||
if let Some(reason) = reason {
|
||||
if let (Some(target), Some(mark)) = (reason.target, reason.mark) {
|
||||
details.push(format!("Трек №{target} · {}", why_view::mark_text(&mark)));
|
||||
@@ -1883,6 +1976,11 @@ impl AirDef {
|
||||
widgets.push(Widget::Text(TextWidget { id: 0, text, color: 0 }));
|
||||
}
|
||||
}
|
||||
if let Some(sup) = self.sim.supply_status(i) {
|
||||
for text in ui_lines(&format!("Снабжение · {}", battery_view::supply_line(&sup))) {
|
||||
widgets.push(Widget::Text(TextWidget { id: 0, text, color: 0 }));
|
||||
}
|
||||
}
|
||||
self.post.decisions = post::recorded_choices(
|
||||
self.sim.recording().into_iter().chain(self.sim.replays.iter().rev()), id,
|
||||
).take(1).collect();
|
||||
@@ -2070,6 +2168,10 @@ impl AirDef {
|
||||
id: BTN_HOLD,
|
||||
label: format!("Огонь ПВО: {}", if self.sim.hold { "запрещён" } else { "разрешён" }),
|
||||
}));
|
||||
widgets.push(Widget::Button(ButtonWidget {
|
||||
id: BTN_AUTOSTRIKE,
|
||||
label: format!("Автоудар по ПУ: {}", onoff(self.sim.auto_strike)),
|
||||
}));
|
||||
let broken = self.sim.sams.iter().filter(|s| s.health < 1.0).count();
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_REPAIR, label: format!("Ремонт всех (повреждено: {broken})") }));
|
||||
let fx = if !self.sim.shader { "выкл" } else if self.hd { "HD (свет, bloom)" } else { "обычные" };
|
||||
@@ -2781,6 +2883,10 @@ impl Mod for AirDef {
|
||||
}
|
||||
}
|
||||
(Page::More, BTN_HOLD) => self.sim.hold = !self.sim.hold,
|
||||
(Page::More, BTN_AUTOSTRIKE) => {
|
||||
self.sim.auto_strike = !self.sim.auto_strike;
|
||||
self.dirty = true;
|
||||
}
|
||||
(Page::More, BTN_REPAIR) => {
|
||||
if self.village_active() {
|
||||
say("В этом сценарии состояние объектов и техники переносится между волнами");
|
||||
@@ -3200,6 +3306,18 @@ impl Mod for AirDef {
|
||||
}
|
||||
None
|
||||
}
|
||||
["stocks"] => {
|
||||
let summary = self.sim.supply_summary();
|
||||
for line in battery_view::stock_summary_lines(&summary) {
|
||||
say(&line);
|
||||
}
|
||||
for (i, sam) in self.sim.sams.iter().enumerate() {
|
||||
if let Some(sup) = self.sim.supply_status(i) {
|
||||
say(&format!("№{} {}: {}", i + 1, sam.kind.name(), battery_view::supply_line(&sup)));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
["ground-stock", n, count] => {
|
||||
let i = n.parse::<usize>().ok().and_then(|v| v.checked_sub(1)).ok_or("/airdef ground-stock <номер склада> <количество>")?;
|
||||
let count = count.parse::<u32>().ok().filter(|v| *v <= 10000).ok_or("Количество: 0..10000")?;
|
||||
@@ -3339,6 +3457,15 @@ impl Mod for AirDef {
|
||||
"Последний шанс: выкл — комплексы стреляют только по своим ролям".into()
|
||||
})
|
||||
}
|
||||
["autostrike", v @ ("on" | "off")] => {
|
||||
self.sim.auto_strike = *v == "on";
|
||||
self.dirty = true;
|
||||
Some(if self.sim.auto_strike {
|
||||
"Автоудар по ПУ: вкл — свободный С-400 без ожидаемых воздушных задач закажет RM48U, выберет разведанную площадку и нанесёт удар во время налёта".into()
|
||||
} else {
|
||||
"Автоудар по ПУ: выкл — удары по площадкам задаются вручную (/airdef strike <номер>)".into()
|
||||
})
|
||||
}
|
||||
["hold", v @ ("on" | "off")] => {
|
||||
self.sim.hold = *v == "on";
|
||||
Some(if self.sim.hold { "ПВО: огонь запрещён".into() } else { "ПВО: огонь разрешён".into() })
|
||||
@@ -3872,4 +3999,37 @@ mod tests {
|
||||
assert!(!scenario.contains("\nair 1 "), "a scenario carries the air state");
|
||||
assert!(sim::Sim::parse_air(&scenario).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autostrike_typed_stocks_and_legacy_cargo_round_trip() {
|
||||
let mut game = test_mod();
|
||||
let depot_id = game.sim.id();
|
||||
let mut depot = Sam::new(depot_id, SamKind::Depot, DVec3::new(0.0, 64.0, 0.0), 0.0);
|
||||
depot.clear_ammo();
|
||||
depot.set_ammo(sim::AmmoKind::S400Missile, 2);
|
||||
depot.set_ammo(sim::AmmoKind::PantsirGun, 3);
|
||||
game.sim.sams.push(depot);
|
||||
let tzm_id = game.sim.id();
|
||||
let mut tzm = Sam::new(tzm_id, SamKind::Tzm, DVec3::new(10.0, 64.0, 0.0), 0.0);
|
||||
tzm.set_ammo(sim::AmmoKind::TorMissile, 1);
|
||||
game.sim.sams.push(tzm);
|
||||
game.sim.auto_strike = true;
|
||||
|
||||
let saved = game.state_text(false, false);
|
||||
let mut restored = test_mod();
|
||||
restored.apply_state(&saved).unwrap();
|
||||
assert!(restored.sim.auto_strike);
|
||||
assert_eq!(restored.sim.sams[0].ammo_stock.get(sim::AmmoKind::S400Missile), 2);
|
||||
assert_eq!(restored.sim.sams[0].ammo_stock.get(sim::AmmoKind::PantsirGun), 3);
|
||||
assert_eq!(restored.sim.sams[0].cargo, 5);
|
||||
assert_eq!(restored.sim.sams[1].ammo_stock.get(sim::AmmoKind::TorMissile), 1);
|
||||
|
||||
// Legacy save without `stock` lines distributes `cargo` across typed kinds on depots and clears TZMs.
|
||||
let legacy = "sam depot 0 64 0 0 0 1 11 0 0 0 0 - - -\nsam tzm 10 64 0 0 0 1 2 0 0 0 0 - - -\n";
|
||||
let mut migrated = test_mod();
|
||||
migrated.apply_state(legacy).unwrap();
|
||||
assert_eq!(migrated.sim.sams[0].ammo_stock.total(), 11);
|
||||
assert_eq!(migrated.sim.sams[1].ammo_stock.total(), 0);
|
||||
assert_eq!(migrated.sim.sams[1].cargo, 0);
|
||||
}
|
||||
}
|
||||
|
||||
+36
-2
@@ -115,6 +115,7 @@ enum Act {
|
||||
RadarEmission,
|
||||
ResetDoc,
|
||||
Strike(u32),
|
||||
AutoStrike,
|
||||
Centre,
|
||||
Inspect,
|
||||
Follow,
|
||||
@@ -1421,6 +1422,11 @@ impl AirDef {
|
||||
}
|
||||
self.emit(out);
|
||||
}
|
||||
Act::AutoStrike => {
|
||||
self.sim.auto_strike = !self.sim.auto_strike;
|
||||
self.dirty = true;
|
||||
ui.note(tick, if self.sim.auto_strike { "Автоудар по ПУ: вкл" } else { "Автоудар по ПУ: выкл" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1699,6 +1705,9 @@ impl AirDef {
|
||||
if let Some(r) = self.sim.roles.get(&s.kind) {
|
||||
sam.roles = *r;
|
||||
}
|
||||
if sam.kind == SamKind::Depot {
|
||||
self.sim.roll_depot_stock(&mut sam);
|
||||
}
|
||||
self.sim.sams.push(sam);
|
||||
}
|
||||
(None, true) => {}
|
||||
@@ -1778,6 +1787,9 @@ impl AirDef {
|
||||
if r > 0.0 && ui.sclass[sys_class(kind)] && (!many || chosen || ghost) {
|
||||
let c = ui.to_screen(pos.x, pos.z);
|
||||
ring(ui, &mut s, c, (r * ui.scale) as f32, 1.0, alpha(if ghost { 0xFFE070 } else { 0x40A0FF }, 0.75));
|
||||
} else if kind == SamKind::Depot && (!many || chosen || ghost) {
|
||||
let c = ui.to_screen(pos.x, pos.z);
|
||||
ring(ui, &mut s, c, (sim::DEPOT_REACH_BLOCKS * ui.scale) as f32, 1.0, alpha(if ghost { 0xFFE070 } else { 0xFFB85C }, 0.65));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1785,10 +1797,13 @@ impl AirDef {
|
||||
if ui.filters[F_VIEW] {
|
||||
self.map_rims(ui, &mut s, &draft, picked);
|
||||
}
|
||||
// The selected system's sensor, sector and guards.
|
||||
// The selected system's sensor, depot reach, sector and guards.
|
||||
if let Some(i) = self.sel_sam(ui) {
|
||||
let sam = &self.sim.sams[i];
|
||||
let c = ui.to_screen(sam.pos.x, sam.pos.z);
|
||||
if sam.kind == SamKind::Depot && !ui.filters[F_RINGS] {
|
||||
ring(ui, &mut s, c, (sim::DEPOT_REACH_BLOCKS * ui.scale) as f32, 1.0, alpha(0xFFB85C, 0.75));
|
||||
}
|
||||
let sens = sam.kind.spec().sensor;
|
||||
if sens > 0.0 && !ui.filters[F_VIEW] {
|
||||
ring(ui, &mut s, c, (sens * ui.scale) as f32, 1.0, alpha(0x80FF90, 0.45));
|
||||
@@ -1859,6 +1874,8 @@ impl AirDef {
|
||||
s.push(line(c, (c.0 + dx as f32 * 11.0, c.1 + dz as f32 * 11.0), 1.5, alpha(0xFFE070, 0.6)));
|
||||
if kind.range() > 0.0 {
|
||||
ring(ui, &mut s, c, (kind.range() * ui.scale) as f32, 1.0, alpha(0xFFE070, 0.55));
|
||||
} else if kind == SamKind::Depot {
|
||||
ring(ui, &mut s, c, (sim::DEPOT_REACH_BLOCKS * ui.scale) as f32, 1.0, alpha(0xFFE070, 0.75));
|
||||
}
|
||||
let _ = y;
|
||||
}
|
||||
@@ -2811,14 +2828,29 @@ impl AirDef {
|
||||
lines.push((format!("Исправен {:.0}% · {:.0} {:.0}", sam.health * 100.0, sam.pos.x, sam.pos.z), GREY));
|
||||
if k == SamKind::Depot {
|
||||
lines.push((format!("Ударные RM48U: {} · снятые 48Н6: {}", sam.ground_stock, sam.air_48n6_stock), WHITE));
|
||||
lines.push((format!("Обычный БК ПВО: {} перезарядок", sam.cargo), WHITE));
|
||||
lines.push((format!("БК ПВО: {} комплектов", sam.ammo_stock.total()), WHITE));
|
||||
let entries: Vec<String> = sam.ammo_stock.non_zero().map(|(kind, cnt)| format!("{}: {cnt}", kind.short_name())).collect();
|
||||
if entries.is_empty() {
|
||||
lines.push(("Боезапас ПВО исчерпан".into(), GREY));
|
||||
} else {
|
||||
for chunk in entries.chunks(3) {
|
||||
lines.push((chunk.join(" · "), WHITE));
|
||||
}
|
||||
}
|
||||
lines.push((format!("Зона прямой перезарядки: {} (оранжевое кольцо)", distance(sim::DEPOT_REACH_BLOCKS)), WHITE));
|
||||
if sam.ground_stock == 0 { lines.push((format!("Начальный запас: /airdef ground-stock {} <число>", n + 1), GREY)); }
|
||||
} else if k == SamKind::Tzm {
|
||||
let carried: Vec<String> = sam.ammo_stock.non_zero().map(|(kind, cnt)| format!("{}: {cnt}", kind.short_name())).collect();
|
||||
let detail = if carried.is_empty() { String::new() } else { format!(" ({})", carried.join(", ")) };
|
||||
lines.push((format!("БК на борту: {}/{}{detail}", sam.ammo_stock.total(), sim::TRUCK_CAPACITY), WHITE));
|
||||
lines.push((format!("Груз RM48U: {} · 48Н6: {}{}", sam.ground_stock, sam.air_48n6_stock, if sam.return_cargo { " · возврат на склад" } else { "" }), WHITE));
|
||||
}
|
||||
if k.armed() {
|
||||
if sam.kind.supports_rm48u() { lines.push((format!("Ударных RM48U: {} (общие ячейки с ПВО){}", sam.ground_rounds, if sam.ground_return { " · ожидает вывоза" } else if sam.ground_request { " · ожидает доставки" } else { "" }), WHITE)); }
|
||||
lines.push((format!("Боезапас: {} ракет, {} очередей{}", sam.missiles, sam.bursts, if sam.reloading > 0 { format!(" · перезарядка {} с", sam.reloading / 20) } else { String::new() }), WHITE));
|
||||
if let Some(sup) = self.sim.supply_status(n) {
|
||||
lines.push((format!("Снабжение: {}", crate::battery_view::supply_line(&sup)), YELLOW));
|
||||
}
|
||||
lines.push((format!("Дальность огня: {}", distance(k.range())), WHITE));
|
||||
}
|
||||
if let Some(sensor) = sam.radar_up().then(|| self.sim.low_sensor(k, sam.pos, Some(sam.id))).flatten() {
|
||||
@@ -2889,12 +2921,14 @@ impl AirDef {
|
||||
}
|
||||
lines.push((format!("Пусков замечено: {}; последний {} с назад", k.launches, now.saturating_sub(k.last) / 20), GREY));
|
||||
lines.push(("Для удара нужен готовый С-400 с RM48U".into(), GREY));
|
||||
lines.push((format!("Автоудар по ПУ: {}", if self.sim.auto_strike { "вкл" } else { "выкл" }), WHITE));
|
||||
if k.aimed {
|
||||
lines.push(("Ракета по ней уже в полёте".into(), YELLOW));
|
||||
}
|
||||
if k.est.is_some_and(|e| e.fix) && !matches!(k.state, SiteState::Destroyed(_)) {
|
||||
btns.push(("Нанести удар".into(), Act::Strike(id), false));
|
||||
}
|
||||
btns.push((format!("Автоудар: {}", if self.sim.auto_strike { "вкл" } else { "выкл" }), Act::AutoStrike, self.sim.auto_strike));
|
||||
btns.push(("В центр".into(), Act::Centre, false));
|
||||
}
|
||||
Some(Sel::Track(id)) => {
|
||||
|
||||
@@ -75,6 +75,7 @@ impl AirDef {
|
||||
self.sim.target_health.clear();
|
||||
self.sim.roles.clear();
|
||||
self.sim.last_chance = true;
|
||||
self.sim.auto_strike = false;
|
||||
self.sim.kills = 0;
|
||||
self.sim.hits = 0;
|
||||
self.sim.launched = 0;
|
||||
|
||||
@@ -302,13 +302,20 @@ impl Sim {
|
||||
out.messages.push(format!("{} №{} УНИЧТОЖЕН", sam.kind.name(), i + 1));
|
||||
let (id, kind) = (sam.id, sam.kind);
|
||||
// A depot's stock (or a truck's load) goes up with it.
|
||||
let stock = if matches!(self.sams[i].kind, SamKind::Depot | SamKind::Tzm) { self.sams[i].cargo } else { 0 };
|
||||
let stock = if matches!(self.sams[i].kind, SamKind::Depot | SamKind::Tzm) {
|
||||
self.sams[i].ammo_stock.total().max(self.sams[i].cargo)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
self.sams[i].ammo_stock = AmmoStock::default();
|
||||
self.sams[i].cargo = 0;
|
||||
self.sams[i].reload_mask = 0;
|
||||
let typed = self.sams[i].ground_stock + self.sams[i].air_48n6_stock;
|
||||
self.sams[i].ground_stock = 0;
|
||||
self.sams[i].air_48n6_stock = 0;
|
||||
self.sams[i].ground_rounds = 0;
|
||||
self.sams[i].ground_request = false;
|
||||
self.sams[i].auto_ground_request = false;
|
||||
self.sams[i].ground_return = false;
|
||||
self.sams[i].return_cargo = false;
|
||||
let missiles = missiles + stock * 2 + typed;
|
||||
@@ -466,6 +473,7 @@ impl Sim {
|
||||
sam.burn = 0;
|
||||
sam.state = SamState::Search;
|
||||
sam.reloading = 0;
|
||||
sam.reload_mask = 0;
|
||||
sam.empty = false;
|
||||
// Rebuilt where it stands: a march under way is called off.
|
||||
sam.dest = None;
|
||||
|
||||
+803
-46
@@ -1,7 +1,216 @@
|
||||
//! Empty magazines are replenished from finite depot stock, either directly or via a truck.
|
||||
//! Empty magazines are replenished from finite typed depot stock, either directly or via a truck.
|
||||
use super::*;
|
||||
|
||||
pub const DEPOT_RM48U_CHANCE: f64 = 0.35;
|
||||
pub(super) const RELOAD_MISSILE: u8 = 1;
|
||||
pub(super) const RELOAD_GUN: u8 = 2;
|
||||
|
||||
/// Typed air-defence ammunition carried by depots and reload trucks, differentiated per system and weapon channel.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
|
||||
pub enum AmmoKind {
|
||||
PatriotMissile,
|
||||
GepardGun,
|
||||
PantsirMissile,
|
||||
PantsirGun,
|
||||
S400Missile,
|
||||
S500Missile,
|
||||
IrisTMissile,
|
||||
NasamsMissile,
|
||||
BukMissile,
|
||||
TorMissile,
|
||||
P1sunMissile,
|
||||
}
|
||||
|
||||
impl AmmoKind {
|
||||
pub const COUNT: usize = 11;
|
||||
pub const ALL: [AmmoKind; Self::COUNT] = [
|
||||
AmmoKind::PatriotMissile,
|
||||
AmmoKind::GepardGun,
|
||||
AmmoKind::PantsirMissile,
|
||||
AmmoKind::PantsirGun,
|
||||
AmmoKind::S400Missile,
|
||||
AmmoKind::S500Missile,
|
||||
AmmoKind::IrisTMissile,
|
||||
AmmoKind::NasamsMissile,
|
||||
AmmoKind::BukMissile,
|
||||
AmmoKind::TorMissile,
|
||||
AmmoKind::P1sunMissile,
|
||||
];
|
||||
|
||||
pub const fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
|
||||
pub const fn key(self) -> &'static str {
|
||||
match self {
|
||||
AmmoKind::PatriotMissile => "patriot",
|
||||
AmmoKind::GepardGun => "gepard_gun",
|
||||
AmmoKind::PantsirMissile => "pantsir_missile",
|
||||
AmmoKind::PantsirGun => "pantsir_gun",
|
||||
AmmoKind::S400Missile => "s400",
|
||||
AmmoKind::S500Missile => "s500",
|
||||
AmmoKind::IrisTMissile => "irist",
|
||||
AmmoKind::NasamsMissile => "nasams",
|
||||
AmmoKind::BukMissile => "buk",
|
||||
AmmoKind::TorMissile => "tor",
|
||||
AmmoKind::P1sunMissile => "p1sun",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_key(key: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|k| k.key() == key)
|
||||
}
|
||||
|
||||
pub const fn short_name(self) -> &'static str {
|
||||
match self {
|
||||
AmmoKind::PatriotMissile => "Patriot",
|
||||
AmmoKind::GepardGun => "Гепард пуш",
|
||||
AmmoKind::PantsirMissile => "Панцирь рак",
|
||||
AmmoKind::PantsirGun => "Панцирь пуш",
|
||||
AmmoKind::S400Missile => "С-400",
|
||||
AmmoKind::S500Missile => "С-500",
|
||||
AmmoKind::IrisTMissile => "IRIS-T",
|
||||
AmmoKind::NasamsMissile => "NASAMS",
|
||||
AmmoKind::BukMissile => "Бук",
|
||||
AmmoKind::TorMissile => "Тор",
|
||||
AmmoKind::P1sunMissile => "P1-SUN",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
AmmoKind::PatriotMissile => "Patriot (PAC-3)",
|
||||
AmmoKind::GepardGun => "Гепард (35 мм)",
|
||||
AmmoKind::PantsirMissile => "Панцирь (57Э6)",
|
||||
AmmoKind::PantsirGun => "Панцирь (30 мм)",
|
||||
AmmoKind::S400Missile => "С-400 (48Н6)",
|
||||
AmmoKind::S500Missile => "С-500 (77Н6)",
|
||||
AmmoKind::IrisTMissile => "IRIS-T SLM",
|
||||
AmmoKind::NasamsMissile => "NASAMS (AMRAAM)",
|
||||
AmmoKind::BukMissile => "Бук-М2 (9М317)",
|
||||
AmmoKind::TorMissile => "Тор-М2 (9М338)",
|
||||
AmmoKind::P1sunMissile => "P1-SUN",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_gun(self) -> bool {
|
||||
matches!(self, AmmoKind::GepardGun | AmmoKind::PantsirGun)
|
||||
}
|
||||
|
||||
pub const fn spawn_range(self) -> (u32, u32) {
|
||||
match self {
|
||||
AmmoKind::PatriotMissile => (1, 4),
|
||||
AmmoKind::GepardGun => (2, 6),
|
||||
AmmoKind::PantsirMissile => (1, 5),
|
||||
AmmoKind::PantsirGun => (2, 6),
|
||||
AmmoKind::S400Missile => (1, 4),
|
||||
AmmoKind::S500Missile => (1, 3),
|
||||
AmmoKind::IrisTMissile => (1, 4),
|
||||
AmmoKind::NasamsMissile => (1, 4),
|
||||
AmmoKind::BukMissile => (1, 4),
|
||||
AmmoKind::TorMissile => (2, 5),
|
||||
AmmoKind::P1sunMissile => (2, 6),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-type air-defence reload stock stored at a depot or carried on a TZM.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
|
||||
pub struct AmmoStock(pub [u32; AmmoKind::COUNT]);
|
||||
|
||||
impl AmmoStock {
|
||||
/// Deterministic stock used by `Sam::new(Depot)` when not deployed with a random roll.
|
||||
pub const fn new_default_depot() -> Self {
|
||||
Self([3; AmmoKind::COUNT])
|
||||
}
|
||||
|
||||
/// Distributes a legacy untyped `cargo` count across all `AmmoKind`s for backward-compatible save loading.
|
||||
pub fn from_legacy_cargo(cargo: u32) -> Self {
|
||||
let base = cargo / AmmoKind::COUNT as u32;
|
||||
let rem = cargo % AmmoKind::COUNT as u32;
|
||||
let mut counts = [base; AmmoKind::COUNT];
|
||||
for (i, c) in counts.iter_mut().enumerate() {
|
||||
if (i as u32) < rem {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
Self(counts)
|
||||
}
|
||||
|
||||
/// Rolls random stock for each system/weapon channel plus a probabilistic RM48U strike allocation.
|
||||
pub fn roll(rng: &mut Rng) -> (Self, u32) {
|
||||
let mut stock = Self::default();
|
||||
for kind in AmmoKind::ALL {
|
||||
let (lo, hi) = kind.spawn_range();
|
||||
let span = hi - lo + 1;
|
||||
let n = lo + ((rng.f() * span as f64) as u32).min(span - 1);
|
||||
stock.set(kind, n);
|
||||
}
|
||||
let rm48u = if rng.chance(DEPOT_RM48U_CHANCE) {
|
||||
if rng.chance(0.30) { 2 } else { 1 }
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(stock, rm48u)
|
||||
}
|
||||
|
||||
pub const fn get(self, kind: AmmoKind) -> u32 {
|
||||
self.0[kind.index()]
|
||||
}
|
||||
|
||||
pub fn set(&mut self, kind: AmmoKind, n: u32) {
|
||||
self.0[kind.index()] = n.min(STOCK_LIMIT);
|
||||
}
|
||||
|
||||
pub fn add(&mut self, kind: AmmoKind, n: u32) -> Option<u32> {
|
||||
let total = self.total();
|
||||
let room = STOCK_LIMIT.saturating_sub(total);
|
||||
let added = n.min(room);
|
||||
self.0[kind.index()] = self.0[kind.index()].saturating_add(added);
|
||||
(added > 0 || n == 0).then_some(added)
|
||||
}
|
||||
|
||||
pub fn take(&mut self, kind: AmmoKind, n: u32) -> u32 {
|
||||
let taken = self.0[kind.index()].min(n);
|
||||
self.0[kind.index()] -= taken;
|
||||
taken
|
||||
}
|
||||
|
||||
pub fn total(self) -> u32 {
|
||||
self.0.iter().copied().sum()
|
||||
}
|
||||
|
||||
pub fn is_empty(self) -> bool {
|
||||
self.0.iter().all(|&n| n == 0)
|
||||
}
|
||||
|
||||
pub fn non_zero(self) -> impl Iterator<Item = (AmmoKind, u32)> {
|
||||
AmmoKind::ALL
|
||||
.into_iter()
|
||||
.filter_map(move |k| {
|
||||
let n = self.get(k);
|
||||
(n > 0).then_some((k, n))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn save_text(self) -> String {
|
||||
let parts: Vec<String> = self.non_zero().map(|(k, n)| format!("{}={n}", k.key())).collect();
|
||||
if parts.is_empty() { "-".into() } else { parts.join(" ") }
|
||||
}
|
||||
}
|
||||
|
||||
impl Sim {
|
||||
/// Rolls random per-complex ammunition and probabilistic RM48U stock when deploying a depot.
|
||||
pub fn roll_depot_stock(&mut self, sam: &mut Sam) {
|
||||
if sam.kind != SamKind::Depot {
|
||||
return;
|
||||
}
|
||||
let (stock, rm48u) = AmmoStock::roll(&mut self.rng);
|
||||
sam.ammo_stock = stock;
|
||||
sam.sync_cargo();
|
||||
sam.ground_stock = rm48u;
|
||||
}
|
||||
|
||||
/// 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("Нет такого комплекса")?;
|
||||
@@ -20,10 +229,11 @@ impl Sim {
|
||||
if let Some((j, _)) = self.sams.iter().enumerate().find(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.pos.distance(s.pos) < DEPOT_REACH) {
|
||||
return Err(format!("Склад №{} рядом, но RM48U: 0. Задайте запас: /airdef ground-stock {} <количество>", j + 1, j + 1));
|
||||
}
|
||||
return Err("Нет живого склада с RM48U рядом (60 блоков)".into());
|
||||
return Err(format!("Нет живого склада с RM48U рядом ({:.0} блоков)", DEPOT_REACH));
|
||||
}
|
||||
if !self.sams.iter().any(|t| t.kind == SamKind::Tzm && t.alive()) { return Err("Для доставки RM48U нужна исправная ТЗМ".into()); }
|
||||
self.sams[i].ground_request = true;
|
||||
self.sams[i].auto_ground_request = false;
|
||||
return Ok(format!("С-400 №{}: заявка RM48U ожидает доставки ТЗМ", i + 1));
|
||||
};
|
||||
let displaced = u32::from(self.sams[i].missiles + self.sams[i].ground_rounds >= self.sams[i].cells());
|
||||
@@ -31,6 +241,7 @@ impl Sim {
|
||||
self.sams[i].missiles -= displaced;
|
||||
self.sams[i].ground_rounds += 1;
|
||||
self.sams[i].ground_request = false;
|
||||
self.sams[i].auto_ground_request = false;
|
||||
if self.sams[i].ground_rounds >= self.sams[i].cells() && self.sams[i].kind.spec().gun.is_none() { self.sams[i].empty = false; }
|
||||
self.sams[depot].ground_stock -= 1;
|
||||
self.sams[depot].air_48n6_stock = air_48n6_stock;
|
||||
@@ -68,6 +279,7 @@ impl Sim {
|
||||
let s = self.sams.get_mut(i).ok_or("Нет такого комплекса")?;
|
||||
if !s.kind.supports_rm48u() || (!s.ground_request && !s.ground_return) { return Err("Нет ожидающей заявки RM48U".into()); }
|
||||
s.ground_request = false;
|
||||
s.auto_ground_request = false;
|
||||
s.ground_return = false;
|
||||
Ok(format!("С-400 №{}: заявка RM48U отменена", i + 1))
|
||||
}
|
||||
@@ -75,19 +287,43 @@ impl Sim {
|
||||
/// Reloads from depots near the systems, and the trucks' rounds.
|
||||
pub(super) fn step_supply(&mut self, out: &mut Out) {
|
||||
let now = self.tick;
|
||||
// Systems by a depot reload from it.
|
||||
// Systems by a depot reload directly from matching typed stock.
|
||||
for i in 0..self.sams.len() {
|
||||
if !self.sams[i].empty || !self.sams[i].alive() {
|
||||
let s = &self.sams[i];
|
||||
if !s.empty || !s.alive() || s.moving() || s.reloading > 0 {
|
||||
continue;
|
||||
}
|
||||
let pos = self.sams[i].pos;
|
||||
if let Some(d) = self
|
||||
.sams
|
||||
.iter()
|
||||
.position(|d| d.kind == SamKind::Depot && d.alive() && d.cargo > 0 && d.pos.distance(pos) < DEPOT_REACH)
|
||||
let pos = s.pos;
|
||||
let (need_m, need_g) = s.needed_ammo();
|
||||
let mut mask = 0u8;
|
||||
if let Some(mk) = need_m
|
||||
&& let Some(d) = self
|
||||
.sams
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.ammo_stock.get(mk) > 0 && d.pos.distance(pos) < DEPOT_REACH)
|
||||
.min_by(|(_, a), (_, b)| a.pos.distance(pos).total_cmp(&b.pos.distance(pos)).then(a.id.cmp(&b.id)))
|
||||
.map(|(j, _)| j)
|
||||
{
|
||||
self.sams[d].cargo -= 1;
|
||||
self.reload_now(i, out);
|
||||
self.sams[d].ammo_stock.take(mk, 1);
|
||||
self.sams[d].sync_cargo();
|
||||
mask |= RELOAD_MISSILE;
|
||||
}
|
||||
if let Some(gk) = need_g
|
||||
&& let Some(d) = self
|
||||
.sams
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.ammo_stock.get(gk) > 0 && d.pos.distance(pos) < DEPOT_REACH)
|
||||
.min_by(|(_, a), (_, b)| a.pos.distance(pos).total_cmp(&b.pos.distance(pos)).then(a.id.cmp(&b.id)))
|
||||
.map(|(j, _)| j)
|
||||
{
|
||||
self.sams[d].ammo_stock.take(gk, 1);
|
||||
self.sams[d].sync_cargo();
|
||||
mask |= RELOAD_GUN;
|
||||
}
|
||||
if mask != 0 {
|
||||
self.reload_weapons(i, mask, out);
|
||||
}
|
||||
}
|
||||
// A destroyed truck drops its job, for another to take.
|
||||
@@ -190,6 +426,7 @@ impl Sim {
|
||||
self.sams[j].ground_rounds += 1;
|
||||
if self.sams[j].ground_rounds >= self.sams[j].cells() && self.sams[j].kind.spec().gun.is_none() { self.sams[j].empty = false; }
|
||||
self.sams[j].ground_request = false;
|
||||
self.sams[j].auto_ground_request = false;
|
||||
self.sams[t].ground_stock -= 1;
|
||||
// A round reserved for return redirected to a waiting request is no
|
||||
// longer return cargo once the last one leaves the truck (#128).
|
||||
@@ -217,7 +454,10 @@ impl Sim {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Where it was going: hand over, or load up.
|
||||
// Priority 3: typed air-defence resupply.
|
||||
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
|
||||
let waiting = self.waiting_needs(truck_id, at, now, &taken);
|
||||
let demand = demand_totals(&waiting);
|
||||
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;
|
||||
@@ -225,45 +465,108 @@ impl Sim {
|
||||
};
|
||||
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);
|
||||
self.sams[j].cargo -= take;
|
||||
self.sams[t].cargo += take;
|
||||
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
|
||||
} else if self.sams[j].empty && self.sams[t].cargo > 0 {
|
||||
self.sams[t].cargo -= 1;
|
||||
self.reload_now(j, out);
|
||||
let mut moved = false;
|
||||
// Unload any cargo not needed by reachable waiting systems (or exceeding total demand).
|
||||
for kind in AmmoKind::ALL {
|
||||
let have = self.sams[t].ammo_stock.get(kind);
|
||||
let excess = have.saturating_sub(demand[kind.index()]);
|
||||
if excess > 0 {
|
||||
let put = self.sams[j].ammo_stock.add(kind, excess).unwrap_or(0);
|
||||
if put > 0 {
|
||||
self.sams[t].ammo_stock.take(kind, put);
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Load needed ammunition kinds in order of nearest waiting systems up to TRUCK_LOAD.
|
||||
'fill: for (_, _, _, needs) in &waiting {
|
||||
for kind in needs.into_iter().flatten() {
|
||||
if self.sams[t].ammo_stock.total() >= TRUCK_LOAD {
|
||||
break 'fill;
|
||||
}
|
||||
let carried = self.sams[t].ammo_stock.get(*kind);
|
||||
if carried < demand[kind.index()] && self.sams[j].ammo_stock.get(*kind) > 0 {
|
||||
let taken_n = self.sams[j].ammo_stock.take(*kind, 1);
|
||||
if taken_n > 0 {
|
||||
self.sams[t].ammo_stock.add(*kind, taken_n);
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.sams[j].sync_cargo();
|
||||
self.sams[t].sync_cargo();
|
||||
if moved {
|
||||
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
|
||||
}
|
||||
} else if self.sams[j].empty && self.sams[j].alive() && !self.sams[j].moving() && self.sams[j].reloading == 0 {
|
||||
let (need_m, need_g) = self.sams[j].needed_ammo();
|
||||
let mut mask = 0u8;
|
||||
if let Some(mk) = need_m && self.sams[t].ammo_stock.take(mk, 1) > 0 {
|
||||
mask |= RELOAD_MISSILE;
|
||||
}
|
||||
if let Some(gk) = need_g && self.sams[t].ammo_stock.take(gk, 1) > 0 {
|
||||
mask |= RELOAD_GUN;
|
||||
}
|
||||
self.sams[t].sync_cargo();
|
||||
if mask != 0 {
|
||||
self.reload_weapons(j, mask, out);
|
||||
}
|
||||
}
|
||||
self.sams[t].job = None;
|
||||
} else if self.sams[j].kind == SamKind::Depot {
|
||||
let depot = &self.sams[j];
|
||||
let can_fetch = self.sams[t].ammo_stock.total() < TRUCK_LOAD
|
||||
&& AmmoKind::ALL.into_iter().any(|k| demand[k.index()] > self.sams[t].ammo_stock.get(k) && depot.ammo_stock.get(k) > 0);
|
||||
let can_drop = depot.ammo_stock.total() < STOCK_LIMIT
|
||||
&& AmmoKind::ALL.into_iter().any(|k| self.sams[t].ammo_stock.get(k) > demand[k.index()]);
|
||||
if !self.routes.out_of_reach(truck_id, depot.id, now) && (can_fetch || can_drop) {
|
||||
let to = depot.pos;
|
||||
self.order_move_near(t, to, HANDOVER - 0.75);
|
||||
continue;
|
||||
}
|
||||
self.sams[t].job = None;
|
||||
} 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;
|
||||
self.order_move_near(t, to, HANDOVER - 0.75);
|
||||
continue;
|
||||
} else {
|
||||
let target_sam = &self.sams[j];
|
||||
let (need_m, need_g) = target_sam.needed_ammo();
|
||||
let has_needed = [need_m, need_g].into_iter().flatten().any(|k| self.sams[t].ammo_stock.get(k) > 0);
|
||||
if target_sam.empty && target_sam.reloading == 0 && !target_sam.moving() && has_needed && !self.routes.out_of_reach(truck_id, target_sam.id, now) {
|
||||
// Stopped short of it (it drove off meanwhile): on to where it stands now.
|
||||
let to = target_sam.pos;
|
||||
self.order_move_near(t, to, HANDOVER - 0.75);
|
||||
continue;
|
||||
}
|
||||
self.sams[t].job = None;
|
||||
}
|
||||
}
|
||||
// A new job: the nearest waiting system no other truck is driving to, or a depot to load at.
|
||||
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive()).filter_map(|s| s.job).collect();
|
||||
let next = if self.sams[t].cargo > 0 {
|
||||
self.sams
|
||||
.iter()
|
||||
.filter(|s| s.empty && s.alive() && !s.moving() && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now))
|
||||
.min_by(|a, b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
|
||||
.map(|s| (s.id, s.pos))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A new job: deliver carried matching ammo first, else fetch needed ammo (or drop unneeded cargo) at a depot.
|
||||
let truck_stock = self.sams[t].ammo_stock;
|
||||
let next = waiting
|
||||
.iter()
|
||||
.find(|(_, _, _, needs)| needs.into_iter().flatten().any(|k| truck_stock.get(*k) > 0))
|
||||
.map(|&(id, pos, _, _)| (id, pos));
|
||||
let next = next.or_else(|| {
|
||||
(self.sams[t].cargo < TRUCK_LOAD)
|
||||
.then(|| {
|
||||
self.sams
|
||||
.iter()
|
||||
.filter(|d| d.kind == SamKind::Depot && d.alive() && d.cargo > 0 && !self.routes.out_of_reach(truck_id, d.id, now))
|
||||
.min_by(|a, b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
|
||||
.map(|d| (d.id, d.pos))
|
||||
})
|
||||
.flatten()
|
||||
let any_demand = demand.iter().any(|&d| d > 0);
|
||||
if truck_stock.total() < TRUCK_LOAD && any_demand {
|
||||
self.sams
|
||||
.iter()
|
||||
.filter(|d| {
|
||||
d.kind == SamKind::Depot
|
||||
&& d.alive()
|
||||
&& !self.routes.out_of_reach(truck_id, d.id, now)
|
||||
&& AmmoKind::ALL.into_iter().any(|k| demand[k.index()] > truck_stock.get(k) && d.ammo_stock.get(k) > 0)
|
||||
})
|
||||
.min_by(|a, b| a.pos.distance(at).total_cmp(&b.pos.distance(at)).then(a.id.cmp(&b.id)))
|
||||
.map(|d| (d.id, d.pos))
|
||||
} else if truck_stock.total() >= TRUCK_LOAD && AmmoKind::ALL.into_iter().any(|k| truck_stock.get(k) > demand[k.index()]) {
|
||||
self.sams
|
||||
.iter()
|
||||
.filter(|d| d.kind == SamKind::Depot && d.alive() && d.ammo_stock.total() < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, d.id, now))
|
||||
.min_by(|a, b| a.pos.distance(at).total_cmp(&b.pos.distance(at)).then(a.id.cmp(&b.id)))
|
||||
.map(|d| (d.id, d.pos))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
if let Some((id, to)) = next {
|
||||
self.sams[t].job = Some(id);
|
||||
@@ -275,15 +578,321 @@ impl Sim {
|
||||
}
|
||||
}
|
||||
|
||||
/// System `i` gets a reload: its magazine fills after its reload time.
|
||||
fn reload_now(&mut self, i: usize, out: &mut Out) {
|
||||
/// Reachable waiting systems sorted by distance from `at`, with each system's needed weapon channels.
|
||||
fn waiting_needs(&self, truck_id: u32, at: DVec3, now: u64, taken: &[u32]) -> Vec<(u32, DVec3, f64, [Option<AmmoKind>; 2])> {
|
||||
let mut out: Vec<_> = self
|
||||
.sams
|
||||
.iter()
|
||||
.filter(|s| s.empty && s.alive() && !s.moving() && s.reloading == 0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now))
|
||||
.filter_map(|s| {
|
||||
let (m, g) = s.needed_ammo();
|
||||
(m.is_some() || g.is_some()).then(|| (s.id, s.pos, s.pos.distance(at), [m, g]))
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.2.total_cmp(&b.2).then(a.0.cmp(&b.0)));
|
||||
out
|
||||
}
|
||||
|
||||
/// System `i` begins reloading the specified weapon channels (`RELOAD_MISSILE | RELOAD_GUN`).
|
||||
fn reload_weapons(&mut self, i: usize, mask: u8, out: &mut Out) {
|
||||
let sam = &mut self.sams[i];
|
||||
sam.empty = false;
|
||||
sam.reload_mask = mask;
|
||||
sam.reloading = sam.reload_time();
|
||||
out.sound("minecraft:block.piston.extend", sam.pos, 2.0, 0.6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an armed unit is currently waiting for ammunition or actively resupplying.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum SupplyStatus {
|
||||
Reloading { ticks_left: u32 },
|
||||
TruckEnRoute { truck_num: usize, truck_id: u32, eta_ticks: u32, rm48u: bool, returning: bool },
|
||||
TruckFetching { truck_num: usize, truck_id: u32, depot_num: usize, eta_ticks: u32, rm48u: bool },
|
||||
NoRm48uStock,
|
||||
OutOfStock { missing: [Option<AmmoKind>; 2] },
|
||||
NoTruck { rm48u: bool },
|
||||
RouteBlocked { rm48u: bool },
|
||||
WaitingForTruck { rm48u: bool, returning: bool },
|
||||
}
|
||||
|
||||
/// Aggregate ammunition & logistics state across all live depots, trucks, and batteries.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SupplySummary {
|
||||
pub depots_alive: u32,
|
||||
pub trucks_alive: u32,
|
||||
pub trucks_busy: u32,
|
||||
pub waiting_ammo: u32,
|
||||
pub waiting_rm48u: u32,
|
||||
pub reloading: u32,
|
||||
pub rm48u_depot: u32,
|
||||
pub rm48u_truck: u32,
|
||||
pub rm48u_loaded: u32,
|
||||
pub depot_ammo: [u32; AmmoKind::COUNT],
|
||||
pub truck_ammo: [u32; AmmoKind::COUNT],
|
||||
}
|
||||
|
||||
impl SupplySummary {
|
||||
pub fn total_for(&self, kind: AmmoKind) -> u32 {
|
||||
self.depot_ammo[kind.index()] + self.truck_ammo[kind.index()]
|
||||
}
|
||||
|
||||
pub fn depot_total(&self) -> u32 {
|
||||
self.depot_ammo.iter().sum::<u32>() + self.rm48u_depot
|
||||
}
|
||||
}
|
||||
|
||||
fn truck_eta_ticks(sim: &Sim, truck: &Sam, dest: DVec3) -> u32 {
|
||||
let dist = sim.routes.remaining_distance(truck.id, truck.pos, dest);
|
||||
let speed = truck.drive_speed().max(0.05);
|
||||
let travel = (dist / speed).ceil() as u32;
|
||||
let march = if truck.state == SamState::Packing {
|
||||
truck.march
|
||||
} else if truck.state != SamState::Moving && dist > HANDOVER {
|
||||
SamKind::Tzm.march_ticks()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
march + travel
|
||||
}
|
||||
|
||||
fn fetch_eta_ticks(sim: &Sim, truck: &Sam, depot: &Sam, target: DVec3) -> u32 {
|
||||
let leg1 = sim.routes.remaining_distance(truck.id, truck.pos, depot.pos);
|
||||
let leg2 = (depot.pos.distance(target) - HANDOVER).max(0.0);
|
||||
let speed = truck.drive_speed().max(0.05);
|
||||
let march1 = if truck.state == SamState::Packing {
|
||||
truck.march
|
||||
} else if truck.state != SamState::Moving && leg1 > HANDOVER {
|
||||
SamKind::Tzm.march_ticks()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let march2 = if leg2 > 0.0 { SamKind::Tzm.march_ticks() } else { 0 };
|
||||
march1 + march2 + ((leg1 + leg2) / speed).ceil() as u32
|
||||
}
|
||||
|
||||
impl Sim {
|
||||
/// Aggregate logistics inventory and delivery queues across live units.
|
||||
pub fn supply_summary(&self) -> SupplySummary {
|
||||
let mut out = SupplySummary::default();
|
||||
for sam in &self.sams {
|
||||
if !sam.alive() {
|
||||
continue;
|
||||
}
|
||||
match sam.kind {
|
||||
SamKind::Depot => {
|
||||
out.depots_alive += 1;
|
||||
out.rm48u_depot += sam.ground_stock;
|
||||
for kind in AmmoKind::ALL {
|
||||
out.depot_ammo[kind.index()] += sam.ammo_stock.get(kind);
|
||||
}
|
||||
}
|
||||
SamKind::Tzm => {
|
||||
out.trucks_alive += 1;
|
||||
if sam.job.is_some() {
|
||||
out.trucks_busy += 1;
|
||||
}
|
||||
out.rm48u_truck += sam.ground_stock;
|
||||
for kind in AmmoKind::ALL {
|
||||
out.truck_ammo[kind.index()] += sam.ammo_stock.get(kind);
|
||||
}
|
||||
}
|
||||
kind if kind.armed() => {
|
||||
if sam.reloading > 0 {
|
||||
out.reloading += 1;
|
||||
} else if sam.empty {
|
||||
out.waiting_ammo += 1;
|
||||
}
|
||||
if sam.ground_request || sam.ground_return {
|
||||
out.waiting_rm48u += 1;
|
||||
}
|
||||
if kind.supports_rm48u() {
|
||||
out.rm48u_loaded += sam.ground_rounds;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Explains why armed unit `i` is reloading or waiting for ammunition / RM48U delivery.
|
||||
pub fn supply_status(&self, i: usize) -> Option<SupplyStatus> {
|
||||
let sam = self.sams.get(i)?;
|
||||
if !sam.alive() || !sam.kind.armed() {
|
||||
return None;
|
||||
}
|
||||
if sam.reloading > 0 {
|
||||
return Some(SupplyStatus::Reloading { ticks_left: sam.reloading });
|
||||
}
|
||||
let now = self.tick;
|
||||
let mobile_trucks = self
|
||||
.sams
|
||||
.iter()
|
||||
.filter(|t| t.kind == SamKind::Tzm && t.alive() && t.drive_speed() > 0.0)
|
||||
.count();
|
||||
|
||||
if sam.ground_return {
|
||||
if let Some((t_idx, truck)) = self
|
||||
.sams
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, t)| t.kind == SamKind::Tzm && t.alive() && t.job == Some(sam.id))
|
||||
{
|
||||
return Some(SupplyStatus::TruckEnRoute {
|
||||
truck_num: t_idx + 1,
|
||||
truck_id: truck.id,
|
||||
eta_ticks: truck_eta_ticks(self, truck, sam.pos),
|
||||
rm48u: true,
|
||||
returning: true,
|
||||
});
|
||||
}
|
||||
if mobile_trucks == 0 {
|
||||
return Some(SupplyStatus::NoTruck { rm48u: true });
|
||||
}
|
||||
let all_blocked = self
|
||||
.sams
|
||||
.iter()
|
||||
.filter(|t| t.kind == SamKind::Tzm && t.alive() && t.drive_speed() > 0.0)
|
||||
.all(|t| self.routes.out_of_reach(t.id, sam.id, now));
|
||||
return Some(if all_blocked {
|
||||
SupplyStatus::RouteBlocked { rm48u: true }
|
||||
} else {
|
||||
SupplyStatus::WaitingForTruck { rm48u: true, returning: true }
|
||||
});
|
||||
}
|
||||
|
||||
if sam.ground_request {
|
||||
if let Some((t_idx, truck)) = self
|
||||
.sams
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, t)| t.kind == SamKind::Tzm && t.alive() && t.job == Some(sam.id))
|
||||
{
|
||||
return Some(SupplyStatus::TruckEnRoute {
|
||||
truck_num: t_idx + 1,
|
||||
truck_id: truck.id,
|
||||
eta_ticks: truck_eta_ticks(self, truck, sam.pos),
|
||||
rm48u: true,
|
||||
returning: false,
|
||||
});
|
||||
}
|
||||
if let Some((t_idx, truck, d_idx, depot)) = self.sams.iter().enumerate().find_map(|(ti, t)| {
|
||||
if t.kind != SamKind::Tzm || !t.alive() || t.ground_stock > 0 {
|
||||
return None;
|
||||
}
|
||||
let job = t.job?;
|
||||
let (di, d) = self.sams.iter().enumerate().find(|(_, d)| d.id == job && d.kind == SamKind::Depot && d.alive() && d.ground_stock > 0)?;
|
||||
Some((ti, t, di, d))
|
||||
}) {
|
||||
return Some(SupplyStatus::TruckFetching {
|
||||
truck_num: t_idx + 1,
|
||||
truck_id: truck.id,
|
||||
depot_num: d_idx + 1,
|
||||
eta_ticks: fetch_eta_ticks(self, truck, depot, sam.pos),
|
||||
rm48u: true,
|
||||
});
|
||||
}
|
||||
let has_rm48u = self
|
||||
.sams
|
||||
.iter()
|
||||
.any(|s| s.alive() && matches!(s.kind, SamKind::Depot | SamKind::Tzm) && s.ground_stock > 0);
|
||||
if !has_rm48u {
|
||||
return Some(SupplyStatus::NoRm48uStock);
|
||||
}
|
||||
if mobile_trucks == 0 {
|
||||
return Some(SupplyStatus::NoTruck { rm48u: true });
|
||||
}
|
||||
let all_blocked = self
|
||||
.sams
|
||||
.iter()
|
||||
.filter(|t| t.kind == SamKind::Tzm && t.alive() && t.drive_speed() > 0.0)
|
||||
.all(|t| self.routes.out_of_reach(t.id, sam.id, now));
|
||||
return Some(if all_blocked {
|
||||
SupplyStatus::RouteBlocked { rm48u: true }
|
||||
} else {
|
||||
SupplyStatus::WaitingForTruck { rm48u: true, returning: false }
|
||||
});
|
||||
}
|
||||
|
||||
if sam.empty {
|
||||
let (need_m, need_g) = sam.needed_ammo();
|
||||
let needs = [need_m, need_g];
|
||||
if need_m.is_none() && need_g.is_none() {
|
||||
return None;
|
||||
}
|
||||
if let Some((t_idx, truck)) = self
|
||||
.sams
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, t)| t.kind == SamKind::Tzm && t.alive() && t.job == Some(sam.id))
|
||||
{
|
||||
return Some(SupplyStatus::TruckEnRoute {
|
||||
truck_num: t_idx + 1,
|
||||
truck_id: truck.id,
|
||||
eta_ticks: truck_eta_ticks(self, truck, sam.pos),
|
||||
rm48u: false,
|
||||
returning: false,
|
||||
});
|
||||
}
|
||||
if let Some((t_idx, truck, d_idx, depot)) = self.sams.iter().enumerate().find_map(|(ti, t)| {
|
||||
if t.kind != SamKind::Tzm || !t.alive() || t.ammo_stock.total() >= TRUCK_LOAD {
|
||||
return None;
|
||||
}
|
||||
let job = t.job?;
|
||||
let (di, d) = self.sams.iter().enumerate().find(|(_, d)| {
|
||||
d.id == job
|
||||
&& d.kind == SamKind::Depot
|
||||
&& d.alive()
|
||||
&& needs.into_iter().flatten().any(|k| d.ammo_stock.get(k) > 0)
|
||||
})?;
|
||||
Some((ti, t, di, d))
|
||||
}) {
|
||||
return Some(SupplyStatus::TruckFetching {
|
||||
truck_num: t_idx + 1,
|
||||
truck_id: truck.id,
|
||||
depot_num: d_idx + 1,
|
||||
eta_ticks: fetch_eta_ticks(self, truck, depot, sam.pos),
|
||||
rm48u: false,
|
||||
});
|
||||
}
|
||||
let has_stock = self.sams.iter().any(|s| {
|
||||
s.alive()
|
||||
&& matches!(s.kind, SamKind::Depot | SamKind::Tzm)
|
||||
&& needs.into_iter().flatten().any(|k| s.ammo_stock.get(k) > 0)
|
||||
});
|
||||
if !has_stock {
|
||||
return Some(SupplyStatus::OutOfStock { missing: needs });
|
||||
}
|
||||
if mobile_trucks == 0 {
|
||||
return Some(SupplyStatus::NoTruck { rm48u: false });
|
||||
}
|
||||
let all_blocked = self
|
||||
.sams
|
||||
.iter()
|
||||
.filter(|t| t.kind == SamKind::Tzm && t.alive() && t.drive_speed() > 0.0)
|
||||
.all(|t| self.routes.out_of_reach(t.id, sam.id, now));
|
||||
return Some(if all_blocked {
|
||||
SupplyStatus::RouteBlocked { rm48u: false }
|
||||
} else {
|
||||
SupplyStatus::WaitingForTruck { rm48u: false, returning: false }
|
||||
});
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn demand_totals(waiting: &[(u32, DVec3, f64, [Option<AmmoKind>; 2])]) -> [u32; AmmoKind::COUNT] {
|
||||
let mut totals = [0u32; AmmoKind::COUNT];
|
||||
for (_, _, _, needs) in waiting {
|
||||
for kind in needs.into_iter().flatten() {
|
||||
totals[kind.index()] += 1;
|
||||
}
|
||||
}
|
||||
totals
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -578,4 +1187,152 @@ mod tests {
|
||||
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depot_spawn_roll_varies_by_system_weapon_and_rolls_rm48u_with_chance() {
|
||||
let mut saw_rm48u = false;
|
||||
let mut saw_zero_rm48u = false;
|
||||
let mut saw_diff_pantsir_channels = false;
|
||||
for seed in 1..=100u64 {
|
||||
let mut sim = Sim::new(seed);
|
||||
let mut depot = Sam::new(1, SamKind::Depot, DVec3::ZERO, 0.0);
|
||||
sim.roll_depot_stock(&mut depot);
|
||||
for kind in AmmoKind::ALL {
|
||||
let (lo, hi) = kind.spawn_range();
|
||||
let n = depot.ammo_stock.get(kind);
|
||||
assert!((lo..=hi).contains(&n), "seed {seed} {kind:?}: {n} not in {lo}..={hi}");
|
||||
}
|
||||
if depot.ammo_stock.get(AmmoKind::PantsirMissile) != depot.ammo_stock.get(AmmoKind::PantsirGun) {
|
||||
saw_diff_pantsir_channels = true;
|
||||
}
|
||||
assert!(depot.ground_stock <= 2);
|
||||
if depot.ground_stock > 0 {
|
||||
saw_rm48u = true;
|
||||
} else {
|
||||
saw_zero_rm48u = true;
|
||||
}
|
||||
assert_eq!(depot.cargo, depot.ammo_stock.total());
|
||||
}
|
||||
assert!(saw_rm48u && saw_zero_rm48u, "RM48U should appear probabilistically across spawns");
|
||||
assert!(saw_diff_pantsir_channels, "Pantsir missile and gun stocks should vary independently");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depot_only_reloads_matching_system_and_weapon_channel() {
|
||||
let mut sim = Sim::new(1);
|
||||
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 10.0), (SamKind::Pantsir, 12.0), (SamKind::Patriot, 25.0)] {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
|
||||
}
|
||||
sim.sams[0].clear_ammo();
|
||||
sim.sams[0].set_ammo(AmmoKind::PatriotMissile, 2);
|
||||
sim.sams[0].set_ammo(AmmoKind::PantsirMissile, 1);
|
||||
sim.sams[1].missiles = 0;
|
||||
sim.sams[1].empty = true;
|
||||
sim.sams[2].missiles = 0;
|
||||
sim.sams[2].bursts = 0;
|
||||
sim.sams[2].empty = true;
|
||||
sim.sams[3].missiles = 0;
|
||||
sim.sams[3].empty = true;
|
||||
sim.step_supply(&mut Out::default());
|
||||
assert_eq!(sim.sams[1].reloading, 0, "S-400 must not reload from Patriot stock");
|
||||
assert!(sim.sams[1].empty);
|
||||
assert_eq!(sim.sams[3].reloading, 0, "Patriot beyond DEPOT_REACH (25 > 16) must not auto-reload directly");
|
||||
assert!(sim.sams[3].empty);
|
||||
assert!(sim.sams[2].reloading > 0, "Pantsir must start reloading missiles");
|
||||
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::PantsirMissile), 0);
|
||||
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::PatriotMissile), 2);
|
||||
// Simulate reload completion in step_sams: only missiles are restored, guns remain 0.
|
||||
sim.sams[2].reloading = 1;
|
||||
sim.step(&mut Ground::default(), None, &mut Out::default());
|
||||
assert_eq!(sim.sams[2].missiles, 12);
|
||||
assert_eq!(sim.sams[2].bursts, 0);
|
||||
// After step_sams detects bursts == 0, Pantsir marks empty again and waits for PantsirGun.
|
||||
assert!(sim.sams[2].empty);
|
||||
sim.sams[0].set_ammo(AmmoKind::PantsirGun, 1);
|
||||
sim.step_supply(&mut Out::default());
|
||||
assert!(sim.sams[2].reloading > 0, "Pantsir must now reload gun channel");
|
||||
sim.sams[2].reloading = 1;
|
||||
sim.step(&mut Ground::default(), None, &mut Out::default());
|
||||
assert_eq!(sim.sams[2].bursts, 140);
|
||||
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::PantsirGun), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tzm_fetches_matching_ammo_and_drops_unneeded_cargo() {
|
||||
let mut sim = Sim::new(4);
|
||||
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::Tor, 160.0), (SamKind::Tzm, 0.0)] {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
|
||||
}
|
||||
sim.sams[0].clear_ammo();
|
||||
sim.sams[0].set_ammo(AmmoKind::TorMissile, 1);
|
||||
sim.sams[1].missiles = 0;
|
||||
sim.sams[1].empty = true;
|
||||
// Full TZM carrying unneeded PatriotMissile must drop it off at the depot and pick up TorMissile.
|
||||
sim.sams[2].set_ammo(AmmoKind::PatriotMissile, 2);
|
||||
sim.tick = 1;
|
||||
serve_until(&mut sim, 2, |s| s.sams[1].reloading > 0);
|
||||
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::PatriotMissile), 2);
|
||||
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::TorMissile), 0);
|
||||
assert_eq!(sim.sams[2].ammo_stock.total(), 0);
|
||||
assert!(!sim.sams[1].empty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supply_summary_and_status_diagnose_all_wait_and_delivery_states() {
|
||||
let mut sim = Sim::new(1);
|
||||
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::Tor, 160.0), (SamKind::S400, 200.0), (SamKind::Tzm, 40.0)] {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
|
||||
}
|
||||
sim.sams[0].clear_ammo();
|
||||
sim.sams[0].ground_stock = 1;
|
||||
sim.sams[1].missiles = 0;
|
||||
sim.sams[1].empty = true;
|
||||
sim.sams[2].ground_request = true;
|
||||
|
||||
assert_eq!(sim.supply_status(0), None);
|
||||
assert_eq!(sim.supply_status(3), None);
|
||||
assert_eq!(sim.supply_status(1), Some(SupplyStatus::OutOfStock { missing: [Some(AmmoKind::TorMissile), None] }));
|
||||
|
||||
sim.sams[0].set_ammo(AmmoKind::TorMissile, 2);
|
||||
sim.sams[0].ground_stock = 0;
|
||||
assert_eq!(sim.supply_status(2), Some(SupplyStatus::NoRm48uStock));
|
||||
|
||||
sim.sams[0].ground_stock = 1;
|
||||
sim.sams[3].job = Some(sim.sams[0].id);
|
||||
match sim.supply_status(2) {
|
||||
Some(SupplyStatus::TruckFetching { truck_num: 4, depot_num: 1, eta_ticks, rm48u: true, .. }) => assert!(eta_ticks > 0),
|
||||
other => panic!("expected RM48U fetch status, got {other:?}"),
|
||||
}
|
||||
|
||||
sim.sams[3].ground_stock = 1;
|
||||
sim.sams[3].job = Some(sim.sams[2].id);
|
||||
match sim.supply_status(2) {
|
||||
Some(SupplyStatus::TruckEnRoute { truck_num: 4, eta_ticks, rm48u: true, returning: false, .. }) => assert!(eta_ticks > 0),
|
||||
other => panic!("expected RM48U delivery status, got {other:?}"),
|
||||
}
|
||||
|
||||
sim.sams[2].ground_request = false;
|
||||
sim.sams[3].job = Some(sim.sams[0].id);
|
||||
match sim.supply_status(1) {
|
||||
Some(SupplyStatus::TruckFetching { truck_num: 4, depot_num: 1, eta_ticks, rm48u: false, .. }) => assert!(eta_ticks > 0),
|
||||
other => panic!("expected Tor fetch status, got {other:?}"),
|
||||
}
|
||||
|
||||
sim.sams[3].job = None;
|
||||
assert_eq!(sim.supply_status(1), Some(SupplyStatus::WaitingForTruck { rm48u: false, returning: false }));
|
||||
sim.routes.unreachable.insert((sim.sams[3].id, sim.sams[1].id), 100);
|
||||
assert_eq!(sim.supply_status(1), Some(SupplyStatus::RouteBlocked { rm48u: false }));
|
||||
sim.sams[3].comps.0[Part::Tracks as usize] = 0.0;
|
||||
assert_eq!(sim.supply_status(1), Some(SupplyStatus::NoTruck { rm48u: false }));
|
||||
sim.sams[1].reloading = 42;
|
||||
assert_eq!(sim.supply_status(1), Some(SupplyStatus::Reloading { ticks_left: 42 }));
|
||||
|
||||
let summary = sim.supply_summary();
|
||||
assert_eq!((summary.depots_alive, summary.trucks_alive, summary.trucks_busy), (1, 1, 0));
|
||||
assert_eq!((summary.rm48u_depot, summary.rm48u_truck, summary.reloading), (1, 1, 1));
|
||||
assert_eq!(summary.total_for(AmmoKind::TorMissile), 2);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -34,6 +34,9 @@ pub use observe::Observation;
|
||||
pub use recon::{Category, Mark, Quality, Source, is_drone_id, priority_parts};
|
||||
pub mod lights;
|
||||
mod logistics;
|
||||
pub use logistics::{AmmoKind, AmmoStock, DEPOT_RM48U_CHANCE, SupplyStatus, SupplySummary};
|
||||
pub const TRUCK_CAPACITY: u32 = TRUCK_LOAD;
|
||||
pub const DEPOT_REACH_BLOCKS: f64 = DEPOT_REACH;
|
||||
mod orders;
|
||||
mod route;
|
||||
mod voices;
|
||||
@@ -1254,6 +1257,12 @@ pub struct Sam {
|
||||
march: u32,
|
||||
/// A depot's reloads in stock; a reload truck's on board.
|
||||
pub cargo: u32,
|
||||
/// Typed air-defence ammunition stock per system and weapon channel (depots and TZMs).
|
||||
pub ammo_stock: AmmoStock,
|
||||
/// Pending automatic RM48U request originated by auto-strike.
|
||||
pub auto_ground_request: bool,
|
||||
/// Bitmask of weapon channels being reloaded (`RELOAD_MISSILE | RELOAD_GUN`).
|
||||
pub(super) reload_mask: u8,
|
||||
/// A reload truck's job: the system it is driving to, or a depot.
|
||||
job: Option<u32>,
|
||||
/// Out of ammunition, waiting for a resupply.
|
||||
@@ -1335,10 +1344,15 @@ impl Sam {
|
||||
dest: None,
|
||||
march: 0,
|
||||
cargo: match kind {
|
||||
SamKind::Depot => 30,
|
||||
SamKind::Tzm => 2,
|
||||
SamKind::Depot => AmmoStock::new_default_depot().total(),
|
||||
_ => 0,
|
||||
},
|
||||
ammo_stock: match kind {
|
||||
SamKind::Depot => AmmoStock::new_default_depot(),
|
||||
_ => AmmoStock::default(),
|
||||
},
|
||||
auto_ground_request: false,
|
||||
reload_mask: 0,
|
||||
job: None,
|
||||
empty: false,
|
||||
ew_on: false,
|
||||
@@ -1380,6 +1394,49 @@ impl Sam {
|
||||
pub fn preparing_cell(&self) -> Option<u32> {
|
||||
self.preparing.map(|p| p.cell)
|
||||
}
|
||||
/// Keeps legacy `cargo` synchronized with `ammo_stock.total()`.
|
||||
pub fn sync_cargo(&mut self) {
|
||||
self.cargo = self.ammo_stock.total();
|
||||
}
|
||||
/// Sets the count of a specific typed air-defence ammunition kind and updates `cargo`.
|
||||
pub fn set_ammo(&mut self, kind: AmmoKind, count: u32) {
|
||||
self.ammo_stock.set(kind, count);
|
||||
self.sync_cargo();
|
||||
}
|
||||
/// Clears all typed air-defence ammunition and sets `cargo` to 0.
|
||||
pub fn clear_ammo(&mut self) {
|
||||
self.ammo_stock = AmmoStock::default();
|
||||
self.cargo = 0;
|
||||
}
|
||||
/// Weapon channels that currently need resupply (`(missile_ammo, gun_ammo)`).
|
||||
pub fn needed_ammo(&self) -> (Option<AmmoKind>, Option<AmmoKind>) {
|
||||
let missile = self
|
||||
.kind
|
||||
.missile_ammo()
|
||||
.filter(|_| self.missiles == 0 && self.part(Part::Launcher) > 0.0 && self.cells() > self.ground_rounds);
|
||||
let gun = self.kind.gun_ammo().filter(|_| self.bursts == 0);
|
||||
(missile, gun)
|
||||
}
|
||||
/// Infers which weapon channels were reloading when loading a save without `reload_mask`.
|
||||
pub fn infer_reload_mask(&mut self) {
|
||||
if self.reloading == 0 {
|
||||
self.reload_mask = 0;
|
||||
return;
|
||||
}
|
||||
let spec = self.kind.spec();
|
||||
let mut mask = 0u8;
|
||||
if spec.missile.is_some() && self.missiles == 0 {
|
||||
mask |= logistics::RELOAD_MISSILE;
|
||||
}
|
||||
if spec.gun.is_some() && self.bursts == 0 {
|
||||
mask |= logistics::RELOAD_GUN;
|
||||
}
|
||||
self.reload_mask = if mask == 0 {
|
||||
logistics::RELOAD_MISSILE | logistics::RELOAD_GUN
|
||||
} else {
|
||||
mask
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- effects
|
||||
@@ -1450,6 +1507,8 @@ pub struct Sim {
|
||||
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,
|
||||
/// Automatic destruction of fixed enemy launch sites by idle S-400s (`/airdef autostrike`).
|
||||
pub auto_strike: 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.
|
||||
@@ -1561,6 +1620,7 @@ impl Sim {
|
||||
shader: false,
|
||||
hold: false,
|
||||
last_chance: true,
|
||||
auto_strike: false,
|
||||
far_shots: true,
|
||||
horizons: HashMap::new(),
|
||||
later: Vec::new(),
|
||||
@@ -1772,6 +1832,7 @@ impl Sim {
|
||||
profile::time(profile::SAMS, || self.step_sams(ground, out));
|
||||
self.step_missiles(ground, out);
|
||||
self.step_strikes(ground, player, out);
|
||||
self.step_auto_strike(out);
|
||||
self.step_fx(ground, out);
|
||||
self.draw_targets(out);
|
||||
self.draw_sites(out);
|
||||
@@ -2453,8 +2514,18 @@ impl Sim {
|
||||
if sam.reloading > 0 {
|
||||
sam.reloading -= 1;
|
||||
if sam.reloading == 0 {
|
||||
sam.missiles = sam.cells().saturating_sub(sam.ground_rounds);
|
||||
sam.bursts = spec.gun.as_ref().map_or(0, |g| g.bursts);
|
||||
let mask = if sam.reload_mask == 0 {
|
||||
logistics::RELOAD_MISSILE | logistics::RELOAD_GUN
|
||||
} else {
|
||||
sam.reload_mask
|
||||
};
|
||||
if mask & logistics::RELOAD_MISSILE != 0 {
|
||||
sam.missiles = sam.cells().saturating_sub(sam.ground_rounds);
|
||||
}
|
||||
if mask & logistics::RELOAD_GUN != 0 {
|
||||
sam.bursts = spec.gun.as_ref().map_or(0, |g| g.bursts);
|
||||
}
|
||||
sam.reload_mask = 0;
|
||||
out.sound("minecraft:block.piston.extend", sam.pos, 2.0, 0.6);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use super::*;
|
||||
|
||||
/// Blocks a tick a vehicle drives (about 25 km/h).
|
||||
const SPEED: f64 = 0.35;
|
||||
pub(super) const SPEED: f64 = 0.35;
|
||||
|
||||
impl SamKind {
|
||||
/// Ticks to pack up for the march, and to deploy again.
|
||||
|
||||
@@ -28,7 +28,7 @@ fn dead_truck_must_not_reserve_a_waiting_system() {
|
||||
let depot=sim.id(); sim.sams.push(Sam::new(depot,SamKind::Depot,DVec3::new(500.,70.,0.),0.));
|
||||
let target=sim.id(); let mut s=Sam::new(target,SamKind::Tor,DVec3::new(0.,70.,0.),0.);s.empty=true;s.missiles=0;sim.sams.push(s);
|
||||
let dead=sim.id();let mut s=Sam::new(dead,SamKind::Tzm,DVec3::new(100.,70.,0.),0.);s.job=Some(target);s.health=0.;sim.sams.push(s);
|
||||
let live=sim.id();sim.sams.push(Sam::new(live,SamKind::Tzm,DVec3::new(30.,70.,0.),0.));
|
||||
let live=sim.id();let mut s=Sam::new(live,SamKind::Tzm,DVec3::new(30.,70.,0.),0.);s.set_ammo(AmmoKind::TorMissile,1);sim.sams.push(s);
|
||||
sim.tick=3;sim.step_supply(&mut Out::default());
|
||||
assert_eq!(sim.sams[3].job,Some(target),"a live loaded truck must take the waiting system");
|
||||
}
|
||||
@@ -39,7 +39,7 @@ fn truck_must_follow_a_target_that_moved_away() {
|
||||
let mut sim=Sim::new(1);
|
||||
let depot=sim.id();sim.sams.push(Sam::new(depot,SamKind::Depot,DVec3::new(500.,70.,0.),0.));
|
||||
let target=sim.id();let mut s=Sam::new(target,SamKind::Tor,DVec3::new(100.,70.,0.),0.);s.empty=true;s.missiles=0;sim.sams.push(s);
|
||||
let truck=sim.id();let mut s=Sam::new(truck,SamKind::Tzm,DVec3::new(0.,70.,0.),0.);s.job=Some(target);sim.sams.push(s);
|
||||
let truck=sim.id();let mut s=Sam::new(truck,SamKind::Tzm,DVec3::new(0.,70.,0.),0.);s.job=Some(target);s.set_ammo(AmmoKind::TorMissile,1);sim.sams.push(s);
|
||||
sim.tick=2;sim.step_supply(&mut Out::default());
|
||||
assert!(sim.sams[2].moving(),"truck at obsolete rendezvous must get a new move order");
|
||||
}
|
||||
|
||||
@@ -228,6 +228,19 @@ pub(super) struct Route {
|
||||
}
|
||||
|
||||
impl Route {
|
||||
/// Horizontal path distance remaining from `pos` to the route's goal.
|
||||
pub(super) fn remaining_distance(&self, pos: DVec3) -> f64 {
|
||||
if self.next >= self.pts.len() {
|
||||
return (horizontal(self.dest - pos).length() - self.slack).max(0.0);
|
||||
}
|
||||
let mut total = 0.0;
|
||||
let mut cur = pos;
|
||||
for &pt in &self.pts[self.next..] {
|
||||
total += horizontal(pt - cur).length();
|
||||
cur = pt;
|
||||
}
|
||||
total
|
||||
}
|
||||
pub(super) fn new(pos: DVec3, dest: DVec3, slack: f64, kind: SamKind, now: u64) -> Self {
|
||||
let dist = horizontal(dest - pos).length();
|
||||
let cell = if dist <= 400.0 { 4 } else if dist <= 900.0 { 6 } else { 8 };
|
||||
@@ -739,6 +752,9 @@ impl Routes {
|
||||
pub(super) fn out_of_reach(&self, truck: u32, job: u32, now: u64) -> bool {
|
||||
self.unreachable.get(&(truck, job)).is_some_and(|&t| t > now)
|
||||
}
|
||||
pub(super) fn remaining_distance(&self, unit_id: u32, pos: DVec3, dest: DVec3) -> f64 {
|
||||
self.map.get(&unit_id).map_or_else(|| (horizontal(dest - pos).length() - HANDOVER).max(0.0), |r| r.remaining_distance(pos))
|
||||
}
|
||||
}
|
||||
|
||||
impl SamKind {
|
||||
|
||||
@@ -13,7 +13,7 @@ const GRAVITY: f64 = 0.05;
|
||||
/// Height over the target where the Oreshnik's blocks release their submunitions.
|
||||
const BLOCK_SPLIT: f64 = 300.0;
|
||||
/// How near a depot a system reloads straight from it.
|
||||
const DEPOT_REACH: f64 = 60.0;
|
||||
const DEPOT_REACH: f64 = 16.0;
|
||||
/// How near a truck must come to hand a reload over, or to load up at a depot.
|
||||
const HANDOVER: f64 = 10.0;
|
||||
/// What a truck carries.
|
||||
|
||||
@@ -736,14 +736,237 @@ impl Sim {
|
||||
.then(a.total_cmp(b)).then(self.sams[*i].id.cmp(&self.sams[*j].id))
|
||||
})
|
||||
.ok_or("Нет готового С-400 с загруженной RM48U в игровой дальности; подготовьте боезапас у склада")?;
|
||||
let sam = &mut self.sams[i];
|
||||
self.prepare_strike_from(i, id, est.pos);
|
||||
Ok(format!("С-400 №{} готовит RM48U по ПУ №{id}", i + 1))
|
||||
}
|
||||
|
||||
fn prepare_strike_from(&mut self, sam_index: usize, site_id: u32, aim: DVec2) {
|
||||
let sam = &mut self.sams[sam_index];
|
||||
sam.sync_tube_cells();
|
||||
let cell = sam.next_tube_cell();
|
||||
sam.preparing = Some(launch::Prepare { target: id, cell, start: self.tick, ground: true });
|
||||
sam.preparing = Some(launch::Prepare { target: site_id, cell, start: self.tick, ground: true });
|
||||
sam.cap_cell = cell as u8;
|
||||
sam.cap_open = 0.0;
|
||||
self.strikes.pending.push(PendingStrike { carrier: sam.id, site: id, aim: est.pos });
|
||||
Ok(format!("С-400 №{} готовит RM48U по ПУ №{id}", i + 1))
|
||||
self.strikes.pending.push(PendingStrike { carrier: sam.id, site: site_id, aim });
|
||||
}
|
||||
|
||||
/// True while a raid is active (planning/queued/drones airborne).
|
||||
pub fn raid_in_progress(&self) -> bool {
|
||||
self.wave.is_some() || !self.queue.is_empty() || self.drones.iter().any(|d| d.alive())
|
||||
}
|
||||
|
||||
fn has_foreseen_air_task(&self, sam: &Sam) -> bool {
|
||||
const AUTO_STRIKE_LOOKAHEAD_TICKS: f64 = 240.0;
|
||||
if sam.target.is_some() || sam.gun_target.is_some() || self.missiles.iter().any(|m| m.sam == sam.id) {
|
||||
return true;
|
||||
}
|
||||
let Some(load) = sam.kind.spec().missile.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
let engage_reach = if self.far_shots { load.max * why::FAR_K } else { load.max };
|
||||
for tr in &sam.tracks {
|
||||
if tr.age(self.tick) > sight::MISSILE_AGE {
|
||||
continue;
|
||||
}
|
||||
let Some(d) = self.drones.iter().find(|d| d.id == tr.id && d.alive()) else {
|
||||
continue;
|
||||
};
|
||||
let in_role = tr.class.in_roles(sam.roles) && sam.doctrine.area_blocks(sam.pos, tr, self.tick) == 0;
|
||||
let urgent = self.last_chance && self.last_chance_for(sam, tr.class, d, 0);
|
||||
if !in_role && !urgent {
|
||||
continue;
|
||||
}
|
||||
let est = tr.est(self.tick);
|
||||
let p0 = est - sam.pos;
|
||||
let dist = p0.length();
|
||||
if dist <= load.max * 1.15 {
|
||||
return true;
|
||||
}
|
||||
let v2 = tr.vel.length_squared();
|
||||
let t = if v2 > 1e-6 { (-p0.dot(tr.vel) / v2).clamp(0.0, AUTO_STRIKE_LOOKAHEAD_TICKS) } else { 0.0 };
|
||||
if (p0 + tr.vel * t).length() <= load.max * 1.1 {
|
||||
return true;
|
||||
}
|
||||
if self.far_shots && dist <= engage_reach && tr.vel.dot((-p0).normalize_or_zero()) > 0.1 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn s400_free_for_auto_strike(&self, i: usize) -> bool {
|
||||
let sam = &self.sams[i];
|
||||
sam.kind.supports_rm48u()
|
||||
&& sam.alive()
|
||||
&& !sam.moving()
|
||||
&& sam.reloading == 0
|
||||
&& sam.cooldown == 0
|
||||
&& sam.part(Part::Launcher) > 0.0
|
||||
&& sam.preparing.is_none()
|
||||
&& !sam.ground_return
|
||||
&& !self.has_foreseen_air_task(sam)
|
||||
}
|
||||
|
||||
fn cancel_auto_ground_requests(&mut self) {
|
||||
for s in &mut self.sams {
|
||||
if s.auto_ground_request {
|
||||
s.ground_request = false;
|
||||
s.auto_ground_request = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Automatic counter-battery: idle S-400s without foreseen air tasks request RM48U and strike fixed sites.
|
||||
pub(super) fn step_auto_strike(&mut self, out: &mut Out) {
|
||||
if !self.auto_strike || self.hold || !self.raid_in_progress() {
|
||||
self.cancel_auto_ground_requests();
|
||||
return;
|
||||
}
|
||||
if self.tick % 10 != 0 {
|
||||
return;
|
||||
}
|
||||
let mut uncovered: Vec<(u32, SiteClass, SiteState, Estimate)> = self
|
||||
.strikes
|
||||
.known
|
||||
.iter()
|
||||
.filter_map(|k| {
|
||||
let est = k.est.filter(|e| e.fix)?;
|
||||
if matches!(k.state, SiteState::Destroyed(_)) {
|
||||
return None;
|
||||
}
|
||||
if !self.sites.get(k.site).is_some_and(|s| s.alive) {
|
||||
return None;
|
||||
}
|
||||
if self.strikes.flights.iter().any(|f| f.site == k.site) || self.strikes.pending.iter().any(|p| p.site == k.site) {
|
||||
return None;
|
||||
}
|
||||
Some((k.site, k.class, k.state, est))
|
||||
})
|
||||
.collect();
|
||||
if uncovered.is_empty() {
|
||||
self.cancel_auto_ground_requests();
|
||||
return;
|
||||
}
|
||||
let threat_rank = |c: SiteClass| match c {
|
||||
SiteClass::Battery => 3u8,
|
||||
SiteClass::Launcher => 2,
|
||||
SiteClass::Ramp => 1,
|
||||
};
|
||||
let pick_best_site = |list: &[(u32, SiteClass, SiteState, Estimate)], sam_pos: DVec3| -> Option<usize> {
|
||||
let sam_xz = DVec2::new(sam_pos.x, sam_pos.z);
|
||||
list.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, _, _, est))| (est.pos - sam_xz).length() <= TUNE.range)
|
||||
.min_by(|(_, (id_a, class_a, st_a, est_a)), (_, (id_b, class_b, st_b, est_b))| {
|
||||
let active_a = matches!(st_a, SiteState::Active);
|
||||
let active_b = matches!(st_b, SiteState::Active);
|
||||
let ok_a = est_a.radius <= TUNE.rough;
|
||||
let ok_b = est_b.radius <= TUNE.rough;
|
||||
active_b
|
||||
.cmp(&active_a)
|
||||
.then(ok_b.cmp(&ok_a))
|
||||
.then(threat_rank(*class_b).cmp(&threat_rank(*class_a)))
|
||||
.then(est_a.radius.total_cmp(&est_b.radius))
|
||||
.then((est_a.pos - sam_xz).length().total_cmp(&(est_b.pos - sam_xz).length()))
|
||||
.then(id_a.cmp(id_b))
|
||||
})
|
||||
.map(|(idx, _)| idx)
|
||||
};
|
||||
|
||||
// Phase 1: Fire already-loaded RM48U on free S-400 launchers.
|
||||
for i in 0..self.sams.len() {
|
||||
if !self.s400_free_for_auto_strike(i) {
|
||||
continue;
|
||||
}
|
||||
let s = &self.sams[i];
|
||||
if s.ground_rounds <= u32::from(s.ground_return) {
|
||||
continue;
|
||||
}
|
||||
if let Some(pos_idx) = pick_best_site(&uncovered, s.pos) {
|
||||
let (site_id, _, _, est) = uncovered.remove(pos_idx);
|
||||
self.prepare_strike_from(i, site_id, est.pos);
|
||||
out.messages.push(format!("Автоудар: С-400 №{} готовит RM48U по ПУ №{site_id}", i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: Order RM48U delivery (or load directly from nearby depot and fire) for remaining uncovered sites.
|
||||
let mut pending_requests = self
|
||||
.sams
|
||||
.iter()
|
||||
.filter(|s| s.alive() && s.kind.supports_rm48u() && s.ground_request)
|
||||
.count();
|
||||
let mut available_rm48u: u32 = self
|
||||
.sams
|
||||
.iter()
|
||||
.filter(|s| s.alive() && matches!(s.kind, SamKind::Depot | SamKind::Tzm))
|
||||
.map(|s| s.ground_stock)
|
||||
.sum();
|
||||
while !uncovered.is_empty() && pending_requests < uncovered.len() && (pending_requests as u32) < available_rm48u {
|
||||
let best_sam = (0..self.sams.len())
|
||||
.filter_map(|i| {
|
||||
if !self.s400_free_for_auto_strike(i) {
|
||||
return None;
|
||||
}
|
||||
let sam = &self.sams[i];
|
||||
if sam.ground_rounds != 0 || sam.ground_request || sam.ground_return || sam.cells() == 0 {
|
||||
return None;
|
||||
}
|
||||
if sam.missiles + sam.ground_rounds >= sam.cells() && sam.doctrine.reserve > 0 && sam.missiles <= sam.doctrine.reserve {
|
||||
return None;
|
||||
}
|
||||
pick_best_site(&uncovered, sam.pos)?;
|
||||
let direct_depot = self
|
||||
.sams
|
||||
.iter()
|
||||
.any(|d| d.kind == SamKind::Depot && d.alive() && d.ground_stock > 0 && d.pos.distance(sam.pos) < DEPOT_REACH);
|
||||
if !direct_depot {
|
||||
let reachable_tzm = self.sams.iter().any(|t| {
|
||||
t.kind == SamKind::Tzm
|
||||
&& t.alive()
|
||||
&& t.drive_speed() > 0.0
|
||||
&& !self.routes.out_of_reach(t.id, sam.id, self.tick)
|
||||
});
|
||||
if !reachable_tzm {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let min_dist = self
|
||||
.sams
|
||||
.iter()
|
||||
.filter(|d| d.alive() && matches!(d.kind, SamKind::Depot | SamKind::Tzm) && d.ground_stock > 0)
|
||||
.map(|d| d.pos.distance(sam.pos))
|
||||
.min_by(f64::total_cmp)
|
||||
.unwrap_or(f64::INFINITY);
|
||||
Some((i, direct_depot, min_dist, sam.missiles, sam.id))
|
||||
})
|
||||
.min_by(|a, b| {
|
||||
b.1.cmp(&a.1)
|
||||
.then(a.2.total_cmp(&b.2))
|
||||
.then(b.3.cmp(&a.3))
|
||||
.then(a.4.cmp(&b.4))
|
||||
})
|
||||
.map(|(i, ..)| i);
|
||||
let Some(i) = best_sam else { break };
|
||||
match self.load_ground_round(i) {
|
||||
Ok(_) => {
|
||||
if self.sams[i].ground_request {
|
||||
self.sams[i].auto_ground_request = true;
|
||||
pending_requests += 1;
|
||||
out.messages.push(format!("Автоудар: С-400 №{} заказал доставку RM48U", i + 1));
|
||||
} else if self.sams[i].ground_rounds > 0 {
|
||||
available_rm48u = available_rm48u.saturating_sub(1);
|
||||
if let Some(pos_idx) = pick_best_site(&uncovered, self.sams[i].pos) {
|
||||
let (site_id, _, _, est) = uncovered.remove(pos_idx);
|
||||
self.prepare_strike_from(i, site_id, est.pos);
|
||||
out.messages.push(format!("Автоудар: С-400 №{} загрузил RM48U и готовит пуск по ПУ №{site_id}", i + 1));
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn prepare_ground_strikes(&mut self, out: &mut Out) {
|
||||
@@ -989,6 +1212,7 @@ impl Sim {
|
||||
v.push("Известных ПУ нет: РЛС должна заметить пуск или вылетевшую цель; для удара нужно определить место пуска".into());
|
||||
}
|
||||
v.push("Удар: /airdef strike <вражеская ПУ>; RM48U: /airdef ground-stock <склад> <число>, затем ground-load <С-400>".into());
|
||||
v.push(format!("Автоудар по ПУ: {} (/airdef autostrike on|off)", if self.auto_strike { "вкл" } else { "выкл" }));
|
||||
v
|
||||
}
|
||||
}
|
||||
@@ -1869,4 +2093,220 @@ mod tests {
|
||||
assert!(rec.tracks.iter().any(|t| t.what == record::What::Strike));
|
||||
assert!(rec.events.iter().any(|e| matches!(e.kind, record::EventKind::Strike { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_strike_disabled_by_default_does_not_request_or_fire() {
|
||||
let mut sim = Sim::new(11);
|
||||
assert!(!sim.auto_strike);
|
||||
fixed_site(&mut sim, DVec3::new(0.0, 64.0, 400.0), 1);
|
||||
let mut s400 = Sam::new(sim.id(), SamKind::S400, DVec3::ZERO, 0.0);
|
||||
s400.cooldown = 0;
|
||||
s400.ground_rounds = 1;
|
||||
s400.missiles = 3;
|
||||
sim.sams.push(s400);
|
||||
let mut depot = Sam::new(sim.id(), SamKind::Depot, DVec3::new(200.0, 64.0, 0.0), 0.0);
|
||||
depot.ground_stock = 2;
|
||||
sim.sams.push(depot);
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(5000.0, 100.0, 5000.0), -DVec3::Z, DVec3::new(5000.0, 64.0, 0.0));
|
||||
let mut ground = Ground::default();
|
||||
let mut out = Out::default();
|
||||
for _ in 0..40 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
}
|
||||
assert!(sim.strikes.pending.is_empty() && sim.strikes.flights.is_empty());
|
||||
assert!(!sim.sams[0].ground_request);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_strike_loads_directly_from_nearby_depot_and_fires() {
|
||||
let mut sim = Sim::new(12);
|
||||
sim.auto_strike = true;
|
||||
let site = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 450.0), 1);
|
||||
let mut s400 = Sam::new(sim.id(), SamKind::S400, DVec3::new(0.0, 64.0, 0.0), 0.0);
|
||||
s400.cooldown = 0;
|
||||
sim.sams.push(s400);
|
||||
let mut depot = Sam::new(sim.id(), SamKind::Depot, DVec3::new(12.0, 64.0, 0.0), 0.0);
|
||||
depot.ground_stock = 2;
|
||||
sim.sams.push(depot);
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(5000.0, 100.0, 5000.0), -DVec3::Z, DVec3::new(5000.0, 64.0, 0.0));
|
||||
let mut ground = Ground::default();
|
||||
let mut out = Out::default();
|
||||
run(&mut sim, &mut ground, &mut out, 40);
|
||||
assert_eq!(sim.strikes.fired, 1);
|
||||
assert_eq!(sim.strikes.flights.len(), 1);
|
||||
assert_eq!(sim.strikes.flights[0].site, site);
|
||||
assert_eq!(sim.sams[1].ground_stock, 1);
|
||||
assert_eq!(sim.sams[1].air_48n6_stock, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_strike_orders_delivery_via_tzm_and_fires_when_s400_is_free() {
|
||||
let mut sim = Sim::new(13);
|
||||
sim.auto_strike = true;
|
||||
let site = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 500.0), 1);
|
||||
let mut depot = Sam::new(sim.id(), SamKind::Depot, DVec3::new(0.0, 64.0, 0.0), 0.0);
|
||||
depot.ground_stock = 1;
|
||||
sim.sams.push(depot);
|
||||
let mut s400 = Sam::new(sim.id(), SamKind::S400, DVec3::new(120.0, 64.0, 0.0), 0.0);
|
||||
s400.cooldown = 0;
|
||||
sim.sams.push(s400);
|
||||
let tzm_id = sim.id();
|
||||
sim.sams.push(Sam::new(tzm_id, SamKind::Tzm, DVec3::new(10.0, 64.0, 0.0), 0.0));
|
||||
// Keep an active raid alive far away so raid_in_progress() stays true without threatening the S-400.
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(6000.0, 100.0, 6000.0), -DVec3::Z, DVec3::new(6000.0, 64.0, 0.0));
|
||||
let (mut ground, land) = (Ground::default(), sites::testland::Land(|_, _| 64));
|
||||
let mut out = Out::default();
|
||||
let mut requested = false;
|
||||
for _ in 0..4000 {
|
||||
sites::testland::step(&mut sim, &mut ground, &land, &mut out);
|
||||
if sim.sams[1].auto_ground_request {
|
||||
requested = true;
|
||||
}
|
||||
if sim.strikes.fired > 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(requested, "idle S-400 should automatically order RM48U delivery");
|
||||
assert_eq!(sim.strikes.fired, 1);
|
||||
assert_eq!(sim.strikes.flights[0].site, site);
|
||||
assert!(!sim.sams[1].auto_ground_request);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_strike_waits_when_in_role_threat_is_foreseen_but_ignores_out_of_role_drone() {
|
||||
let mut sim = Sim::new(14);
|
||||
sim.auto_strike = true;
|
||||
fixed_site(&mut sim, DVec3::new(0.0, 64.0, 450.0), 1);
|
||||
let mut s400 = Sam::new(sim.id(), SamKind::S400, DVec3::ZERO, 0.0);
|
||||
s400.cooldown = 0;
|
||||
s400.ground_rounds = 1;
|
||||
s400.missiles = 3;
|
||||
let s400_id = s400.id;
|
||||
// Confirmed Drone (out of S-400's default roles) approaching from 1500 blocks out: must NOT block auto-strike.
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 100.0, 1500.0), -DVec3::Z * 0.6, DVec3::ZERO);
|
||||
let shahed_id = sim.drones[0].id;
|
||||
s400.tracks.push(Track {
|
||||
id: shahed_id,
|
||||
class: ClassEst::Firm(Class::Drone),
|
||||
pos: DVec3::new(0.0, 100.0, 1500.0),
|
||||
vel: DVec3::new(0.0, 0.0, -0.6),
|
||||
tick: 0,
|
||||
own_tick: 0,
|
||||
source: s400_id,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 100,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 100,
|
||||
ttl: 200,
|
||||
hits: 4,
|
||||
locked: false,
|
||||
});
|
||||
// Approaching Kh-101 (cruise missile, in S-400 roles) 1400 blocks out -> reaches within 240 ticks -> MUST block!
|
||||
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 100.0, 1400.0), -DVec3::Z * 2.4, DVec3::ZERO);
|
||||
let kh_id = sim.drones[1].id;
|
||||
s400.tracks.push(Track {
|
||||
id: kh_id,
|
||||
class: ClassEst::Firm(Class::Cruise),
|
||||
pos: DVec3::new(0.0, 100.0, 1400.0),
|
||||
vel: DVec3::new(0.0, 0.0, -2.4),
|
||||
tick: 0,
|
||||
own_tick: 0,
|
||||
source: s400_id,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 100,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 100,
|
||||
ttl: 200,
|
||||
hits: 4,
|
||||
locked: false,
|
||||
});
|
||||
sim.sams.push(s400);
|
||||
assert!(sim.has_foreseen_air_task(&sim.sams[0]));
|
||||
sim.tick = 10;
|
||||
let mut out = Out::default();
|
||||
sim.step_auto_strike(&mut out);
|
||||
assert!(sim.strikes.pending.is_empty(), "approaching Kh-101 must hold auto-strike");
|
||||
// Remove the Kh-101 so only the out-of-role Shahed remains.
|
||||
sim.drones[1].flight = super::super::Flight::Falling;
|
||||
assert!(!sim.has_foreseen_air_task(&sim.sams[0]));
|
||||
sim.tick = 20;
|
||||
sim.step_auto_strike(&mut out);
|
||||
assert_eq!(sim.strikes.pending.len(), 1, "out-of-role drone must not block auto-strike");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_strike_does_not_over_order_for_single_site_and_prioritizes_higher_threat_site() {
|
||||
let mut sim = Sim::new(15);
|
||||
sim.auto_strike = true;
|
||||
let ramp = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 300.0), 1);
|
||||
let bat_id = sim.sites.add(LaunchSite {
|
||||
id: 0,
|
||||
side: 0,
|
||||
sector: 0,
|
||||
bearing: 0.0,
|
||||
class: SiteClass::Battery,
|
||||
pos: DVec3::new(0.0, 64.0, 600.0),
|
||||
range: 600.0,
|
||||
water: false,
|
||||
stock: 1,
|
||||
planned: 1,
|
||||
alive: true,
|
||||
next_free: 0,
|
||||
offmap: false,
|
||||
});
|
||||
sim.strikes.known.push(Known {
|
||||
site: bat_id,
|
||||
class: SiteClass::Battery,
|
||||
obs: Vec::new(),
|
||||
est: Some(Estimate { pos: DVec2::new(0.0, 600.0), radius: 15.0, fix: true, bearing: 0.0, bearing_err: 0.01, origin: DVec2::ZERO }),
|
||||
launches: 1,
|
||||
last: 0,
|
||||
state: SiteState::Active,
|
||||
aimed: false,
|
||||
});
|
||||
let mut s1 = Sam::new(sim.id(), SamKind::S400, DVec3::ZERO, 0.0);
|
||||
s1.cooldown = 0;
|
||||
s1.ground_rounds = 1;
|
||||
s1.missiles = 3;
|
||||
sim.sams.push(s1);
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(6000.0, 100.0, 6000.0), -DVec3::Z, DVec3::new(6000.0, 64.0, 0.0));
|
||||
sim.tick = 10;
|
||||
let mut out = Out::default();
|
||||
sim.step_auto_strike(&mut out);
|
||||
assert_eq!(sim.strikes.pending.len(), 1);
|
||||
assert_eq!(sim.strikes.pending[0].site, bat_id, "Battery must outrank Ramp ({ramp})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_strike_cancels_auto_request_when_turned_off_but_keeps_manual_request() {
|
||||
let mut sim = Sim::new(16);
|
||||
sim.auto_strike = true;
|
||||
fixed_site(&mut sim, DVec3::new(0.0, 64.0, 450.0), 1);
|
||||
let mut depot = Sam::new(sim.id(), SamKind::Depot, DVec3::ZERO, 0.0);
|
||||
depot.ground_stock = 3;
|
||||
sim.sams.push(depot);
|
||||
// S-400 #1 has a manual request; S-400 #2 gets an automatic request.
|
||||
let mut s_manual = Sam::new(sim.id(), SamKind::S400, DVec3::new(150.0, 64.0, 0.0), 0.0);
|
||||
s_manual.cooldown = 0;
|
||||
s_manual.ground_request = true;
|
||||
sim.sams.push(s_manual);
|
||||
let mut s_auto = Sam::new(sim.id(), SamKind::S400, DVec3::new(160.0, 64.0, 0.0), 0.0);
|
||||
s_auto.cooldown = 0;
|
||||
sim.sams.push(s_auto);
|
||||
let tzm_id = sim.id();
|
||||
sim.sams.push(Sam::new(tzm_id, SamKind::Tzm, DVec3::new(200.0, 64.0, 0.0), 0.0));
|
||||
// Keep only 1 uncovered site + 1 extra site so s_auto can request, or add a second site.
|
||||
fixed_site(&mut sim, DVec3::new(0.0, 64.0, 550.0), 1);
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(6000.0, 100.0, 6000.0), -DVec3::Z, DVec3::new(6000.0, 64.0, 0.0));
|
||||
sim.tick = 10;
|
||||
let mut out = Out::default();
|
||||
sim.step_auto_strike(&mut out);
|
||||
assert!(sim.sams[1].ground_request && !sim.sams[1].auto_ground_request);
|
||||
assert!(sim.sams[2].ground_request && sim.sams[2].auto_ground_request);
|
||||
sim.auto_strike = false;
|
||||
sim.tick = 11;
|
||||
sim.step_auto_strike(&mut out);
|
||||
assert!(sim.sams[1].ground_request, "manual request must stay active");
|
||||
assert!(!sim.sams[2].ground_request && !sim.sams[2].auto_ground_request, "auto request must cancel when auto_strike is off");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +156,35 @@ impl SamKind {
|
||||
pub fn has_gun(self) -> bool {
|
||||
self.spec().gun.is_some()
|
||||
}
|
||||
/// Typed missile ammunition kind consumed by this unit, if it launches air-defence missiles.
|
||||
pub fn missile_ammo(self) -> Option<AmmoKind> {
|
||||
match self {
|
||||
SamKind::Patriot => Some(AmmoKind::PatriotMissile),
|
||||
SamKind::Pantsir => Some(AmmoKind::PantsirMissile),
|
||||
SamKind::S400 => Some(AmmoKind::S400Missile),
|
||||
SamKind::S500 => Some(AmmoKind::S500Missile),
|
||||
SamKind::IrisT => Some(AmmoKind::IrisTMissile),
|
||||
SamKind::Nasams => Some(AmmoKind::NasamsMissile),
|
||||
SamKind::Buk => Some(AmmoKind::BukMissile),
|
||||
SamKind::Tor => Some(AmmoKind::TorMissile),
|
||||
SamKind::P1sun => Some(AmmoKind::P1sunMissile),
|
||||
SamKind::Gepard
|
||||
| SamKind::Radar
|
||||
| SamKind::Depot
|
||||
| SamKind::Tzm
|
||||
| SamKind::Ew
|
||||
| SamKind::Light
|
||||
| SamKind::Optical => None,
|
||||
}
|
||||
}
|
||||
/// Typed gun ammunition kind consumed by this unit, if it has anti-aircraft guns.
|
||||
pub fn gun_ammo(self) -> Option<AmmoKind> {
|
||||
match self {
|
||||
SamKind::Gepard => Some(AmmoKind::GepardGun),
|
||||
SamKind::Pantsir => Some(AmmoKind::PantsirGun),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sam {
|
||||
|
||||
@@ -1357,13 +1357,14 @@ mod tests {
|
||||
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;
|
||||
depot.clear_ammo();
|
||||
depot.set_ammo(AmmoKind::S400Missile, 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));
|
||||
assert_eq!((sim.sams[0].missiles, sim.sams[1].ammo_stock.get(AmmoKind::S400Missile), sim.sams[1].cargo), (4, 0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+199
-4
@@ -74,6 +74,14 @@ fn contact_symbol(estimate: sim::ClassEst) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
fn site_class_name(c: sim::sites::SiteClass) -> &'static str {
|
||||
match c {
|
||||
sim::sites::SiteClass::Ramp => "рампа дронов",
|
||||
sim::sites::SiteClass::Launcher => "пусковая ракет",
|
||||
sim::sites::SiteClass::Battery => "батарея баллистических",
|
||||
}
|
||||
}
|
||||
|
||||
fn public_live(sim: &sim::Sim) -> Value {
|
||||
let now = sim.tick;
|
||||
let picture = sim.air_picture();
|
||||
@@ -100,10 +108,14 @@ fn public_live(sim: &sim::Sim) -> Value {
|
||||
let mut row = position(s.id, format!("№{} {}", i + 1, s.kind.name()), s.pos);
|
||||
let emitting = s.radar_up();
|
||||
let radar_range = emitting.then(|| s.kind.spec().sensor * s.radar_profile().reach);
|
||||
let supply = sim.supply_status(i).map(|st| battery_view::supply_line(&st));
|
||||
let depot_reach = (s.kind == sim::SamKind::Depot).then_some(sim::DEPOT_REACH_BLOCKS);
|
||||
merge(
|
||||
&mut row,
|
||||
json!({
|
||||
"status": post::state(s), "details": battery_view::sam_status(s, now),
|
||||
"supply": supply,
|
||||
"depotReach": depot_reach,
|
||||
"health": s.health, "rounds": s.missiles, "bursts": s.bursts,
|
||||
"symbol": if s.kind == sim::SamKind::Radar { "radar" } else { "unit" },
|
||||
"radarRange": radar_range,
|
||||
@@ -113,6 +125,68 @@ fn public_live(sim: &sim::Sim) -> Value {
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
let sites: Vec<_> = sim
|
||||
.strikes
|
||||
.known
|
||||
.iter()
|
||||
.filter_map(|k| {
|
||||
let e = k.est.filter(|e| e.fix)?;
|
||||
let status = match k.state {
|
||||
sim::strike::SiteState::Active => "Действует".to_string(),
|
||||
sim::strike::SiteState::Stunned(t) => {
|
||||
format!("Подавлена ещё {} с", t.saturating_sub(now) / 20)
|
||||
}
|
||||
sim::strike::SiteState::Destroyed(_) => "Уничтожена".to_string(),
|
||||
};
|
||||
let destroyed = matches!(k.state, sim::strike::SiteState::Destroyed(_));
|
||||
let mut row = position(k.site, format!("ПУ врага №{}", k.site), DVec3::new(e.pos.x, 0.0, e.pos.y));
|
||||
merge(
|
||||
&mut row,
|
||||
json!({
|
||||
"symbol": "site",
|
||||
"status": status,
|
||||
"className": site_class_name(k.class),
|
||||
"accuracy": sim::strike::accuracy(&e),
|
||||
"radius": e.radius,
|
||||
"launches": k.launches,
|
||||
"aimed": k.aimed,
|
||||
"destroyed": destroyed,
|
||||
"canStrike": !destroyed,
|
||||
}),
|
||||
);
|
||||
Some(row)
|
||||
})
|
||||
.take(ENTITY_LIMIT)
|
||||
.collect();
|
||||
let sup = sim.supply_summary();
|
||||
let ammo_kinds: Vec<_> = sim::AmmoKind::ALL
|
||||
.into_iter()
|
||||
.filter_map(|k| {
|
||||
let depot = sup.depot_ammo[k.index()];
|
||||
let truck = sup.truck_ammo[k.index()];
|
||||
(depot + truck > 0).then(|| {
|
||||
json!({
|
||||
"key": k.key(),
|
||||
"name": k.short_name(),
|
||||
"depot": depot,
|
||||
"truck": truck,
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let logistics = json!({
|
||||
"depots": sup.depots_alive,
|
||||
"trucks": sup.trucks_alive,
|
||||
"trucksBusy": sup.trucks_busy,
|
||||
"waitingAmmo": sup.waiting_ammo,
|
||||
"waitingRm48u": sup.waiting_rm48u,
|
||||
"reloading": sup.reloading,
|
||||
"rm48uDepot": sup.rm48u_depot,
|
||||
"rm48uTruck": sup.rm48u_truck,
|
||||
"rm48uLoaded": sup.rm48u_loaded,
|
||||
"ammoTotal": sup.depot_ammo.iter().sum::<u32>() + sup.truck_ammo.iter().sum::<u32>(),
|
||||
"kinds": ammo_kinds,
|
||||
});
|
||||
let objects: Vec<_> = sim.targets.iter().take(ENTITY_LIMIT).enumerate().map(|(i, &p)| {
|
||||
let mut row = position(i + 1, format!("Объект №{}", i + 1), p);
|
||||
let health = sim.target_health.get(i).copied();
|
||||
@@ -125,10 +199,11 @@ fn public_live(sim: &sim::Sim) -> Value {
|
||||
row
|
||||
}).collect();
|
||||
json!({
|
||||
"units": units, "objects": objects, "contacts": contacts, "interceptors": interceptors,
|
||||
"summary": { "kills": sim.kills, "hits": sim.hits, "planning": sim.planning(), "hold": sim.hold },
|
||||
"units": units, "objects": objects, "contacts": contacts, "interceptors": interceptors, "sites": sites,
|
||||
"logistics": logistics,
|
||||
"summary": { "kills": sim.kills, "hits": sim.hits, "planning": sim.planning(), "hold": sim.hold, "autoStrike": sim.auto_strike },
|
||||
"limited": sim.sams.len() > ENTITY_LIMIT || (!picture.unaided && picture.tracks.len() > ENTITY_LIMIT)
|
||||
|| sim.missiles.len() > ENTITY_LIMIT || sim.targets.len() > ENTITY_LIMIT
|
||||
|| sim.missiles.len() > ENTITY_LIMIT || sim.targets.len() > ENTITY_LIMIT || sim.strikes.known.len() > ENTITY_LIMIT
|
||||
})
|
||||
}
|
||||
|
||||
@@ -173,7 +248,7 @@ fn perspectives(sim: &sim::Sim, debug: bool) -> (Value, Value) {
|
||||
})
|
||||
.collect();
|
||||
(
|
||||
json!({"contacts": observed, "units": [], "objects": [], "interceptors": [], "reports": reports, "sorties": sorties,
|
||||
json!({"contacts": observed, "units": [], "objects": [], "interceptors": [], "sites": [], "reports": reports, "sorties": sorties,
|
||||
"limited": report.observations.len() > ENTITY_LIMIT}),
|
||||
json!(truth),
|
||||
)
|
||||
@@ -380,6 +455,29 @@ impl AirDef {
|
||||
)?;
|
||||
Ok(receipt["message"].as_str().map(str::to_owned))
|
||||
}
|
||||
["action", id, session, action, value] if token(id) => {
|
||||
let receipt = if let Some((_, previous)) =
|
||||
self.web.receipts.iter().find(|(key, _)| key == id)
|
||||
{
|
||||
previous.clone()
|
||||
} else {
|
||||
let result = self.panel_action(session, action, value);
|
||||
let receipt = match result {
|
||||
Ok(message) => json!({"id": id, "accepted": true, "message": message}),
|
||||
Err(error) => json!({"id": id, "accepted": false, "message": error}),
|
||||
};
|
||||
if self.web.receipts.len() == RECEIPT_LIMIT {
|
||||
self.web.receipts.pop_front();
|
||||
}
|
||||
self.web.receipts.push_back((id.to_string(), receipt.clone()));
|
||||
receipt
|
||||
};
|
||||
storage::set(
|
||||
RECEIPT,
|
||||
&serde_json::to_vec(&receipt).map_err(|e| e.to_string())?,
|
||||
)?;
|
||||
Ok(receipt["message"].as_str().map(str::to_owned))
|
||||
}
|
||||
_ => Err("Неизвестный запрос веб-пульта".into()),
|
||||
}
|
||||
}
|
||||
@@ -401,6 +499,34 @@ impl AirDef {
|
||||
.then_some(n)
|
||||
.ok_or_else(|| "Игра не приняла сценарий".into())
|
||||
}
|
||||
|
||||
fn panel_action(&mut self, session: &str, action: &str, value: &str) -> Result<String, String> {
|
||||
if self.web.session.is_empty() || self.web.session != session {
|
||||
return Err("Игровая сессия сменилась. Обновите карту".into());
|
||||
}
|
||||
let p = player().filter(|_| self.world.is_some()).ok_or("Игровой мир закрыт")?;
|
||||
match action {
|
||||
"autostrike" => {
|
||||
let on = match value {
|
||||
"on" | "true" | "1" => true,
|
||||
"off" | "false" | "0" => false,
|
||||
_ => return Err("Неверное значение autostrike".into()),
|
||||
};
|
||||
self.sim.auto_strike = on;
|
||||
self.dirty = true;
|
||||
Ok(if on { "Автоудар по ПУ: вкл" } else { "Автоудар по ПУ: выкл" }.into())
|
||||
}
|
||||
"strike" => {
|
||||
let site_id: u32 = value.parse().map_err(|_| "Неверный номер ПУ".to_string())?;
|
||||
let mut out = Out::default();
|
||||
let msg = self.sim.order_strike(site_id, DVec3::new(p.x, p.y, p.z), &mut out)?;
|
||||
self.emit(out);
|
||||
self.dirty = true;
|
||||
Ok(msg)
|
||||
}
|
||||
_ => Err("Неизвестное действие веб-пульта".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -449,4 +575,73 @@ mod tests {
|
||||
assert_eq!(cursors("new:1.101.200.5,2.0.50.4", "new", 1), (101, 200, 5));
|
||||
assert_eq!(cursors("old:1.101.200.5", "new", 1), (0, 0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_live_exposes_only_fixed_radar_sites_logistics_and_depot_reach() {
|
||||
let mut sim = sim::Sim::new(1);
|
||||
let depot_id = sim.id();
|
||||
let mut depot = sim::Sam::new(depot_id, sim::SamKind::Depot, DVec3::ZERO, 0.0);
|
||||
depot.clear_ammo();
|
||||
depot.set_ammo(sim::AmmoKind::TorMissile, 3);
|
||||
depot.ground_stock = 2;
|
||||
sim.sams.push(depot);
|
||||
let tor_id = sim.id();
|
||||
let mut tor = sim::Sam::new(tor_id, sim::SamKind::Tor, DVec3::new(100.0, 0.0, 0.0), 0.0);
|
||||
tor.missiles = 0;
|
||||
tor.empty = true;
|
||||
sim.sams.push(tor);
|
||||
// Secret enemy site in truth (far at x=9999) + bearing-only + fixed radar estimate.
|
||||
sim.strikes.known.push(sim::strike::Known {
|
||||
site: 1,
|
||||
class: sim::sites::SiteClass::Launcher,
|
||||
obs: Vec::new(),
|
||||
est: Some(sim::strike::Estimate {
|
||||
pos: glam::DVec2::new(500.0, -300.0),
|
||||
radius: 45.0,
|
||||
fix: true,
|
||||
bearing: 0.5,
|
||||
bearing_err: 0.05,
|
||||
origin: glam::DVec2::ZERO,
|
||||
}),
|
||||
launches: 2,
|
||||
last: 10,
|
||||
state: sim::strike::SiteState::Active,
|
||||
aimed: true,
|
||||
});
|
||||
sim.strikes.known.push(sim::strike::Known {
|
||||
site: 2,
|
||||
class: sim::sites::SiteClass::Ramp,
|
||||
obs: Vec::new(),
|
||||
est: Some(sim::strike::Estimate {
|
||||
pos: glam::DVec2::new(777.0, 777.0),
|
||||
radius: 200.0,
|
||||
fix: false,
|
||||
bearing: 1.0,
|
||||
bearing_err: 0.1,
|
||||
origin: glam::DVec2::ZERO,
|
||||
}),
|
||||
launches: 1,
|
||||
last: 10,
|
||||
state: sim::strike::SiteState::Active,
|
||||
aimed: false,
|
||||
});
|
||||
|
||||
let snap = public_live(&sim);
|
||||
let sites = snap["sites"].as_array().unwrap();
|
||||
assert_eq!(sites.len(), 1, "unfixed bearing-only sites must not leak onto map");
|
||||
assert_eq!(sites[0]["id"], 1);
|
||||
assert_eq!(sites[0]["symbol"], "site");
|
||||
assert_eq!(sites[0]["x"], 500.0);
|
||||
assert_eq!(sites[0]["z"], -300.0);
|
||||
assert_eq!(sites[0]["aimed"], true);
|
||||
assert_eq!(snap["units"][0]["depotReach"], sim::DEPOT_REACH_BLOCKS);
|
||||
assert_eq!(snap["units"][1]["supply"], "Ждёт БК: нет исправной ТЗМ");
|
||||
assert_eq!(snap["logistics"]["depots"], 1);
|
||||
assert_eq!(snap["logistics"]["ammoTotal"], 3);
|
||||
assert_eq!(snap["logistics"]["rm48uDepot"], 2);
|
||||
assert_eq!(snap["summary"]["autoStrike"], false);
|
||||
|
||||
let (enemy, _) = perspectives(&sim, true);
|
||||
assert_eq!(enemy["sites"], json!([]));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user