313 lines
16 KiB
Rust
313 lines
16 KiB
Rust
//! Player-facing labels for battery configuration and status.
|
||
use crate::sim::battery::{BatteryStatus, RadarProfile, SamMode};
|
||
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 {
|
||
let channels = if profile.channels == 0 { "без каналов уточнения".to_string() } else { format!("каналы {}", profile.channels) };
|
||
format!(
|
||
"{} [{}]: {}, оборот {:.1} с, {}, локальный поиск {}; развёртывание: {}",
|
||
profile.name,
|
||
profile.id,
|
||
profile.products_text(),
|
||
profile.cycle as f64 / 20.0,
|
||
channels,
|
||
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
|
||
profile.deployment,
|
||
)
|
||
}
|
||
|
||
pub fn status(status: BatteryStatus) -> String {
|
||
match status {
|
||
BatteryStatus::Radar { index, role, emitting, operational } => {
|
||
let profile = role.profile();
|
||
format!(
|
||
"№{} РЛС: {}; излучение {}, {}",
|
||
index + 1,
|
||
radar_profile_line(profile),
|
||
if emitting { "вкл" } else { "выкл" },
|
||
if operational { "работает" } else { "нет связи или РЛС не работает" }
|
||
)
|
||
}
|
||
BatteryStatus::Launcher { index, kind, mode, linked } => format!(
|
||
"№{} {}: {}{}", index + 1, kind.name(), mode.key(),
|
||
if mode == SamMode::LauncherOnly {
|
||
if linked { ", РЛС связана" } else { ", нет связанной РЛС сопровождения" }
|
||
} else { "" }
|
||
),
|
||
}
|
||
}
|
||
|
||
/// One system's line in the summary panel and on the map.
|
||
pub fn sam_status(sam: &Sam, now: u64) -> String {
|
||
let spec = sam.kind.spec();
|
||
let mut text = spec.name.to_string();
|
||
if !sam.alive() {
|
||
return text + " УНИЧТОЖЕН";
|
||
}
|
||
if sam.moving() {
|
||
return text + " " + &sam.state.name().to_lowercase();
|
||
}
|
||
match sam.kind {
|
||
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);
|
||
}
|
||
SamKind::Radar => {
|
||
let broken = if sam.comps.whole() { String::new() } else { format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind)) };
|
||
let profile = sam.radar_profile();
|
||
let channels = if profile.channels == 0 {
|
||
"без уточнения".to_string()
|
||
} else {
|
||
format!("каналы {}/{}", sam.own_channels_used(now), profile.channels)
|
||
};
|
||
return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len());
|
||
}
|
||
SamKind::Light => return format!("{text}{}", if sam.target.is_some() { ": в луче цель" } else { "" }),
|
||
SamKind::Optical => {
|
||
let mut t = format!("{text}: {}", sam.optical.status_text());
|
||
if sam.health < 1.0 {
|
||
t += &format!(" ({:.0}%)", sam.health * 100.0);
|
||
}
|
||
if !sam.comps.whole() {
|
||
t += &format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind));
|
||
}
|
||
return t;
|
||
}
|
||
_ => {}
|
||
}
|
||
if let Some(cell) = sam.preparing_cell() {
|
||
text += &format!(" · открытие ТПК №{}", cell + 1);
|
||
}
|
||
if sam.empty && sam.missiles == 0 {
|
||
text += " ЖДЁТ БК";
|
||
}
|
||
if sam.health < 1.0 {
|
||
text += &format!(" ({:.0}%)", sam.health * 100.0);
|
||
}
|
||
if !sam.comps.whole() {
|
||
text += &format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind));
|
||
}
|
||
if sam.reloading > 0 {
|
||
text += &format!(" перезарядка {}с", sam.reloading.div_ceil(20));
|
||
} else {
|
||
if let Some(magazine) = sam.kind.missile_magazine() {
|
||
if sam.kind.supports_rm48u() {
|
||
text += &format!(" ПВО {} · RM48U {} / {} ячеек", sam.missiles, sam.ground_rounds, sam.cells());
|
||
if sam.ground_return { text += " · ожидает вывоза RM48U"; }
|
||
} else {
|
||
text += &format!(" ракеты {}/{}", sam.missiles, magazine);
|
||
}
|
||
}
|
||
if sam.kind.has_gun() {
|
||
text += &format!(" очереди {}", sam.bursts);
|
||
}
|
||
}
|
||
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::*;
|
||
use crate::sim::battery::RadarRole;
|
||
use crate::sim::{Part, Sam, SamKind, SamState};
|
||
use glam::DVec3;
|
||
|
||
#[test]
|
||
fn renders_system_status_in_existing_format() {
|
||
let mut s400 = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0);
|
||
s400.missiles = 1;
|
||
s400.ground_rounds = 2;
|
||
assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек");
|
||
s400.ground_return = true;
|
||
assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U");
|
||
|
||
let mut pantsir = Sam::new(2, SamKind::Pantsir, DVec3::ZERO, 0.0);
|
||
pantsir.missiles = 7;
|
||
pantsir.bursts = 100;
|
||
assert_eq!(sam_status(&pantsir, 0), "Панцирь-С1 ракеты 7/12 очереди 100");
|
||
|
||
let mut worn = Sam::new(3, SamKind::Patriot, DVec3::ZERO, 0.0);
|
||
worn.health = 0.5;
|
||
worn.comps.0[Part::Sensor as usize] = 0.4;
|
||
worn.reloading = 21;
|
||
assert_eq!(sam_status(&worn, 0), "Patriot (50%) [РЛС 40%] перезарядка 2с");
|
||
}
|
||
|
||
#[test]
|
||
fn renders_special_system_lines_in_existing_format() {
|
||
let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0);
|
||
radar.own.push(7);
|
||
radar.comps.0[Part::Sensor as usize] = 0.0;
|
||
assert_eq!(sam_status(&radar, 0), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
|
||
|
||
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
|
||
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 БК (1 видов), RM48U 3, снятых ПВО 1");
|
||
|
||
let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0);
|
||
tzm.set_ammo(crate::sim::AmmoKind::TorMissile, 1);
|
||
tzm.return_cargo = true;
|
||
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;
|
||
ew.heat = 0.5;
|
||
assert_eq!(sam_status(&ew, 0), "Станция РЭБ: ГЛУШИТ, нагрев 50%");
|
||
|
||
let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0);
|
||
light.target = Some(1);
|
||
assert_eq!(sam_status(&light, 0), "Прожектор: в луче цель");
|
||
|
||
let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0);
|
||
assert_eq!(sam_status(&optical, 0), "Оптический пост: ищет");
|
||
}
|
||
|
||
#[test]
|
||
fn renders_moving_and_destroyed_systems_in_existing_format() {
|
||
let mut moving = Sam::new(9, SamKind::S400, DVec3::ZERO, 0.0);
|
||
moving.state = SamState::Moving;
|
||
assert_eq!(sam_status(&moving, 0), "С-400 на марше");
|
||
|
||
let mut dead = Sam::new(10, SamKind::S400, DVec3::ZERO, 0.0);
|
||
dead.health = 0.0;
|
||
assert_eq!(sam_status(&dead, 0), "С-400 УНИЧТОЖЕН");
|
||
}
|
||
|
||
#[test]
|
||
fn profiles_explain_their_different_functions() {
|
||
for role in [RadarRole::Search, RadarRole::Height, RadarRole::Engagement, RadarRole::Multifunction] {
|
||
let text = radar_profile_line(role.profile());
|
||
assert!(text.contains(role.profile().id));
|
||
assert!(text.contains(&format!("оборот {:.1} с", role.profile().cycle as f64 / 20.0)));
|
||
}
|
||
assert!(radar_profile_line(RadarRole::Search.profile()).contains("без каналов"));
|
||
assert!(radar_profile_line(RadarRole::Engagement.profile()).contains("каналы 2"));
|
||
assert!(radar_profile_line(RadarRole::Height.profile()).contains("уточнение"));
|
||
}
|
||
|
||
#[test]
|
||
fn renders_battery_status_in_existing_format() {
|
||
assert_eq!(
|
||
status(BatteryStatus::Radar { index: 0, role: RadarRole::Search, emitting: false, operational: false }),
|
||
"№1 РЛС: дальнего обзора [radar_search]: обзор, оборот 8.5 с, без каналов уточнения, локальный поиск во всей дальности; развёртывание: крупная стационарная антенна; излучение выкл, нет связи или РЛС не работает"
|
||
);
|
||
assert_eq!(
|
||
status(BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }),
|
||
"№2 РЛС: сопровождения [radar_track]: обзор, уточнение, пуск, оборот 3.5 с, каналы 2, локальный поиск 12% дальности; развёртывание: мобильная панель; излучение вкл, работает"
|
||
);
|
||
assert_eq!(status(BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: true }), "№3 С-400: launcher, РЛС связана");
|
||
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)"));
|
||
}
|
||
}
|