Add the AirDef tablet web panel and battle archive (#153)

This commit is contained in:
2026-12-02 00:46:18 +03:00
parent dfb306edd7
commit 906159b17f
22 changed files with 2770 additions and 1 deletions
+9 -1
View File
@@ -115,6 +115,14 @@ pub fn tree() -> Tree {
])),
Node::lit("recon").runs(),
Node::lit("post").runs().then(Node::arg("поиск", Value::word()).runs()),
Node::lit("panel").with([
Node::lit("snapshot").then(Node::arg("запрос", Value::word()).then(
Node::arg("ракурс", Value::choice(["public", "debug"])).then(Node::arg("позиция", Value::word()).runs())
)),
Node::lit("launch").then(Node::arg("запрос", Value::word()).then(
Node::arg("сессия", Value::word()).then(Node::arg("сценарий", Value::word()).runs())
)),
]),
Node::lit("stats").runs(),
])
}
@@ -255,7 +263,7 @@ mod tests {
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
}
assert!(top.contains(&"post".to_string()));
assert_eq!(top.len(), 39);
assert_eq!(top.len(), 40);
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
+6
View File
@@ -35,6 +35,7 @@ pub use airdef_core::sim;
mod scenario;
mod village;
mod wave;
mod web_panel;
mod world_view;
mod why_view;
use sim::{Class, DroneKind, Ground, Out, Sam, SamKind, Sim};
@@ -88,6 +89,7 @@ struct AirDef {
/// The menu's page while it is open.
menu: Option<Page>,
chain_view: ChainView,
web: web_panel::Link,
/// 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.
@@ -1361,6 +1363,7 @@ impl AirDef {
self.grid_ids.clear();
self.post = post::Post::default();
self.chain_view = ChainView::default();
self.web = web_panel::Link::default();
// The overlay key lets go with the world: its camera projects nothing here anyway.
self.overlay_held = false;
self.world_hud_shown = false;
@@ -2298,6 +2301,7 @@ impl Mod for AirDef {
health_mark: 0,
menu: None,
chain_view: ChainView::default(),
web: web_panel::Link::default(),
listener: DVec3::ZERO,
punch: 0.0,
pending: Vec::new(),
@@ -3014,6 +3018,7 @@ impl Mod for AirDef {
None
}
["capabilities"] => Some(capabilities::diagnostics()),
["panel", args @ ..] => return self.panel_command(args),
["monitor"] => {
self.cycle_monitor();
None
@@ -3468,6 +3473,7 @@ mod tests {
health_mark: 0,
menu: None,
chain_view: ChainView::default(),
web: web_panel::Link::default(),
listener: DVec3::ZERO,
punch: 0.0,
pending: Vec::new(),
+3
View File
@@ -99,11 +99,13 @@ pub struct Entry {
#[derive(Default)]
pub struct History {
entries: VecDeque<Entry>,
first: u64,
last: HashMap<(u32, Channel), (Option<u32>, Outcome)>,
truncated: bool,
}
impl History {
pub fn first_index(&self) -> u64 { self.first }
pub fn entries(&self) -> impl DoubleEndedIterator<Item = &Entry> {
self.entries.iter()
}
@@ -184,6 +186,7 @@ impl History {
fn push(&mut self, entry: Entry) {
if self.entries.len() == MAX_ENTRIES {
self.entries.pop_front();
self.first += 1;
self.truncated = true;
}
self.entries.push_back(entry);
+7
View File
@@ -162,6 +162,7 @@ impl Recording {
pub fn blank(len: u32) -> Self {
Recording {
number: 1,
started_at: 0,
origin: DVec3::ZERO,
len,
tracks: Vec::new(),
@@ -416,6 +417,10 @@ pub struct SceneJournal {
}
impl SceneJournal {
pub fn track_limit_reached(&self) -> bool {
self.track_events >= MAX_SCENE_TRACK_EVENTS
}
/// Read-only transitions in chronological order.
pub fn events(&self) -> &[SceneEvent] { &self.events }
@@ -577,6 +582,7 @@ impl Tally {
pub struct Recording {
/// Which raid of the session (1, 2, …).
pub number: u32,
pub started_at: u64,
pub origin: DVec3,
/// Its length in ticks.
pub len: u32,
@@ -830,6 +836,7 @@ impl Recording {
let origin = sim.targets.first().copied().or_else(|| sim.sams.first().map(|s| s.pos)).unwrap_or(DVec3::ZERO);
Recording {
number,
started_at: sim.tick,
origin: origin.floor(),
len: 0,
tracks: Vec::new(),
+420
View File
@@ -0,0 +1,420 @@
//! Local bridge for the optional web panel. The engine's control endpoint stays local.
//! Snapshot and receipt I/O runs on explicit commands, never inside a tick or frame hook.
use crate::{AirDef, Out, battery_view, player, post, sim, wave, why_view};
use glam::DVec3;
use horizon_mod_sdk::storage;
use serde_json::{Value, json};
use std::collections::{HashSet, VecDeque};
const SNAPSHOT: &str = "panel-snapshot-v1.json";
const RECEIPT: &str = "panel-receipt-v1.json";
// Leave space under Horizon's 1 MiB per-call storage budget for both debug views
// and incremental logs from the active recording and the three retained replays.
const ENTITY_LIMIT: usize = 256;
const LOG_BATCH: usize = 128;
const RECEIPT_LIMIT: usize = 64;
#[derive(Default)]
pub(super) struct Link {
session: String,
receipts: VecDeque<(String, Value)>,
}
fn token(s: &str) -> bool {
(16..=32).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_hexdigit())
}
fn position(id: impl Into<Value>, label: impl Into<Value>, p: DVec3) -> Value {
json!({ "id": id.into(), "label": label.into(), "x": p.x, "y": p.y, "z": p.z })
}
fn merge(row: &mut Value, fields: Value) {
row.as_object_mut()
.unwrap()
.extend(fields.as_object().unwrap().clone());
}
fn configs() -> Value {
let presets: Vec<_> = wave::PRESETS
.iter()
.enumerate()
.map(|(i, preset)| {
let mut w = wave::WaveConfig::default();
w.apply(i);
json!({
"name": preset.name, "counts": w.counts.to_vec(), "distance": w.dist,
"approach": sim::Approach::ALL.iter().position(|a| *a == w.approach).unwrap(),
"aim": sim::Aim::ALL.iter().position(|a| *a == w.aim).unwrap()
})
})
.collect();
json!({
"kinds": wave::KINDS.iter().map(|k| k.spec().name).collect::<Vec<_>>(),
"approaches": sim::Approach::ALL.map(sim::Approach::name),
"aims": sim::Aim::ALL.map(sim::Aim::name),
"distance": [wave::DIST_MIN, wave::DIST_MAX],
"presets": presets,
})
}
fn public_live(sim: &sim::Sim) -> Value {
let now = sim.tick;
let picture = sim.air_picture();
// The local HUD has an unaided truth fallback. The web network view deliberately has none.
let mut known = HashSet::new();
let contacts: Vec<_> = picture.tracks.iter().take(ENTITY_LIMIT).filter(|_| !picture.unaided).map(|t| {
known.insert(t.id);
let mut row = position(t.id, t.class.name(), t.est(now));
merge(&mut row, json!({
"status": if t.forecast(now) { "Оценка положения" } else { "Измерено" },
"source": (t.source != 0).then_some(t.source), "age": t.age(now),
"quality": t.quality, "confidence": t.ident().name(), "radius": t.uncertainty(now),
"vx": t.vel.x * 20.0, "vz": t.vel.z * 20.0,
}));
row
}).collect();
let units: Vec<_> = sim
.sams
.iter()
.take(ENTITY_LIMIT)
.enumerate()
.map(|(i, s)| {
let mut row = position(s.id, format!("№{} {}", i + 1, s.kind.name()), s.pos);
merge(
&mut row,
json!({
"status": post::state(s), "details": battery_view::sam_status(s, now),
"health": s.health, "rounds": s.missiles, "bursts": s.bursts,
"target": s.target.or(s.gun_target).filter(|id| known.contains(id)),
}),
);
row
})
.collect();
let objects: Vec<_> = sim.targets.iter().take(ENTITY_LIMIT).enumerate().map(|(i, &p)| {
let mut row = position(i + 1, format!("Объект №{}", i + 1), p);
let health = sim.target_health.get(i).copied();
merge(&mut row, json!({ "health": health, "status": if health == Some(0.0) { "Уничтожен" } else { "Под защитой" } }));
row
}).collect();
let interceptors: Vec<_> = sim.missiles.iter().take(ENTITY_LIMIT).map(|m| {
let mut row = position(m.id, format!("Перехватчик №{}", m.id), m.pos);
merge(&mut row, json!({ "target": known.contains(&m.target()).then_some(m.target()), "status": "В полёте" }));
row
}).collect();
json!({
"units": units, "objects": objects, "contacts": contacts, "interceptors": interceptors,
"summary": { "kills": sim.kills, "hits": sim.hits, "planning": sim.planning(), "hold": sim.hold },
"limited": sim.sams.len() > ENTITY_LIMIT || (!picture.unaided && picture.tracks.len() > ENTITY_LIMIT)
|| sim.missiles.len() > ENTITY_LIMIT || sim.targets.len() > ENTITY_LIMIT
})
}
fn perspectives(sim: &sim::Sim, debug: bool) -> (Value, Value) {
if !debug {
return (Value::Null, Value::Null);
}
let report = sim.enemy_picture();
let observed: Vec<_> = report.observations.iter().take(ENTITY_LIMIT).map(|o| {
let mut row = position(o.id, o.kind.unwrap_or(o.category), o.at);
merge(&mut row, json!({
"status": format!("Донесение · {}", o.category), "confidence": format!("{:?}", o.confidence),
"radius": o.radius, "age": o.age, "source": o.channel, "quality": o.quality, "rank": o.rank,
}));
row
}).collect();
let reports: Vec<_> = report
.aims
.iter()
.filter(|a| a.unit != 0 && report.observations.iter().any(|o| o.id == a.unit))
.take(256)
.map(|a| json!({"contact": a.unit, "reason": a.intent, "at": a.since}))
.collect();
let sorties: Vec<_> = report
.recon_sorties
.iter()
.take(64)
.map(|r| json!({"phase": r.phase, "zones": r.zones_left, "reportIn": r.report_in}))
.collect();
let truth: Vec<_> = sim
.drones
.iter()
.filter(|d| d.alive())
.take(ENTITY_LIMIT)
.map(|d| {
let mut row = position(d.id, d.kind.spec().name, d.pos);
merge(
&mut row,
json!({"status": "Истина", "vx": d.vel.x * 20.0, "vz": d.vel.z * 20.0}),
);
row
})
.collect();
(
json!({"contacts": observed, "units": [], "objects": [], "interceptors": [], "reports": reports, "sorties": sorties,
"limited": report.observations.len() > ENTITY_LIMIT}),
json!(truth),
)
}
fn record_data(rec: &sim::record::Recording, cursor: (u64, usize, usize), active: bool) -> Value {
let first = rec.decisions.first_index();
let (dec, ev, sc) = cursor;
let decisions: Vec<_> = rec.decisions.entries().enumerate().skip(dec.saturating_sub(first) as usize).take(LOG_BATCH)
.map(|(i, &entry)| {
let choice = post::RecordedChoice { raid: rec.number, entry };
json!({ "seq": first + i as u64, "at": entry.at, "unit": entry.unit, "target": entry.target,
"label": post::decision_label(entry.outcome), "lines": post::decision_lines(choice, Some(rec)) })
}).collect();
let next_dec = decisions
.last()
.and_then(|d| d["seq"].as_u64())
.map_or(dec.max(first), |seq| seq + 1);
let mut next_ev = ev.min(rec.events.len());
let mut events = Vec::new();
for (i, event) in rec.events.iter().enumerate().skip(next_ev).take(LOG_BATCH) {
use sim::record::EventKind;
next_ev = i + 1;
let (label, unit, target, object) = match event.kind {
EventKind::Kill { sam, drone, .. } => ("Цель сбита", Some(sam), Some(drone), None),
EventKind::Hit {
drone,
object: Some(object),
..
} => ("Попадание по объекту", None, Some(drone), Some(object + 1)),
EventKind::Hit {
drone,
sam: Some((_, i)),
..
} => (
"Попадание по комплексу",
rec.sams.get(i).map(|s| s.0),
Some(drone),
None,
),
EventKind::SamLost { sam, .. } => ("Комплекс уничтожен", Some(sam), None, None),
_ => continue,
};
events.push(json!({ "seq": i, "at": event.at, "unit": unit, "target": target, "object": object, "label": label, "lines": [] }));
}
let mut observations = Vec::new();
let mut next_sc = sc;
if let Some(scene) = &rec.scene {
use sim::record::SceneKind::*;
next_sc = next_sc.min(scene.events().len());
for (i, event) in scene.events().iter().enumerate().skip(next_sc) {
next_sc = i + 1;
let (label, unit, target) = match event.kind {
TrackAcquired { sam, target, .. } => ("Отметка получена", sam, target),
TrackSource { sam, target, .. } => ("Изменился источник отметки", sam, target),
TrackLock {
sam,
target,
locked,
} => (
if locked {
"Контакт взят на сопровождение"
} else {
"Сопровождение прервано"
},
sam,
target,
),
TrackLost { sam, target } => ("Отметка потеряна", sam, target),
_ => continue,
};
observations.push(json!({ "seq": i, "at": event.at, "unit": unit, "target": target, "label": label, "lines": [] }));
if observations.len() == LOG_BATCH {
break;
}
}
}
json!({ "id": rec.number, "start": rec.started_at, "length": rec.len, "active": active,
"first": first, "gap": dec < first,
"limited": rec.decisions.truncated() || rec.scene.as_ref().is_some_and(|s| s.truncated || s.track_limit_reached()),
"next": [next_dec, next_ev as u64, next_sc as u64], "decisions": decisions, "events": events, "observations": observations })
}
fn cursors(raw: &str, session: &str, raid: u32) -> (u64, usize, usize) {
let Some((epoch, list)) = raw.split_once(':') else {
return (0, 0, 0);
};
if epoch != session {
return (0, 0, 0);
}
list.split(',')
.take(4)
.find_map(|s| {
let mut fields = s.split('.');
let number = fields.next()?.parse::<u32>().ok()?;
(number == raid).then_some((
fields.next()?.parse().ok()?,
fields.next()?.parse().ok()?,
fields.next().and_then(|n| n.parse().ok()).unwrap_or(0),
))
})
.unwrap_or_default()
}
fn parse_wave(raw: &str) -> Result<wave::WaveConfig, String> {
let chunks: Vec<_> = raw.split(':').collect();
let [a, d, aim, counts] = chunks.as_slice() else {
return Err("Неверный формат сценария".into());
};
let approach = a
.parse::<usize>()
.ok()
.and_then(|i| sim::Approach::ALL.get(i))
.ok_or("Неизвестный подход")?;
let aim = aim
.parse::<usize>()
.ok()
.and_then(|i| sim::Aim::ALL.get(i))
.ok_or("Неизвестная цель сценария")?;
let dist = d
.parse::<f64>()
.ok()
.filter(|x| (wave::DIST_MIN..=wave::DIST_MAX).contains(x))
.ok_or("Дальность вне диапазона")?;
let counts: Vec<u32> = counts
.split(',')
.map(str::parse)
.collect::<Result<_, _>>()
.map_err(|_| "Неверное количество")?;
if counts.len() != wave::KINDS.len()
|| counts.iter().any(|&n| n > 80)
|| counts.iter().all(|&n| n == 0)
{
return Err("Укажите допустимое количество аппаратов по каждому типу".into());
}
Ok(wave::WaveConfig {
counts: counts.try_into().unwrap(),
approach: *approach,
dist,
aim: *aim,
preset: 0,
})
}
impl AirDef {
pub(super) fn panel_command(&mut self, args: &[&str]) -> Result<Option<String>, String> {
match args {
["snapshot", nonce, privacy, raw]
if token(nonce) && matches!(*privacy, "public" | "debug") =>
{
if self.world.is_none() || player().is_none() {
return Err("Откройте игровой мир".into());
}
if self.web.session.is_empty() {
self.web.session = nonce.to_string();
}
let session = &self.web.session;
let (enemy, truth) = perspectives(&self.sim, *privacy == "debug");
let raids: Vec<_> = self
.sim
.replays
.iter()
.map(|r| (r, false))
.chain(self.sim.recording().map(|r| (r, true)))
.map(|(r, active)| record_data(r, cursors(raw, session, r.number), active))
.collect();
let selected = self.monitor_index().and_then(|i| {
self.sim.battle_reason(i).map(|reason| {
json!({"unit": self.sim.sams[i].id, "reason": why_view::unit_headline(reason)})
})
});
let content = json!({
"version": 1, "nonce": nonce, "session": session, "world": self.state_key(), "tick": self.sim.tick,
"live": public_live(&self.sim), "enemy": enemy, "truth": truth, "raids": raids, "catalog": configs(),
"selected": selected, "canLaunch": !self.sim.planning() && !self.village_active() && self.presentation.is_live(),
});
let bytes = serde_json::to_vec(&content).map_err(|e| e.to_string())?;
storage::set(SNAPSHOT, &bytes)?;
Ok(None)
}
["launch", id, session, wave] if token(id) => {
let receipt = if let Some((_, previous)) =
self.web.receipts.iter().find(|(key, _)| key == id)
{
previous.clone()
} else {
let result = self.panel_launch(session, wave);
let receipt = match result {
Ok(n) => {
json!({"id": id, "accepted": true, "message": format!("Игра приняла сценарий на {n} аппаратов")})
}
Err(error) => json!({"id": id, "accepted": false, "message": error}),
};
if self.web.receipts.len() == RECEIPT_LIMIT {
self.web.receipts.pop_front();
}
self.web
.receipts
.push_back((id.to_string(), receipt.clone()));
receipt
};
storage::set(
RECEIPT,
&serde_json::to_vec(&receipt).map_err(|e| e.to_string())?,
)?;
Ok(receipt["message"].as_str().map(str::to_owned))
}
_ => Err("Неизвестный запрос веб-пульта".into()),
}
}
fn panel_launch(&mut self, session: &str, raw: &str) -> Result<u32, String> {
if self.web.session.is_empty() || self.web.session != session {
return Err("Игровая сессия сменилась. Обновите карту".into());
}
if self.sim.planning() || self.village_active() || !self.presentation.is_live() {
return Err("В этом режиме нельзя запускать сценарий".into());
}
let p = player().ok_or("Игровой мир закрыт")?;
let wave = parse_wave(raw)?;
let objects = self.objects(DVec3::new(p.x, p.y, p.z));
let mut out = Out::default();
let n = self.sim.order_raid(&wave.order(), &objects, &mut out);
self.emit(out);
(n > 0)
.then_some(n)
.ok_or_else(|| "Игра не приняла сценарий".into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_network_snapshot_has_no_truth_without_sensors() {
let mut sim = sim::Sim::new(1);
sim.launch(
sim::DroneKind::Shahed,
DVec3::X,
DVec3::Z,
DVec3::ZERO,
&mut Out::default(),
);
assert!(public_live(&sim)["contacts"].as_array().unwrap().is_empty());
let (_, truth) = perspectives(&sim, true);
assert_eq!(truth.as_array().unwrap().len(), 1);
assert!(perspectives(&sim, false).1.is_null());
}
#[test]
fn validates_wave_as_data_and_resets_cursors_between_game_sessions() {
let mut counts = vec!["0"; wave::KINDS.len()];
counts[0] = "2";
assert_eq!(
parse_wave(&format!("0:300:0:{}", counts.join(",")))
.unwrap()
.total(),
2
);
assert!(parse_wave("0:NaN:0:2").is_err());
assert!(parse_wave("0:300:0:1;clear").is_err());
assert_eq!(cursors("new:1.101.200.5,2.0.50.4", "new", 1), (101, 200, 5));
assert_eq!(cursors("old:1.101.200.5", "new", 1), (0, 0, 0));
}
}