Merge recon flights and partial reports into the classified radar picture (#135)
build / mod (push) Failing after 1m5s

Co-Authored-By: Kimi Code <noreply@moonshot.ai>

# Conflicts:
#	airdef-mod/src/sim/mod.rs
This commit is contained in:
2026-11-21 00:07:39 +03:00
13 changed files with 2171 additions and 71 deletions
+15 -2
View File
@@ -229,10 +229,23 @@ API мода `render.set-lights` (до 512, плавно интерполиру
- `/airdef clear` — убрать дроны и ракеты;
- `/airdef targets clear` — снять все цели;
- `/airdef stats` — сводка.
- `/airdef recon` — debug/послебоевой разбор разведки противника (#135): отметки его картины best-first с причиной приоритета (`свежесть×4 + качество×3 + наблюдаемая роль`), фазы вылетов и дроны, нацеленные на отметку. То же — страница «Разведка противника (разбор)» в меню N. Всеведущая картина противника в обычный HUD не выводится.
Интерфейс:
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт;
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели: форма значка различает дрон, самолёт, крылатую, сверхзвуковую и баллистическую ракету, хвост показывает курс, а близкие отметки объединяются с числом; жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара.
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт; если сеть держит разведчиков противника — их число и фаза вылета (разведка/донесение/завершение);
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели: форма значка различает дрон, самолёт, крылатую, сверхзвуковую и баллистическую ракету, хвост показывает курс, а близкие отметки объединяются с числом; жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара. Разведчик противника в картине сети — жёлтый полый ромб с подписью «разведчик».
**Разведка противника (#135).** Налёт с целью «умный противник» перед ударом высылает небольшой бюджет
невооружённых разведчиков: они физически проходят игровые зоны вокруг отмеченных целей и передают домой
только область, грубую категорию, канал (пролёт/излучение/РЭБ/пуск) и возраст — не точную точку, тип,
прочность и боезапас. Сбитый до донесения разведчик ничего не передаёт; уже переданное противник помнит
между налётами, а скрытый переезд или выключение не переписывают старую отметку. На карте сети разведчик —
узнаваемый жёлтый ромб с подписью «разведчик» (в sandbox-режиме `/airdef truth on` — янтарная метка и
счётчик отметок), в сводке и на карте видна фаза вылета: разведка → донесение → завершение. Что противник
запомнил и почему выбирает цель, показывает `/airdef recon` и страница «Разведка противника (разбор)» в меню
N (есть и в «Повторы…»): отметки best-first с разбором приоритета (свежесть, качество, наблюдаемая роль) и
дроны, нацеленные на отметку. Это явный debug/послебоевой разбор — всеведущая картина противника в обычный
HUD не выводится. Простые пресеты налёта фазу разведки не получают.
Комплексы ПВО и цели сохраняются между сессиями.
+4 -3
View File
@@ -106,6 +106,7 @@ pub fn tree() -> Tree {
Node::lit("guard").with([Node::lit("off").runs(), Node::arg("объекты", Value::word()).runs()]),
Node::lit("reset").runs(),
])),
Node::lit("recon").runs(),
Node::lit("stats").runs(),
])
}
@@ -162,7 +163,7 @@ mod tests {
#[test]
fn every_branch_of_the_handler_parses() {
for line in [
"", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "roles",
"", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "recon", "roles",
"replay", "replay map", "replay full", "replay reel", "replay film", "replay film best", "replay film all",
"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",
@@ -241,10 +242,10 @@ mod tests {
fn completion_offers_the_next_word_only() {
let top = complete("", &[]);
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel"] {
"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"] {
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
}
assert_eq!(top.len(), 35);
assert_eq!(top.len(), 36);
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
+32
View File
@@ -24,6 +24,7 @@ mod monitor;
mod panel;
mod presentation;
mod radar;
mod recon_view;
mod replay;
mod scene;
mod smoke;
@@ -200,6 +201,8 @@ enum Page {
More,
/// The last raid's events and its replays.
Replays,
/// The enemy's recon picture and why it prices each mark: debug and after-action review (#135).
Recon,
/// The systems with their doctrines, and one system's doctrine (by id) (#47).
Fleet,
Doctrine(u32),
@@ -235,7 +238,9 @@ 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 BTN_MAP: u32 = 40;
const BTN_FULL: u32 = 41;
const BTN_REEL: u32 = 42;
@@ -1587,6 +1592,7 @@ impl AirDef {
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_REPLAYS, label: "Повторы…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_MORE, label: "Огонь, ремонт, эффекты…".into() }));
}
Page::BatteryDeploy => {
@@ -1608,6 +1614,7 @@ 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_RECON, label: "Разведка противника (разбор)".into() }));
}
None => {
title = "Повторы".into();
@@ -1616,10 +1623,17 @@ impl AirDef {
text: "Повторов пока нет: налёт записывается сам и появится здесь, когда небо очистится".into(),
color: 0,
}));
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
}
}
Page::Recon => {
title = "Разведка противника — разбор (debug): что враг запомнил и почему".into();
let rows: Vec<String> = recon_view::picture_lines(&self.sim.enemy_picture()).into_iter().take(200).collect();
widgets.push(Widget::List(ListWidget { id: RECON_ROWS, rows, selected: None }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
Page::More => {
title = "AirDef — управление".to_string();
widgets.push(Widget::Button(ButtonWidget {
@@ -2267,6 +2281,16 @@ impl Mod for AirDef {
self.open_menu(Page::Main);
return;
}
(Page::Main, BTN_RECON) | (Page::Replays, BTN_RECON) => {
self.open_menu(Page::Recon);
return;
}
(Page::Recon, BTN_BACK) => {
self.open_menu(Page::Main);
return;
}
// 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;
@@ -2592,6 +2616,14 @@ impl Mod for AirDef {
self.set_effects(*v != "off", *v == "hd");
Some(format!("Эффекты: {}", match *v { "off" => "выкл", "hd" => "HD", _ => "обычные" }))
}
["recon"] => {
// The enemy's partial picture and why it prices each mark: explicit debug, never the
// normal HUD (#135). The same lines fill the after-action review page.
for l in recon_view::picture_lines(&self.sim.enemy_picture()) {
say(&l);
}
None
}
["stats"] => Some(format!(
"В воздухе: {}, ракет: {}, ПВО: {}, сбито: {}, поражений: {}, разбились о препятствия: {}; удары по ПУ: пущено {}, уничтожено {}, подавлено {}, промахов {}, сбито ПВО {}; {}",
self.sim.drones.iter().filter(|d| d.alive()).count(),
+50 -17
View File
@@ -784,16 +784,26 @@ fn map_truth(sim: &Sim, ui: &mut MapUi, hover: Option<Hover>, s: &mut Vec<Shape>
}
prev = p;
}
// The drone: a white frame, never the network's red diamond.
s.extend(frame(c.0 - 5.0, c.1 - 5.0, 10.0, 10.0, 1.2, alpha(WHITE, 0.95)));
s.push(fill(c.0 - 1.0, c.1 - 1.0, 2.0, 2.0, WHITE));
// The drone: a white frame, never the network's red diamond. A recon aircraft has a
// sign of its own: an amber diamond, not the strike's frame (#135).
let recon = sim.is_recon_drone(d.id);
if recon {
let p = [(c.0, c.1 - 5.0), (c.0 + 5.0, c.1), (c.0, c.1 + 5.0), (c.0 - 5.0, c.1)];
for i in 0..4 {
s.push(line(p[i], p[(i + 1) % 4], 1.2, alpha(0xFFC040, 0.95)));
}
} else {
s.extend(frame(c.0 - 5.0, c.1 - 5.0, 10.0, 10.0, 1.2, alpha(WHITE, 0.95)));
}
s.push(fill(c.0 - 1.0, c.1 - 1.0, 2.0, 2.0, if recon { alpha(0xFFC040, 0.95) } else { WHITE }));
if ui.on_screen(aim, 6.0) {
s.push(diamond(aim.0, aim.1, 4.5, alpha(0xFFE070, 0.85)));
s.push(fill(aim.0 - 1.0, aim.1 - 1.0, 2.0, 2.0, alpha(0xFFE070, 0.9)));
}
taken.push([c.0 - 6.0, c.1 - 6.0, 12.0, 12.0]);
let chosen = hover == Some(Hover::Drone(d.id));
add_lab(ui, labs, format!("{} №{}", d.kind.spec().name, d.id), c, 7.0, alpha(YELLOW, 0.95), chosen);
let name = if recon { format!("разведчик №{}", d.id) } else { format!("{} №{}", d.kind.spec().name, d.id) };
add_lab(ui, labs, name, c, 7.0, alpha(YELLOW, 0.95), chosen);
if chosen {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
}
@@ -2349,26 +2359,34 @@ impl AirDef {
let chosen = ui.sel == Some(Sel::Track(id));
let forecast = t.forecast(now);
let age = t.age(now);
let col = if forecast { alpha(0xFFB0B0, 0.65) } else { 0xFFFF5050 };
s.push(diamond(c.0, c.1, TRACK_R, col));
if !forecast {
s.push(diamond(c.0, c.1, 3.0, 0xFF200808));
// A recon aircraft is a role of its own: a yellow hollow diamond and a named label, so
// the player tells it from a strike drone the network tracks the same way (#135).
let recon = sim::is_drone_id(id);
let r = if recon { 5.0 } else { TRACK_R };
let col = if recon { YELLOW } else if forecast { alpha(0xFFB0B0, 0.65) } else { 0xFFFF5050 };
s.push(diamond(c.0, c.1, r, col));
if recon || !forecast {
s.push(diamond(c.0, c.1, if recon { 2.0 } else { 3.0 }, 0xFF200808));
}
// Its measured course, a tick out of the marker.
let v = t.vel.normalize_or_zero();
if v != DVec3::ZERO {
s.push(line(c, (c.0 + v.x as f32 * 10.0, c.1 + v.z as f32 * 10.0), 1.5, col));
}
taken.push([c.0 - TRACK_R - 1.0, c.1 - TRACK_R - 1.0, TRACK_R * 2.0 + 2.0, TRACK_R * 2.0 + 2.0]);
let mark = t.class.mark();
let age = if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) };
let txt = match (mark.is_empty(), forecast) {
(true, true) => format!("~{age}"),
(true, false) => age,
(false, true) => format!("{mark} ~{age}"),
(false, false) => format!("{mark} {age}"),
taken.push([c.0 - r - 1.0, c.1 - r - 1.0, r * 2.0 + 2.0, r * 2.0 + 2.0]);
let age_txt = if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) };
let txt = if recon {
format!("разведчик {age_txt}")
} else {
let mark = t.class.mark();
match (mark.is_empty(), forecast) {
(true, true) => format!("~{age_txt}"),
(true, false) => age_txt,
(false, true) => format!("{mark} ~{age_txt}"),
(false, false) => format!("{mark} {age_txt}"),
}
};
add_lab(ui, labs, txt, c, TRACK_R + 1.0, col, chosen);
add_lab(ui, labs, txt, c, r + 1.0, col, chosen);
if chosen {
s.extend(frame(c.0 - 10.0, c.1 - 10.0, 20.0, 20.0, 1.0, GREEN));
}
@@ -2487,6 +2505,9 @@ impl AirDef {
inner.push(text(l, x0, y, GREY));
y += lh - 1.0;
}
let rn = self.sim.picture().values().filter(|t| sim::is_drone_id(t.id)).count();
inner.push(text(format!("жёлтый ромб — разведчик ({rn})"), x0, y, GREY));
y += lh - 1.0;
}
_ => {
inner.push(text("Имя сценария", x0, y, GREY));
@@ -2827,6 +2848,10 @@ impl AirDef {
lines.push((format!("Трек №{id}: потерян сетью"), GREY));
return;
};
if sim::is_drone_id(id) {
lines.push((format!("Разведчик противника №{id}"), YELLOW));
lines.push(("Роль: разведка (без оружия) — ищет технику вокруг объектов".into(), YELLOW));
}
let player = crate::player().map(|p| DVec3::new(p.x, p.y, p.z));
track_lines(&self.sim, t, player, lines);
lines.push(("Тонкая линия — пройденное по измерениям,".into(), GREY));
@@ -2846,6 +2871,14 @@ impl AirDef {
lines.push(("Режим ИСТИНА: настоящие дроны, их цели и маршруты.".into(), YELLOW));
lines.push(("Это песочница, не данные сети. T — обратно.".into(), YELLOW));
}
// The recon flight's phase, only while the network actually holds a recon aircraft:
// what the visible aircraft are doing, not what the enemy learned (#135).
if self.sim.picture().values().any(|t| sim::is_drone_id(t.id)) {
let pic = self.sim.enemy_picture();
if let Some(phase) = crate::recon_view::battle_phase(&pic) {
lines.push((format!("Разведка противника: {phase} · разведчиков {}", pic.recon_sorties.len()), YELLOW));
}
}
if self.battle() {
lines.push(("Идёт налёт: расстановка закрыта".into(), YELLOW));
}
+78
View File
@@ -64,6 +64,17 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
));
}
}
// Recon aircraft the network tracks: their presence and the coarse phase of the flight. This is
// what the visible aircraft are doing, not the enemy's knowledge — the marks and the reasons are
// the debug command's and the after-action review's alone (#135).
let recon_n = pic.tracks.iter().filter(|t| crate::sim::is_drone_id(t.id)).count();
if recon_n > 0 {
let mut text = format!("Разведка противника: разведчиков в воздухе {recon_n}");
if let Some(phase) = crate::recon_view::battle_phase(&sim.enemy_picture()) {
text += &format!(" · фаза: {phase}");
}
lines.push(line(text, YELLOW));
}
if sim.truth {
let real = sim.drones.iter().filter(|d| d.alive()).count();
let unseen = sim.drones.iter().filter(|d| d.alive() && pic.get(d.id).is_none()).count();
@@ -72,6 +83,12 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
text += ", противник планирует налёт";
}
lines.push(line(text, YELLOW));
// The recon phase, in the truth only: the aircraft out and the marks the enemy holds
// are its knowledge, not the player's (#135).
let (out, marks) = sim.recon_status();
if out > 0 || marks > 0 {
lines.push(line(format!("РАЗВЕДКА ПРОТИВНИКА: в воздухе {out}, отметок в картине {marks}"), YELLOW));
}
}
// The launch sites found, and the strike missiles (#101).
if !sim.strikes.known.is_empty() || !sim.strikes.flights.is_empty() {
@@ -135,3 +152,64 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
));
lines
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{Aim, AirPicture, Approach, DroneKind, Out, RaidOrder, Track};
use glam::DVec3;
fn track(id: u32, class: ClassEst) -> Track {
Track { id, class, pos: DVec3::new(0.0, 120.0, 300.0), vel: DVec3::new(0.0, 0.0, -0.5), tick: 100, own_tick: 100, source: 0, product: crate::sim::battery::Measure::Search, quality: 40, own_product: crate::sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: false }
}
// A recon aircraft the network holds is named as such, with the flight's coarse phase; the line
// carries no mark, area or priority — the enemy's knowledge is not the HUD's (#135).
#[test]
fn a_tracked_recon_aircraft_shows_presence_and_phase_not_marks() {
let mut sim = Sim::new(135);
let object = DVec3::new(0.0, 70.0, 0.0);
sim.targets.push(object);
sim.target_health.push(100.0);
let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart };
sim.order_raid(&order, &[object], &mut Out::default());
let pic = sim.air_picture();
assert!(pic.tracks.iter().any(|t| crate::sim::is_drone_id(t.id)), "the smart wave sent no recon to track");
let lines = summary(&sim, &pic, DVec3::ZERO);
let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line");
assert!(recon.text.contains("разведчиков в воздухе"), "{}", recon.text);
assert!(recon.text.contains("фаза:"), "the flight's phase was not shown: {}", recon.text);
assert!(!recon.text.contains("приоритет") && !recon.text.contains("Отметка"), "the HUD leaked the enemy's marks: {}", recon.text);
assert!(lines.iter().all(|l| !l.text.contains("Отметка") && !l.text.contains("приоритет")), "a mark reached the normal HUD");
}
// An ordinary strike track is not a recon flight: no recon line appears.
#[test]
fn an_ordinary_track_is_not_called_recon() {
let sim = Sim::new(1);
let pic = AirPicture { now: 100, tracks: vec![track(1, ClassEst::Firm(Class::Drone))], unaided: false };
let lines = summary(&sim, &pic, DVec3::ZERO);
assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}");
}
// A recon id in the picture is enough for the presence line even without a live sortie (a flight
// finishing its way home): the phase is then omitted, the presence stays.
#[test]
fn a_recon_track_without_a_sortie_still_names_the_presence() {
let sim = Sim::new(1);
let pic = AirPicture { now: 100, tracks: vec![track(0x3000_0001, ClassEst::Firm(Class::Drone))], unaided: false };
let lines = summary(&sim, &pic, DVec3::ZERO);
let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line");
assert!(recon.text.contains("разведчиков в воздухе 1"), "{}", recon.text);
assert!(!recon.text.contains("фаза:"), "a phase was invented without a sortie: {}", recon.text);
}
#[test]
fn an_empty_sky_has_no_recon_line() {
let sim = Sim::new(1);
let pic = AirPicture { now: 100, tracks: Vec::new(), unaided: false };
let lines = summary(&sim, &pic, DVec3::ZERO);
assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}");
}
}
+286
View File
@@ -0,0 +1,286 @@
//! Text for the enemy's reconnaissance (#135): the readable phase of a recon flight and the
//! reason a mark outranks another. It reads only the diagnostic report types (`EnemyPictureReport`,
//! `ReconReport`, `ReconSortieReport`) — an area, a public category, a channel, an age and a quality,
//! never a true place, `SamKind`, health, magazine, link or real id. The full picture is for the
//! explicit debug command and the after-action review; the battle HUD takes only the coarse phase
//! of aircraft the player's own network already tracks.
use crate::sim::{Category, Confidence, EnemyPictureReport, Quality, ReconReport, ReconSortieReport, priority_parts};
/// The public category a look reported, in the panel's words.
pub fn category_name(key: &str) -> &'static str {
match key {
"radar" => "РЛС",
"launcher" => "пусковая",
"gun" => "пушка",
"ew" => "РЭБ",
"support" => "тыл",
_ => "не определено",
}
}
/// A radar's role, public only once a refined look told it.
pub fn role_name(key: &str) -> &'static str {
match key {
"multi" => "многофункциональная",
"search" => "обзорная",
"engagement" => "наведения",
"height" => "высотомер",
_ => "не определена",
}
}
/// The channel that showed the unit.
pub fn source_name(key: &str) -> &'static str {
match key {
"emission" => "излучение",
"jamming" => "РЭБ",
"launch" => "пуск",
_ => "пролёт",
}
}
/// How well the area is known.
pub fn quality_name(key: &str) -> &'static str {
match key {
"refined" => "уточнённая",
_ => "грубая",
}
}
/// The trust the picture puts in a mark of this age.
pub fn confidence_name(confidence: Confidence) -> &'static str {
match confidence {
Confidence::Confirmed => "подтверждена",
Confidence::Probable => "вероятна",
Confidence::Doubtful => "сомнительна",
}
}
/// The phase of a sortie, as the timeline and the battle UI read it.
pub fn phase_name(phase: &str) -> &'static str {
match phase {
"reporting" => "донесение",
"done" => "завершение",
"looking" => "осмотр",
_ => "разведка",
}
}
/// Why a smart drone's aim is what it is, in words.
pub fn intent_name(intent: &str) -> &'static str {
match intent {
"sead" => "подавление ПВО",
"react" => "реакция",
"replace" => "замена",
_ => "план",
}
}
/// One mark in a line: its area's category and role, the channel, the quality, the trust, the age
/// and the priority the planner prices it at.
pub fn mark_line(m: &ReconReport) -> String {
let role = m.role.map(|k| format!(" ({})", role_name(k))).unwrap_or_default();
format!(
"Отметка {}: {}{} · {} · {} · {} · {} с назад · приоритет {}",
m.id,
category_name(m.category),
role,
source_name(m.source),
quality_name(m.quality),
confidence_name(m.confidence),
m.age / 20,
m.priority
)
}
/// Why the mark has the priority it does: the observed role, the freshness and the quality, each
/// with the weight the planner gives it, summing to the priority. The unit's true importance is not
/// in it — only what the look reported.
pub fn mark_reason(m: &ReconReport) -> String {
let category = Category::from_key(m.category).unwrap_or(Category::Unknown);
let quality = Quality::from_key(m.quality).unwrap_or(Quality::Coarse);
let role = m.role.and_then(crate::sim::battery::RadarRole::from_key);
let (freshness, quality_w, role_w) = priority_parts(m.confidence, quality, category, role);
let role_txt = match m.role {
Some(key) => format!("роль «{}»", role_name(key)),
None => format!("категория «{}»", category_name(m.category)),
};
format!(
"приоритет {} = свежесть {}×4 + качество {}×3 + роль {}: {} {}, {}",
m.priority,
freshness,
quality_w,
role_w,
confidence_name(m.confidence),
quality_name(m.quality),
role_txt
)
}
/// One sortie in a line: its phase, the zones left and when its pending report is due.
pub fn sortie_line(s: &ReconSortieReport) -> String {
let mut text = format!("Разведчик {}: {}", s.drone, phase_name(s.phase));
if s.zones_left > 0 {
text += &format!(" · зон осталось {}", s.zones_left);
}
if let Some(due) = s.report_in {
text += &format!(" · донесение через {} с", due / 20);
}
text
}
/// The coarse phase of the recon flight for the battle UI: a report going home now, else aircraft
/// still looking, else the flight finishing. `None` when no sortie is out. It says nothing of what
/// the enemy learned — only what its visible aircraft are doing.
pub fn battle_phase(pic: &EnemyPictureReport) -> Option<&'static str> {
if pic.recon_sorties.iter().any(|s| s.phase == "reporting") {
Some("донесение")
} else if pic.recon_sorties.iter().any(|s| s.phase == "outbound" || s.phase == "looking") {
Some("разведка")
} else if !pic.recon_sorties.is_empty() {
Some("завершение")
} else {
None
}
}
/// The whole picture for the debug command and the after-action review: the sorties and their
/// phases, then the marks best-first with the reason each outranks the rest, then the drones aimed
/// at a mark. Explicitly the enemy's belief, not the truth; never the normal HUD.
pub fn picture_lines(pic: &EnemyPictureReport) -> Vec<String> {
let mut lines = Vec::new();
if pic.recon.is_empty() && pic.recon_sorties.is_empty() {
lines.push("Разведки не было: противник не высылал разведчиков и ничего не запомнил.".into());
return lines;
}
lines.push(format!(
"Картина противника (debug/разбор): отметок {}, разведчиков в воздухе {}",
pic.recon.len(),
pic.recon_sorties.len()
));
for s in &pic.recon_sorties {
lines.push(sortie_line(s));
}
let mut marks: Vec<&ReconReport> = pic.recon.iter().collect();
marks.sort_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
for m in marks {
lines.push(mark_line(m));
lines.push(format!(" ↳ {}", mark_reason(m)));
}
for a in pic.aims.iter().filter(|a| a.recon) {
lines.push(format!(
"Дрон {} целится в отметку {} (приоритет {}, {})",
a.drone,
a.unit,
a.priority.unwrap_or(0),
intent_name(a.intent)
));
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{AimReport, Confidence, EnemyPictureReport, ReconReport, ReconSortieReport};
use glam::DVec3;
fn mark(id: u32, category: &'static str, role: Option<&'static str>, quality: &'static str, confidence: Confidence, age: u64) -> ReconReport {
let cat = Category::from_key(category).unwrap();
let qual = Quality::from_key(quality).unwrap();
let role_enum = role.and_then(crate::sim::battery::RadarRole::from_key);
let (f, q, r) = priority_parts(confidence, qual, cat, role_enum);
ReconReport { id, area: DVec3::ZERO, radius: 120.0, category, role, source: "flyby", age, quality, confidence, live: true, priority: f * 4 + q * 3 + r }
}
fn sortie(drone: u32, phase: &'static str, zones_left: usize, report_in: Option<u64>) -> ReconSortieReport {
ReconSortieReport { drone, phase, zones_left, report_in }
}
fn picture(recon: Vec<ReconReport>, recon_sorties: Vec<ReconSortieReport>, aims: Vec<AimReport>) -> EnemyPictureReport {
EnemyPictureReport { now: 1000, contacts: Vec::new(), aims, pending: Vec::new(), work_per_tick: 4, recon, recon_sorties }
}
// The reason names all three factors with the planner's own weights, and they sum to the priority.
#[test]
fn the_reason_is_the_observed_role_freshness_and_quality() {
let m = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Confirmed, 100);
let reason = mark_reason(&m);
assert_eq!(m.priority, 4 * 4 + 2 * 3 + 3);
assert!(reason.contains("приоритет 25 = свежесть 4×4 + качество 2×3 + роль 3"), "{reason}");
assert!(reason.contains("подтверждена") && reason.contains("уточнённая") && reason.contains("роль «наведения»"), "{reason}");
// A coarse, doubtful, unknown mark: every part is zero, and the reason says so.
let weak = mark(0x1000_0002, "unknown", None, "coarse", Confidence::Doubtful, 5000);
assert_eq!(weak.priority, 0);
let weak_reason = mark_reason(&weak);
assert!(weak_reason.contains("свежесть 0×4 + качество 0×3 + роль 0"), "{weak_reason}");
assert!(weak_reason.contains("сомнительна") && weak_reason.contains("категория «не определено»"), "{weak_reason}");
}
// A fresh modest mark can outrank a stale big one: the reason reflects the age, not the truth.
#[test]
fn a_fresh_modest_mark_outranks_a_stale_big_one() {
let stale_big = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Doubtful, 5000);
let fresh_modest = mark(0x1000_0002, "gun", None, "coarse", Confidence::Confirmed, 100);
assert!(fresh_modest.priority > stale_big.priority, "{} vs {}", fresh_modest.priority, stale_big.priority);
let fresh_id = fresh_modest.id;
let lines = picture_lines(&picture(vec![stale_big, fresh_modest], Vec::new(), Vec::new()));
let first = lines.iter().position(|l| l.starts_with("Отметка")).unwrap();
assert!(lines[first].contains(&format!("Отметка {fresh_id}")), "the fresh modest mark did not lead: {lines:?}");
}
#[test]
fn the_phase_reads_recon_report_and_done() {
assert_eq!(phase_name("outbound"), "разведка");
assert_eq!(phase_name("reporting"), "донесение");
assert_eq!(phase_name("done"), "завершение");
let reporting = picture(Vec::new(), vec![sortie(0x3000_0001, "reporting", 0, Some(40)), sortie(0x3000_0002, "outbound", 2, None)], Vec::new());
assert_eq!(battle_phase(&reporting), Some("донесение"));
let looking = picture(Vec::new(), vec![sortie(0x3000_0001, "outbound", 2, None)], Vec::new());
assert_eq!(battle_phase(&looking), Some("разведка"));
let done = picture(Vec::new(), vec![sortie(0x3000_0001, "done", 0, None)], Vec::new());
assert_eq!(battle_phase(&done), Some("завершение"));
assert_eq!(battle_phase(&picture(Vec::new(), Vec::new(), Vec::new())), None);
assert!(sortie_line(&sortie(0x3000_0001, "reporting", 1, Some(40))).contains("донесение через 2 с"));
}
#[test]
fn an_empty_picture_says_there_was_no_recon() {
let lines = picture_lines(&picture(Vec::new(), Vec::new(), Vec::new()));
assert_eq!(lines.len(), 1);
assert!(lines[0].contains("Разведки не было"), "{lines:?}");
}
// The review shows the marks with their reasons and the drones aimed at them; the ids are the
// synthetic ones, and nothing of the unit's truth (kind, health, exact place) is in the report.
#[test]
fn the_review_lists_marks_reasons_and_recon_aims() {
let m = mark(0x1000_0001, "launcher", None, "coarse", Confidence::Probable, 1000);
let mid = m.id;
let aim = AimReport { drone: 7, unit: mid, intent: "sead", since: 900, switches: 0, confidence: Some(Confidence::Probable), recon: true, priority: Some(m.priority) };
let unit_aim = AimReport { drone: 8, unit: 3, intent: "plan", since: 900, switches: 0, confidence: Some(Confidence::Confirmed), recon: false, priority: None };
let lines = picture_lines(&picture(vec![m], vec![sortie(0x3000_0001, "outbound", 1, None)], vec![aim, unit_aim]));
assert!(lines.iter().any(|l| l.contains(&format!("Отметка {mid}")) && l.contains("пусковая")), "{lines:?}");
assert!(lines.iter().any(|l| l.contains("↳") && l.contains("приоритет")), "{lines:?}");
assert!(lines.iter().any(|l| l.contains("Дрон 7 целится в отметку") && l.contains("подавление ПВО")), "{lines:?}");
// A unit contact's aim is not a recon aim: it is not listed here.
assert!(!lines.iter().any(|l| l.contains("Дрон 8")), "{lines:?}");
// No true unit id leaks: the mark id is synthetic, far above any real unit's.
assert!(mid >= 0x1000_0000);
}
#[test]
fn every_public_name_is_translated() {
for key in ["unknown", "radar", "launcher", "gun", "ew", "support"] {
assert_ne!(category_name(key), key, "{key}");
}
for key in ["multi", "search", "engagement", "height"] {
assert_ne!(role_name(key), key, "{key}");
}
for key in ["flyby", "emission", "jamming", "launch"] {
assert_ne!(source_name(key), key, "{key}");
}
assert_ne!(quality_name("coarse"), "coarse");
assert_ne!(quality_name("refined"), "refined");
}
}
+281 -3
View File
@@ -9,6 +9,11 @@
//! picture is mixed into a replay: a recording keeps trajectories, and this section is written and
//! read for the live simulation only.
//!
//! Reconnaissance flights and the partial picture they radioed home are part of the same
//! section (#135): their marks (an area, a category and an age, never a unit's truth), the
//! sorties still out with their pending reports, and the zones already checked. A save keeps
//! that memory across raids, and a restored flight finishes the same way.
//!
//! The format is its own versioned section of `state_text` (`air 1 ...`). A save without the section
//! (every save made before #127) loads exactly as before: the layout, and an empty sky. Every value is
//! checked before anything is restored, like [`layout`](crate::layout): a bad line refuses the whole
@@ -25,6 +30,9 @@ const MAX_DRONES: usize = 512;
/// Bytes the section may take before further drones are left out (the host allows 1 MiB a write;
/// the layout and the headroom of the rest of the state stay clear of it).
const MAX_BYTES: usize = 900_000;
/// Bytes the recon block (marks, checked zones, sorties) may take. The drone loop keeps this much
/// room free, so the recon memory never pushes the section past `MAX_BYTES` (#135).
const MAX_RECON_BYTES: usize = 150_000;
/// Route points one drone may have in a save.
const MAX_ROUTE: usize = 512;
/// Contacts (the picture, and a job's picture rebuilt from it) a save may hold.
@@ -32,6 +40,10 @@ const MAX_CONTACTS: usize = 4096;
/// Relief versions a save may hold, and the cells of each.
const MAX_RELIEFS: usize = 8;
const MAX_CELLS: usize = 40_000;
/// Recon marks, checked zones and sorties a save may hold (#135).
const MAX_RECON_MARKS: usize = recon::MAX_MARKS;
const MAX_RECON_CHECKED: usize = recon::MAX_CHECKED;
const MAX_RECON_SORTIES: usize = recon::SORTIES_MAX * 2;
/// What the air section of a save holds, checked as a whole before the scene is touched.
pub struct AirSave {
@@ -45,6 +57,8 @@ pub struct AirSave {
jobs: Vec<JobRec>,
/// The land new retarget jobs take as their version.
known_relief: Option<std::sync::Arc<ew::KnownRelief>>,
/// The enemy's recon flights and the partial picture they radioed home (#135).
recon: recon::Recon,
}
pub(crate) struct JobRec {
@@ -198,6 +212,7 @@ impl Sim {
^ (self.retargets.len() as u64) << 24
^ (self.intel.contacts().len() as u64) << 36
^ (self.job_next as u64) << 48
^ self.recon.mark().rotate_left(12)
}
/// The air section of the state text: `None` when there is nothing to keep (an empty sky and no
@@ -273,7 +288,7 @@ impl Sim {
// job with it (a job whose drone is not saved could never be restored).
let mut body = String::new();
let mut saved: std::collections::HashSet<u32> = std::collections::HashSet::new();
let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() <= MAX_BYTES;
let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() + MAX_RECON_BYTES <= MAX_BYTES;
let mut drone_count = 0usize;
for d in &drones {
let line = d.air_line("airdrone", "");
@@ -296,14 +311,15 @@ impl Sim {
saved.insert(d.id);
queued_count += 1;
}
let units: std::collections::HashSet<u32> = contacts.iter().map(|c| c.id).collect();
// A job's unit may be an exact contact or a recon mark's synthetic id (#135).
let units: std::collections::HashSet<u32> = contacts.iter().map(|c| c.id).chain(self.recon.marks.keys().copied()).collect();
let jobs: Vec<(&ew::RouteJob, Option<usize>)> = self
.retargets
.iter()
.zip(job_relief)
.filter(|(j, _)| saved.contains(&j.drone) && (j.unit == 0 || units.contains(&j.unit)))
.collect();
if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() {
if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() && self.recon.is_empty() {
return None;
}
let head = head.replacen(
@@ -328,6 +344,89 @@ impl Sim {
relief.map_or_else(|| "-".into(), |t| t.to_string())
);
}
// Recon: the marks are memory (survive a new raid), the sorties are the aircraft still
// out, and the zones already reported empty. Everything is bounded, and each line is
// added only while the block stays inside its budget (#135).
if !self.recon.is_empty() {
let room = MAX_RECON_BYTES.min(MAX_BYTES.saturating_sub(text.len() + 96));
let mut recon_body = String::new();
let mut add = |line: &str| -> bool {
if recon_body.len() + line.len() > room {
return false;
}
recon_body.push_str(line);
true
};
let mut marks = 0usize;
for m in self.recon.marks.values().take(MAX_RECON_MARKS) {
let truth = self.recon.truth.get(&m.id).copied().unwrap_or(0);
let line = format!(
"airreconmark {} {} {} {} {} {} {} {} {} {} {} {} {}\n",
m.id,
truth,
coord(m.area.x),
coord(m.area.y),
coord(m.area.z),
coord(m.radius),
m.category.name(),
m.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()),
m.source.name(),
m.quality.name(),
m.observed,
m.reported,
m.looks,
);
if !add(&line) {
break;
}
marks += 1;
}
let mut checked = 0usize;
for ((i, j), t) in self.recon.checked.iter().take(MAX_RECON_CHECKED) {
if !add(&format!("airreconchecked {i} {j} {t}\n")) {
break;
}
checked += 1;
}
let mut sorties = 0usize;
for s in self.recon.sorties.iter().filter(|s| saved.contains(&s.drone)).take(MAX_RECON_SORTIES) {
// A sortie is written whole or not at all: its look and zone lines follow its header.
let mut body = format!(
"airrec {} {} {} {} {} {} {}\n",
s.drone,
s.launched,
s.next,
tick(s.report_at),
s.report_zone.map_or_else(|| "-".into(), |z| z.to_string()),
s.pending.len(),
s.zones.len(),
);
for l in &s.pending {
body += &format!(
"airrecobs {} {} {} {} {} {} {} {} {} {}\n",
l.truth,
coord(l.area.x),
coord(l.area.y),
coord(l.area.z),
coord(l.radius),
l.category.name(),
l.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()),
l.quality.name(),
l.source.name(),
l.observed,
);
}
for z in &s.zones {
body += &format!("airreczone {} {} {} {}\n", coord(z.center.x), coord(z.center.y), coord(z.center.z), coord(z.radius));
}
if !add(&body) {
break;
}
sorties += 1;
}
text += &format!("airrecon {} {} {} {} {}\n", self.recon.next, self.recon.drone_next, marks, sorties, checked);
text += &recon_body;
}
Some(text)
}
@@ -373,6 +472,12 @@ impl Sim {
let mut drones: BTreeMap<u32, Drone> = BTreeMap::new();
let mut queue: Vec<(u64, Drone)> = Vec::new();
let mut jobs: Vec<JobRec> = Vec::new();
// Recon (#135): a mark line carries the unit it is of (the observer's secret, never in
// the planner's picture); a sortie's look and zone lines follow its header.
let mut recon = recon::Recon::default();
let mut recon_head: Option<(usize, usize, usize)> = None;
let mut recon_sortie_at: Option<usize> = None;
let mut recon_expect: Vec<(usize, usize)> = Vec::new();
for (n, w) in &lines {
if w.first() == Some(&"air") {
continue;
@@ -512,6 +617,148 @@ impl Sim {
};
jobs.push(JobRec { id, drone, aim, unit, version, intent, relief });
}
"airrecon" => {
if w.len() != 6 {
return Err(l.bad("разведка", "нужны счётчики отметок и дронов, отметки, разведчики и проверенные зоны"));
}
let next = l.int(1, "счётчик отметок", 0, i64::from(recon::MARK_TOP - recon::ID_BASE - 1))? as u32;
let drone_next = l.int(2, "счётчик дронов", 0, i64::from(recon::DRONE_TOP - recon::DRONE_BASE - 1))? as u32;
let marks = l.count(3, "отметки", MAX_RECON_MARKS)?;
let sorties = l.count(4, "разведчики", MAX_RECON_SORTIES)?;
let checked = l.count(5, "проверенные зоны", MAX_RECON_CHECKED)?;
if recon_head.is_some() {
return Err(l.bad("разведка", "заголовок записан дважды"));
}
recon_head = Some((marks, sorties, checked));
recon.next = next;
recon.drone_next = drone_next;
}
"airreconmark" => {
if w.len() != 14 {
return Err(l.bad("отметка разведки", "нужны id, юнит, место, категория, источник, качество и времена"));
}
let id = l.int(1, "id отметки", 0, i64::from(u32::MAX))? as u32;
if !recon::is_mark(id) {
return Err(l.bad("id отметки", "не в диапазоне отметок"));
}
let truth = l.int(2, "юнит отметки", 0, 1 << 30)? as u32;
let area = DVec3::new(l.num(3, "отметка X")?, l.num(4, "отметка Y")?, l.num(5, "отметка Z")?);
let radius = l.num(6, "радиус отметки")?;
if radius <= 0.0 {
return Err(l.bad("радиус отметки", "должен быть больше нуля"));
}
let category = recon::Category::from_key(l.word(7, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?;
let role = match l.word(8, "роль")? {
"-" => None,
key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?),
};
let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?;
let quality = recon::Quality::from_key(l.word(10, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?;
let observed = l.int(11, "такт наблюдения", 0, tick as i64)? as u64;
let reported = l.int(12, "такт донесения", 0, tick as i64)? as u64;
let looks = l.int(13, "число взглядов", 0, u16::MAX as i64)? as u16;
if recon.marks.contains_key(&id) {
return Err(l.bad("id отметки", "отметка записана дважды"));
}
recon.truth.insert(id, truth);
recon.marks.insert(id, recon::Mark {
id,
area,
radius,
category,
role,
source,
observed,
reported,
quality,
looks,
});
let slot = id.saturating_sub(recon::ID_BASE);
recon.next = recon.next.max(slot);
}
"airreconchecked" => {
if w.len() != 4 {
return Err(l.bad("проверенная зона", "нужны X, Z и такт"));
}
let i = l.int(1, "зона X", -3_000_000, 3_000_000)?;
let j = l.int(2, "зона Z", -3_000_000, 3_000_000)?;
let t = l.int(3, "такт проверки", 0, tick as i64)? as u64;
recon.checked.insert((i, j), t);
}
"airrec" => {
if w.len() != 8 {
return Err(l.bad("разведчик", "нужны дрон, вылет, зона, донесение и счётчики"));
}
let drone = l.int(1, "дрон разведчика", 1, 1 << 30)? as u32;
let launched = l.int(2, "вылет", 0, tick as i64)? as u64;
let next = l.count(3, "следующая зона", 1_000_000)?;
let report_at = l.opt_tick(4, "такт донесения")?;
let report_zone = match l.word(5, "зона донесения")? {
"-" => None,
v => Some(v.parse::<usize>().map_err(|_| l.bad("зона донесения", "не номер"))?),
};
let pending = l.count(6, "ожидающие наблюдения", recon::MAX_OBSERVED)?;
let zones = l.count(7, "зоны разведчика", recon::ZONES_MAX)?;
if recon.sorties.iter().any(|s| s.drone == drone) {
return Err(l.bad("дрон разведчика", "разведчик записан дважды"));
}
recon.sorties.push(recon::Sortie {
drone,
zones: Vec::new(),
next,
launched,
report_at,
report_zone,
pending: Vec::new(),
});
recon_sortie_at = Some(recon.sorties.len() - 1);
recon_expect.push((pending, zones));
}
"airrecobs" => {
if w.len() != 11 {
return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник и такт"));
}
let Some(at) = recon_sortie_at else {
return Err(l.bad("наблюдение разведки", "строка без разведчика"));
};
let (want, _) = recon_expect[at];
if recon.sorties[at].pending.len() >= want {
return Err(l.bad("наблюдение разведки", "наблюдений больше объявленного"));
}
let truth = l.int(1, "юнит наблюдения", 0, 1 << 30)? as u32;
let area = DVec3::new(l.num(2, "наблюдение X")?, l.num(3, "наблюдение Y")?, l.num(4, "наблюдение Z")?);
let radius = l.num(5, "радиус наблюдения")?;
if radius <= 0.0 {
return Err(l.bad("радиус наблюдения", "должен быть больше нуля"));
}
let category = recon::Category::from_key(l.word(6, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?;
let role = match l.word(7, "роль")? {
"-" => None,
key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?),
};
let quality = recon::Quality::from_key(l.word(8, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?;
let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?;
let observed = l.int(10, "такт наблюдения", 0, tick as i64)? as u64;
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed });
}
"airreczone" => {
if w.len() != 5 {
return Err(l.bad("зона разведчика", "нужны X, Y, Z и радиус"));
}
let Some(at) = recon_sortie_at else {
return Err(l.bad("зона разведчика", "строка без разведчика"));
};
let (_, want) = recon_expect[at];
if recon.sorties[at].zones.len() >= want {
return Err(l.bad("зона разведчика", "зон больше объявленного"));
}
let center = DVec3::new(l.num(1, "зона X")?, l.num(2, "зона Y")?, l.num(3, "зона Z")?);
let radius = l.num(4, "радиус зоны")?;
if radius <= 0.0 {
return Err(l.bad("радиус зоны", "должен быть больше нуля"));
}
recon.sorties[at].zones.push(recon::Zone { center, radius });
}
other => return Err(l.bad("строка", &format!("неизвестная строка воздушной части «{other}»"))),
}
}
@@ -540,6 +787,32 @@ impl Sim {
if let Some(g) = global && reliefs[g].is_none() {
return Err("воздушная часть: глобальный рельеф не записан".into());
}
if let Some((marks, sorties, checked)) = recon_head {
if recon.marks.len() != marks {
return Err(format!("воздушная часть: отметок разведки {} вместо {marks}", recon.marks.len()));
}
if recon.sorties.len() != sorties {
return Err(format!("воздушная часть: разведчиков {} вместо {sorties}", recon.sorties.len()));
}
if recon.checked.len() != checked {
return Err(format!("воздушная часть: проверенных зон {} вместо {checked}", recon.checked.len()));
}
} else if !recon.is_empty() {
return Err("воздушная часть: разведка без заголовка airrecon".into());
}
for (i, (pending, zones)) in recon_expect.iter().enumerate() {
if recon.sorties[i].pending.len() != *pending || recon.sorties[i].zones.len() != *zones {
return Err(format!("воздушная часть: разведчик {i} записан не полностью"));
}
if recon.sorties[i].next > recon.sorties[i].zones.len() {
return Err(format!("воздушная часть: разведчик {i} смотрит за пределами зон"));
}
if let Some(z) = recon.sorties[i].report_zone
&& z >= recon.sorties[i].zones.len()
{
return Err(format!("воздушная часть: разведчик {i} доносит из несуществующей зоны"));
}
}
let intel = intel.ok_or("воздушная часть: нет счётчиков секторов")?;
let mut kills = [0u32; ew::SECTORS];
let mut hits = [0u32; ew::SECTORS];
@@ -555,6 +828,7 @@ impl Sim {
queue,
jobs,
known_relief: global.and_then(|g| reliefs[g].clone()),
recon,
}))
}
@@ -571,6 +845,10 @@ impl Sim {
self.known_relief = save.known_relief;
self.drones = save.drones;
self.queue = save.queue;
self.recon = save.recon;
let alive: std::collections::HashSet<u32> = self.drones.iter().map(|d| d.id).chain(self.queue.iter().map(|(_, d)| d.id)).collect();
self.recon.retain_drones(&alive);
self.recon.expire(self.tick);
self.retargets.clear();
// A job's picture is its version's: the contacts observed no later than it, plus its own
// target (whose last saved observation stands in for one made after the version).
+198 -31
View File
@@ -19,6 +19,12 @@
//! contact is a plain function of the contact's age, and its idea of a unit's
//! capabilities is the type's published one — a contact says nothing about
//! damage, roles, link health or magazine.
//!
//! A smart raid may also send a few recon aircraft ahead (#135). What they see is a
//! different, coarser kind of knowledge: an area, a public category, the channel that
//! showed it and its age, radioed home only after a delay and only while the aircraft
//! lives. It is kept as a `recon::Mark`, separate from a disclosure `Contact`; its
//! confidence is age alone and a duplicate report does not improve it.
use super::*;
use std::collections::{BTreeMap, VecDeque};
use std::sync::Arc;
@@ -323,6 +329,15 @@ pub(super) const CONTACT_TTL: u64 = 6000;
const CONFIRMED_AGE: u64 = 600;
const PROBABLE_AGE: u64 = 3000;
/// The one source of confidence: a contact's age, in the bands the picture trusts.
pub(super) fn confidence_for_age(age: u64) -> Confidence {
match age {
0..=CONFIRMED_AGE => Confidence::Confirmed,
..=PROBABLE_AGE => Confidence::Probable,
_ => Confidence::Doubtful,
}
}
impl Contact {
pub fn age(&self, now: u64) -> u64 {
now.saturating_sub(self.tick)
@@ -332,11 +347,7 @@ impl Contact {
self.destroyed.is_none() && self.age(now) < CONTACT_TTL
}
pub fn confidence(&self, now: u64) -> Confidence {
match self.age(now) {
0..=CONFIRMED_AGE => Confidence::Confirmed,
..=PROBABLE_AGE => Confidence::Probable,
_ => Confidence::Doubtful,
}
confidence_for_age(self.age(now))
}
/// Whether the enemy believes this unit sees on its own radar (#127). A kind without a
/// sensor never does. A kind with one does while an emission fix of this contact is
@@ -556,6 +567,9 @@ impl Sim {
/// Whether the picture holds a live contact for this unit: what the old revelation log
/// answered at a scan, now one map lookup.
pub(super) fn known_live(&self, id: u32) -> bool {
if recon::is_mark(id) {
return self.recon.live(id, self.tick);
}
self.intel.contacts.get(&id).is_some_and(|c| c.live(self.tick))
}
@@ -578,8 +592,10 @@ impl Sim {
/// the picture killed is a distinct, lower-priority decision.
fn adapt_targets(&mut self) {
self.intel.expire(self.tick);
self.recon.expire(self.tick);
let picture = Arc::new(self.picture_of_defences());
if picture.is_empty() {
let leads = self.recon.leads(self.tick);
if picture.is_empty() && leads.is_empty() {
return;
}
// Every job of this adaptive tick plans over the same relief version, even if another smart
@@ -601,9 +617,17 @@ impl Sim {
if !eligible {
continue;
}
// A recon mark is an area, not a unit: it is kept while the mark lives. A
// hidden move does not move the aim; only a newer report can re-place it (#135).
if recon::is_mark(d.aim.unit) {
if self.recon.live(d.aim.unit, now) {
continue;
}
// The mark aged out: the drone falls through to a fresh lead below.
}
// What it is aiming at in the picture now, if anything (a unit merely moved is still
// aimed where it was seen: a contact is matched by its observed place).
if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) {
else if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) {
// Already aiming at a unit: a fresh disclosure may be worth a switch, under the throttle.
let Some(c) = Self::switch_candidate(&picture, current, d, now) else { continue };
if per_contact.get(&c.id).copied().unwrap_or(0) >= ASSIGN_PER_CONTACT {
@@ -627,13 +651,30 @@ impl Sim {
if assigned >= ASSIGN_PER_TICK {
continue;
}
let Some(c) = Self::fresh_target(&picture, &per_contact, d.kind, n) else { continue };
*per_contact.entry(c.id).or_insert(0) += 1;
let exact = Self::fresh_target(&picture, &per_contact, d.kind, n);
// No disclosure contact to take: a recon mark whose observed role fits this drone,
// best role and freshest first, bounded per mark as any assignment is. Where both
// exist, the better observed role and fresher mark wins; a hidden unit is in neither.
let mark = Self::fresh_recon_target(&leads, &per_contact);
let (at, unit, confidence) = match (exact, mark) {
(Some(c), Some(m)) => {
let exact_rank = Self::exact_rank(&c, now);
if m.priority(now) > exact_rank {
(m.area, m.id, m.confidence(now))
} else {
(c.at, c.id, c.confidence(now))
}
}
(Some(c), None) => (c.at, c.id, c.confidence(now)),
(None, Some(m)) => (m.area, m.id, m.confidence(now)),
(None, None) => continue,
};
*per_contact.entry(unit).or_insert(0) += 1;
assigned += 1;
d.target = c.at + d.err;
d.target = at + d.err;
d.intent = Intent::React;
// A first assignment is not a switch: the aim's clock starts here, the count is kept.
d.aim = Aim { unit: c.id, since: now, switches: d.aim.switches, confidence: Some(c.confidence(now)) };
d.aim = Aim { unit, since: now, switches: d.aim.switches, confidence: Some(confidence) };
if Self::route_plannable(d) {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&picture), relief.clone()));
job_next += 1;
@@ -648,11 +689,14 @@ impl Sim {
// moved is still aimed where seen.
for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart) {
let aim = d.target - d.err;
let aim_gone = self
.intel
.contacts
.values()
.any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick));
let aim_gone = if recon::is_mark(d.aim.unit) {
!self.recon.live(d.aim.unit, self.tick)
} else {
self.intel
.contacts
.values()
.any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick))
};
if !aim_gone {
continue;
}
@@ -663,17 +707,37 @@ impl Sim {
if d.aim.switches >= SWITCH_CAP || assigned >= ASSIGN_PER_TICK {
continue;
}
let next = picture
let exact = picture
.iter()
.filter(|c| !plannable || Self::can_turn_to(d, c.at))
.filter(|c| per_contact.get(&c.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
.min_by(|a, b| a.at.distance(d.pos).total_cmp(&b.at.distance(d.pos)));
if let Some(c) = next {
*per_contact.entry(c.id).or_insert(0) += 1;
.map(|c| (c.at.distance(d.pos), c.id, c.at, c.confidence(now)))
.min_by(|a, b| a.0.total_cmp(&b.0));
let mark = leads
.iter()
.filter(|m| !plannable || Self::can_turn_to(d, m.area))
.filter(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
.map(|m| (m.area.distance(d.pos), m.id, m.area, m.confidence(now), m.priority(now)))
.min_by(|a, b| b.4.cmp(&a.4).then(a.0.total_cmp(&b.0)));
// A confirmed recon mark outranks a doubtful disclosure; an exact contact of equal
// freshness is preferred, because it is a fix rather than an area.
let exact_rank = exact.map(|(_, _, _, c)| match c {
Confidence::Confirmed => 30,
Confidence::Probable => 15,
Confidence::Doubtful => 0,
});
let next = match (exact, mark) {
(Some(_), Some(m)) if m.4 > exact_rank.unwrap_or(0) + 3 => Some((m.0, m.1, m.2, m.3)),
(Some(e), _) => Some(e),
(None, Some(m)) => Some((m.0, m.1, m.2, m.3)),
(None, None) => None,
};
if let Some((_, unit, at, confidence)) = next {
*per_contact.entry(unit).or_insert(0) += 1;
assigned += 1;
d.target = c.at + d.err;
d.target = at + d.err;
d.intent = Intent::Replace;
d.aim = d.aim.replaced(c.id, now, c.confidence(now));
d.aim = d.aim.replaced(unit, now, confidence);
if plannable {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Replace, Arc::clone(&picture), relief.clone()));
job_next += 1;
@@ -716,6 +780,28 @@ impl Sim {
all.get(n % all.len().max(1)).map(|c| **c)
}
/// The rank of an exact disclosure contact: its confidence, what its observed kind is
/// worth, and a small premium for being a fix rather than an area.
fn exact_rank(c: &Contact, now: u64) -> u8 {
let seen = match c.confidence(now) {
Confidence::Confirmed => 30,
Confidence::Probable => 15,
Confidence::Doubtful => 0,
};
seen + recon::Category::of(c.kind).weight() + 3
}
/// The best recon mark a drone not yet sent at a unit may be given: observed role and
/// freshness first (the list is sorted), bounded per mark. A mark's category must be one
/// worth a strike; a support or unknown mark is only navigation interest.
fn fresh_recon_target(leads: &[recon::Mark], per_contact: &HashMap<u32, usize>) -> Option<recon::Mark> {
leads
.iter()
.copied()
.filter(|m| m.category.weight() >= 2)
.find(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
}
/// Whether a fresh disclosure is worth replacing this drone's aim: a contact observed after the
/// aim was chosen, trusted (not `Doubtful`), clearly better placed or better believed, and the
/// throttle (hold time, switch cap) allows it (#127). A route change costs the planner a new
@@ -1009,7 +1095,7 @@ pub struct ContactReport {
#[derive(Clone, Debug, PartialEq)]
pub struct AimReport {
pub drone: u32,
/// The unit aimed at (0: a marked object).
/// The unit aimed at (0: a marked object; a recon mark has a synthetic id).
pub unit: u32,
/// "plan", "sead", "react" or "replace".
pub intent: &'static str,
@@ -1019,6 +1105,43 @@ pub struct AimReport {
pub switches: u16,
/// The confidence of the contact the aim rests on, when it is a unit.
pub confidence: Option<Confidence>,
/// Whether the aim is a recon mark's area rather than a unit contact.
pub recon: bool,
/// A recon mark's priority (observed role, freshness, quality); `None` for a unit contact.
pub priority: Option<u8>,
}
/// A recon mark as the diagnostic reports it (#135): an area, a coarse category, the channel,
/// its age and quality. There is no true place, SamKind, health, magazine, link or real id here.
#[derive(Clone, Debug, PartialEq)]
pub struct ReconReport {
pub id: u32,
pub area: DVec3,
pub radius: f64,
/// "unknown", "radar", "launcher", "gun", "ew" or "support".
pub category: &'static str,
/// A radar's role once a refined look told it.
pub role: Option<&'static str>,
/// "flyby", "emission", "jamming" or "launch".
pub source: &'static str,
pub age: u64,
/// "coarse" or "refined".
pub quality: &'static str,
pub confidence: Confidence,
pub live: bool,
/// What the planner makes of it, in words: observed role and freshness only.
pub priority: u8,
}
/// One recon sortie as the diagnostic reports it (#135).
#[derive(Clone, Debug, PartialEq)]
pub struct ReconSortieReport {
pub drone: u32,
/// "outbound", "looking", "reporting" or "done".
pub phase: &'static str,
pub zones_left: usize,
/// The tick its pending report is due.
pub report_in: Option<u64>,
}
/// A route job the planner has not finished (#127): what it is for, why it is still waiting,
@@ -1052,6 +1175,10 @@ pub struct EnemyPictureReport {
pub pending: Vec<PendingReport>,
/// The planner's work a tick, for the pending queue's budget.
pub work_per_tick: usize,
/// The partial picture recon flights radioed home (#135).
pub recon: Vec<ReconReport>,
/// The recon flights still out.
pub recon_sorties: Vec<ReconSortieReport>,
}
impl Sim {
@@ -1099,13 +1226,18 @@ impl Sim {
.map(|(_, d)| d)
.chain(self.drones.iter())
.filter(|d| d.alive() && d.smart)
.map(|d| AimReport {
drone: d.id,
unit: d.aim.unit,
intent: d.intent.name(),
since: d.aim.since,
switches: d.aim.switches,
confidence: d.aim.confidence,
.map(|d| {
let mark = self.recon.marks.get(&d.aim.unit).filter(|m| m.live(now)).copied();
AimReport {
drone: d.id,
unit: d.aim.unit,
intent: d.intent.name(),
since: d.aim.since,
switches: d.aim.switches,
confidence: d.aim.confidence,
recon: mark.is_some(),
priority: mark.map(|m| m.priority(now)),
}
})
.collect();
let pending = self
@@ -1129,7 +1261,42 @@ impl Sim {
},
})
.collect();
EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK }
let recon = self
.recon
.marks
.values()
.map(|m| ReconReport {
id: m.id,
area: m.area,
radius: m.radius,
category: m.category.name(),
role: m.role.map(|r| r.key()),
source: m.source.name(),
age: m.age(now),
quality: m.quality.name(),
confidence: m.confidence(now),
live: m.live(now),
priority: m.priority(now),
})
.collect();
let recon_sorties = self
.recon
.sorties
.iter()
.map(|s| ReconSortieReport {
drone: s.drone,
phase: if s.report_at.is_some() {
"reporting"
} else if s.next < s.zones.len() {
"outbound"
} else {
"done"
},
zones_left: s.zones.len().saturating_sub(s.next),
report_in: s.report_at.map(|t| t.saturating_sub(now)),
})
.collect();
EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK, recon, recon_sorties }
}
/// What the planner makes of a contact, in words for the diagnostic (#127).
+13 -1
View File
@@ -26,8 +26,10 @@ mod sight;
mod terrain;
mod ew;
mod optical;
mod recon;
mod durable;
pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport};
pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport, ReconReport, ReconSortieReport};
pub use recon::{Category, Mark, Quality, Source, is_drone_id, priority_parts};
pub mod lights;
mod logistics;
mod orders;
@@ -175,6 +177,11 @@ impl Rng {
pub fn state(&self) -> u64 {
self.0
}
/// Puts the generator back exactly where it was (a recon launch must not spend the
/// strike's combat randomness).
pub(super) fn set_state(&mut self, state: u64) {
self.0 = state;
}
pub fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
@@ -1475,6 +1482,8 @@ pub struct Sim {
pub tally: record::Tally,
/// What the enemy has learned.
intel: ew::Intel,
/// Reconnaissance flights and the partial picture they radioed home (#135).
recon: recon::Recon,
/// Night: guns need light (the mod sets it from the game's clock).
pub night: bool,
/// The long fires at crash and impact points (#52).
@@ -1551,6 +1560,7 @@ impl Sim {
recordings: 0,
tally: record::Tally::default(),
intel: ew::Intel::default(),
recon: recon::Recon::default(),
night: false,
fires: fires::Fires::default(),
day_time: None,
@@ -1663,6 +1673,7 @@ impl Sim {
self.plan = None;
self.retargets.clear();
self.known_relief = None;
self.recon.clear_sorties();
self.wave = None;
// Ammunition still to cook off, flares in the sky.
self.later.clear();
@@ -1710,6 +1721,7 @@ impl Sim {
self.release_queue(ground, out);
self.begin_recording_if_active();
self.step_drones(ground, player, out);
self.step_recon(out);
self.step_later(ground, player, out);
self.step_moves(ground, out);
self.step_supply(out);
+62 -9
View File
@@ -284,6 +284,9 @@ impl Sim {
// read-only while the plan is built, and taking it per drone made a big second order
// quadratic in the force's size (#122); a map of contacts makes it linear in them (#127).
let picture = self.picture_of_defences();
// The partial picture the recon flights have radioed home. It is memory, not the
// force: a mark has an area, a category and an age, never a unit's exact place (#135).
let leads = self.recon.leads(self.tick);
// A smart enemy comes from where its raids got through best.
let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU };
// The raid's sides (1, 2, or 4-5): its launch sites go there (#100).
@@ -312,7 +315,7 @@ impl Sim {
index += 1;
let (target, at_sam) = match job {
Some((at, id)) => (at, Some(id)),
None => self.choose_target(kind, object, order.aim, &picture),
None => self.choose_target(kind, object, order.aim, &picture, &leads),
};
let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0);
let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0;
@@ -323,7 +326,11 @@ impl Sim {
// The plan's own decision, recorded as such (#127): a radar job is SEAD, a unit
// chosen for the raid is the plan's objective, anything else is a marked object.
if let Some(id) = at_sam {
let confidence = picture.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick));
let confidence = picture
.iter()
.find(|c| c.id == id)
.map(|c| c.confidence(self.tick))
.or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick)));
d.intent = if job.is_some() { ew::Intent::Sead } else { ew::Intent::Plan };
d.aim = confidence.map_or_else(|| ew::Aim::point(self.tick), |c| ew::Aim::unit(id, self.tick, c));
} else {
@@ -363,6 +370,11 @@ impl Sim {
waited: 0,
mapped: !smart,
});
// The smart enemy may send a small recon flight ahead of the strike -- physically in
// the air, not a pause: the strike is planned while they fly (#135).
if smart {
self.start_recon(objects, bearing, order.dist, out);
}
// A raid without routes is ready at once.
self.plan_step(None, out);
total
@@ -580,12 +592,25 @@ impl Sim {
/// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid.
/// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile.
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact]) -> Vec<Option<(DVec3, u32)>> {
let mut radars: Vec<(u32, DVec3)> = picture
// Exact disclosure contacts and recon marks of radars, best first. The order is the
// observed role, freshness and quality -- never the id: a hidden station has no id,
// and a big observed radar is worth more than a modest one (#135).
let now = self.tick;
let mut radars: Vec<(u8, u64, u32, DVec3)> = picture
.iter()
.filter(|c| c.kind == SamKind::Radar && c.confidence(self.tick) >= ew::Confidence::Probable)
.map(|c| (c.id, c.at))
.filter(|c| c.kind == SamKind::Radar && c.confidence(now) >= ew::Confidence::Probable)
.map(|c| {
let seen = match c.confidence(now) {
ew::Confidence::Confirmed => 4,
ew::Confidence::Probable => 2,
ew::Confidence::Doubtful => 0,
};
(seen * 10 + 3, c.tick, c.id, c.at)
})
.chain(self.recon.leads(now).into_iter().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area)))
.collect();
radars.sort_by_key(|(id, _)| *id);
radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect();
let flat: Vec<DroneKind> = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect();
let mut jobs = vec![None; flat.len()];
if radars.is_empty() {
@@ -609,8 +634,8 @@ impl Sim {
/// point and the unit's id. The planner has only the picture (#93, #127): what it knows of a
/// unit is the last observation — the place seen then, the type identified then — never where
/// the unit actually is or what it has become since.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact]) -> (DVec3, Option<u32>) {
if picture.is_empty() || kind.spec().decoy || aim == Aim::Objects {
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact], leads: &[recon::Mark]) -> (DVec3, Option<u32>) {
if (picture.is_empty() && leads.is_empty()) || kind.spec().decoy || aim == Aim::Objects {
return (object, None);
}
let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> {
@@ -641,7 +666,15 @@ impl Sim {
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r),
_ => None,
};
choice.map_or((object, None), |(p, id)| (p, Some(id)))
if let Some((p, id)) = choice {
return (p, Some(id));
}
// Nothing disclosed and nothing the kind's usual preference picked: a recon mark
// whose observed role fits is the next best reason to turn a strike off the object.
if let Some(m) = recon_pick(kind, leads, r) {
return (m.area, Some(m.id));
}
(object, None)
}
/// The price of each cell of `grid` for this kind flying low: 1, and much more where a
@@ -935,6 +968,11 @@ const AIR_START_WAIT: u32 = 120;
if !why.is_empty() {
out.messages.push(format!("Неудачи ПВО: {why}"));
}
// What the enemy's recon flights saw: the marks are memory, so the picture may be old (#135).
let marks = self.recon.marks.values().filter(|m| m.live(self.tick)).count();
if marks > 0 {
out.messages.push(format!("Разведка противника: в картине {marks} отметок (возраст и качество — в разборе)"));
}
// What the counter-strikes did to the raid (#101): the launches that never happened.
let cut: u32 = self.strikes.cancelled.iter().map(|c| c.1).sum();
if cut > 0 {
@@ -956,6 +994,21 @@ fn route_length(from: DVec3, route: &[DVec3], to: DVec3) -> f64 {
len
}
/// A recon mark whose observed category fits this kind. The list is already in priority
/// order, so the first fit is the best reason.
fn recon_pick(kind: DroneKind, leads: &[recon::Mark], r: f64) -> Option<recon::Mark> {
use recon::Category as C;
let fits = |c: C| match kind {
DroneKind::Lancet => matches!(c, C::Gun | C::Launcher | C::Ew),
DroneKind::Kh22 | DroneKind::Zircon => matches!(c, C::Radar | C::Launcher | C::Ew),
DroneKind::Iskander | DroneKind::Kinzhal => matches!(c, C::Radar | C::Launcher),
DroneKind::Shahed | DroneKind::Geran3 => matches!(c, C::Radar | C::Launcher | C::Gun | C::Ew),
_ => false,
};
let fits: Vec<&recon::Mark> = leads.iter().filter(|m| fits(m.category)).collect();
fits.get((r * fits.len() as f64) as usize).copied().copied()
}
#[cfg(test)]
mod tests {
use super::*;
File diff suppressed because it is too large Load Diff
+15 -5
View File
@@ -1,8 +1,9 @@
//! Raids are recorded for their replays: every drone's and interceptor's
//! track (a point every other tick, falling wrecks included) and what
//! happened (shot down, by what; hits; systems lost; the Oreshnik's split).
//! A recording starts with the first drone in the sky and ends when the sky
//! has been clear a while; the last few are kept.
//! A recording starts with the first strike drone in the sky and ends when the sky
//! has been clear a while; the last few are kept. A recon aircraft is a role of its own
//! and is not part of the strike's replay (#135).
use super::*;
/// A system's pose at a moment of a recording.
@@ -834,8 +835,11 @@ impl Sim {
}
/// Open before the combat update so transitions on the first active tick are not lost.
/// A recon aircraft neither opens nor holds a strike's recording (#135).
pub(super) fn begin_recording_if_active(&mut self) {
if self.rec.is_none() && (self.drones.iter().any(|d| d.alive()) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) {
if self.rec.is_none()
&& (self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id)) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty())
{
self.recordings += 1;
self.rec = Some(Recording::new(self.recordings, self));
}
@@ -853,7 +857,13 @@ impl Sim {
pub(super) fn record(&mut self) {
// Wrecks still falling (far off they fall a long while) don't keep it going. A counter-strike is a recorded
// object in its own right (#109): it holds the recording open until it lands, whatever the sky is doing.
let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty();
// A recon flight is not part of the strike's replay: it neither opens nor holds a
// recording open. The strike's own drones and interceptors do (#135).
let busy = self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id))
|| !self.missiles.is_empty()
|| !self.queue.is_empty()
|| !self.strikes.flights.is_empty()
|| !self.strikes.pending.is_empty();
self.begin_recording_if_active();
let Some(r) = &mut self.rec else { return };
r.note_tracks(&self.sams);
@@ -867,7 +877,7 @@ impl Sim {
if r.len % STEP == 0 {
let now = r.len;
r.note_sams(&self.sams, now);
for d in &self.drones {
for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) {
r.point(d.id, What::Drone(d.kind), d.pos);
}
for m in &self.missiles {
+1
View File
@@ -55,6 +55,7 @@
| #124 | Motion + object transforms + feature-gated DLSS SR: engine `ed751714e`; NGX+HDR bootstrap, долгоживущий SDK/context, display↔linear conversion и ordered submit; native TAAU fallback. Полный `cargo xwin build` на MSVC и `v0.4.0-dlss-rc1` с PE32+, `airdef.hmod`, `nvngx_dlss.dll`, notices и A/B launchers опубликованы; 24 HD + layout, mods/no-mods, обычный Metal кадр проверены | Runtime/качество/FPS на RTX/Vulkan не подтверждены; нужна приёмка по `docs/DLSS-TESTING.md`. Ванильные сущности/ветер camera-only; reactive/transparency, FSR3/MetalFX и FG отдельно |
| #130 | Первый небольшой backport: upstream `f7b77fbc8` перенесён как engine `94b572cd2`; oversized staging allocations округляются до степени двойки и переиспользуются, копируются только фактические байты; 3 upload/GPU readback-теста прошли на Metal | Полная миграция на Nightly не начата; VSync/pacing, дальний рельеф и другие кандидаты остаются; Windows/Vulkan и долгий игровой RSS-профиль не проверялись |
| #127 | Этапы 1–2. **Картина:** журнал раскрытий заменён картой контактов (`Intel.contacts`: последнее «пуск/излучение/глушение», место, время, метка эмиссии, наблюдённая гибель, счётчик увиденных пусков), уверенность — функция возраста (Confirmed/Probable/Doubtful, TTL 6000), угроза и цены читают только published-параметры и факты наблюдений (launcher-only без донора «слеп»), уничтожение учится только из BSA. **Structured intent:** `Intent` (Plan/Sead/React/Replace) и `Aim` (юнит, since, switches, confidence) отделены от random-выбора; throttle `SWITCH_HOLD=160`, `SWITCH_CAP=3`, `ASSIGN_PER_TICK=16`, `ASSIGN_PER_CONTACT=6`, цена смены `SWITCH_GAIN=120`; в полёте цель меняется только когда картинка её убила/забыла. **Durable queue:** автосейв пишет версионированную секцию `air 1` — дроны, очередь запуска, задания (id, дрон, цель, юнит, версия, приоритет, намерение, версия рельефа), контакты, RLE-рельеф; очередь ограничена 256, устаревшие/фантомные/дублирующие задания отменяются при загрузке (`JOB_TTL=1200`), картина задания восстанавливается на свою версию, старые saves читаются (пустое небо), сценарии воздух не несут, Live/Replay не смешиваются. **Неизвестная земля не бесплатна** (`Relief.unknown=6` у повторного плана). **Объяснимость:** `enemy_picture()` дополнен aims/pending reason/aimed_by/pending_jobs без русского текста в core. Метаморфные тесты скрытых изменений (включая нагрев/замок РЭБ), save/restore посреди незавершённой очереди, детерминизм seed, 40+ массовый ретаргет. Замеры: `docs/measurements/issue-127-intent-queue-{baseline,result}.json` | GUI поверх `enemy_picture()`, игровая приёмка сохранения налёта на Windows/Linux, оценка баланса ew-adaptive (kills 59→58/59→58/56→63, потери 3→3/3→4/4→2 — следствие throttle, параметры не менялись) |
| #135 | **Core (`9d8f3da57`):** умная волна высылает ограниченный бюджет невооружённых разведчиков (Gerbera, собственные id `0x3000_0000`, не тратят combat RNG волны и не входят в её replay); они физически проходят игровые зоны вокруг отмеченных целей и через `REPORT_DELAY` передают только область, публичную категорию, канал (пролёт/излучение/РЭБ/пуск), возраст и качество — без точной точки, `SamKind`, HP, боезапаса, сети и реального id. Сбитый до донесения разведчик ничего не передаёт; уже переданное остаётся и переживает налёты. Планировщик читает отметки наравне с контактами раскрытия и назначает по наблюдаемой роли/свежести/качеству (`Mark::priority`), скрытая станция не становится целью, старая сомнительная отметка уступает свежей скромной; бюджет назначений и исходные цели волны сохранены. Save/load хранит отметки, вылеты, ожидающие донесения и проверенные зоны. **UI/диагностика (этот коммит):** на карте сети разведчик — узнаваемый жёлтый ромб с подписью «разведчик», роль в панели выбора и легенда фильтра; в боевом HUD и на карте — понятная фаза вылета (разведка/донесение/завершение) только пока сеть держит разведчика; в sandbox-режиме `truth` — янтарная метка и счётчик отметок. Причина выбора показана в `/airdef recon` и на странице меню «Разведка противника (разбор)» (из «Повторы…»): отметки best-first с разбором `приоритет = свежесть×4 + качество×3 + роль` (`recon::priority_parts`, сверен тестом с `Mark::priority`) и дроны, нацеленные на отметку. Всеведущая картина противника в обычный HUD не выводится — только явный debug/разбор. Механика, модели и текстуры не менялись. Тесты: `priority_parts`-кросс-чек, `recon_view`, панель, дерево команд | Игровая/визуальная приёмка значка и фазы на Windows/Linux; приёмка разбора в GUI; баланс приоритетов по серии seed остаётся за core-приёмкой |
По #127 реализованы карта контактов, структурированное намерение с throttle и durable-очередь:
autosave хранит дронов, очередь запуска, задания с картиной и рельефом своей версии, поэтому