Add village defense campaign and breakthrough reports

Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
2026-11-26 01:12:38 +03:00
parent aa842d8a1f
commit 7e6d9d8b9a
13 changed files with 1225 additions and 12 deletions
+8 -3
View File
@@ -56,7 +56,11 @@ pub fn tree() -> Tree {
),
Node::lit("list").runs(),
Node::lit("delete").then(Node::arg("имя", Value::names(SCENARIOS)).runs()),
Node::lit("village").runs().then(
Node::arg("режим", Value::choice(["easy", "normal", "hard", "start", "status", "prices", "stop"])).runs(),
),
]),
Node::lit("breaches").runs().then(Node::arg("страница", Value::int_from(1)).runs()),
Node::lit("why").runs().then(
Node::arg("номер", Value::int_from(1)).runs().then(Node::lit("source").runs()),
),
@@ -171,7 +175,8 @@ mod tests {
"replay film 3", "replay export", "replay export mine", "replay export best", "replay export all", "replay export 3",
"replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop",
"scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list",
"scenario delete a", "why", "why 2", "why 2 source", "chains", "chains 2", "ew on", "ew off", "move 4", "target here", "targets clear",
"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",
"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",
@@ -248,11 +253,11 @@ mod tests {
"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"] {
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
}
assert_eq!(top.len(), 37);
assert_eq!(top.len(), 38);
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
assert_eq!(complete("scenario ", &[]), ["delete", "list", "load", "save"]);
assert_eq!(complete("scenario ", &[]), ["delete", "list", "load", "save", "village"]);
assert_eq!(complete("wave ", &[]).len(), 14);
assert!(complete("wave s", &[]).contains(&"shahed".to_string()));
assert_eq!(complete("shader ", &[]), ["hd", "off", "on"]);
+136 -9
View File
@@ -31,6 +31,7 @@ mod scene;
mod smoke;
pub use airdef_core::sim;
mod scenario;
mod village;
mod wave;
mod world_view;
mod why_view;
@@ -56,6 +57,7 @@ struct AirDef {
grid_ids: Vec<u32>,
/// The raid the wave menu orders.
wave: wave::WaveConfig,
village: Option<village::Village>,
/// Playback lifecycle. Export owns the exact replay player it is capturing.
presentation: presentation::Session<replay::Player, Export>,
/// The effects preset a film replaced: (shader, hd).
@@ -206,6 +208,8 @@ enum Page {
/// The raid's make-up, then its parameters and the launch.
Wave,
WaveGo,
Village,
Breaches(usize),
/// Fire, repair, effects, damage.
More,
/// The last raid's events and its replays.
@@ -273,6 +277,17 @@ const BTN_CLASS: u32 = 100;
const BTN_ALL: u32 = 120;
const BTN_DEFAULT: u32 = 121;
const BTN_NONE: u32 = 122;
const BTN_VILLAGE: u32 = 60;
const BTN_BREACHES: u32 = 61;
const VILLAGE_STATUS: u32 = 62;
const VILLAGE_EASY: u32 = 63;
const VILLAGE_NORMAL: u32 = 64;
const VILLAGE_HARD: u32 = 65;
const VILLAGE_START: u32 = 66;
const VILLAGE_STOP: u32 = 67;
const BREACHES_LIST: u32 = 68;
const BREACHES_PREV: u32 = 69;
const BREACHES_NEXT: u32 = 70;
const BTN_BACK: u32 = 199;
fn say(text: &str) {
@@ -323,6 +338,10 @@ fn aim() -> Option<DVec3> {
impl AirDef {
fn use_item(&mut self, id: &str) {
let Some(p) = player() else { return };
if self.village_active() && (id == "airdef:designator" || sim::catalog::launch_item(id).is_some()) {
say("В «Обороне деревни» цели и волны заданы сценарием");
return;
}
let mut out = Out::default();
match id {
"airdef:designator" => match aim() {
@@ -360,7 +379,10 @@ impl AirDef {
Some(at) => {
let d = view(&p);
let heading = (-d.x).atan2(-d.z);
self.place(kind, mode, role, at, heading);
if let Err(e) = self.place(kind, mode, role, at, heading) {
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()));
@@ -978,6 +1000,9 @@ impl AirDef {
}
// 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)) {
text += &line;
}
if air && let Some(a) = self.sim.air_text() {
text += &a;
}
@@ -1048,6 +1073,7 @@ impl AirDef {
let layout = layout::Layout::parse(text)?;
// The air section is checked before anything is touched, like the layout (#127).
let air = sim::Sim::parse_air(text)?;
let mut village = village::Village::read(text, layout.targets.len())?;
self.commit_layout(layout);
if let Some(air) = air {
let cancelled = self.sim.restore_air(air);
@@ -1055,6 +1081,10 @@ impl AirDef {
say(&format!("Воздушная обстановка восстановлена: отменено устаревших заданий {cancelled}"));
}
}
if let Some(village) = &mut village {
village.resume(self.sim.tick);
}
self.village = village;
Ok(())
}
@@ -1229,14 +1259,15 @@ impl AirDef {
/// Another world opened: the last one's state saved, a clean simulation with this one's loaded.
fn open_world(&mut self, world: Option<String>) {
if self.world.is_some() && self.dirty {
// Leaving the world: the layout is kept, a raid still being planned is not (it would have
// no drones to resume and the world it belonged to is going).
self.save_with(false);
// The village resumes an in-flight wave. A wave still in planning restarts from its saved countdown.
let keep_air = self.village.is_some_and(village::Village::fighting) && !self.sim.planning();
self.save_with(keep_air);
}
self.end_session(presentation::ExitCause::WorldChange);
let shader = self.sim.shader;
let seed = game::get_clock().map_or(0x5eed, |c| c.game_time.wrapping_mul(2654435761) ^ 0x9e37);
self.sim = Sim::new(seed);
self.village = None;
// A fresh world's CPU profile starts from zero (#147 step 3.1).
sim::profile::reset();
self.next_save = 0;
@@ -1549,6 +1580,9 @@ impl AirDef {
}
fn launch_wave(&mut self, out: &mut Out) -> Result<(), String> {
if self.village_active() {
return Err("Волны запускает сценарий «Оборона деревни»".into());
}
let p = player().ok_or("Нет игрока")?;
if self.wave.total() == 0 {
return Err("Налёт пуст: выберите типы и число".into());
@@ -1609,7 +1643,13 @@ impl AirDef {
}
/// Places a configured system at `at` facing `heading` and settles it.
fn place(&mut self, kind: SamKind, mode: sim::battery::SamMode, role: sim::battery::RadarRole, at: DVec3, heading: f64) -> u32 {
fn place(&mut self, kind: SamKind, mode: sim::battery::SamMode, role: sim::battery::RadarRole, at: DVec3, heading: f64) -> Result<u32, String> {
if self.village_active() {
let used = self.village_layout_cost();
if let Some(village) = &mut self.village {
village.charge(used, village::cost(kind))?;
}
}
let id = self.sim.id();
let mut sam = Sam::new(id, kind, at, heading);
sam.set_mode(mode);
@@ -1618,7 +1658,7 @@ impl AirDef {
self.sim.sams.push(sam);
self.sim.settle(id);
self.dirty = true;
id
Ok(id)
}
fn deploy_configured(&mut self, key: &str) -> Result<String, String> {
@@ -1627,7 +1667,7 @@ 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));
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()))
}
@@ -1654,10 +1694,40 @@ impl AirDef {
let custom = self.sim.sams.iter().filter(|s| !s.doctrine.is_default()).count();
widgets.push(Widget::Button(ButtonWidget { id: BTN_DOCTRINE, label: format!("Доктрины: охрана, сектор, резерв (особых: {custom})…") }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_WAVE, label: "Налёт: состав и запуск…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_VILLAGE, label: "Оборона деревни…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_REPLAYS, label: "Повторы…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_MORE, label: "Огонь, ремонт, эффекты…".into() }));
}
Page::Village => {
title = "Оборона деревни".into();
let status = self.village_status();
widgets.push(Widget::List(ListWidget { id: VILLAGE_STATUS, rows: status.lines().map(str::to_owned).collect(), selected: None }));
if self.village_active() {
if self.village.is_some_and(village::Village::ready) {
widgets.push(Widget::Button(ButtonWidget { id: VILLAGE_START, label: "Начать оборону".into() }));
}
widgets.push(Widget::Button(ButtonWidget { id: VILLAGE_STOP, label: "Остановить сценарий".into() }));
} else {
for (id, label) in [(VILLAGE_EASY, "Легко"), (VILLAGE_NORMAL, "Обычно"), (VILLAGE_HARD, "Сложно")] {
widgets.push(Widget::Button(ButtonWidget { id, label: label.into() }));
}
}
widgets.push(Widget::Button(ButtonWidget { id: BTN_BREACHES, label: "Разбор прорывов…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "Назад".into() }));
}
Page::Breaches(page) => {
title = "Разбор прорывов".into();
let report = self.sim.breakthrough_page(page);
widgets.push(Widget::List(ListWidget { id: BREACHES_LIST, rows: report.lines().map(str::to_owned).collect(), selected: None }));
if page > 0 {
widgets.push(Widget::Button(ButtonWidget { id: BREACHES_PREV, label: "Предыдущая страница".into() }));
}
if page + 1 < self.sim.breakthrough_pages() {
widgets.push(Widget::Button(ButtonWidget { id: BREACHES_NEXT, label: "Следующая страница".into() }));
}
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "Назад".into() }));
}
Page::Replays => {
match self.sim.replays.last() {
Some(rec) => {
@@ -1683,6 +1753,7 @@ impl AirDef {
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
}
widgets.push(Widget::Button(ButtonWidget { id: BTN_BREACHES, label: "Разбор прорывов…".into() }));
}
Page::Chains => {
match self.sim.replays.last() {
@@ -1950,6 +2021,7 @@ impl Mod for AirDef {
grid: false,
grid_ids: Vec::new(),
wave: wave::WaveConfig::default(),
village: None,
presentation: presentation::Session::default(),
block_log: None,
time_view: false,
@@ -2101,6 +2173,7 @@ impl Mod for AirDef {
self.sim.night = game::get_clock().is_some_and(|c| (13000..23000).contains(&(c.day_time % 24000)));
self.sim.day_time = game::get_clock().map(|c| c.day_time);
self.sim.step(&mut self.ground, Some(DVec3::new(p.x, p.y, p.z)), &mut out);
self.tick_village(&mut out);
let context = presentation::Context::live(self.presentation.generation(), self.world.clone(), self.sim.engine_tick, self.sim.tick, self.sim.day_time, self.listener);
let scene = scene::Snapshot::at_context(&context, scene::Source::Live(&self.sim));
self.smoke.update(&scene);
@@ -2307,6 +2380,10 @@ impl Mod for AirDef {
return;
}
(Page::More, BTN_REPAIR) => {
if self.village_active() {
say("В этом сценарии состояние объектов и техники переносится между волнами");
return;
}
self.sim.repair();
self.dirty = true;
}
@@ -2358,6 +2435,41 @@ impl Mod for AirDef {
self.open_menu(Page::Wave);
return;
}
(Page::Main, BTN_VILLAGE) => {
self.open_menu(Page::Village);
return;
}
(Page::Village, VILLAGE_EASY | VILLAGE_NORMAL | VILLAGE_HARD | VILLAGE_START | VILLAGE_STOP) => {
let action = match id {
VILLAGE_EASY => "easy",
VILLAGE_NORMAL => "normal",
VILLAGE_HARD => "hard",
VILLAGE_START => "start",
_ => "stop",
};
match self.village_command(&[action]) {
Ok(message) | Err(message) => say(&message),
}
self.open_menu(Page::Village);
return;
}
(Page::Village | Page::Replays, BTN_BREACHES) => {
self.open_menu(Page::Breaches(0));
return;
}
(Page::Breaches(page), BREACHES_PREV | BREACHES_NEXT) => {
let next = if id == BREACHES_PREV { page.saturating_sub(1) } else { page.saturating_add(1).min(self.sim.breakthrough_pages().saturating_sub(1)) };
self.open_menu(Page::Breaches(next));
return;
}
(Page::Breaches(_), BTN_BACK) => {
self.open_menu(Page::Main);
return;
}
(Page::Village, BTN_BACK) => {
self.open_menu(Page::Main);
return;
}
(Page::Main, BTN_REPLAYS) => {
self.open_menu(Page::Replays);
return;
@@ -2510,6 +2622,11 @@ impl Mod for AirDef {
fn command(&mut self, _name: &str, args: &str) -> Result<Option<String>, String> {
let w: Vec<&str> = args.split_whitespace().collect();
if self.village_active() && matches!(w.as_slice(),
["import" | "repair" | "clear"] | ["target" | "targets" | "wave" | "ground-stock", ..]
) {
return Err("Это действие доступно после завершения или остановки «Обороны деревни»".into());
}
let mut out = Out::default();
let reply = match w.as_slice() {
["menu"] => {
@@ -2588,7 +2705,16 @@ impl Mod for AirDef {
}
None
}
["scenario", "village", rest @ ..] => Some(self.village_command(rest)?),
["scenario", rest @ ..] => Some(self.scenario_command(rest)?),
["breaches", rest @ ..] => {
let page = match rest {
[] => 0,
[n] => n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("Укажите номер страницы от 1")?,
_ => return Err("/airdef breaches [страница]".into()),
};
Some(self.sim.breakthrough_page(page))
}
["why", rest @ ..] => {
// The system n of the summary, else the monitored one.
let i = match rest.first() {
@@ -2889,7 +3015,7 @@ mod tests {
] {
let (k, m, r) = sim::catalog::deploy_item_configuration(item).expect(item);
assert_eq!((k, m, r), (kind, mode, role), "{item}");
let id = game.place(k, m, r, DVec3::new(game.sim.sams.len() as f64 * 10.0, 70.0, 0.0), 0.0);
let id = game.place(k, m, r, DVec3::new(game.sim.sams.len() as f64 * 10.0, 70.0, 0.0), 0.0).unwrap();
let sam = game.sim.sams.iter().find(|s| s.id == id).unwrap();
assert_eq!((sam.kind, sam.mode, sam.radar_role), (kind, mode, role), "{item}");
if kind == SamKind::Radar {
@@ -2922,7 +3048,7 @@ mod tests {
);
}
fn test_mod() -> AirDef {
pub(crate) fn test_mod() -> AirDef {
AirDef {
sim: Sim::new(1),
ground: Ground::default(),
@@ -2934,6 +3060,7 @@ mod tests {
grid: false,
grid_ids: Vec::new(),
wave: wave::WaveConfig::default(),
village: None,
presentation: presentation::Session::default(),
block_log: None,
time_view: false,
+21
View File
@@ -1603,6 +1603,27 @@ impl AirDef {
ui.note(tick, "Бой идёт: расстановка закрыта");
return;
}
if self.village_active() {
let objects_changed = ui.draft.objs.len() != self.sim.targets.len()
|| ui.draft.objs.iter().any(|o| o.gone
|| o.idx.and_then(|i| self.sim.targets.get(i)) != Some(&o.pos));
if objects_changed {
ui.note(tick, "Цели в «Обороне деревни» закреплены");
return;
}
let cost = |s: &DSam| crate::village::cost(s.kind);
let added = ui.draft.sams.iter().filter(|s| s.id.is_none() && !s.gone).map(cost).sum();
let removed: u32 = ui.draft.sams.iter()
.filter(|s| s.gone && s.id.is_some_and(|id| self.sim.sams.iter().any(|current| current.id == id)))
.map(cost).sum();
let kept = self.village_layout_cost().saturating_sub(removed);
if let Some(village) = &mut self.village
&& let Err(e) = village.charge(kept, added)
{
ui.note(tick, &e);
return;
}
}
let d = std::mem::take(&mut ui.draft);
// Objects: removals from the end so the indices hold.
let mut gone: Vec<usize> = d.objs.iter().filter(|o| o.gone).filter_map(|o| o.idx).collect();
+5
View File
@@ -67,7 +67,9 @@ impl AirDef {
}
// Everything of the last layout goes: its systems with their jobs and targets, the sky,
// the cook-offs to come; ids are made anew with the new systems.
self.village = None;
self.sim.clear();
self.sim.clear_breakthroughs();
self.sim.sams.clear();
self.sim.targets.clear();
self.sim.target_health.clear();
@@ -108,6 +110,9 @@ impl AirDef {
))
}
["load", name, flags @ ..] => {
if self.village_active() {
return Err("Чтобы загрузить другой сценарий, остановите «Оборону деревни»".into());
}
let name = valid(name)?;
let bytes = storage::get(&key(&name)).ok_or(format!("Нет сценария «{name}» (/airdef scenario list)"))?;
self.apply_scenario(&String::from_utf8_lossy(&bytes), flags.contains(&"force"))?;
+268
View File
@@ -0,0 +1,268 @@
//! Bounded, observed facts about impacts. This is session history, not save data.
use super::*;
const MAX_ACTIVE: usize = 4096;
const MAX_HITS: usize = 128;
const PAGE_SIZE: usize = 3;
#[derive(Clone, Copy, Default)]
pub(super) struct FlightFacts {
/// False when observation began after the flight began, or after a load.
complete: bool,
pub(super) first: Option<(u64, u32)>,
launches: u32,
}
impl FlightFacts {
pub(super) fn new(complete: bool) -> Self {
Self {
complete,
..Default::default()
}
}
}
struct Hit {
tick: u64,
id: u32,
kind: DroneKind,
pos: DVec3,
object: Option<usize>,
facts: Option<FlightFacts>,
nearby: Vec<BatterySnapshot>,
}
struct BatterySnapshot {
kind: SamKind,
reason: why::BattleReason,
terrain_blocked: bool,
}
#[derive(Default)]
pub(super) struct Breakthroughs {
pub(super) active: HashMap<u32, FlightFacts>,
hits: VecDeque<Hit>,
}
impl Breakthroughs {
pub(super) fn begin(&mut self, id: u32, complete: bool) {
if self.active.len() < MAX_ACTIVE {
self.active.insert(id, FlightFacts::new(complete));
}
}
pub(super) fn bytes(&self) -> usize {
use super::memory::{map_bytes, vec_bytes, vecdeque_bytes};
map_bytes(
self.active.capacity(),
std::mem::size_of::<(u32, FlightFacts)>(),
) + vecdeque_bytes(&self.hits)
+ self
.hits
.iter()
.map(|h| vec_bytes(&h.nearby))
.sum::<usize>()
}
}
impl Sim {
/// Clears the displayed history; observation of flights already in progress continues.
pub fn clear_breakthroughs(&mut self) {
self.breakthroughs.hits.clear();
}
pub(super) fn breakthrough_launch(&mut self, id: u32) {
if let Some(facts) = self.breakthroughs.active.get_mut(&id) {
facts.launches = facts.launches.saturating_add(1);
}
}
pub(super) fn breakthrough_hit(
&mut self,
id: u32,
kind: DroneKind,
pos: DVec3,
object: Option<usize>,
) {
// Only the nearest three armed systems; this runs once per impact, not per tick.
let mut nearest: Vec<_> = self
.sams
.iter()
.enumerate()
.filter(|(_, s)| s.kind.armed())
.map(|(i, s)| (i, s.pos.distance_squared(pos)))
.collect();
nearest.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
let nearby = nearest
.into_iter()
.take(3)
.filter_map(|(i, _)| {
let sam = &self.sams[i];
Some(BatterySnapshot {
kind: sam.kind,
reason: self.battle_reason_at(i, Some(id))?,
terrain_blocked: sam.terrain_verdict(id, self.tick).is_some_and(|v| v != 0),
})
})
.collect();
let hit = Hit {
tick: self.tick,
id,
kind,
pos,
object,
facts: self.breakthroughs.active.get(&id).copied(),
nearby,
};
if self.breakthroughs.hits.len() == MAX_HITS {
self.breakthroughs.hits.pop_front();
}
self.breakthroughs.hits.push_back(hit);
}
pub fn breakthrough_pages(&self) -> usize {
self.breakthroughs.hits.len().div_ceil(PAGE_SIZE)
}
/// Most recent recorded impacts, three per page. Page is zero-based.
pub fn breakthrough_page(&self, page: usize) -> String {
let total = self.breakthroughs.hits.len();
if total == 0 {
return "Прорывов в истории нет".into();
}
let pages = self.breakthrough_pages();
if page >= pages {
return format!("Нет страницы {}. Страниц: {pages}", page.saturating_add(1));
}
let mut lines = vec![format!(
"Прорывы: страница {}/{} (последние {total})",
page + 1,
pages
)];
for hit in self
.breakthroughs
.hits
.iter()
.rev()
.skip(page * PAGE_SIZE)
.take(PAGE_SIZE)
{
let detection = match hit.facts {
Some(f) if f.complete => match f.first {
Some((t, radar)) => format!(
"первое измерение РЛС id {radar}: тик {t}, за {:.1} с до удара",
hit.tick.saturating_sub(t) as f64 / 20.0
),
None => "своих измерений РЛС не было".into(),
},
Some(f) => match f.first {
Some((t, radar)) => format!(
"первое известное измерение РЛС id {radar}: тик {t} (предыдущее неизвестно)"
),
None => "обнаружение до загрузки или начала наблюдения неизвестно".into(),
},
None => "данные обнаружения недоступны".into(),
};
let launches = hit.facts.map_or("пуски неизвестны".to_string(), |f| {
if f.complete {
format!("пусков: {}", f.launches)
} else {
format!("известных пусков: {} (предыдущие неизвестны)", f.launches)
}
});
let object = hit
.object
.map_or_else(String::new, |i| format!(" · объект №{}", i + 1));
lines.push(format!(
"{} №{} · ({:.0}, {:.0}, {:.0}){object}",
hit.kind.spec().name,
hit.id,
hit.pos.x,
hit.pos.y,
hit.pos.z
));
lines.push(format!("{detection} · {launches}"));
if !hit.nearby.is_empty() {
lines.push("Снимок перед ударом · ближайшие комплексы".into());
for battery in &hit.nearby {
let terrain = if battery.terrain_blocked {
" · рельеф перекрывал траекторию"
} else {
""
};
lines.push(format!(
"{} №{} · {}{terrain}",
battery.kind.name(),
battery.reason.sam + 1,
reason_text(&battery.reason),
));
}
}
}
lines.join("\n")
}
}
fn reason_text(reason: &why::BattleReason) -> &'static str {
use why::{BattleBlock as B, BattleKind as K};
match reason.kind {
K::Ready => "готов к пуску",
K::ObserveOnly => "только обзор",
K::AwaitingTrack => "ждёт сопровождения",
K::ChannelsBusy => "каналы заняты",
K::NoAmmo => "нет боезапаса или перезарядка",
K::Blocked => match reason.block {
Some(B::Destroyed) => "уничтожен",
Some(B::Moving) => "на марше",
Some(B::Hold) => "огонь запрещён",
Some(B::NoWeapon) => "нет оружия",
Some(B::NoTarget) => "нет цели",
Some(B::NoTrack) => "нет трассы",
Some(B::OutOfRoles) => "вне ролей",
Some(B::OutOfReach) => "вне дальности",
Some(B::Claimed) => "занята перехватчиками",
Some(B::Doctrine) => "доктрина",
Some(B::Aiming) => "наводится",
Some(B::Preparing) => "подготовка пуска",
Some(B::LauncherDown) => "пусковая отказала",
Some(B::Other) | None => "другая причина",
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn impact_history_is_bounded_and_pages_are_safe() {
let mut sim = Sim::new(1);
for id in 0..130 {
sim.tick = id as u64;
sim.breakthrough_hit(id, DroneKind::Geran3, DVec3::ZERO, None);
}
assert_eq!(sim.breakthroughs.hits.len(), MAX_HITS);
assert!(sim.breakthrough_page(0).contains("№129"));
assert!(sim.breakthrough_page(usize::MAX).contains("Нет страницы"));
sim.clear_breakthroughs();
assert!(sim.breakthrough_page(0).contains("истории нет"));
}
#[test]
fn detection_and_launches_distinguish_complete_and_partial_history() {
let mut sim = Sim::new(1);
sim.tick = 20;
sim.breakthroughs.active.insert(1, FlightFacts::new(true));
sim.breakthrough_launch(1);
sim.breakthrough_hit(1, DroneKind::Geran3, DVec3::ZERO, None);
let page = sim.breakthrough_page(0);
assert!(page.contains("измерений РЛС не было"));
assert!(page.contains("пусков: 1"));
sim.breakthroughs.active.insert(2, FlightFacts::new(false));
sim.breakthrough_hit(2, DroneKind::Geran3, DVec3::ZERO, None);
assert!(
sim.breakthrough_page(0)
.contains("до загрузки или начала наблюдения неизвестно")
);
}
}
+4
View File
@@ -892,6 +892,7 @@ impl Sim {
/// job whose drone, aim or unit no longer stands is dropped — a restored job is never a ghost.
/// The live air state is replaced, never merged: what the sky held before the load goes.
pub fn restore_air(&mut self, save: AirSave) -> u32 {
self.breakthroughs.active.clear();
self.diversions_left = save.diversions_left;
self.tick = save.tick;
// New jobs must not reuse an id a restored job already holds.
@@ -900,6 +901,9 @@ impl Sim {
self.intel = ew::Intel::restore(save.contacts.clone(), save.kills, save.hits, save.outcomes.clone());
self.known_relief = save.known_relief;
self.drones = save.drones;
for d in &self.drones {
self.breakthroughs.begin(d.id, false);
}
self.queue = save.queue;
let alive: std::collections::HashSet<u32> = self.drones.iter().map(|d| d.id).chain(self.queue.iter().map(|(_, d)| d.id)).collect();
self.retargets.clear();
+1
View File
@@ -171,6 +171,7 @@ impl Sim {
+ self.known_relief.as_ref().map_or(0, |k| k.bytes());
r.other = map_bytes(self.roles.len(), std::mem::size_of::<SamKind>() + std::mem::size_of::<u8>())
+ self.fires.bytes()
+ self.breakthroughs.bytes()
+ std::mem::size_of::<record::Tally>()
+ std::mem::size_of::<Self>();
r
+9
View File
@@ -40,6 +40,7 @@ mod voices;
pub mod outcome;
mod units;
pub mod why;
mod breakthrough;
pub mod world;
pub mod memory;
pub use memory::MemoryReport;
@@ -1431,6 +1432,7 @@ enum Fx {
// ---------------------------------------------------------------- the simulation
pub struct Sim {
breakthroughs: breakthrough::Breakthroughs,
/// Roles set for a kind of system (`/airdef roles`), new ones included.
pub roles: HashMap<SamKind, u8>,
pub drones: Vec<Drone>,
@@ -1561,6 +1563,7 @@ fn fx_ident(counter: &mut u32) -> u32 {
impl Sim {
pub fn new(seed: u64) -> Self {
Self {
breakthroughs: Default::default(),
roles: HashMap::new(),
drones: Vec::new(),
missiles: Vec::new(),
@@ -1695,6 +1698,7 @@ impl Sim {
fn add_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) {
// Its navigation error is drawn in `make_drone`, the one path of manual and raid launches (#65).
let d = self.make_drone(kind, from, dir, target);
self.breakthroughs.begin(d.id, true);
self.drones.push(d);
self.launched += 1;
}
@@ -1730,6 +1734,7 @@ impl Sim {
self.strikes.pending.clear();
for sam in &mut self.sams { sam.cancel_prepare(); }
self.drones.clear();
self.breakthroughs.active.clear();
self.missiles.clear();
self.fx.clear();
self.blasts.clear();
@@ -2159,6 +2164,7 @@ impl Sim {
};
let object = self.targets.iter().position(|t| t.distance(pos) < 16.0);
let sam = self.sams.iter().enumerate().find(|(_, s)| s.alive() && s.pos.distance(pos) < 12.0).map(|(i, s)| (s.kind, i));
self.breakthrough_hit(drone, kind, pos, object);
self.emit_combat_event(pos, record::EventKind::Hit { drone, kind, power, object, sam });
let vel = self.drones.iter().find(|x| x.id == drone).map_or(DVec3::ZERO, |x| x.vel);
self.direct_hit(pos, vel, tnt, out);
@@ -2170,9 +2176,11 @@ impl Sim {
for (pos, warhead, small) in boom {
self.explode(pos, warhead, small, ground, player, out);
}
for id in &removed { self.breakthroughs.active.remove(id); }
self.drones.retain(|d| !removed.contains(&d.id));
for (kind, pos, vel, target, sector) in released {
let id = self.id();
self.breakthroughs.begin(id, true);
self.drones.push(Drone {
id,
kind,
@@ -2808,6 +2816,7 @@ impl Sim {
let spec = kind.spec();
let id = self.id();
let v0 = if spec.cold > 0 { spec.eject } else { 0.8 };
self.breakthrough_launch(target);
self.missiles.push(Missile { id, kind, pos: muzzle, vel: dir * v0, target, sam, age: 0, hold: 0, fix, seen: 0 });
if spec.cold > 0 {
// Thrown out by gas: a puff, a thump; the motor lights later.
+9
View File
@@ -605,6 +605,14 @@ impl Sim {
out.sound("minecraft:event.raid.horn", plan.centre, 64.0, 1.0);
}
/// Start a new scenario with a fresh enemy picture while preserving the player's layout.
pub fn reset_raid_intelligence(&mut self) {
self.intel = ew::Intel::default();
self.recon = recon::Recon::default();
self.bearing = ew::BearingReport::default();
self.refresh = None;
}
/// Whether a raid is still being planned.
pub fn planning(&self) -> bool {
self.plan.is_some()
@@ -993,6 +1001,7 @@ impl Sim {
out.particles("minecraft:large_smoke", d.pos - dir * 2.5, 0.5, DVec3::new(0.0, 0.05, 0.0), 0.02, 4);
}
}
self.breakthroughs.begin(d.id, true);
self.drones.push(d);
self.launched += 1;
}
+6
View File
@@ -473,6 +473,9 @@ impl Sim {
let heights: Vec<Option<f64>> =
self.drones.iter().map(|d| ground.at(d.pos, now).map(|g| d.pos.y - g)).collect();
let drone_at: HashMap<u32, usize> = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect();
if now % 80 == 0 {
self.breakthroughs.active.retain(|id, _| drone_at.contains_key(id));
}
let seed = self.seed;
let mut index: HashMap<u32, usize> = HashMap::new();
for sam in &mut self.sams {
@@ -563,6 +566,9 @@ impl Sim {
if dist > NEAR && dice(seed, now, key, 0) >= p {
continue;
}
if let Some(facts) = self.breakthroughs.active.get_mut(&d.id) {
facts.first.get_or_insert((now, sam.id));
}
let sigma = if locked { 0.3 } else { profile.sigma + dist * profile.spread };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * profile.vertical, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
let measured = d.pos + noise;
+678
View File
@@ -0,0 +1,678 @@
//! Three rounds over one village layout. The existing simulation owns all units,
//! health, ammunition, and combat. The scenario only schedules the rounds and scores objectives.
use super::*;
const PAUSE: u64 = 20 * 30;
const WAVES: u8 = 3;
const WAVE_SEED: u64 = 0x5649_4c4c_4147_4501;
const OBJECTIVES: [(&str, u32); 3] = [("Штаб", 50), ("Лазарет", 30), ("Укрытие", 20)];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Level {
Easy,
Normal,
Hard,
}
impl Level {
fn parse(key: &str) -> Option<Self> {
match key {
"easy" => Some(Self::Easy),
"normal" => Some(Self::Normal),
"hard" => Some(Self::Hard),
_ => None,
}
}
fn key(self) -> &'static str {
match self {
Self::Easy => "easy",
Self::Normal => "normal",
Self::Hard => "hard",
}
}
fn budget(self) -> u32 {
match self {
Self::Easy => 30,
Self::Normal => 25,
Self::Hard => 22,
}
}
fn order(self, wave: u8) -> sim::RaidOrder {
use DroneKind::*;
let extra = match self {
Self::Easy => 0,
Self::Normal => 3,
Self::Hard => 6,
};
let (kinds, dist, approach) = match wave {
0 => (
vec![
(Gerbera, 4 + extra),
(Shahed, 8 + extra),
(Geran3, 2 + extra),
],
430.0,
sim::Approach::Sector,
),
1 => (
vec![
(Gerbera, 6 + extra),
(Shahed, 10 + extra),
(Geran3, 5 + extra),
(Kh101, 3 + extra),
],
600.0,
sim::Approach::TwoSectors,
),
_ => (
vec![
(Gerbera, 8 + extra),
(Shahed, 12 + extra),
(Geran3, 6 + extra),
(Kh101, 4 + extra),
(Iskander, 1 + extra / 3),
],
760.0,
sim::Approach::Waves,
),
};
sim::RaidOrder {
kinds,
dist,
approach,
aim: sim::Aim::Smart,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
Survey { origin: DVec3, until: u64 },
Setup,
Waiting { wave: u8, until: u64 },
Fighting(u8),
Finished([f64; 3]),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Village {
level: Level,
phase: Phase,
spent: u32,
}
pub(crate) fn cost(kind: SamKind) -> u32 {
match kind {
SamKind::Light | SamKind::Optical => 1,
SamKind::Gepard | SamKind::Radar | SamKind::Depot | SamKind::Tzm | SamKind::Ew => 2,
SamKind::Pantsir | SamKind::Tor | SamKind::P1sun => 3,
SamKind::IrisT | SamKind::Nasams | SamKind::Buk => 4,
SamKind::Patriot | SamKind::S400 => 5,
SamKind::S500 => 6,
}
}
pub(crate) fn active(village: Option<Village>) -> bool {
village.is_some_and(|v| !matches!(v.phase, Phase::Finished(_)))
}
fn idle(sim: &Sim) -> bool {
!sim.planning() && sim.queue.is_empty() && sim.missiles.is_empty() && sim.drones.is_empty()
}
fn score(health: &[f64]) -> (f64, bool) {
let points = OBJECTIVES
.iter()
.zip(health)
.map(|((_, weight), hp)| f64::from(*weight) * hp.clamp(0.0, 100.0) / 100.0)
.sum::<f64>();
(
points,
points >= 65.0 && health.first().is_some_and(|hp| *hp > 0.0),
)
}
fn objective_status(health: &[f64]) -> String {
OBJECTIVES
.iter()
.zip(health)
.map(|((name, _), hp)| format!("{name} {:.0}%", hp))
.collect::<Vec<_>>()
.join(" · ")
}
impl Village {
fn used(self, layout_cost: u32) -> u32 {
if matches!(self.phase, Phase::Survey { .. } | Phase::Setup) {
layout_cost
} else {
self.spent
}
}
pub(crate) fn charge(&mut self, layout_cost: u32, cost: u32) -> Result<(), String> {
if matches!(self.phase, Phase::Finished(_)) {
return Ok(());
}
if !matches!(self.phase, Phase::Setup | Phase::Waiting { .. }) {
return Err("Расстановка доступна при подготовке и в паузе между волнами".into());
}
let remaining = self.level.budget().saturating_sub(self.used(layout_cost));
if cost > remaining {
return Err(format!(
"На эту технику нужно {cost} очк., доступно {remaining}"
));
}
if matches!(self.phase, Phase::Waiting { .. }) {
self.spent += cost;
}
Ok(())
}
pub(crate) fn ready(self) -> bool {
self.phase == Phase::Setup
}
pub(crate) fn fighting(self) -> bool {
matches!(self.phase, Phase::Fighting(_))
}
pub(crate) fn save(self, now: u64, air: bool) -> Option<String> {
let phase = match self.phase {
Phase::Survey { .. } => return None,
Phase::Setup => "setup 0 0".into(),
Phase::Waiting { wave, until } => format!("wait {wave} {}", until.saturating_sub(now)),
Phase::Fighting(wave) if air => format!("fight {wave} 0"),
Phase::Fighting(wave) => format!("wait {wave} 20"),
Phase::Finished([hq, clinic, shelter]) => format!("done 0 0 {hq} {clinic} {shelter}"),
};
Some(format!(
"village {} {} {phase}\n",
self.level.key(),
self.spent
))
}
pub(crate) fn read(text: &str, objectives: usize) -> Result<Option<Self>, String> {
let bad = || "Некорректное состояние сценария «Оборона деревни»".to_string();
let mut rows = text.lines().filter_map(|row| row.strip_prefix("village "));
let Some(row) = rows.next() else {
return Ok(None);
};
if rows.next().is_some() {
return Err(bad());
}
let words: Vec<_> = row.split_whitespace().collect();
let [level, spent, phase, wave, remaining, scores @ ..] = words.as_slice() else {
return Err(bad());
};
let level = Level::parse(level).ok_or_else(bad)?;
let spent = spent
.parse::<u32>()
.ok()
.filter(|&n| n <= level.budget())
.ok_or_else(bad)?;
let wave = wave
.parse::<u8>()
.ok()
.filter(|&n| n < WAVES)
.ok_or_else(bad)?;
let remaining = remaining
.parse::<u64>()
.ok()
.filter(|&n| n <= PAUSE)
.ok_or_else(bad)?;
let phase = match (*phase, wave, remaining, scores) {
("done", 0, 0, [hq, clinic, shelter]) => {
let parse = |s: &str| {
s.parse::<f64>()
.ok()
.filter(|hp| (0.0..=100.0).contains(hp))
.ok_or_else(bad)
};
Phase::Finished([parse(hq)?, parse(clinic)?, parse(shelter)?])
}
("setup", 0, 0, []) if objectives == OBJECTIVES.len() => Phase::Setup,
("wait", wave, remaining, []) if objectives == OBJECTIVES.len() => Phase::Waiting {
wave,
until: remaining,
},
("fight", wave, 0, []) if objectives == OBJECTIVES.len() => Phase::Fighting(wave),
_ => return Err(bad()),
};
Ok(Some(Self {
level,
phase,
spent,
}))
}
/// Move a saved countdown from its relative clock to the restored simulation clock.
pub(crate) fn resume(&mut self, now: u64) {
if let Phase::Waiting { until, .. } = &mut self.phase {
*until = until.saturating_add(now);
}
}
}
impl AirDef {
pub(crate) fn village_active(&self) -> bool {
active(self.village)
}
pub(crate) fn village_layout_cost(&self) -> u32 {
self.sim.sams.iter().map(|s| cost(s.kind)).sum()
}
fn request_village(&mut self, level: Level, origin: DVec3) -> Result<String, String> {
if self.village_active() || !idle(&self.sim) {
return Err("Завершите текущий налёт или остановите сценарий".into());
}
if self.village_layout_cost() > level.budget() {
return Err(format!(
"Текущая расстановка превышает бюджет в {} очк.",
level.budget()
));
}
let phase = if self.sim.targets.is_empty() {
Phase::Survey {
origin,
until: self.sim.tick + 160,
}
} else {
if self.sim.targets.len() != 3 || self.sim.target_health.as_slice() != [100.0; 3] {
return Err("Отметьте ровно три целых объекта или уберите все отметки для автоматической расстановки".into());
}
Phase::Setup
};
self.village = Some(Village {
phase,
level,
spent: 0,
});
self.dirty = true;
Ok(self.village_status())
}
pub(crate) fn village_status(&self) -> String {
let Some(v) = self.village else {
return "Оборона деревни · выберите сложность или /airdef scenario village normal"
.into();
};
let phase = match v.phase {
Phase::Survey { .. } => "ищу точки для объектов".into(),
Phase::Setup => "расставьте технику, затем начните оборону".into(),
Phase::Waiting { wave, until } => format!(
"волна {}/{WAVES} через {} с",
wave + 1,
until.saturating_sub(self.sim.tick).div_ceil(20)
),
Phase::Fighting(wave) => format!("идёт волна {}/{WAVES}", wave + 1),
Phase::Finished(health) => {
let (points, win) = score(&health);
format!(
"{} · {:.0}/100",
if win {
"Победа"
} else {
"Поражение"
},
points
)
}
};
let remaining = v
.level
.budget()
.saturating_sub(v.used(self.village_layout_cost()));
let health = match &v.phase {
Phase::Finished(health) => health.as_slice(),
_ => self.sim.target_health.as_slice(),
};
format!(
"Оборона деревни · {phase} · бюджет {remaining}/{}\n{}",
v.level.budget(),
objective_status(health)
)
}
pub(crate) fn village_command(&mut self, args: &[&str]) -> Result<String, String> {
match args {
[] | ["status"] => Ok(self.village_status()),
["prices"] => Ok(SamKind::ALL
.iter()
.map(|&k| format!("{} {}", k.name(), cost(k)))
.collect::<Vec<_>>()
.join(" · ")),
["stop"] => {
self.village = None;
self.dirty = true;
Ok("Сценарий остановлен. Расстановка и текущий налёт остаются в мире".into())
}
["start"] => {
let layout = self.village_layout_cost();
let v = self
.village
.as_mut()
.ok_or("Сначала выберите сложность сценария")?;
if v.phase != Phase::Setup || !idle(&self.sim) {
return Err(
"Оборона запускается после подготовки трёх объектов в спокойном небе"
.into(),
);
}
if layout == 0 || layout > v.level.budget() {
return Err(format!(
"Перед запуском разместите технику в пределах {} очк.",
v.level.budget()
));
}
v.spent = layout;
v.phase = Phase::Waiting {
wave: 0,
until: self.sim.tick + 20 * 5,
};
self.sim.reset_raid_intelligence();
self.sim.clear_breakthroughs();
self.dirty = true;
Ok(self.village_status())
}
[level] => {
let level = Level::parse(level).ok_or("Сложность: easy, normal или hard")?;
let p = player().ok_or("Нет игрока")?;
self.request_village(level, DVec3::new(p.x, p.y, p.z))
}
_ => Err("/airdef scenario village [easy|normal|hard|start|status|prices|stop]".into()),
}
}
pub(crate) fn tick_village(&mut self, out: &mut Out) {
let Some(mut v) = self.village else { return };
let now = self.sim.tick;
match v.phase {
Phase::Survey { origin, until } => {
let mut objects = [
origin,
origin + DVec3::new(48.0, 0.0, 12.0),
origin + DVec3::new(-35.0, 0.0, -32.0),
];
let mut ready = true;
for point in &mut objects {
if let Some(y) = self.ground.at(*point, now) {
point.y = y;
} else {
ready = false;
self.ground.want_chunk((
(point.x.floor() as i32) >> 4,
(point.z.floor() as i32) >> 4,
));
}
}
if ready {
self.sim.targets.extend(objects);
self.sim.target_health.extend([100.0; 3]);
v.phase = Phase::Setup;
out.messages.push(
"Штаб, лазарет и укрытие отмечены. Расставьте технику и начните оборону"
.into(),
);
} else if now >= until {
self.village = None;
self.dirty = true;
out.messages.push("Местность не загрузилась. Отметьте три объекта вручную или начните сценарий ближе к центру деревни".into());
return;
} else {
return;
}
}
Phase::Waiting { wave, until } if now >= until && idle(&self.sim) => {
let objects: Vec<_> = self
.sim
.targets
.iter()
.zip(&self.sim.target_health)
.filter(|(_, hp)| **hp > 0.0)
.map(|(&pos, _)| pos)
.collect();
if objects.is_empty() {
v.phase = Phase::Finished(
self.sim
.target_health
.as_slice()
.try_into()
.unwrap_or([0.0; 3]),
);
} else {
self.sim.reseed(WAVE_SEED.wrapping_add(u64::from(wave)));
if self.sim.order_raid(&v.level.order(wave), &objects, out) == 0 {
return;
}
v.phase = Phase::Fighting(wave);
out.messages
.push(format!("Оборона деревни · волна {}/{WAVES}", wave + 1));
}
}
Phase::Fighting(wave) if now % 20 == 0 && idle(&self.sim) => {
if wave + 1 == WAVES || self.sim.target_health.iter().all(|&hp| hp <= 0.0) {
v.phase = Phase::Finished(
self.sim
.target_health
.as_slice()
.try_into()
.unwrap_or([0.0; 3]),
);
} else {
v.phase = Phase::Waiting {
wave: wave + 1,
until: now + PAUSE,
};
out.messages.push(format!(
"Волна {}/{} завершена. Следующая через {} с. {}",
wave + 1,
WAVES,
PAUSE / 20,
objective_status(&self.sim.target_health)
));
}
}
_ => return,
}
self.village = Some(v);
self.dirty = true;
if self.menu == Some(Page::Village) {
self.open_menu(Page::Village);
}
if matches!(v.phase, Phase::Finished(_)) {
out.messages.push(format!(
"{} · разбор: /airdef breaches",
self.village_status()
));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::test_mod;
fn setup() -> AirDef {
let mut game = test_mod();
game.sim
.targets
.extend([DVec3::ZERO, DVec3::X * 50.0, DVec3::Z * 50.0]);
game.sim.target_health.extend([100.0; 3]);
game.request_village(Level::Normal, DVec3::ZERO).unwrap();
game
}
fn deploy(game: &mut AirDef, kind: SamKind) -> Result<u32, String> {
game.place(
kind,
sim::battery::SamMode::Integrated,
sim::battery::RadarRole::Multifunction,
DVec3::ZERO,
0.0,
)
}
#[test]
fn budget_guards_deployment_and_spent_points_stay_spent() {
let mut game = setup();
for _ in 0..4 {
deploy(&mut game, SamKind::S400).unwrap();
}
assert!(deploy(&mut game, SamKind::S500).is_err());
game.village_command(&["start"]).unwrap();
deploy(&mut game, SamKind::S400).unwrap();
game.sim.sams.remove(0);
assert!(deploy(&mut game, SamKind::Light).is_err());
assert!(game.command("airdef", "repair").is_err());
assert!(game.command("airdef", "targets clear").is_err());
assert!(game.command("airdef", "wave shahed 1").is_err());
assert_eq!(game.sim.targets.len(), 3);
}
#[test]
fn waiting_resumes_and_all_three_waves_keep_the_layout_state() {
let mut game = setup();
deploy(&mut game, SamKind::S400).unwrap();
game.village_command(&["start"]).unwrap();
game.sim.tick = 60;
game.sim.sams[0].missiles = 2;
game.sim.target_health[1] = 80.0;
let saved = game.state_text(false, false);
let mut restored = test_mod();
restored.apply_state(&saved).unwrap();
game = restored;
let mut out = Out::default();
for wave in 0..WAVES {
let v = game.village.unwrap();
let Phase::Waiting { wave: index, until } = v.phase else {
panic!("{:?}", v.phase)
};
assert_eq!(index, wave);
assert_eq!(until - game.sim.tick, if wave == 0 { 40 } else { PAUSE });
game.sim.tick = until - 1;
game.tick_village(&mut out);
assert!(!game.sim.planning());
game.sim.tick = until;
game.tick_village(&mut out);
assert!(game.sim.planning());
assert_eq!(game.village.unwrap().phase, Phase::Fighting(wave));
assert!(deploy(&mut game, SamKind::Gepard).is_err());
// Complete the combat externally here to test the scenario transitions in isolation.
game.sim.clear();
game.sim.tick = game.sim.tick.div_ceil(20) * 20;
game.tick_village(&mut out);
assert_eq!(game.sim.sams[0].missiles, 2);
assert_eq!(game.sim.target_health, [100.0, 80.0, 100.0]);
}
assert_eq!(
game.village.unwrap().phase,
Phase::Finished([100.0, 80.0, 100.0])
);
assert!(game.village_status().contains("Победа · 94/100"));
game.sim.targets.clear();
game.sim.target_health.clear();
let mut restored = test_mod();
restored
.apply_state(&game.state_text(false, false))
.unwrap();
assert!(restored.village_status().contains("Победа · 94/100"));
assert!(
out.messages
.iter()
.any(|line| line.contains("/airdef breaches"))
);
}
#[test]
fn three_playable_rounds_finish_and_the_report_lists_real_impacts() {
struct Flat;
impl sim::world::WorldSource for Flat {
fn solid(&self, _: i32, y: i32, _: i32) -> Option<bool> {
Some(y < 64)
}
}
let mut game = test_mod();
game.request_village(Level::Easy, DVec3::new(0.0, 64.0, 0.0))
.unwrap();
// Lay one battery and hold its fire so the mission reaches the report path.
game.sim.damage = false;
game.sim.hold = true;
let mut out = Out::default();
let mut wave_count = 0;
for _ in 0..9000 {
let now = game.sim.tick;
let columns = game
.ground
.take_wanted()
.into_iter()
.map(|(x, z)| (x, z, 64))
.collect();
game.ground.answer(columns, now);
let sections = game.ground.world.take_wanted(now);
game.ground.world.serve(&Flat, sections, now);
let rays = game.ground.world.take_rays(now);
game.ground.world.serve_rays(&Flat, rays);
game.ground.take_chunks();
game.sim.step(&mut game.ground, None, &mut out);
game.tick_village(&mut out);
let phase = game.village.unwrap().phase;
if phase == Phase::Setup {
deploy(&mut game, SamKind::Gepard).unwrap();
game.village_command(&["start"]).unwrap();
}
wave_count += out
.messages
.iter()
.filter(|m| m.starts_with("Оборона деревни · волна "))
.count();
if matches!(phase, Phase::Finished(_)) {
break;
}
out = Out::default();
}
assert_eq!(wave_count, 3);
assert!(matches!(game.village.unwrap().phase, Phase::Finished(_)));
assert!(game.sim.breakthrough_pages() > 0);
assert!(
game.sim
.breakthrough_page(0)
.contains("Снимок перед ударом")
);
}
#[test]
fn survey_uses_world_heights_and_score_weights_each_object() {
let mut game = test_mod();
game.request_village(Level::Easy, DVec3::ZERO).unwrap();
let mut out = Out::default();
game.tick_village(&mut out);
assert!(game.sim.targets.is_empty());
let wanted = game.ground.take_wanted();
assert_eq!(wanted.len(), 3);
game.ground.answer(
wanted
.into_iter()
.enumerate()
.map(|(i, (x, z))| (x, z, 64 + i as i32))
.collect(),
game.sim.tick,
);
game.tick_village(&mut out);
assert_eq!(
game.sim.targets.iter().map(|p| p.y).collect::<Vec<_>>(),
[64.0, 65.0, 66.0]
);
assert_eq!(score(&[0.0, 100.0, 100.0]), (50.0, false));
assert_eq!(score(&[90.0, 60.0, 10.0]), (65.0, true));
}
}