From 5e3907aa9954c76b026a576491c3d7922762a9fc Mon Sep 17 00:00:00 2001 From: chexit Date: Tue, 1 Dec 2026 23:01:17 +0300 Subject: [PATCH] Keep battle reviews reachable and tied to the recorded outcome (#148, #153) --- README.md | 18 +-- airdef-mod/src/lib.rs | 295 +++++++++++++++++++++-------------- airdef-mod/src/map.rs | 10 +- airdef-mod/src/monitor.rs | 2 +- airdef-mod/src/post.rs | 17 +- airdef-mod/src/replay.rs | 86 +++++++++- airdef-mod/src/sim/record.rs | 37 ++++- 7 files changed, 326 insertions(+), 139 deletions(-) diff --git a/README.md b/README.md index 415e027..010f001 100644 --- a/README.md +++ b/README.md @@ -60,9 +60,9 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает то | Развернуть Patriot / Гепард / Панцирь-С1 / С-400 / С-500 | ставит комплекс на блок под прицелом, носом по взгляду | | Свернуть ПВО | убирает ближайший комплекс у точки под прицелом | -**Командный пункт:** клавиша **N** или `/airdef menu`. В нём список комплексов: выбери комплекс и включай или выключай классы целей -(дроны, реактивные дроны, крылатые, сверхзвуковые, баллистика), есть сброс по умолчанию. Там же кнопки «Командный -пункт» (сетка), «Налёт…» и «Огонь, ремонт, эффекты…» (огонь ПВО, ремонт всех, эффекты, разрушения). +**Меню AirDef:** клавиша **N** или `/airdef menu`. В разделе «Классы целей» можно включить или выключить +классы для каждого типа комплекса и сбросить их по умолчанию. В меню также открываются командный пункт, +налёты, повторы и настройки. **Налёт (меню N → «Налёт: состав и запуск…»):** на первой странице состав — клик по типу листает число (0, 1, 2, 3, 4, 6, 8, 10, 15, 20, 30, 40); на второй — готовый вариант («Рой Шахедов», «Массированный удар», @@ -198,8 +198,8 @@ API мода `render.set-lights` (до 512, плавно интерполиру - камера комплекса: настоящий вид мира из точки комплекса (второй рендер форка), с зумом на цель — тепловизор при сопровождении, в поиске днём цвет, ночью ПНВ; рамка захвата, дальность, высота, скорость и пеленг. -**Командный пункт ПВО:** клавиша **J** или кнопка в меню **N** открывает прокручиваемый список всей развёрнутой -техники. Кнопка фильтра перебирает роли и состояния. Для поиска по названию или номеру используйте +**Командный пункт ПВО:** клавиша **J** или строка «Командный пункт» в меню **N** открывает прокручиваемый список +всей развёрнутой техники. Кнопка фильтра перебирает роли и состояния. Для поиска по названию или номеру используйте `/airdef post Панцирь` или `/airdef post 12`. Нажатие на строку открывает карточку. В ней видны текущая причина, отметка и её источник. Из карточки можно открыть карту, камеру, цепочки последнего повтора и закрепить технику. Та же карточка доступна с выбранного маркера на карте **M** и по **I** при открытом мониторе **K**. @@ -234,10 +234,10 @@ API 31 форка) и следуют за взглядом покадрово; - **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты; - **цепочки боя** — меню N → «Повторы…» → «Цепочки боя»: по каждому контакту короткая строка - «отметка → передача → захват → пуск → исход» из 4–5 измеренных переходов записи, без домыслов. Видны - время каждого шага, батарея и контакт, у пропущенных контактов — «без пуска». Фильтр по батарее - переключает список; клик открывает кадр повтора (клип исхода, а если исхода нет — карту налёта на - моменте пуска или отметки). То же списком: `/airdef chains [номер батареи]`. + «отметка → передача → захват → пуск → исход» с записанными шагами и их временем. Можно отобрать + цепочки по комплексу, прорывы и контакты без записи пуска. В длинном списке можно листать страницы. + Нажатие на строку открывает клип исхода или карту налёта на моменте пуска или отметки. + Текстовый список открывается командой `/airdef chains [номер батареи]`. Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. Управление (подсказка показывается в начале, после нажатия и на паузе): **← →** — перемотка на 5 с (в нарезке — соседний момент), diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs index e796e48..c89d365 100644 --- a/airdef-mod/src/lib.rs +++ b/airdef-mod/src/lib.rs @@ -86,8 +86,7 @@ struct AirDef { health_mark: u64, /// The menu's page while it is open. menu: Option, - /// The battery the after-action chain list is filtered to (its id; None: all). - chain_filter: Option, + chain_view: ChainView, /// Where the player is, for the sounds' delay and far variants. listener: DVec3, /// The picture punch (#51) the HD exposure and bloom were last set for. @@ -123,6 +122,25 @@ struct ExportOpts { audio: bool, seconds: Option, } + +const CHAINS_PER_PAGE: usize = 200; + +#[derive(Default)] +struct ChainView { + filter: replay::ChainFilter, + /// Battery ID from the recording. None shows all recorded systems. + battery: Option, + /// The replay and rows exactly as displayed when the player opened the list. + recording: Option, + page: replay::ChainPage, + from_unit: Option<(u32, post::From)>, +} + +impl ChainView { + fn pages(&self) -> usize { + self.page.total.div_ceil(CHAINS_PER_PAGE).max(1) + } +} #[derive(PartialEq)] enum Stage { Planning, @@ -206,6 +224,7 @@ fn travels(event: &str) -> bool { #[derive(Clone, Copy, PartialEq)] enum Page { Main, + RoleKinds, Roles(SamKind), /// The raid's make-up, then its parameters and the launch. Wave, @@ -228,7 +247,18 @@ enum Page { Doctrine(u32), } +const MAIN_ROWS: u32 = 8; const MENU_KINDS: u32 = 1; +const MAIN_PAGES: [(Page, &str); 8] = [ + (Page::Post, "Командный пункт (J)"), + (Page::Replays, "Повторы"), + (Page::Wave, "Налёт: состав и запуск"), + (Page::Village, "Оборона деревни"), + (Page::More, "Огонь, ремонт, эффекты"), + (Page::RoleKinds, "Классы целей"), + (Page::Fleet, "Доктрины"), + (Page::Recon, "Разведка противника"), +]; /// A battery deploy piece from the catalog: a unit kind, one of its variants, or /// the remote item that places either. @@ -245,9 +275,6 @@ fn deploy_configuration(key: &str) -> Option<(SamKind, sim::battery::SamMode, si const BTN_HOLD: u32 = 10; const BTN_SHADER: u32 = 11; const BTN_DAMAGE: u32 = 12; -const BTN_MONITOR: u32 = 13; -const BTN_GRID: u32 = 14; -const BTN_WAVE: u32 = 15; const BTN_REPAIR: u32 = 16; const WAVE_KINDS: u32 = 2; const BTN_PRESET: u32 = 30; @@ -256,21 +283,20 @@ const BTN_DIST: u32 = 32; const BTN_AIM: u32 = 33; const BTN_LAUNCH: u32 = 34; const BTN_NEXT: u32 = 35; -const BTN_MORE: u32 = 17; -const BTN_REPLAYS: u32 = 18; const BTN_RECON: u32 = 23; const REPLAY_EVENTS: u32 = 3; const RECON_ROWS: u32 = 6; const CHAIN_ROWS: u32 = 7; const BTN_CHAINS: u32 = 43; const BTN_CHAIN_FILTER: u32 = 44; +const BTN_CHAIN_OUTCOME: u32 = 45; +const BTN_CHAIN_PAGE: u32 = 46; const BTN_MAP: u32 = 40; const BTN_FULL: u32 = 41; const BTN_REEL: u32 = 42; const BTN_FAR: u32 = 19; const BTN_ACOUSTICS: u32 = 20; const BTN_DLSS: u32 = 24; -const BTN_DOCTRINE: u32 = 21; const FLEET_ROWS: u32 = 4; const BTN_RESERVE: u32 = 50; const BTN_SALVO: u32 = 51; @@ -282,7 +308,6 @@ 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; @@ -300,6 +325,7 @@ const POST_PREV: u32 = 74; const POST_NEXT: u32 = 75; const POST_CLEAR: u32 = 76; const POST_ACTIONS: u32 = 77; +const POST_REFRESH: u32 = 78; const BTN_BACK: u32 = 199; fn say(text: &str) { @@ -933,8 +959,8 @@ impl AirDef { fn draw_hud(&mut self, player: DVec3, yaw: f32) { let pic = self.sim.air_picture(); - // The command post's grid and replays cover the screen: the other panels wait under them. - if self.grid || self.presentation.playback().is_some() || (pic.tracks.is_empty() && self.sim.sams.is_empty() && self.sim.missiles.is_empty()) { + // Full-screen views and the command post own the space used by the live status panels. + if self.grid || self.post_open() || self.presentation.playback().is_some() || (pic.tracks.is_empty() && self.sim.sams.is_empty() && self.sim.missiles.is_empty()) { if self.hud_shown { hud::clear(); render::clear_corner(); @@ -1313,6 +1339,7 @@ impl AirDef { self.grid = false; self.grid_ids.clear(); self.post = post::Post::default(); + self.chain_view = ChainView::default(); // The overlay key lets go with the world: its camera projects nothing here anyway. self.overlay_held = false; self.overlay_shown = false; @@ -1368,11 +1395,14 @@ impl AirDef { /// Plays the last recorded raid: "map", "full", "reel" or (with `event`) a clip. fn start_replay(&mut self, what: &str, event: Option) -> Result<(), String> { switch_allowed(self.presentation.is_exporting())?; - let n = self.sim.replays.len(); - if n == 0 { - return Err("Повторов пока нет: запишется первый же налёт (когда небо очистится)".into()); - } - let rec = &self.sim.replays[n - 1]; + let number = self.sim.replays.last() + .ok_or("Повторов пока нет: запишется первый же налёт (когда небо очистится)")?.number; + self.start_replay_at(number, what, event) + } + + fn start_replay_at(&mut self, number: u32, what: &str, event: Option) -> Result<(), String> { + switch_allowed(self.presentation.is_exporting())?; + let rec = self.sim.replay(number).ok_or("Эта запись уже вышла из истории")?; let mode = match (what, event) { (_, Some(i)) if i < rec.events.len() => replay::Player::event_clip(rec, i), ("full", _) => replay::Mode::Full, @@ -1397,19 +1427,33 @@ impl AirDef { /// Opens a battle chain's replay frame: its outcome clip when recorded, else the map at the /// launch (or the mark) held still. - fn start_chain(&mut self, row: replay::ChainRow) -> Result<(), String> { - match row.event { - Some(i) => self.start_replay("clip", Some(i)), - None => { - self.start_replay("map", None)?; - if let Some(player) = self.presentation.playback_mut() - && let Some(rec) = self.sim.replays.last() - { - player.seek(rec, row.at); - } - Ok(()) - } + fn start_chain(&mut self, recording: u32, event: Option, at: f64) -> Result<(), String> { + self.start_replay_at(recording, if event.is_some() { "clip" } else { "map" }, event)?; + if event.is_none() + && let Some(player) = self.presentation.playback_mut() + && let Some(rec) = self.sim.replay(recording) + { + player.seek(rec, at); } + Ok(()) + } + + fn open_chains(&mut self, from_unit: Option<(u32, post::From)>) { + self.chain_view = ChainView { + recording: self.sim.replays.last().map(|rec| rec.number), + battery: from_unit.map(|(unit, _)| unit), + from_unit, + ..ChainView::default() + }; + self.refresh_chains(0); + self.open_menu(Page::Chains); + } + + fn refresh_chains(&mut self, page: usize) { + self.chain_view.page = self.chain_view.recording.and_then(|number| self.sim.replay(number)).map_or_else( + replay::ChainPage::default, + |rec| replay::chain_page(rec, self.chain_view.battery, self.chain_view.filter, page, CHAINS_PER_PAGE), + ); } fn stop_replay(&mut self) { @@ -1690,6 +1734,10 @@ impl AirDef { } } + fn post_open(&self) -> bool { + matches!(self.menu, Some(Page::Post | Page::Unit(..) | Page::UnitChecks(..))) + } + fn open_monitor_card(&mut self) { if self.presentation.is_live() && let Some(id) = self.monitor.filter(|_| self.monitor_index().is_some()) @@ -1736,7 +1784,12 @@ impl AirDef { let title; match page { Page::Main => { - title = "AirDef — командный пункт (N меню, K монитор)".to_string(); + title = "AirDef".into(); + let rows = MAIN_PAGES.iter().map(|(_, label)| (*label).into()).collect(); + widgets.push(Widget::List(ListWidget { id: MAIN_ROWS, rows, selected: None })); + } + Page::RoleKinds => { + title = "Классы целей по типу комплекса".into(); let rows = SamKind::ARMED .iter() .map(|k| { @@ -1746,14 +1799,7 @@ impl AirDef { }) .collect(); widgets.push(Widget::List(ListWidget { id: MENU_KINDS, rows, selected: None })); - widgets.push(Widget::Button(ButtonWidget { id: BTN_GRID, label: "Командный пункт (J)".into() })); - 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() })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "К меню".into() })); } Page::Post => { let indices = self.post.matching(&self.sim.sams); @@ -1766,7 +1812,7 @@ impl AirDef { widgets.push(Widget::Button(ButtonWidget { id: POST_FILTER, label: format!("Фильтр · {}", self.post.filter.label()) })); let rows = indices.iter().map(|&i| { let sam = &self.sim.sams[i]; - post::row(sam, i, self.post.pinned == Some(sam.id)) + monitor::fit(post::row(sam, i, self.post.pinned == Some(sam.id)), 184.0) }).collect(); if self.post.shown.is_empty() { widgets.push(Widget::Text(TextWidget { id: 0, text: "Подходящей техники нет".into(), color: 0 })); @@ -1785,6 +1831,7 @@ impl AirDef { } } widgets.push(Widget::Button(ButtonWidget { id: POST_VIEW, label: "Сетка камер".into() })); + widgets.push(Widget::Button(ButtonWidget { id: POST_REFRESH, label: "Обновить список".into() })); } Page::Unit(id, from) | Page::UnitChecks(id, from) => { let Some(i) = self.sim.sams.iter().position(|s| s.id == id) else { @@ -1807,19 +1854,18 @@ impl AirDef { widgets.push(Widget::List(ListWidget { id: POST_ACTIONS, rows, selected: None })); } else { use post::Action; - let headline = reason.filter(|_| sam.kind.armed()).map_or_else( - || post::state(sam).to_owned(), - why_view::unit_headline, - ); - for text in ui_lines(&format!("Сейчас · {headline}")) { - widgets.push(Widget::Text(TextWidget { id: 0, text, color: 0 })); + if let Some(reason) = reason.filter(|_| sam.kind.armed()) { + for text in ui_lines(&format!("Сейчас · {}", why_view::unit_headline(reason))) { + widgets.push(Widget::Text(TextWidget { id: 0, text, color: 0 })); + } } let mut actions = vec![ (Action::Checks, "Статус и отметка"), (Action::Map, "Показать на карте"), (Action::Camera, "Открыть камеру"), ]; - if let Some(source) = reason.and_then(|r| r.mark) + if from != post::From::Source + && let Some(source) = reason.and_then(|r| r.mark) .filter(|mark| !mark.own) .and_then(|mark| mark.source) .and_then(|i| self.sim.sams.get(i)) @@ -1836,6 +1882,7 @@ impl AirDef { (_, post::From::Post) => "К списку", (_, post::From::Map(_)) => "К карте", (_, post::From::Monitor) => "К монитору", + (_, post::From::Source) => "К исходному комплексу", }; widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: label.into() })); } @@ -1869,6 +1916,7 @@ impl AirDef { widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "Назад".into() })); } Page::Replays => { + widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAINS, label: "Цепочки боя".into() })); match self.sim.replays.last() { Some(rec) => { let kills = rec.events.iter().filter(|e| matches!(e.kind, sim::record::EventKind::Kill { .. })).count(); @@ -1878,7 +1926,6 @@ impl AirDef { widgets.push(Widget::Button(ButtonWidget { id: BTN_MAP, label: "Карта налёта (R)".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_FULL, label: "Полный повтор".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_REEL, label: format!("Лучшие моменты ({})", replay::reel(rec).len()) })); - widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAINS, label: format!("Цепочки боя (разбор): {}", rec.chains(None).len()) })); widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() })); } None => { @@ -1888,7 +1935,6 @@ impl AirDef { text: "Повторов пока нет: налёт записывается сам и появится здесь, когда небо очистится".into(), color: 0, })); - widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAINS, label: "Цепочки боя (разбор)".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() })); } @@ -1896,32 +1942,48 @@ impl AirDef { widgets.push(Widget::Button(ButtonWidget { id: BTN_BREACHES, label: "Разбор прорывов…".into() })); } Page::Chains => { - match self.sim.replays.last() { + match self.chain_view.recording.and_then(|number| self.sim.replay(number)) { Some(rec) => { - let rows = replay::chain_rows(rec, self.chain_filter); - let filter = self.chain_filter.and_then(|id| { - rec.sams.iter().position(|s| s.0 == id).map(|i| format!("№{} {}", i + 1, rec.sam(id).map_or("ПВО", |(k, _)| k.name()))) - }); + let battery = match self.chain_view.battery { + None => "Все комплексы".into(), + Some(id) => { + rec.sams.iter().position(|s| s.0 == id) + .map_or_else(|| "Комплекса нет в записи".into(), |i| format!("№{} {}", i + 1, rec.sams[i].1.name())) + } + }; title = format!( - "Цепочки боя: отметка → передача → захват → пуск → исход · {} · фильтр: {} · клик: кадр повтора", - if rows.is_empty() { "нет цепочек".to_string() } else { format!("{}", rows.len()) }, - filter.unwrap_or_else(|| "все батареи".into()), + "Повтор №{} · {} · {} цепочек{}", + rec.number, battery, self.chain_view.page.total, + if rec.scene.as_ref().is_some_and(|scene| scene.truncated) { " · журнал неполный" } else { "" }, ); - let rows = rows.into_iter().take(200).map(|r| r.text).collect(); - widgets.push(Widget::List(ListWidget { id: CHAIN_ROWS, rows, selected: None })); - widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAIN_FILTER, label: "Фильтр по батарее".into() })); - widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← К повторам".into() })); + if self.chain_view.page.rows.is_empty() { + widgets.push(Widget::Text(TextWidget { id: 0, text: "Подходящих цепочек нет".into(), color: 0 })); + } else { + let rows = self.chain_view.page.rows.iter().map(|r| r.text.clone()).collect(); + widgets.push(Widget::List(ListWidget { id: CHAIN_ROWS, rows, selected: None })); + } + widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAIN_OUTCOME, label: format!("Фильтр · {}", self.chain_view.filter.label()) })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAIN_FILTER, label: "Следующий комплекс".into() })); + let pages = self.chain_view.pages(); + if pages > 1 { + widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAIN_PAGE, label: format!("Страница {}/{} →", self.chain_view.page.index + 1, pages) })); + } } None => { title = "Цепочки боя".into(); - widgets.push(Widget::Text(horizon_mod_sdk::ui::TextWidget { + widgets.push(Widget::Text(TextWidget { id: 0, - text: "Повторов пока нет: цепочки появятся после первого налёта".into(), + text: if self.chain_view.recording.is_some() { + "Этот повтор уже вышел из истории" + } else { + "Запись появится после налёта" + }.into(), color: 0, })); - widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← К повторам".into() })); } } + let back = if self.chain_view.from_unit.is_some() { "К карточке" } else { "К повторам" }; + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: back.into() })); } Page::Recon => { title = "Разведка противника — разбор (debug): что враг запомнил и почему".into(); @@ -2176,7 +2238,7 @@ impl Mod for AirDef { world: None, health_mark: 0, menu: None, - chain_filter: None, + chain_view: ChainView::default(), listener: DVec3::ZERO, punch: 0.0, pending: Vec::new(), @@ -2407,7 +2469,7 @@ impl Mod for AirDef { render::set_time_override(ctx.day_time); self.show_world_at(r.rec, r.time(), r.filming()); self.monitor_shown = true; - } else if matches!(self.menu, Some(Page::Post | Page::Unit(..) | Page::UnitChecks(..))) { + } else if self.post_open() { if self.monitor_shown || self.overlay_shown { render::set_hud(&[]); render::set_views(&[]); @@ -2485,6 +2547,7 @@ impl Mod for AirDef { } (Page::Post, POST_PREV) => self.post.page = self.post.page.saturating_sub(1), (Page::Post, POST_NEXT) => self.post.page += 1, + (Page::Post, POST_REFRESH) => {} (Page::Post, POST_VIEW) => { self.pick_grid(); self.grid = true; @@ -2494,17 +2557,17 @@ impl Mod for AirDef { (Page::Unit(unit, from), POST_ACTIONS) => { match self.post.actions.get(row as usize).copied() { Some(post::Action::Checks) => self.open_menu(Page::UnitChecks(unit, from)), - Some(post::Action::Map) => self.open_unit_map(unit), + Some(post::Action::Map) => self.open_unit_map(unit, true), Some(post::Action::Camera) if self.sim.sams.iter().any(|s| s.id == unit) => { self.monitor = Some(unit); self.grid = false; self.close_menu(); } - Some(post::Action::Source(source)) => self.open_menu(Page::Unit(source, from)), - Some(post::Action::History) => { - self.chain_filter = Some(unit); - self.open_menu(Page::Chains); + Some(post::Action::Source(source)) => { + self.post.source_origin = Some((unit, from)); + self.open_menu(Page::Unit(source, post::From::Source)); } + Some(post::Action::History) => self.open_chains(Some((unit, from))), Some(post::Action::Pin) => { self.post.pinned = (self.post.pinned != Some(unit)).then_some(unit); self.post.page = 0; @@ -2521,19 +2584,34 @@ impl Mod for AirDef { (Page::Unit(_, from), BTN_BACK) => { match from { post::From::Post => self.open_post(), - post::From::Map(id) => self.open_unit_map(id), + post::From::Map(id) => self.open_unit_map(id, false), post::From::Monitor => self.close_menu(), + post::From::Source => { + if let Some((id, from)) = self.post.source_origin.take() { + self.open_menu(Page::Unit(id, from)); + } else { + self.open_post(); + } + } } return; } - (Page::Main, MENU_KINDS) => { + (Page::Main, MAIN_ROWS) => { + match MAIN_PAGES.get(row as usize) { + Some((Page::Post, _)) => self.open_post(), + Some((page, _)) => self.open_menu(*page), + None => {} + } + return; + } + (Page::RoleKinds, MENU_KINDS) => { if let Some(k) = SamKind::ARMED.get(row as usize) { self.open_menu(Page::Roles(*k)); } return; } - (Page::Main, BTN_DOCTRINE) => { - self.open_menu(Page::Fleet); + (Page::RoleKinds, BTN_BACK) => { + self.open_menu(Page::Main); return; } (Page::Fleet, FLEET_ROWS) => { @@ -2585,11 +2663,6 @@ impl Mod for AirDef { } } (Page::More, BTN_HOLD) => self.sim.hold = !self.sim.hold, - (Page::Main, BTN_MONITOR) => self.cycle_monitor(), - (Page::Main, BTN_WAVE) => { - self.open_menu(Page::Wave); - return; - } (Page::More, BTN_REPAIR) => { if self.village_active() { say("В этом сценарии состояние объектов и техники переносится между волнами"); @@ -2646,10 +2719,6 @@ 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", @@ -2681,10 +2750,6 @@ impl Mod for AirDef { self.open_menu(Page::Main); return; } - (Page::Main, BTN_REPLAYS) => { - self.open_menu(Page::Replays); - return; - } (Page::Replays, REPLAY_EVENTS | BTN_MAP | BTN_FULL | BTN_REEL) => { let r = match id { REPLAY_EVENTS => self.start_replay("clip", Some(row as usize)), @@ -2706,37 +2771,43 @@ impl Mod for AirDef { return; } (Page::Replays, BTN_CHAINS) => { - self.open_menu(Page::Chains); + self.open_chains(None); return; } (Page::Chains, CHAIN_ROWS) => { - let Some(rec) = self.sim.replays.last() else { return }; - let Some(row) = replay::chain_rows(rec, self.chain_filter).into_iter().nth(row as usize) else { return }; - match self.start_chain(row) { - Ok(()) => { - self.menu = None; - ui::close_screen(); - } + let Some(number) = self.chain_view.recording else { return }; + let Some(row) = self.chain_view.page.rows.get(row as usize) else { return }; + match self.start_chain(number, row.event, row.at) { + Ok(()) => self.close_menu(), Err(e) => say(&e), } return; } (Page::Chains, BTN_CHAIN_FILTER) => { - // All → each battery → all. Only systems are offered; a battery with no chains - // still narrows the list to "nothing", which is the honest answer. - let ids: Vec = self.sim.sams.iter().map(|s| s.id).collect(); - self.chain_filter = match self.chain_filter { - None => ids.first().copied(), - Some(id) => ids.iter().position(|x| *x == id).and_then(|i| ids.get(i + 1).copied()), - }; - self.open_menu(Page::Chains); - return; + let Some(rec) = self.chain_view.recording.and_then(|number| self.sim.replay(number)) else { return }; + let sams = &rec.sams; + self.chain_view.battery = match self.chain_view.battery { + None => sams.first(), + Some(id) => sams.iter().position(|s| s.0 == id).and_then(|i| sams.get(i + 1)), + }.map(|s| s.0); + self.refresh_chains(0); + } + (Page::Chains, BTN_CHAIN_OUTCOME) => { + self.chain_view.filter = self.chain_view.filter.next(); + self.refresh_chains(0); + } + (Page::Chains, BTN_CHAIN_PAGE) => { + let page = (self.chain_view.page.index + 1) % self.chain_view.pages(); + self.refresh_chains(page); } (Page::Chains, BTN_BACK) => { - self.open_menu(Page::Replays); + match self.chain_view.from_unit { + Some((id, from)) => self.open_menu(Page::Unit(id, from)), + None => self.open_menu(Page::Replays), + } return; } - (Page::Main, BTN_RECON) | (Page::Replays, BTN_RECON) => { + (Page::Replays, BTN_RECON) => { self.open_menu(Page::Recon); return; } @@ -2746,14 +2817,6 @@ impl Mod for AirDef { } // The review is read-only: a row click changes nothing. (Page::Recon, RECON_ROWS) => return, - (Page::Main, BTN_MORE) => { - self.open_menu(Page::More); - return; - } - (Page::Main, BTN_GRID) => { - self.open_post(); - return; - } (Page::More, BTN_SHADER) => { // Off → effects → HD → off. let (shader, hd) = match (self.sim.shader, self.hd) { @@ -2800,7 +2863,7 @@ impl Mod for AirDef { (Page::Roles(kind), BTN_DEFAULT) => self.set_roles(kind, None), (Page::Roles(kind), BTN_NONE) => self.set_roles(kind, Some(0)), (Page::Roles(_), BTN_BACK) => { - self.open_menu(Page::Main); + self.open_menu(Page::RoleKinds); return; } _ => return, @@ -2818,7 +2881,7 @@ impl Mod for AirDef { if self.presentation.is_live() { match self.post.transition.take() { Some((transition, false)) => self.post.transition = Some((transition, true)), - Some((post::Transition::Map(id), true)) => self.show_unit_on_map(id), + Some((post::Transition::Map { unit, centre }, true)) => self.show_unit_on_map(unit, centre), Some((post::Transition::Card(id), true)) if player().is_some() => { self.open_menu(Page::Unit(id, post::From::Map(id))); } @@ -3304,7 +3367,7 @@ mod tests { world: None, health_mark: 0, menu: None, - chain_filter: None, + chain_view: ChainView::default(), listener: DVec3::ZERO, punch: 0.0, pending: Vec::new(), diff --git a/airdef-mod/src/map.rs b/airdef-mod/src/map.rs index f5d5b84..a40445f 100644 --- a/airdef-mod/src/map.rs +++ b/airdef-mod/src/map.rs @@ -917,12 +917,12 @@ impl AirDef { self.map.drag = None; } - pub(crate) fn open_unit_map(&mut self, id: u32) { + pub(crate) fn open_unit_map(&mut self, unit: u32, centre: bool) { self.close_menu(); - self.post.transition = Some((crate::post::Transition::Map(id), false)); + self.post.transition = Some((crate::post::Transition::Map { unit, centre }, false)); } - pub(crate) fn show_unit_on_map(&mut self, id: u32) { + pub(crate) fn show_unit_on_map(&mut self, id: u32, centre: bool) { let Some(sam) = self.sim.sams.iter().find(|sam| sam.id == id) else { say("Комплекс уже убран"); return; @@ -932,7 +932,9 @@ impl AirDef { self.map_toggle(); } self.map.sel = Some(Sel::Sam(id)); - self.map.centre = (pos.x, pos.z); + if centre { + self.map.centre = (pos.x, pos.z); + } self.map.follow = false; self.map.dirty = true; } diff --git a/airdef-mod/src/monitor.rs b/airdef-mod/src/monitor.rs index acd8b21..8d9c0f4 100644 --- a/airdef-mod/src/monitor.rs +++ b/airdef-mod/src/monitor.rs @@ -21,7 +21,7 @@ fn quad(a: (f32, f32), b: (f32, f32), c: (f32, f32), d: (f32, f32), color: u32) } /// `t` cut to `w` GUI pixels, with an ellipsis. -fn fit(t: String, w: f32) -> String { +pub(crate) fn fit(t: String, w: f32) -> String { if render::text_width(&t) <= w { return t; } diff --git a/airdef-mod/src/post.rs b/airdef-mod/src/post.rs index a0b5ef8..d71634b 100644 --- a/airdef-mod/src/post.rs +++ b/airdef-mod/src/post.rs @@ -1,5 +1,5 @@ //! The command post lists every deployed unit without requesting camera views. -use crate::sim::{Part, PartState, Sam, SamKind, SamState}; +use crate::sim::{Part, PartState, Sam, SamKind, SamState, battery::RadarRole}; /// Keep enough room under the engine's 512-row limit for large layouts. pub const PAGE_SIZE: usize = 200; @@ -65,6 +65,7 @@ pub enum From { Post, Map(u32), Monitor, + Source, } #[derive(Clone, Copy)] @@ -78,7 +79,7 @@ pub enum Action { } pub enum Transition { - Map(u32), + Map { unit: u32, centre: bool }, Card(u32), } @@ -91,6 +92,7 @@ pub struct Post { /// IDs and actions exactly as shown in the screen, even if the sim advances before a click. pub shown: Vec, pub actions: Vec, + pub source_origin: Option<(u32, From)>, /// Let the client finish closing one screen before opening a different kind. pub transition: Option<(Transition, bool)>, } @@ -132,7 +134,16 @@ pub fn state(sam: &Sam) -> &'static str { } pub fn row(sam: &Sam, index: usize, pinned: bool) -> String { - let name = sam.kind.name(); + let name = match sam.kind { + SamKind::Radar => match sam.radar_role { + RadarRole::Search => "РЛС обзора", + RadarRole::Engagement => "РЛС сопровождения", + RadarRole::Height => "РЛС высоты", + RadarRole::Multifunction => "РЛС", + }, + SamKind::Depot => "Склад", + _ => sam.kind.name(), + }; let status = if Filter::NoLink.matches(sam) { "Нет связи" } else if Filter::NoAmmo.matches(sam) && sam.reloading == 0 { diff --git a/airdef-mod/src/replay.rs b/airdef-mod/src/replay.rs index f73c243..4007477 100644 --- a/airdef-mod/src/replay.rs +++ b/airdef-mod/src/replay.rs @@ -200,7 +200,61 @@ pub struct ChainRow { /// The short chains of a raid: отметка → передача → захват → пуск → исход, filtered by a /// battery's id when asked. The list is the recording's measured transitions, not a guess. pub fn chain_rows(rec: &Recording, battery: Option) -> Vec { - rec.chains(battery).iter().map(|chain| ChainRow { text: chain_row(rec, chain), event: chain.outcome_event(), at: chain_jump_at(chain) }).collect() + chain_page(rec, battery, ChainFilter::All, 0, usize::MAX).rows +} + +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub(crate) enum ChainFilter { + #[default] + All, + NoLaunch, + Breach, +} + +impl ChainFilter { + pub fn next(self) -> Self { + match self { + Self::All => Self::NoLaunch, + Self::NoLaunch => Self::Breach, + Self::Breach => Self::All, + } + } + + pub fn label(self) -> &'static str { + match self { + Self::All => "Все цепочки", + Self::NoLaunch => "Без записи пуска", + Self::Breach => "Прорывы", + } + } + + fn matches(self, chain: &Chain) -> bool { + match self { + Self::All => true, + Self::NoLaunch => chain.missed(), + Self::Breach => chain.outcome == ChainOutcome::Hit, + } + } +} + +#[derive(Default)] +pub(crate) struct ChainPage { + pub rows: Vec, + pub total: usize, + pub index: usize, +} + +pub(crate) fn chain_page(rec: &Recording, battery: Option, filter: ChainFilter, page: usize, size: usize) -> ChainPage { + let mut chains = rec.chains(battery); + chains.retain(|chain| filter.matches(chain)); + let total = chains.len(); + let index = page.min(total.div_ceil(size).saturating_sub(1)); + let rows = chains.iter().skip(index * size).take(size).map(|chain| ChainRow { + text: chain_row(rec, chain), + event: chain.outcome_event(), + at: chain_jump_at(chain), + }).collect(); + ChainPage { rows, total, index } } /// Where a chain opens in a replay when its outcome has no recorded event. @@ -244,7 +298,7 @@ pub fn chain_row(rec: &Recording, chain: &Chain) -> String { "{} {battery} → «{target}»: {}{}", clock(chain.marked_at() as f64), steps.join(" → "), - if chain.missed() { " · без пуска" } else { "" }, + if chain.missed() { " · пуск не записан" } else { "" }, ) } @@ -1232,6 +1286,34 @@ mod surface_tests { assert!((player.time() - rows[0].at).abs() < 1e-9); } + #[test] + fn pages_and_filters_keep_the_original_replay_jump() { + use crate::sim::record::{Event, SceneEvent, SceneJournal, SceneKind}; + let mut rec = Recording::blank(300); + let mut scene = SceneJournal::default(); + for target in 1..=4 { + scene.fixture_push(SceneEvent { + at: target * 20, + pos: DVec3::ZERO, + kind: SceneKind::TrackAcquired { sam: 10, target, ever_own: true }, + }); + } + rec.scene = Some(scene); + rec.events.push(Event { + at: 100, + pos: DVec3::ZERO, + kind: EventKind::Hit { drone: 3, kind: DroneKind::Shahed, power: 1, object: Some(0), sam: None }, + }); + let page = chain_page(&rec, Some(10), ChainFilter::NoLaunch, 1, 2); + assert_eq!((page.index, page.total, page.rows.len()), (1, 4, 2)); + assert_eq!((page.rows[0].event, page.rows[0].at), (Some(0), 60.0)); + assert_eq!((page.rows[1].event, page.rows[1].at), (None, 80.0)); + let page = chain_page(&rec, Some(10), ChainFilter::Breach, 9, 2); + assert_eq!((page.index, page.total, page.rows.len()), (0, 1, 1)); + assert_eq!(page.rows[0].event, Some(0)); + assert!(chain_page(&rec, Some(11), ChainFilter::All, 1, 2).rows.is_empty()); + } + /// A gun standing on the sea floor films from above the water, not from under it. #[test] fn the_gun_camera_is_lifted_above_the_water() { diff --git a/airdef-mod/src/sim/record.rs b/airdef-mod/src/sim/record.rs index 542db14..3e5b4c0 100644 --- a/airdef-mod/src/sim/record.rs +++ b/airdef-mod/src/sim/record.rs @@ -1340,17 +1340,18 @@ impl Recording { } } } - EventKind::Hit { drone, sam, .. } => { - let by_sam = sam.and_then(|(_, i)| self.sams.get(i).map(|s| s.0)); + EventKind::Hit { drone, .. } => { + // This is the contact's outcome, whatever it hit. A system named in + // the impact is the object hit, not the observer on the chain. for ((_, target), chain) in chains.iter_mut() { - if *target == drone && by_sam.is_none_or(|id| id == chain.sam) { + if *target == drone { set_chain_outcome(chain, ChainOutcome::Hit, event.at, Some(index)); } } } EventKind::Crash { drone, .. } => { for ((_, target), chain) in chains.iter_mut() { - if *target == drone && !chain.launched() { + if *target == drone && chain.outcome == ChainOutcome::Unfinished && !chain.launched() { set_chain_outcome(chain, ChainOutcome::Lost, event.at, Some(index)); } } @@ -1362,6 +1363,7 @@ impl Recording { for event in scene.events() { if let SceneKind::TrackLost { sam, target } = event.kind && let Some(chain) = chains.get_mut(&(sam, target)) + && chain.outcome == ChainOutcome::Unfinished && !chain.launched() { set_chain_outcome(chain, ChainOutcome::Lost, event.at, None); @@ -1727,6 +1729,33 @@ mod tests { assert_eq!(chain.outcome_event(), None); } + #[test] + fn a_recorded_impact_stays_in_every_observers_chain_when_the_track_ends() { + let mut r = Recording::blank(100); + r.sams = vec![(10, SamKind::Pantsir, DVec3::ZERO), (20, SamKind::S400, DVec3::X)]; + let mut scene = SceneJournal::default(); + for sam in [10, 20] { + scene.push(SceneEvent { at: 10, pos: DVec3::ZERO, kind: SceneKind::TrackAcquired { sam, target: 7, ever_own: false } }); + } + for sam in [10, 20] { + scene.push(SceneEvent { at: 51, pos: DVec3::ZERO, kind: SceneKind::TrackLost { sam, target: 7 } }); + } + r.scene = Some(scene); + r.events.push(Event { + at: 50, + pos: DVec3::ZERO, + kind: EventKind::Hit { drone: 7, kind: DroneKind::Shahed, power: 2, object: None, sam: Some((SamKind::S400, 1)) }, + }); + for id in [10, 20] { + let chains = r.chains(Some(id)); + assert_eq!(chains.len(), 1); + assert_eq!(chains[0].outcome, ChainOutcome::Hit); + assert_eq!(chains[0].outcome_event(), Some(0)); + assert_eq!(chains[0].step(ChainStepKind::Outcome).unwrap().at, 50); + assert!(chains[0].missed()); + } + } + fn recording() -> Recording { Recording::blank(0) }