Files
airdef/airdef-mod/src/map.rs
T
chexit f2bc8550f5
build / mod (push) Failing after 28s
Tie a radar's refine/fire channel to its own plot's freshness (#140)
A station counted any own plot, however old, as a busy refine/fire
channel: a network heartbeat kept a stale contact's track fresh, so two
long-expired own fire plots still held both channels of the engagement
radar and a new contact nearby got only a coarse search plot, even with
the search radar running.

Channel occupancy now follows the station's own tracking.
Track::holds_channel requires an own (never relayed) refine/fire plot no
older than the station's track_ttl — three missed turns, the same value
that already bounds a contact without a fresh measurement. The planner
counts channels with the same Sam::own_channels_used(now) the panel,
monitor, map and "why" views read, so the UI and the allocation cannot
disagree about a stale channel. A stale channel frees for a new contact
without the network's survey track being removed; the hard per-profile
limit and the own measurement's provenance are unchanged, and a relayed
plot still never holds a channel.

Test: two contacts take both channels at the station, then leave its
reach while the search radar beside them keeps relaying them; a third
contact arrives nearby and gets its own fire channel (the test fails on
the old counting), and the relayed survey tracks of the old contacts
stay.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:53:43 +03:00

3116 lines
139 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The command map (#48): a full-screen map of the land with the systems, the objects, the launch sites
//! the radars found and the tracks the player's network holds; a placement editor for the layout before
//! a battle; the doctrine's guards and sector picked on the map.
//!
//! The map shows what the network knows (`Sim::picture`: the last measurement and the forecast of each
//! track), never the true drones, unless the sandbox's `truth` is on, and then it says so. The terrain
//! comes from the game as tiles (`render::TerrainShape`): the mod only says which, and the game scans the
//! loaded chunks within a budget; land it hasn't got is drawn as unknown.
use crate::panel::distance;
use crate::sim::{self, Class, Drone, LowSensor, Sam, SamKind, Sim, doctrine::Doctrine, Track, strike::SiteState};
use crate::{AirDef, say};
use glam::DVec3;
use horizon_mod_sdk::render::{self, CanvasEvent, FillShape, Point, QuadShape, Rect, Shape, TerrainShape, TextShape};
use std::collections::HashMap;
use std::f32::consts::TAU;
const FILTERS: [&str; 9] = ["рельеф", "системы", "объекты", "цели сети", "следы", "пусковые", "дальности", "обзор РЛС", "заливка"];
const F_TERRAIN: usize = 0;
const F_SAMS: usize = 1;
const F_OBJECTS: usize = 2;
const F_TRACKS: usize = 3;
const F_TRAILS: usize = 4;
const F_SITES: usize = 5;
const F_RINGS: usize = 6;
const F_VIEW: usize = 7;
const F_TINT: usize = 8;
/// Classes of systems for the filter: missile systems, guns, radars, the rear.
const SYS_CLASSES: [&str; 4] = ["ЗРК", "ЗАК", "РЛС", "тыл"];
/// Classes of the network's targets: the class the tracks were *estimated* (#133), not what the
/// targets are; the unidentified are always shown — they cannot be filtered by a class they don't have yet.
const TGT_CLASSES: [&str; 5] = ["Д", "Г", "К", "С", "Б"];
/// Whether the track passes the class filter: its estimated class is switched on, or it has none yet.
fn tclass_shown(t: &Track, on: &[bool; 5]) -> bool {
t.class.class().is_none_or(|c| on[c as usize])
}
/// A label line's height, pixels the markers merge within, how far from the pointer labels are kept at
/// a low zoom, and the most labels at once.
const LH: f32 = 9.0;
const CLUSTER_R: f32 = 9.0;
/// Tracks merge within this many pixels: their markers are bigger than the systems' (#132).
const TRACK_CLUSTER_R: f32 = 11.0;
/// A track marker's half-size, and the room its label keeps clear of it.
const TRACK_R: f32 = 6.0;
const MAX_LABELS: usize = 70;
/// Ticks a radar's computed coverage edge lives, and how many are recomputed in a redraw.
const RIM_REFRESH: u64 = 100;
const RIMS_PER_FRAME: usize = 3;
/// The most dashes of coverage edges in a redraw, the most cells of the tint, and the most land questions for one tint.
const RIM_DASHES: usize = 2400;
const TINT_CELLS: f32 = 1000.0;
const TINT_ASKS: usize = 12_000;
const SCN_ROWS: usize = 6;
/// Blocks per pixel limits: the whole raid, and one vehicle.
const SCALE_MIN: f64 = 0.04;
const SCALE_MAX: f64 = 24.0;
const TRAIL_POINTS: usize = 90;
/// Ticks between trail samples.
const SAMPLE: u64 = 10;
/// Pixels within which the pointer picks something.
const PICK_R: f32 = 9.0;
const DRAFT_UNDO: usize = 40;
const GREEN: u32 = 0xFF80FF90;
const WHITE: u32 = 0xFFFFFFFF;
const GREY: u32 = 0xFFB0B0B0;
const YELLOW: u32 = 0xFFFFE070;
const RED: u32 = 0xFFFF5050;
const CYAN: u32 = 0xFF9FE0FF;
const ORANGE: u32 = 0xFFFFA040;
const PANEL: u32 = 0xD0101814;
#[derive(Clone, Copy, PartialEq, Debug)]
enum Sel {
Sam(u32),
Object(usize),
Site(u32),
Track(u32),
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Pick {
None,
Sam(SamKind),
Object,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Mode {
View,
/// Pick the objects the system guards.
Guard(u32),
/// Pick the sector's centre, then its width.
Sector(u32, Option<f64>),
Editor,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Act {
Filter(usize),
Editor,
Pick(Pick),
Confirm,
Cancel,
Undo,
Guard,
Sector,
SectorOff,
Reserve,
Salvo,
Role(u8),
RadarEmission,
ResetDoc,
Strike(u32),
Centre,
Follow,
Rotate,
Delete,
Close,
Player,
SysClass(usize),
TgtClass(usize),
Tab(usize),
Panel,
NameFocus,
SaveScn,
LoadScn(usize),
ScnPage(i32),
/// Switches the map between the network's data and the sandbox's truth (#132).
Truth,
}
/// What the pointer hovers: a network track, or a true drone in the truth mode.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Hover {
Track(u32),
Drone(u32),
}
/// A system in the draft layout: an existing one (by id) or one to be built.
#[derive(Clone, Debug)]
struct DSam {
id: Option<u32>,
kind: SamKind,
pos: DVec3,
heading: f64,
gone: bool,
}
#[derive(Clone, Debug)]
struct DObj {
idx: Option<usize>,
pos: DVec3,
gone: bool,
}
#[derive(Clone, Debug, Default)]
struct Draft {
sams: Vec<DSam>,
objs: Vec<DObj>,
}
enum Drag {
Pan { from: (f32, f32), centre: (f64, f64), moved: bool },
Sam(usize),
Obj(usize),
}
struct Btn {
rect: [f32; 4],
act: Act,
}
/// A coverage edge worked out: how far a low flyer is seen along each ray before the land hides it.
struct Rim {
tick: u64,
pos: DVec3,
reach: f64,
terrain: bool,
d: Vec<f32>,
}
/// The coverage tint of a view, kept while the view and the layout stay the same: runs of cells (x, y, w, h, colour).
#[derive(Default)]
struct Tint {
key: u64,
runs: Vec<([f32; 4], u32)>,
}
/// Markers that merged into one at this zoom: where, and what a click on them zooms to.
struct Cluster {
c: (f32, f32),
}
/// A label waiting for a place.
struct Lab {
text: String,
w: f32,
at: (f32, f32),
r: f32,
col: u32,
prio: f32,
}
/// What the map keeps between frames.
pub struct MapUi {
pub open: bool,
size: (f32, f32),
cursor: (f32, f32),
centre: (f64, f64),
scale: f64,
placed: bool,
drag: Option<Drag>,
sel: Option<Sel>,
follow: bool,
mode: Mode,
filters: [bool; 9],
sclass: [bool; 4],
tclass: [bool; 5],
/// The left panel's page (layers, filters, scenarios) and whether it is folded away.
tab: usize,
folded: bool,
/// The layout's scale for the window (1 small, up to 1.4 large).
u: f32,
/// Scenario buttons: the name being typed, whether the field takes the keys, the names saved, the page of them,
/// and what a second click confirms (a delete, an overwrite, a load from another world).
name: String,
name_focus: bool,
scn: Vec<String>,
scn_page: usize,
confirm: Option<(Act, String)>,
rims: HashMap<u32, Rim>,
tint: Tint,
clusters: Vec<Cluster>,
/// Where panels are, so labels keep clear of them.
blocked: Vec<[f32; 4]>,
widths: HashMap<String, f32>,
trails: HashMap<u32, Vec<(f32, f32)>>,
/// The true places sampled while the sandbox's truth mode is on (#132), apart from the network's.
truth_trails: HashMap<u32, Vec<(f32, f32)>>,
seen: HashMap<u32, u64>,
/// When a true drone was last seen, kept apart from the network's `seen` (#132).
truth_seen: HashMap<u32, u64>,
sampled: u64,
draft: Draft,
history: Vec<Draft>,
pick: Pick,
heading: f64,
ed_sel: Option<EdSel>,
note: Option<(String, u64)>,
dirty: bool,
drawn: u64,
buttons: Vec<Btn>,
chunks_at: u64,
close: bool,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum EdSel {
Sam(usize),
Obj(usize),
}
impl Default for MapUi {
fn default() -> Self {
MapUi {
open: false,
size: (480.0, 270.0),
cursor: (0.0, 0.0),
centre: (0.0, 0.0),
scale: 0.5,
placed: false,
drag: None,
sel: None,
follow: false,
mode: Mode::View,
filters: [true, true, true, true, true, true, true, true, false],
sclass: [true; 4],
tclass: [true; 5],
tab: 0,
folded: false,
u: 1.0,
name: String::new(),
name_focus: false,
scn: Vec::new(),
scn_page: 0,
confirm: None,
rims: HashMap::new(),
tint: Tint::default(),
clusters: Vec::new(),
blocked: Vec::new(),
widths: HashMap::new(),
trails: HashMap::new(),
truth_trails: HashMap::new(),
seen: HashMap::new(),
truth_seen: HashMap::new(),
sampled: 0,
draft: Draft::default(),
history: Vec::new(),
pick: Pick::None,
heading: 0.0,
ed_sel: None,
note: None,
dirty: true,
drawn: u64::MAX,
buttons: Vec::new(),
chunks_at: 0,
close: false,
}
}
}
fn pt(x: f32, y: f32) -> Point {
Point { x, y }
}
fn fill(x: f32, y: f32, w: f32, h: f32, color: u32) -> Shape {
Shape::Fill(FillShape { rect: Rect { x, y, w, h }, color })
}
fn text(t: impl Into<String>, x: f32, y: f32, color: u32) -> Shape {
Shape::Text(TextShape { text: t.into(), at: pt(x, y), color: color & 0xFFFFFF, centered: false, shadow: true })
}
fn text_c(t: impl Into<String>, x: f32, y: f32, color: u32) -> Shape {
Shape::Text(TextShape { text: t.into(), at: pt(x, y), color: color & 0xFFFFFF, centered: true, shadow: true })
}
/// A line of `w` pixels.
fn line(a: (f32, f32), b: (f32, f32), w: f32, color: u32) -> Shape {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = dx.hypot(dy).max(0.001);
let (nx, ny) = (-dy / len * w / 2.0, dx / len * w / 2.0);
Shape::Quad(QuadShape { corners: (pt(a.0 + nx, a.1 + ny), pt(b.0 + nx, b.1 + ny), pt(b.0 - nx, b.1 - ny), pt(a.0 - nx, a.1 - ny)), color })
}
fn frame(x: f32, y: f32, w: f32, h: f32, b: f32, color: u32) -> [Shape; 4] {
[fill(x, y, w, b, color), fill(x, y + h - b, w, b, color), fill(x, y, b, h, color), fill(x + w - b, y, b, h, color)]
}
fn alpha(rgb: u32, a: f32) -> u32 {
(((a.clamp(0.0, 1.0) * 255.0) as u32) << 24) | (rgb & 0xFFFFFF)
}
/// A diamond, a square and the like around (x, y).
fn diamond(x: f32, y: f32, r: f32, color: u32) -> Shape {
Shape::Quad(QuadShape { corners: (pt(x, y - r), pt(x + r, y), pt(x, y + r), pt(x - r, y)), color })
}
/// The direction a heading looks along on the map (x east, z south): `heading_of`'s inverse.
fn dir_of(h: f64) -> (f64, f64) {
(-h.sin(), -h.cos())
}
impl MapUi {
fn to_screen(&self, x: f64, z: f64) -> (f32, f32) {
(
(self.size.0 as f64 / 2.0 + (x - self.centre.0) * self.scale) as f32,
(self.size.1 as f64 / 2.0 + (z - self.centre.1) * self.scale) as f32,
)
}
fn to_world(&self, p: (f32, f32)) -> (f64, f64) {
(
self.centre.0 + (p.0 as f64 - self.size.0 as f64 / 2.0) / self.scale,
self.centre.1 + (p.1 as f64 - self.size.1 as f64 / 2.0) / self.scale,
)
}
fn on_screen(&self, p: (f32, f32), margin: f32) -> bool {
p.0 > -margin && p.1 > -margin && p.0 < self.size.0 + margin && p.1 < self.size.1 + margin
}
fn note(&mut self, tick: u64, s: impl Into<String>) {
self.note = Some((s.into(), tick + 100));
self.dirty = true;
}
/// Remembers where the network's tracks are, every few ticks, for the trails.
pub fn sample(&mut self, sim: &Sim) {
if sim.tick < self.sampled {
self.trails.clear();
self.truth_trails.clear();
self.seen.clear();
self.truth_seen.clear();
}
if sim.tick < self.sampled + SAMPLE {
return;
}
self.sampled = sim.tick;
for (id, t) in sim.picture() {
// Only measurements: a forecast is not a place the target has been.
if t.age(sim.tick) > SAMPLE * 2 {
continue;
}
let trail = self.trails.entry(id).or_default();
let p = (t.pos.x as f32, t.pos.z as f32);
if trail.last().is_none_or(|l| (l.0 - p.0).hypot(l.1 - p.1) > 4.0) {
trail.push(p);
if trail.len() > TRAIL_POINTS {
trail.remove(0);
}
}
self.seen.insert(id, sim.tick);
}
// The truth mode keeps its own trail of the real places, never mixed into the network's (#132).
if sim.truth {
for d in sim.drones.iter().filter(|d| d.alive()) {
let trail = self.truth_trails.entry(d.id).or_default();
let p = (d.pos.x as f32, d.pos.z as f32);
if trail.last().is_none_or(|l| (l.0 - p.0).hypot(l.1 - p.1) > 4.0) {
trail.push(p);
if trail.len() > TRAIL_POINTS {
trail.remove(0);
}
}
self.truth_seen.insert(d.id, sim.tick);
}
}
let now = sim.tick;
self.seen.retain(|_, t| now.saturating_sub(*t) < 1200);
self.truth_seen.retain(|_, t| now.saturating_sub(*t) < 1200);
let seen = &self.seen;
self.trails.retain(|id, _| seen.contains_key(id));
let truth_seen = &self.truth_seen;
self.truth_trails.retain(|id, _| truth_seen.contains_key(id));
}
fn enter_editor(&mut self) {
self.draft = Draft::default();
self.history.clear();
self.mode = Mode::Editor;
self.pick = Pick::None;
self.ed_sel = None;
self.sel = None;
self.dirty = true;
}
fn push_history(&mut self) {
self.history.push(self.draft.clone());
if self.history.len() > DRAFT_UNDO {
self.history.remove(0);
}
}
}
impl MapUi {
/// A line's width in GUI pixels; the game is asked once for each text.
fn tw(&mut self, t: &str) -> f32 {
if let Some(w) = self.widths.get(t) {
return *w;
}
if self.widths.len() > 1500 {
self.widths.clear();
}
let w = render::text_width(t);
self.widths.insert(t.to_string(), w);
w
}
/// The names of the saved scenarios, and a name for the next save that no scenario has.
fn refresh_scenarios(&mut self) {
self.scn = crate::scenario::saved_names();
self.scn_page = self.scn_page.min(self.scn.len().saturating_sub(1) / SCN_ROWS);
if self.name.is_empty() || self.scn.contains(&self.name) && !self.name_focus {
self.name = (1..).map(|n| format!("map-{n}")).find(|n| !self.scn.contains(n)).unwrap_or_default();
}
}
}
/// The class of a system in the filter: 0 missile systems, 1 guns, 2 radars, 3 the rear.
fn sys_class(k: SamKind) -> usize {
if k.armed() {
if k == SamKind::Gepard { 1 } else { 0 }
} else if k == SamKind::Optical || k.spec().sensor > 0.0 {
2
} else {
3
}
}
/// A name that fits beside a marker.
fn short_name(k: SamKind) -> &'static str {
match k {
SamKind::Radar => "РЛС",
SamKind::Depot => "Склад",
SamKind::Tzm => "ТЗМ",
SamKind::Ew => "РЭБ",
SamKind::Light => "Прож.",
SamKind::Optical => "Опт.",
SamKind::Pantsir => "Панцирь",
SamKind::IrisT => "IRIS-T",
SamKind::S400 => "С-400",
SamKind::S500 => "С-500",
SamKind::Buk => "Бук",
SamKind::Tor => "Тор",
SamKind::Gepard => "Гепард",
_ => k.name(),
}
}
/// Markers within `r` pixels of the first of a group go with it: the groups, as indices into `pos`.
pub(crate) fn group(pos: &[(f32, f32)], r: f32) -> Vec<Vec<usize>> {
let r2 = r * r;
let mut g: Vec<Vec<usize>> = Vec::new();
'next: for (i, p) in pos.iter().enumerate() {
for grp in g.iter_mut() {
let a = pos[grp[0]];
if (a.0 - p.0).powi(2) + (a.1 - p.1).powi(2) <= r2 {
grp.push(i);
continue 'next;
}
}
g.push(vec![i]);
}
g
}
/// The groups of markers: those in `solo` stand alone; the rest merge when `cluster` is on.
fn groups_of(pos: &[(f32, f32)], solo: &[bool], r: f32, cluster: bool) -> Vec<Vec<usize>> {
let mut g: Vec<Vec<usize>> = (0..pos.len()).filter(|&i| solo[i]).map(|i| vec![i]).collect();
let rest: Vec<usize> = (0..pos.len()).filter(|&i| !solo[i]).collect();
if !cluster {
g.extend(rest.into_iter().map(|i| vec![i]));
return g;
}
let ps: Vec<(f32, f32)> = rest.iter().map(|&i| pos[i]).collect();
g.extend(group(&ps, r).into_iter().map(|grp| grp.into_iter().map(|k| rest[k]).collect::<Vec<_>>()));
g
}
/// Several markers as one: a box with their number, in the middle of them; a click zooms in on it.
fn draw_cluster(ui: &mut MapUi, s: &mut Vec<Shape>, taken: &mut Vec<[f32; 4]>, members: &[(f32, f32)], col: u32) {
let n = members.len() as f32;
let c = (members.iter().map(|m| m.0).sum::<f32>() / n, members.iter().map(|m| m.1).sum::<f32>() / n);
let label = members.len().to_string();
let half = (ui.tw(&label) / 2.0 + 3.0).max(7.0);
s.push(fill(c.0 - half - 1.0, c.1 - 6.0, half * 2.0 + 2.0, 12.0, col));
s.push(fill(c.0 - half, c.1 - 5.0, half * 2.0, 10.0, 0xFF101810));
s.push(text_c(label, c.0, c.1 - 4.0, col));
taken.push([c.0 - half - 1.0, c.1 - 6.0, half * 2.0 + 2.0, 12.0]);
ui.clusters.push(Cluster { c });
}
/// Asks for a label beside a marker; near the pointer it is kept, far from it at a low zoom it isn't.
fn add_lab(ui: &mut MapUi, labs: &mut Vec<Lab>, text: String, at: (f32, f32), r: f32, col: u32, chosen: bool) {
let d = (at.0 - ui.cursor.0).hypot(at.1 - ui.cursor.1);
let attn = if ui.scale < 0.15 {
90.0
} else if ui.scale < 0.6 {
200.0
} else {
f32::MAX
};
if !chosen && d > attn {
return;
}
let w = ui.tw(&text);
labs.push(Lab { text, w, at, r, col, prio: if chosen { -1.0e6 } else { d } });
}
fn overlap(a: [f32; 4], b: [f32; 4]) -> bool {
a[0] < b[0] + b[2] && a[0] + a[2] > b[0] && a[1] < b[1] + b[3] && a[1] + a[3] > b[1]
}
/// Puts the labels where nothing else is: the selected first, then those nearest the pointer; each beside its
/// marker (right, left, above, below), or not at all. `taken` holds the panels and the markers.
fn place_labels(size: (f32, f32), mut labs: Vec<Lab>, mut taken: Vec<[f32; 4]>, out: &mut Vec<Shape>) {
labs.sort_by(|a, b| a.prio.total_cmp(&b.prio));
let mut put = 0;
for l in labs {
if put >= MAX_LABELS {
break;
}
let (x, y) = l.at;
let gap = l.r + 2.0;
let tries = [
(x + gap, y - LH / 2.0),
(x - gap - l.w, y - LH / 2.0),
(x - l.w / 2.0, y - gap - LH),
(x - l.w / 2.0, y + gap),
(x + gap, y + 1.0),
(x + gap, y - LH - 1.0),
];
for (tx, ty) in tries {
let r = [tx, ty, l.w, LH];
if tx < 0.0 || ty < 0.0 || tx + l.w > size.0 || ty + LH > size.1 {
continue;
}
if taken.iter().any(|t| overlap(r, [t[0] - 1.0, t[1] - 1.0, t[2] + 2.0, t[3] + 2.0])) {
continue;
}
out.push(text(l.text.as_str(), tx, ty, l.col));
taken.push(r);
put += 1;
break;
}
}
}
/// Whether a system reaches the point (its weapons, on the plane).
fn reaches(kind: SamKind, pos: DVec3, p: DVec3) -> bool {
kind.range() > 0.0 && (pos.x - p.x).hypot(pos.z - p.z) <= kind.range()
}
fn class_name(c: sim::sites::SiteClass) -> &'static str {
match c {
sim::sites::SiteClass::Ramp => "рампа дронов",
sim::sites::SiteClass::Launcher => "пусковая ракет",
sim::sites::SiteClass::Battery => "батарея баллистических",
}
}
/// What the pointer is over, in the view: a network track, or a true drone while the sandbox's truth mode is on.
/// The network's tracks come from `Sim::picture` only; a drone the network has not measured is not hoverable
/// outside the truth mode (#132). Panels and cards take the pointer first.
fn hover_at(sim: &Sim, ui: &MapUi) -> Option<Hover> {
let p = ui.cursor;
if ui.blocked.iter().any(|r| p.0 >= r[0] && p.1 >= r[1] && p.0 <= r[0] + r[2] && p.1 <= r[1] + r[3]) {
return None;
}
let near = PICK_R + 2.0;
let mut best: Option<(f32, Hover)> = None;
if ui.filters[F_TRACKS] {
let now = sim.tick;
for (id, t) in sim.picture() {
if !tclass_shown(&t, &ui.tclass) {
continue;
}
let e = t.est(now);
let c = ui.to_screen(e.x, e.z);
if !ui.on_screen(c, 6.0) {
continue;
}
let d = (c.0 - p.0).hypot(c.1 - p.1);
if d <= near && best.is_none_or(|b| d < b.0) {
best = Some((d, Hover::Track(id)));
}
}
}
// The true place wins over its own track: the mode is explicit and the card says so.
if sim.truth {
for d in sim.drones.iter().filter(|d| d.alive()) {
let c = ui.to_screen(d.pos.x, d.pos.z);
if !ui.on_screen(c, 6.0) {
continue;
}
let dist = (c.0 - p.0).hypot(c.1 - p.1);
if dist <= near && best.is_none_or(|b| dist <= b.0 + 0.5) {
best = Some((dist, Hover::Drone(d.id)));
}
}
}
best.map(|b| b.1)
}
/// The network's knowledge of one track: type, status, source, distance, speed, whatever holds or intercepts it.
/// The target and the route are never known to the network unless the sandbox's truth mode adds them (#132).
fn track_lines(sim: &Sim, t: &Track, player: Option<DVec3>, lines: &mut Vec<(String, u32)>) {
let now = sim.tick;
let age = t.age(now);
let forecast = t.forecast(now);
lines.push((format!("Трек №{} · {}", t.id, t.class.name()), RED));
lines.push((
format!("Статус: {}{}", t.ident().name(), if forecast { format!(" · прогноз {} с", age / 20) } else { format!(" · измерение {} с назад", age / 20) }),
if forecast { YELLOW } else { GREEN },
));
let source = sim.sams.iter().enumerate().find(|(_, s)| s.id == t.source).map_or(
if t.source == 0 { "неизвестен".to_string() } else { format!("№? ({})", t.source) },
|(n, s)| format!("№{} {} ({})", n + 1, s.kind.name(), s.radar_profile().id),
);
lines.push((format!("Источник: {} · измерил {}", if t.own_within(now, t.ttl as u64) { "своя РЛС" } else { "сеть (чужое измерение)" }, source), WHITE));
lines.push((format!("Продукт: {} · качество {}%", t.product.name(), t.quality), WHITE));
let authority = if t.own_authorizes(now) {
"у измерившей станции пригодно для пуска".to_string()
} else if t.own_tick > 0 {
format!("измерение станции {} с назад, для пуска не пригодно", now.saturating_sub(t.own_tick) / 20)
} else {
"передано сетью: собственного измерения нет, нужен огневой трек станции".to_string()
};
lines.push((format!("Пуск: {authority}"), if t.own_authorizes(now) { GREEN } else { YELLOW }));
if t.locked {
lines.push(("Огневой захват: да".into(), YELLOW));
}
let e = t.est(now);
if let Some(p) = player {
lines.push((format!("Дистанция: {} · высота {:.0} м", distance(e.distance(p)), e.y), WHITE));
}
lines.push((
format!("Скорость: {:.0} км/ч · погрешность места {}", t.vel.length() * 20.0 * 3.6, distance(t.uncertainty(now))),
WHITE,
));
let missiles = sim.missiles.iter().filter(|m| m.target() == t.id).count();
lines.push((
if missiles > 0 { format!("Перехват: {missiles} ракет в полёте") } else { "Перехват: ракет нет".into() },
if missiles > 0 { GREEN } else { GREY },
));
let who = who_tracks(sim, t);
if !who.is_empty() {
lines.push((format!("Держат: {who}"), WHITE));
}
}
/// The systems whose tracks hold this one, by name (the network's own bookkeeping, not the drone's).
fn who_tracks(sim: &Sim, t: &Track) -> String {
let n = sim.sams.iter().filter(|s| s.tracks.iter().any(|x| x.id == t.id)).count();
if n == 0 { String::new() } else { format!("{n} комплексов") }
}
/// What a true drone is aimed at, in the sandbox's words: a unit, a marked object, or a bare point (#132).
fn aim_text(sim: &Sim, d: &Drone) -> String {
let unit = d.aim_unit();
if unit != 0 {
return match sim.sams.iter().position(|s| s.id == unit) {
Some(i) => format!("{} №{}", sim.sams[i].kind.name(), i + 1),
None => format!("комплекс №{unit}"),
};
}
let aim = d.aim_pos();
match sim.targets.iter().position(|p| p.distance(aim) < 8.0) {
Some(i) => format!("объект №{}", i + 1),
None => format!("точка {:.0} {:.0}", aim.x, aim.z),
}
}
/// The truth's lines for one drone: what it is, whether the network holds it, where it goes, what it is sent at,
/// and who is shooting at it. Only the sandbox's truth mode asks for these (#132).
fn truth_lines(sim: &Sim, d: &Drone, player: Option<DVec3>, lines: &mut Vec<(String, u32)>) {
let tracked = sim.picture().contains_key(&d.id);
lines.push((format!("ИСТИНА · {} ({}) №{}", d.kind.spec().name, d.kind.spec().class.name(), d.id), YELLOW));
lines.push((
format!("Статус: {}{}", if d.jammed { "в воздухе, навигация подавлена" } else { "в воздухе" }, if tracked { ", в картине сети" } else { ", вне картины сети" }),
if tracked { WHITE } else { ORANGE },
));
if d.kind.spec().decoy {
lines.push(("Ложная цель: без боевой части".into(), GREY));
}
if let Some(p) = player {
lines.push((format!("Дистанция: {} · высота {:.0} м", distance(d.pos.distance(p)), d.pos.y), WHITE));
}
lines.push((format!("Скорость: {:.0} км/ч", d.vel.length() * 20.0 * 3.6), WHITE));
lines.push((format!("Цель: {}", aim_text(sim, d)), YELLOW));
let route = d.route();
if route.is_empty() {
lines.push(("Маршрут: прямо на цель".into(), YELLOW));
} else {
lines.push((format!("Маршрут: {} точек, следующая через {}", route.len(), distance(d.pos.distance(route[0]))), YELLOW));
}
let aim = d.aim_pos();
let speed = d.vel.length().max(0.001);
lines.push((format!("До цели: {} (~{:.0} с)", distance(d.pos.distance(aim)), d.pos.distance(aim) / speed / 20.0), WHITE));
let missiles = sim.missiles.iter().filter(|m| m.target() == d.id).count();
lines.push((
if missiles > 0 || d.engaged > 0 {
format!("Перехват: {missiles} ракет в полёте, наведено {}", d.engaged)
} else {
"Перехват: никто не ведёт".into()
},
if missiles > 0 || d.engaged > 0 { GREEN } else { GREY },
));
}
/// The truth layer: the real drones as white frames, their sampled path, the route and aim ahead in yellow, marked
/// apart from the network's red tracks. Drawn only while the sandbox's truth mode is on (#132).
fn map_truth(sim: &Sim, ui: &mut MapUi, hover: Option<Hover>, s: &mut Vec<Shape>, labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
for d in sim.drones.iter().filter(|d| d.alive()) {
let c = ui.to_screen(d.pos.x, d.pos.z);
if ui.filters[F_TRAILS]
&& let Some(trail) = ui.truth_trails.get(&d.id)
{
let mut prev: Option<(f32, f32)> = None;
for p in trail {
let q = ui.to_screen(p.0 as f64, p.1 as f64);
if let Some(a) = prev
&& (ui.on_screen(a, 0.0) || ui.on_screen(q, 0.0))
{
s.push(line(a, q, 1.4, alpha(WHITE, 0.45)));
}
prev = Some(q);
}
}
if !ui.on_screen(c, 20.0) {
continue;
}
// The way ahead: the route's points, then the aim. Dashes, because a plan is not a measurement.
let aim = ui.to_screen(d.aim_pos().x, d.aim_pos().z);
let mut prev = c;
for p in d.route().iter().map(|p| ui.to_screen(p.x, p.z)).chain(std::iter::once(aim)) {
if ui.on_screen(prev, 0.0) || ui.on_screen(p, 0.0) {
route_dashed(s, prev, p, alpha(0xFFE070, 0.55));
}
prev = p;
}
// 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));
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));
}
}
}
/// The hover card: beside the pointer, over the picture. A network track's card never claims its target or route;
/// in the truth mode the true drone's card adds the route, the aim and the interception (#132).
fn hover_card(sim: &Sim, ui: &mut MapUi, h: Hover, player: Option<DVec3>, out: &mut Vec<Shape>, taken: &mut Vec<[f32; 4]>) {
let mut lines: Vec<(String, u32)> = Vec::new();
let border;
match h {
Hover::Track(id) => {
let pic = sim.picture();
let Some(t) = pic.get(&id) else { return };
border = RED;
track_lines(sim, t, player, &mut lines);
lines.push(("Цель и маршрут сети неизвестны".into(), GREY));
if sim.truth && let Some(d) = sim.drones.iter().find(|d| d.id == id && d.alive()) {
lines.push(("Истина (песочница):".into(), YELLOW));
lines.push((format!("Тип: {} · {}", d.kind.spec().name, aim_text(sim, d)), YELLOW));
}
}
Hover::Drone(id) => {
let Some(d) = sim.drones.iter().find(|d| d.id == id && d.alive()) else { return };
border = YELLOW;
truth_lines(sim, d, player, &mut lines);
lines.push(("Жёлтый пунктир — маршрут и цель; белые рамки — истина.".into(), GREY));
}
}
if lines.is_empty() {
return;
}
let (w, h) = ui.size;
let card_w = 250.0f32.min(w - 16.0);
let lines = wrap_lines(ui, lines, card_w);
let lh = (11.0 * ui.u).round();
let total = lines.len() as f32 * lh + 8.0;
let mut x = ui.cursor.0 + 14.0;
if x + card_w + 4.0 > w {
x = ui.cursor.0 - card_w - 14.0;
}
let x = x.clamp(4.0, (w - card_w - 4.0).max(4.0));
let y = (ui.cursor.1 - 10.0).clamp(4.0, (h - total - 4.0).max(4.0));
out.push(fill(x - 3.0, y - 3.0, card_w + 6.0, total + 6.0, 0xE8101814));
out.extend(frame(x - 3.0, y - 3.0, card_w + 6.0, total + 6.0, 1.0, border));
let mut ty = y;
for (l, c) in &lines {
out.push(text(l.as_str(), x + 2.0, ty, *c));
ty += lh;
}
taken.push([x - 3.0, y - 3.0, card_w + 6.0, total + 6.0]);
}
/// Long lines broken at the card's width.
fn wrap_lines(ui: &mut MapUi, lines: Vec<(String, u32)>, width: f32) -> Vec<(String, u32)> {
let mut wrapped: Vec<(String, u32)> = Vec::new();
for (l, c) in lines {
let mut cur = String::new();
for word in l.split(' ') {
let try_ = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") };
if ui.tw(&try_) > width - 8.0 && !cur.is_empty() {
wrapped.push((std::mem::take(&mut cur), c));
cur = word.to_string();
} else {
cur = try_;
}
}
wrapped.push((cur, c));
}
wrapped
}
impl AirDef {
/// Opens the map (the key, or the menu).
pub(crate) fn map_toggle(&mut self) {
if self.map.open {
self.map_close();
return;
}
if self.presentation.playback().is_some() {
say("Карта: сначала закройте повтор");
return;
}
let Some(p) = crate::player() else { return };
let ui = &mut self.map;
ui.open = true;
ui.mode = Mode::View;
ui.drag = None;
ui.size = render::gui_size();
if !ui.placed {
ui.centre = (p.x, p.z);
ui.placed = true;
ui.folded = ui.size.0 < 520.0;
}
ui.refresh_scenarios();
ui.dirty = true;
ui.drawn = u64::MAX;
render::open_canvas();
}
pub(crate) fn map_close(&mut self) {
if self.map.open {
render::close_canvas();
render::set_canvas(&[]);
}
self.map.open = false;
self.map.draft = Draft::default();
self.map.mode = Mode::View;
self.map.drag = None;
}
/// Once a frame while the map is open.
pub(crate) fn map_frame(&mut self) {
if !self.map.open {
return;
}
if !render::canvas_open() {
// The game closed it (the world was left, or it was not the time).
self.map.open = false;
self.map.draft = Draft::default();
self.map.mode = Mode::View;
return;
}
let mut ui = std::mem::take(&mut self.map);
for ev in render::canvas_events() {
self.map_event(&mut ui, ev);
if ui.close {
break;
}
}
if ui.close {
ui.close = false;
self.map = ui;
self.map_close();
return;
}
if ui.open {
if ui.follow
&& let Some(Sel::Track(id)) = ui.sel
&& let Some(t) = self.sim.picture().get(&id)
{
let e = t.est(self.sim.tick);
ui.centre = (e.x, e.z);
ui.dirty = true;
}
// The data moves at the sim's pace: a few redraws a second even when nothing is touched.
let step = self.sim.tick / 2;
if ui.dirty || ui.drawn != step {
ui.dirty = false;
ui.drawn = step;
let shapes = self.map_shapes(&mut ui);
render::set_canvas(&shapes);
}
}
self.map = ui;
}
fn ground_y(&mut self, x: f64, z: f64) -> Option<f64> {
self.ground.at(DVec3::new(x, 0.0, z), self.sim.tick)
}
fn map_event(&mut self, ui: &mut MapUi, ev: CanvasEvent) {
match ev {
CanvasEvent::Resized((w, h)) => {
ui.size = (w, h);
ui.dirty = true;
}
CanvasEvent::Moved(p) => {
ui.cursor = (p.x, p.y);
ui.dirty = true;
match &mut ui.drag {
Some(Drag::Pan { from, centre, moved }) => {
let (dx, dy) = (p.x - from.0, p.y - from.1);
if dx.hypot(dy) > 3.0 {
*moved = true;
}
if *moved {
ui.centre = (centre.0 - dx as f64 / ui.scale, centre.1 - dy as f64 / ui.scale);
ui.follow = false;
}
}
Some(Drag::Sam(i)) => {
let i = *i;
let (x, z) = ui.to_world((p.x, p.y));
if let Some(y) = self.ground_y(x, z)
&& let Some(d) = ui.draft.sams.get_mut(i)
{
d.pos = DVec3::new(x, y, z);
}
}
Some(Drag::Obj(i)) => {
let i = *i;
let (x, z) = ui.to_world((p.x, p.y));
if let Some(y) = self.ground_y(x, z)
&& let Some(d) = ui.draft.objs.get_mut(i)
{
d.pos = DVec3::new(x, y, z);
}
}
None => {}
}
}
CanvasEvent::Scrolled(s) => {
let at = (s.at.x, s.at.y);
let before = ui.to_world(at);
ui.scale = (ui.scale * 1.25f64.powf(s.steps as f64)).clamp(SCALE_MIN, SCALE_MAX);
// The point under the pointer stays under it.
ui.centre = (before.0 - (at.0 as f64 - ui.size.0 as f64 / 2.0) / ui.scale, before.1 - (at.1 as f64 - ui.size.1 as f64 / 2.0) / ui.scale);
ui.follow = false;
ui.dirty = true;
}
CanvasEvent::Pressed(b) => {
let at = (b.at.x, b.at.y);
ui.cursor = at;
ui.dirty = true;
if b.button == 0 {
let hit = ui.buttons.iter().find(|bt| at.0 >= bt.rect[0] && at.0 <= bt.rect[0] + bt.rect[2] && at.1 >= bt.rect[1] && at.1 <= bt.rect[1] + bt.rect[3]).map(|bt| bt.act);
if let Some(act) = hit {
self.map_act(ui, act);
return;
}
ui.name_focus = false;
ui.confirm = None;
}
match (b.button, ui.mode) {
(0, Mode::Editor) => self.editor_press(ui, at),
(0 | 2, _) => {
ui.drag = Some(Drag::Pan { from: at, centre: ui.centre, moved: false });
}
(1, Mode::Editor) => self.editor_remove_at(ui, at),
(1, _) => self.map_right(ui, at),
_ => {}
}
}
CanvasEvent::Released(b) => {
let at = (b.at.x, b.at.y);
ui.cursor = at;
ui.dirty = true;
let drag = ui.drag.take();
match drag {
Some(Drag::Pan { moved: false, .. }) if b.button == 0 => self.map_click(ui, at),
Some(Drag::Sam(_) | Drag::Obj(_)) => {}
_ => {}
}
}
CanvasEvent::Key(k) => self.map_key(ui, &k),
}
}
fn map_key(&mut self, ui: &mut MapUi, key: &str) {
ui.dirty = true;
// The name of a scenario being typed takes every key.
if ui.name_focus {
match key {
"key.keyboard.escape" => ui.name_focus = false,
"key.keyboard.enter" | "key.keyboard.keypad.enter" => self.map_act(ui, Act::SaveScn),
"key.keyboard.backspace" | "key.keyboard.delete" => {
ui.name.pop();
}
"key.keyboard.minus" if ui.name.len() < 32 => ui.name.push('-'),
k => {
if let Some(c) = k.strip_prefix("key.keyboard.")
&& c.len() == 1
&& c.as_bytes()[0].is_ascii_alphanumeric()
&& ui.name.len() < 32
{
ui.name.push(c.as_bytes()[0].to_ascii_lowercase() as char);
}
}
}
return;
}
let step = (60.0 / ui.scale).max(2.0);
match key {
"key.keyboard.escape" => {
if ui.drag.is_some() {
ui.drag = None;
} else if ui.mode == Mode::Editor {
if ui.pick != Pick::None || ui.ed_sel.is_some() {
ui.pick = Pick::None;
ui.ed_sel = None;
} else {
ui.mode = Mode::View;
ui.draft = Draft::default();
ui.note(self.sim.tick, "Расстановка отменена");
}
} else if ui.mode != Mode::View {
ui.mode = Mode::View;
} else if ui.sel.is_some() {
ui.sel = None;
ui.follow = false;
} else {
ui.close = true;
}
}
"key.keyboard.m" => {
if ui.mode == Mode::Editor && (!ui.draft.sams.is_empty() || !ui.draft.objs.is_empty()) && self.draft_changed(ui) {
ui.note(self.sim.tick, "Есть неподтверждённые изменения: Enter подтвердить, Esc отмена");
return;
}
ui.close = true;
}
"key.keyboard.left" => ui.centre.0 -= step,
"key.keyboard.right" => ui.centre.0 += step,
"key.keyboard.up" => ui.centre.1 -= step,
"key.keyboard.down" => ui.centre.1 += step,
"key.keyboard.equal" => self.map_zoom_centre(ui, 1.25),
"key.keyboard.minus" => self.map_zoom_centre(ui, 0.8),
"key.keyboard.c" => self.map_act(ui, Act::Player),
"key.keyboard.e" => self.map_act(ui, Act::Editor),
"key.keyboard.enter" if ui.mode == Mode::Editor => self.map_act(ui, Act::Confirm),
"key.keyboard.z" if ui.mode == Mode::Editor => self.map_act(ui, Act::Undo),
"key.keyboard.r" if ui.mode == Mode::Editor => self.map_act(ui, Act::Rotate),
"key.keyboard.delete" | "key.keyboard.backspace" if ui.mode == Mode::Editor => self.map_act(ui, Act::Delete),
"key.keyboard.f" => self.map_act(ui, Act::Follow),
"key.keyboard.t" => self.map_act(ui, Act::Truth),
k if k.len() == 14 && k.starts_with("key.keyboard.") && k.as_bytes()[13].is_ascii_digit() && k.as_bytes()[13] != b'0' => {
let n = (k.as_bytes()[13] - b'1') as usize;
if n < FILTERS.len() {
ui.filters[n] = !ui.filters[n];
}
}
"key.keyboard.s" => {
ui.folded = false;
ui.tab = 2;
ui.refresh_scenarios();
}
"key.keyboard.n" if ui.tab == 2 && !ui.folded => ui.name_focus = true,
"key.keyboard.tab" => {
ui.folded = !ui.folded;
}
_ => {}
}
}
fn map_zoom_centre(&mut self, ui: &mut MapUi, k: f64) {
ui.scale = (ui.scale * k).clamp(SCALE_MIN, SCALE_MAX);
}
/// The draft differs from the layout.
fn draft_changed(&self, ui: &MapUi) -> bool {
let d = &ui.draft;
d.sams.iter().any(|s| match s.id {
None => !s.gone,
Some(id) => s.gone || self.sim.sams.iter().find(|x| x.id == id).is_none_or(|x| x.pos.distance(s.pos) > 0.01 || (x.heading - s.heading).abs() > 1e-6),
}) || d.objs.iter().any(|o| match o.idx {
None => !o.gone,
Some(i) => o.gone || self.sim.targets.get(i).is_none_or(|t| t.distance(o.pos) > 0.01),
})
}
/// Loads the layout into the draft the first time the editor needs it.
fn ensure_draft(&mut self, ui: &mut MapUi) {
if !ui.draft.sams.is_empty() || !ui.draft.objs.is_empty() {
return;
}
ui.draft.sams = self.sim.sams.iter().map(|s| DSam { id: Some(s.id), kind: s.kind, pos: s.pos, heading: s.heading, gone: false }).collect();
ui.draft.objs = self.sim.targets.iter().enumerate().map(|(i, p)| DObj { idx: Some(i), pos: *p, gone: false }).collect();
}
fn battle(&self) -> bool {
!self.sim.drones.is_empty() || !self.sim.queue.is_empty() || self.sim.planning()
}
fn map_act(&mut self, ui: &mut MapUi, act: Act) {
ui.dirty = true;
let tick = self.sim.tick;
if act != Act::NameFocus {
ui.name_focus = false;
}
if !matches!(act, Act::SaveScn | Act::LoadScn(_)) {
ui.confirm = None;
}
match act {
Act::SysClass(i) => ui.sclass[i] = !ui.sclass[i],
Act::TgtClass(i) => ui.tclass[i] = !ui.tclass[i],
Act::Tab(i) => {
ui.tab = i;
if i == 2 {
ui.refresh_scenarios();
}
}
Act::Panel => ui.folded = !ui.folded,
Act::NameFocus => ui.name_focus = true,
Act::ScnPage(d) => {
let pages = ui.scn.len().div_ceil(SCN_ROWS).max(1);
ui.scn_page = (ui.scn_page as i32 + d).clamp(0, pages as i32 - 1) as usize;
}
Act::SaveScn => {
let name = ui.name.clone();
if ui.scn.contains(&name) && !matches!(&ui.confirm, Some((Act::SaveScn, n)) if *n == name) {
ui.confirm = Some((Act::SaveScn, name));
ui.note(tick, "Такое имя уже есть: нажмите ещё раз, чтобы перезаписать");
return;
}
ui.confirm = None;
match self.scenario_command(&["save", &name]) {
Ok(m) => {
say(&m);
ui.note(tick, m);
}
Err(e) => ui.note(tick, e),
}
ui.refresh_scenarios();
}
Act::LoadScn(i) => {
let Some(name) = ui.scn.get(i).cloned() else { return };
let again = matches!(&ui.confirm, Some((Act::LoadScn(k), _)) if *k == i);
let args: Vec<&str> = if again { vec!["load", &name, "force"] } else { vec!["load", &name] };
match self.scenario_command(&args) {
Ok(m) => {
say(&m);
ui.confirm = None;
ui.sel = None;
ui.follow = false;
ui.draft = Draft::default();
ui.history.clear();
ui.mode = Mode::View;
ui.pick = Pick::None;
ui.ed_sel = None;
ui.trails.clear();
ui.truth_trails.clear();
ui.truth_seen.clear();
ui.rims.clear();
ui.note(tick, m);
}
Err(e) if e.contains("другом мире") && !again => {
ui.confirm = Some((Act::LoadScn(i), name));
ui.note(tick, "Сценарий сделан в другом мире: нажмите ещё раз, чтобы загрузить всё равно");
}
Err(e) => {
ui.confirm = None;
ui.note(tick, e);
}
}
}
Act::Filter(i) => ui.filters[i] = !ui.filters[i],
Act::Truth => {
self.sim.truth = !self.sim.truth;
// The two pictures are kept apart: a mode switch starts its trails afresh (#132).
ui.truth_trails.clear();
ui.truth_seen.clear();
ui.note(tick, if self.sim.truth {
"Режим ИСТИНА (песочница): настоящие дроны, их цели и маршруты. Треки сети остаются на карте."
} else {
"Режим данных сети РЛС: только то, что засекли радары."
});
}
Act::Close => {
ui.close = true;
}
Act::Player => {
if let Some(p) = crate::player() {
ui.centre = (p.x, p.z);
ui.follow = false;
}
}
Act::Editor => {
if ui.mode == Mode::Editor {
if self.draft_changed(ui) {
ui.note(tick, "Есть неподтверждённые изменения: Enter подтвердить, «Отмена» сбросить");
} else {
ui.mode = Mode::View;
ui.draft = Draft::default();
}
} else if self.battle() {
ui.note(tick, "Бой идёт: расстановка закрыта до конца налёта");
} else {
ui.enter_editor();
self.ensure_draft(ui);
}
}
Act::Pick(p) => {
ui.pick = if ui.pick == p { Pick::None } else { p };
ui.ed_sel = None;
}
Act::Cancel => {
ui.draft = Draft::default();
ui.history.clear();
ui.mode = Mode::View;
ui.pick = Pick::None;
ui.note(tick, "Изменения отменены, ничего не построено");
}
Act::Undo => {
if let Some(d) = ui.history.pop() {
ui.draft = d;
ui.ed_sel = None;
}
}
Act::Rotate => {
let step = std::f64::consts::FRAC_PI_4;
match ui.ed_sel {
Some(EdSel::Sam(i)) => {
ui.push_history();
if let Some(d) = ui.draft.sams.get_mut(i) {
d.heading += step;
}
}
_ => ui.heading += step,
}
}
Act::Delete => {
if let Some(s) = ui.ed_sel.take() {
ui.push_history();
match s {
EdSel::Sam(i) => remove_dsam(&mut ui.draft, i),
EdSel::Obj(i) => remove_dobj(&mut ui.draft, i),
}
}
}
Act::Confirm => self.commit_draft(ui),
Act::Centre => {
if let Some(p) = self.sel_pos(ui) {
ui.centre = (p.x, p.z);
}
}
Act::Follow => {
if matches!(ui.sel, Some(Sel::Track(_))) {
ui.follow = !ui.follow;
}
}
Act::Guard => {
if let Some(Sel::Sam(id)) = ui.sel {
ui.mode = if ui.mode == Mode::Guard(id) { Mode::View } else { Mode::Guard(id) };
}
}
Act::Sector => {
if let Some(Sel::Sam(id)) = ui.sel {
ui.mode = if matches!(ui.mode, Mode::Sector(i, _) if i == id) { Mode::View } else { Mode::Sector(id, None) };
}
}
Act::SectorOff => {
if let Some(i) = self.sel_sam(ui) {
self.edit_doctrine(i, |d| d.sector = None);
}
ui.mode = Mode::View;
}
Act::Reserve => {
if let Some(i) = self.sel_sam(ui) {
self.edit_doctrine(i, |d| d.reserve = [0, 1, 2, 4, 8, 16].into_iter().find(|&r| r > d.reserve).unwrap_or(0));
}
}
Act::Salvo => {
if let Some(i) = self.sel_sam(ui) {
self.edit_doctrine(i, |d| d.salvo = d.salvo.next());
}
}
Act::ResetDoc => {
if let Some(i) = self.sel_sam(ui) {
self.edit_doctrine(i, |d| *d = Doctrine::default());
}
ui.mode = Mode::View;
}
Act::RadarEmission => {
if let Some(i) = self.sel_sam(ui) {
self.sim.sams[i].radar_on = !self.sim.sams[i].radar_on;
self.dirty = true;
}
}
Act::Role(bit) => {
if let Some(i) = self.sel_sam(ui) {
let s = &mut self.sim.sams[i];
s.roles ^= bit;
s.target = None;
s.gun_target = None;
self.dirty = true;
}
}
Act::Strike(site) => {
let Some(p) = crate::player() else { return };
let mut out = sim::Out::default();
match self.sim.order_strike(site, DVec3::new(p.x, p.y, p.z), &mut out) {
Ok(m) => {
// The stock went down: the durable state must not forget it (#113).
self.dirty = true;
say(&m);
ui.note(tick, "Ударная ракета пошла");
}
Err(e) => {
ui.note(tick, e.clone());
say(&e);
}
}
self.emit(out);
}
}
}
fn sel_sam(&self, ui: &MapUi) -> Option<usize> {
match ui.sel {
Some(Sel::Sam(id)) => self.sim.sams.iter().position(|s| s.id == id),
_ => None,
}
}
fn sel_pos(&self, ui: &MapUi) -> Option<DVec3> {
match ui.sel? {
Sel::Sam(id) => self.sim.sams.iter().find(|s| s.id == id).map(|s| s.pos),
Sel::Object(i) => self.sim.targets.get(i).copied(),
Sel::Site(id) => self.sim.strikes.get(id).and_then(|k| k.est.filter(|e| e.fix)).map(|e| DVec3::new(e.pos.x, 0.0, e.pos.y)),
Sel::Track(id) => self.sim.picture().get(&id).map(|t| t.est(self.sim.tick)),
}
}
/// What is under the pointer: systems, objects, launch sites, then tracks.
fn pick_at(&self, ui: &MapUi, p: (f32, f32)) -> Option<Sel> {
let near = |w: DVec3| {
let s = ui.to_screen(w.x, w.z);
(s.0 - p.0).hypot(s.1 - p.1) <= PICK_R
};
if ui.filters[F_SAMS] {
if let Some(s) = self.sim.sams.iter().find(|s| near(s.pos) && ui.sclass[sys_class(s.kind)]) {
return Some(Sel::Sam(s.id));
}
}
if ui.filters[F_OBJECTS] {
if let Some(i) = self.sim.targets.iter().position(|t| near(*t)) {
return Some(Sel::Object(i));
}
}
if ui.filters[F_SITES] {
for k in &self.sim.strikes.known {
if let Some(e) = k.est.filter(|e| e.fix)
&& near(DVec3::new(e.pos.x, 0.0, e.pos.y))
{
return Some(Sel::Site(k.site));
}
}
}
if ui.filters[F_TRACKS] {
let now = self.sim.tick;
let pic = self.sim.picture();
let mut best: Option<(f32, u32)> = None;
for (id, t) in &pic {
if !tclass_shown(t, &ui.tclass) {
continue;
}
let e = t.est(now);
let s = ui.to_screen(e.x, e.z);
let d = (s.0 - p.0).hypot(s.1 - p.1);
if d <= PICK_R + 2.0 && best.is_none_or(|b| d < b.0) {
best = Some((d, *id));
}
}
if let Some((_, id)) = best {
return Some(Sel::Track(id));
}
}
None
}
fn map_click(&mut self, ui: &mut MapUi, at: (f32, f32)) {
// Markers merged into one: a click goes in on them.
if let Some(cl) = ui.clusters.iter().find(|c| (c.c.0 - at.0).hypot(c.c.1 - at.1) <= 11.0) {
let (x, z) = ui.to_world(cl.c);
ui.centre = (x, z);
ui.scale = (ui.scale * 3.0).clamp(SCALE_MIN, SCALE_MAX);
ui.follow = false;
return;
}
let hit = self.pick_at(ui, at);
match ui.mode {
Mode::Guard(id) => {
if let Some(Sel::Object(k)) = hit
&& let Some(i) = self.sim.sams.iter().position(|s| s.id == id)
{
let g = self.sim.targets[k];
self.edit_doctrine(i, |d| match d.guards.iter().position(|x| x.distance(g) < 16.0) {
Some(j) => {
d.guards.remove(j);
}
None => d.guards.push(g),
});
} else if hit.is_none() {
ui.mode = Mode::View;
}
}
Mode::Sector(id, centre) => {
let Some(i) = self.sim.sams.iter().position(|s| s.id == id) else {
ui.mode = Mode::View;
return;
};
let (x, z) = ui.to_world(at);
let a = sim::heading_of(DVec3::new(x - self.sim.sams[i].pos.x, 0.0, z - self.sim.sams[i].pos.z));
match centre {
None => ui.mode = Mode::Sector(id, Some(a)),
Some(c) => {
let half = sim_angle_diff(c, a).abs().clamp(10f64.to_radians(), std::f64::consts::PI);
self.edit_doctrine(i, |d| d.sector = Some((c, half)));
ui.mode = Mode::View;
}
}
}
_ => {
ui.sel = hit;
ui.follow = false;
}
}
}
/// Right button in the view: a mobile system selected drives to the point.
fn map_right(&mut self, ui: &mut MapUi, at: (f32, f32)) {
if let Some(i) = self.sel_sam(ui)
&& self.sim.sams[i].kind.mobile()
{
let (x, z) = ui.to_world(at);
match self.ground_y(x, z) {
Some(y) => {
if self.sim.order_move(i, DVec3::new(x, y, z)) {
let s = &self.sim.sams[i];
ui.note(self.sim.tick, format!("{} №{}: на марш, {}", s.kind.name(), i + 1, distance(s.pos.distance(DVec3::new(x, y, z)))));
}
}
None => ui.note(self.sim.tick, "Земля там не загружена: подождите и повторите"),
}
} else {
ui.sel = None;
ui.mode = Mode::View;
}
}
// ------------------------------------------------------------------ the editor
fn draft_pick(&self, ui: &MapUi, at: (f32, f32)) -> Option<EdSel> {
let near = |w: DVec3| {
let s = ui.to_screen(w.x, w.z);
(s.0 - at.0).hypot(s.1 - at.1) <= PICK_R
};
if let Some(i) = ui.draft.sams.iter().position(|s| !s.gone && near(s.pos)) {
return Some(EdSel::Sam(i));
}
ui.draft.objs.iter().position(|o| !o.gone && near(o.pos)).map(EdSel::Obj)
}
fn editor_press(&mut self, ui: &mut MapUi, at: (f32, f32)) {
self.ensure_draft(ui);
if let Some(hit) = self.draft_pick(ui, at) {
ui.push_history();
ui.ed_sel = Some(hit);
ui.drag = Some(match hit {
EdSel::Sam(i) => Drag::Sam(i),
EdSel::Obj(i) => Drag::Obj(i),
});
return;
}
let (x, z) = ui.to_world(at);
match ui.pick {
Pick::None => {
ui.ed_sel = None;
ui.drag = Some(Drag::Pan { from: at, centre: ui.centre, moved: false });
}
p => {
let Some(y) = self.ground_y(x, z) else {
ui.note(self.sim.tick, "Земля здесь не загружена: подождите секунду и нажмите снова");
return;
};
ui.push_history();
let pos = DVec3::new(x, y, z);
match p {
Pick::Sam(kind) => {
ui.draft.sams.push(DSam { id: None, kind, pos, heading: ui.heading, gone: false });
ui.ed_sel = Some(EdSel::Sam(ui.draft.sams.len() - 1));
}
Pick::Object => {
ui.draft.objs.push(DObj { idx: None, pos, gone: false });
ui.ed_sel = Some(EdSel::Obj(ui.draft.objs.len() - 1));
}
Pick::None => {}
}
}
}
}
fn editor_remove_at(&mut self, ui: &mut MapUi, at: (f32, f32)) {
if let Some(hit) = self.draft_pick(ui, at) {
ui.push_history();
match hit {
EdSel::Sam(i) => remove_dsam(&mut ui.draft, i),
EdSel::Obj(i) => remove_dobj(&mut ui.draft, i),
}
ui.ed_sel = None;
} else {
ui.pick = Pick::None;
}
}
/// Builds what the draft says: nothing before this, and nothing is spent until it.
fn commit_draft(&mut self, ui: &mut MapUi) {
let tick = self.sim.tick;
if !self.draft_changed(ui) {
ui.mode = Mode::View;
ui.draft = Draft::default();
return;
}
if self.battle() {
ui.note(tick, "Бой идёт: расстановка закрыта");
return;
}
let d = std::mem::take(&mut ui.draft);
// Objects: removals from the end so the indices hold.
let mut gone: Vec<usize> = d.objs.iter().filter(|o| o.gone).filter_map(|o| o.idx).collect();
gone.sort_unstable_by(|a, b| b.cmp(a));
for o in &d.objs {
if let (Some(i), false) = (o.idx, o.gone)
&& let Some(t) = self.sim.targets.get_mut(i)
{
*t = o.pos;
}
}
for i in gone {
if i < self.sim.targets.len() {
self.sim.targets.remove(i);
if i < self.sim.target_health.len() {
self.sim.target_health.remove(i);
}
}
}
for o in d.objs.iter().filter(|o| o.idx.is_none() && !o.gone) {
self.sim.targets.push(o.pos);
self.sim.target_health.push(100.0);
}
for s in &d.sams {
match (s.id, s.gone) {
(Some(id), true) => self.sim.sams.retain(|x| x.id != id),
(Some(id), false) => {
if let Some(i) = self.sim.sams.iter().position(|x| x.id == id) {
let moved = self.sim.sams[i].pos.distance(s.pos) > 0.01;
let sam = &mut self.sim.sams[i];
sam.heading = s.heading;
if moved {
// Before the battle a unit is simply put down elsewhere.
sam.pos = s.pos;
sam.dest = None;
}
}
}
(None, false) => {
let id = self.sim.id();
let mut sam = Sam::new(id, s.kind, s.pos, s.heading);
if let Some(r) = self.sim.roles.get(&s.kind) {
sam.roles = *r;
}
self.sim.sams.push(sam);
}
(None, true) => {}
}
}
self.dirty = true;
ui.mode = Mode::View;
ui.history.clear();
ui.pick = Pick::None;
ui.ed_sel = None;
ui.sel = None;
ui.note(tick, "Расстановка подтверждена");
}
// ------------------------------------------------------------------ drawing
fn map_shapes(&mut self, ui: &mut MapUi) -> Vec<Shape> {
ui.buttons.clear();
ui.clusters.clear();
ui.blocked.clear();
let (w, h) = ui.size;
ui.u = (h / 300.0).clamp(1.0, 1.4);
let now = self.sim.tick;
let editing = ui.mode == Mode::Editor;
let cur_world = ui.to_world(ui.cursor);
// The ground under the pointer is asked for while placing, so that the click finds it.
if editing || ui.pick != Pick::None {
let _ = self.ground_y(cur_world.0, cur_world.1);
}
// Chunks round the view's middle are loaded now and then, so a place looked at fills in.
if now >= ui.chunks_at + 10 && ui.scale >= 0.2 {
ui.chunks_at = now;
let (cx, cz) = ((ui.centre.0.floor() as i32) >> 4, (ui.centre.1.floor() as i32) >> 4);
let wanted: Vec<(i32, i32)> = (-2..2).flat_map(|dz| (-2..2).map(move |dx| (cx + dx, cz + dz))).collect();
render::load_chunks(&wanted);
}
let draft = ui.draft.clone();
// The panels first: the labels keep clear of them. They are drawn last, over the picture.
let mut panels: Vec<Shape> = Vec::with_capacity(400);
self.map_panels(ui, &mut panels, &draft);
// The hover card (#132): beside the pointer, over the picture; the labels keep clear of it too.
let hover = if !editing && ui.drag.is_none() { hover_at(&self.sim, ui) } else { None };
let mut hover_taken: Vec<[f32; 4]> = Vec::new();
if let Some(h) = hover {
hover_card(&self.sim, ui, h, crate::player().map(|p| DVec3::new(p.x, p.y, p.z)), &mut panels, &mut hover_taken);
}
let mut s: Vec<Shape> = Vec::with_capacity(2048);
let mut labs: Vec<Lab> = Vec::new();
let mut taken: Vec<[f32; 4]> = ui.blocked.clone();
taken.extend(hover_taken);
// Terrain.
if ui.filters[F_TERRAIN] {
self.map_terrain(ui, &mut s);
}
self.map_grid(ui, &mut s);
// What covers what.
let armed: Vec<(SamKind, DVec3)> = if editing {
draft.sams.iter().filter(|d| !d.gone && d.kind.range() > 0.0).map(|d| (d.kind, d.pos)).collect()
} else {
self.sim.sams.iter().filter(|x| x.alive() && x.kind.range() > 0.0).map(|x| (x.kind, x.pos)).collect()
};
if editing || ui.filters[F_TINT] {
self.map_tint(ui, &mut s, &draft, &armed);
}
let picked = if editing { match ui.ed_sel { Some(EdSel::Sam(i)) => draft.sams.get(i).map(|d| d.pos), _ => None } } else { self.sel_pos(ui) };
// Reach rings of the weapons.
if ui.filters[F_RINGS] {
let list: Vec<(SamKind, DVec3, bool)> = if editing {
draft.sams.iter().filter(|d| !d.gone).map(|d| (d.kind, d.pos, d.id.is_none())).collect()
} else {
self.sim.sams.iter().filter(|x| x.alive()).map(|x| (x.kind, x.pos, false)).collect()
};
let many = list.len() > 12;
for (kind, pos, ghost) in list {
let r = kind.range();
let chosen = picked.is_some_and(|p| p.distance(pos) < 1.0);
if r > 0.0 && ui.sclass[sys_class(kind)] && (!many || chosen || ghost) {
let c = ui.to_screen(pos.x, pos.z);
ring(ui, &mut s, c, (r * ui.scale) as f32, 1.0, alpha(if ghost { 0xFFE070 } else { 0x40A0FF }, 0.75));
}
}
}
// The radars' coverage edges: what a low flyer is seen at, the land taken into account.
if ui.filters[F_VIEW] {
self.map_rims(ui, &mut s, &draft, picked);
}
// The selected system's sensor, sector and guards.
if let Some(i) = self.sel_sam(ui) {
let sam = &self.sim.sams[i];
let c = ui.to_screen(sam.pos.x, sam.pos.z);
let sens = sam.kind.spec().sensor;
if sens > 0.0 && !ui.filters[F_VIEW] {
ring(ui, &mut s, c, (sens * ui.scale) as f32, 1.0, alpha(0x80FF90, 0.45));
}
self.map_sector(ui, &mut s, sam.pos, &sam.doctrine, sam.kind.range().max(200.0));
for g in &sam.doctrine.guards {
let gp = ui.to_screen(g.x, g.z);
s.push(line(c, gp, 1.0, alpha(0xFFE070, 0.7)));
ring(ui, &mut s, gp, (sim::doctrine::GUARD_R * ui.scale) as f32, 1.0, alpha(0xFFE070, 0.6));
}
}
if let Mode::Sector(id, centre) = ui.mode
&& let Some(sam) = self.sim.sams.iter().find(|x| x.id == id)
{
let a = sim::heading_of(DVec3::new(cur_world.0 - sam.pos.x, 0.0, cur_world.1 - sam.pos.z));
let d = match centre {
None => Doctrine { sector: Some((a, 15f64.to_radians())), ..Default::default() },
Some(c) => Doctrine { sector: Some((c, sim_angle_diff(c, a).abs().clamp(10f64.to_radians(), std::f64::consts::PI))), ..Default::default() },
};
self.map_sector(ui, &mut s, sam.pos, &d, sam.kind.range().max(200.0));
}
// Flights of the strike missiles: the line to the target, the marker where the missile really is (#106).
for f in &self.sim.strikes.flights {
let a = ui.to_screen(f.from.x, f.from.z);
let b = ui.to_screen(f.aim.x, f.aim.y);
s.push(line(a, b, 1.0, alpha(0xFFA040, 0.5)));
let c = ui.to_screen(f.pos.x, f.pos.z);
s.push(diamond(c.0, c.1, 3.0, ORANGE));
}
// Objects.
if ui.filters[F_OBJECTS] {
self.map_objects(ui, &mut s, &draft, &armed, &mut labs, &mut taken);
}
// Systems.
if ui.filters[F_SAMS] {
self.map_sams(ui, &mut s, &draft, &mut labs, &mut taken);
}
// Launch sites the radars found.
if ui.filters[F_SITES] {
self.map_sites(ui, &mut s, &mut labs, &mut taken);
}
// Own interceptors.
for m in &self.sim.missiles {
let c = ui.to_screen(m.pos.x, m.pos.z);
if ui.on_screen(c, 4.0) {
s.push(fill(c.0 - 1.0, c.1 - 1.0, 2.0, 2.0, YELLOW));
}
}
// The network's tracks.
if ui.filters[F_TRACKS] || ui.filters[F_TRAILS] {
self.map_tracks(ui, &mut s, &mut labs, &mut taken);
}
// The optical posts and the contacts they watch (#136): a line to a contact last seen in clear sight.
if ui.filters[F_SAMS] || ui.filters[F_TRACKS] {
self.map_optical(ui, &mut s, &mut labs);
}
// The truth, when the sandbox shows it, marked as such: the real drones, their routes and aims.
if self.sim.truth {
map_truth(&self.sim, ui, hover, &mut s, &mut labs, &mut taken);
}
// The ghost under the pointer while placing.
if editing && let Some(y) = self.ground_y(cur_world.0, cur_world.1) {
let c = ui.cursor;
match ui.pick {
Pick::Sam(kind) => {
s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, alpha(0xFFE070, 0.6)));
let (dx, dz) = dir_of(ui.heading);
s.push(line(c, (c.0 + dx as f32 * 11.0, c.1 + dz as f32 * 11.0), 1.5, alpha(0xFFE070, 0.6)));
if kind.range() > 0.0 {
ring(ui, &mut s, c, (kind.range() * ui.scale) as f32, 1.0, alpha(0xFFE070, 0.55));
}
let _ = y;
}
Pick::Object => s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, alpha(0xFFE070, 0.6))),
Pick::None => {}
}
} else if editing && ui.pick != Pick::None {
s.push(text("земля не загружена", ui.cursor.0 + 8.0, ui.cursor.1 + 8.0, RED));
}
place_labels((w, h), labs, taken, &mut s);
// The picture is cut, never the panels over it.
s.truncate(8000 - panels.len().min(900));
s.extend(panels);
s
}
/// The objects: merged where they crowd, the number beside each.
fn map_objects(&self, ui: &mut MapUi, s: &mut Vec<Shape>, draft: &Draft, armed: &[(SamKind, DVec3)], labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
let editing = ui.mode == Mode::Editor;
let list: Vec<(usize, DVec3, bool)> = if editing {
draft.objs.iter().enumerate().filter(|(_, o)| !o.gone).map(|(i, o)| (i, o.pos, o.idx.is_none())).collect()
} else {
self.sim.targets.iter().enumerate().map(|(i, p)| (i, *p, false)).collect()
};
let vis: Vec<(usize, DVec3, bool, (f32, f32))> = list
.into_iter()
.map(|(i, p, g)| (i, p, g, ui.to_screen(p.x, p.z)))
.filter(|v| ui.on_screen(v.3, 20.0))
.collect();
let pos: Vec<(f32, f32)> = vis.iter().map(|v| v.3).collect();
let solo: Vec<bool> = vis.iter().map(|v| ui.sel == Some(Sel::Object(v.0)) || ui.ed_sel == Some(EdSel::Obj(v.0)) && editing).collect();
let covered = |p: DVec3| armed.iter().any(|(k, pos)| reaches(*k, *pos, p));
for grp in groups_of(&pos, &solo, CLUSTER_R, !editing) {
if grp.len() > 1 {
let bare = grp.iter().any(|&k| !covered(vis[k].1));
let col = if bare && !armed.is_empty() { RED } else { WHITE };
let members: Vec<(f32, f32)> = grp.iter().map(|&k| vis[k].3).collect();
draw_cluster(ui, s, taken, &members, col);
continue;
}
let (i, p, ghost, c) = vis[grp[0]];
let cov = covered(p);
let col = if !cov && (editing || !armed.is_empty()) { RED } else if ghost { YELLOW } else { WHITE };
s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, col));
s.push(fill(c.0 - 2.5, c.1 - 2.5, 5.0, 5.0, 0xFF101010));
taken.push([c.0 - 5.0, c.1 - 5.0, 10.0, 10.0]);
let chosen = ui.sel == Some(Sel::Object(i)) && !editing;
if !editing {
let hp = self.sim.target_health.get(i).copied().unwrap_or(100.0);
add_lab(ui, labs, format!("{}{}", i + 1, if hp < 100.0 { format!(" {hp:.0}%") } else { String::new() }), c, 6.0, col, chosen);
} else if !cov {
add_lab(ui, labs, "не прикрыт".into(), c, 6.0, RED, false);
}
if chosen {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
}
}
}
/// The systems: merged where they crowd, with short names; the filter by class applies.
fn map_sams(&self, ui: &mut MapUi, s: &mut Vec<Shape>, draft: &Draft, labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
let editing = ui.mode == Mode::Editor;
// (id, kind, position, heading, ghost, alive, place in the draft, number)
let list: Vec<(Option<u32>, SamKind, DVec3, f64, bool, bool, usize, usize)> = if editing {
draft.sams.iter().enumerate().filter(|(_, d)| !d.gone).map(|(i, d)| (d.id, d.kind, d.pos, d.heading, d.id.is_none(), true, i, i + 1)).collect()
} else {
self.sim.sams.iter().enumerate().map(|(i, x)| (Some(x.id), x.kind, x.pos, x.heading, false, x.alive(), 0, i + 1)).collect()
};
let vis: Vec<_> = list
.into_iter()
.filter(|v| editing || ui.sclass[sys_class(v.1)] || ui.sel == v.0.map(Sel::Sam))
.map(|v| (v, ui.to_screen(v.2.x, v.2.z)))
.filter(|v| ui.on_screen(v.1, 30.0))
.collect();
let pos: Vec<(f32, f32)> = vis.iter().map(|v| v.1).collect();
let solo: Vec<bool> = vis
.iter()
.map(|(v, _)| !editing && v.0.is_some() && ui.sel == v.0.map(Sel::Sam) || editing && ui.ed_sel == Some(EdSel::Sam(v.6)))
.collect();
for grp in groups_of(&pos, &solo, CLUSTER_R, !editing) {
if grp.len() > 1 {
let members: Vec<(f32, f32)> = grp.iter().map(|&k| vis[k].1).collect();
let col = if grp.iter().any(|&k| vis[k].0.1.armed()) { 0xFF40A0FF } else { 0xFF60D0A0 };
draw_cluster(ui, s, taken, &members, col);
continue;
}
let ((id, kind, _, heading, ghost, alive, di, n), c) = vis[grp[0]];
let col = if !alive {
0xFF704040
} else if ghost {
YELLOW
} else if kind.range() > 0.0 {
0xFF40A0FF
} else {
0xFF60D0A0
};
s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, col));
let (dx, dz) = dir_of(heading);
s.push(line(c, (c.0 + dx as f32 * 11.0, c.1 + dz as f32 * 11.0), 1.5, col));
taken.push([c.0 - 5.0, c.1 - 5.0, 10.0, 10.0]);
let chosen = !editing && id.is_some() && ui.sel == id.map(Sel::Sam);
let ed = editing && ui.ed_sel == Some(EdSel::Sam(di));
let name = if chosen || ed || ui.scale > 1.5 { format!("{} {n}", short_name(kind)) } else { short_name(kind).to_string() };
add_lab(ui, labs, name, c, 7.0, alpha(col, 0.95), chosen || ed);
if chosen || ed {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
}
}
}
/// The optical posts (#136): a short status by each, and a line to the contact it has in clear
/// sight (or last saw), never to a radar's measurement. At most a screenful, so a crowd stays cheap.
fn map_optical(&self, ui: &mut MapUi, s: &mut Vec<Shape>, labs: &mut Vec<Lab>) {
let now = self.sim.tick;
let picture = self.sim.picture();
let mut drawn = 0usize;
for (i, sam) in self.sim.sams.iter().enumerate().filter(|(_, sam)| sam.kind == SamKind::Optical && sam.alive()) {
if drawn >= 16 {
break;
}
let c = ui.to_screen(sam.pos.x, sam.pos.z);
if !ui.on_screen(c, 30.0) {
continue;
}
drawn += 1;
let Some(report) = self.sim.optical_report(sam.id) else { continue };
let chosen = ui.sel == Some(Sel::Sam(sam.id));
let color = match report.state {
sim::OpticalState::Observing => GREEN,
sim::OpticalState::Holding => CYAN,
sim::OpticalState::NoSight => ORANGE,
sim::OpticalState::Searching => GREY,
};
add_lab(ui, labs, format!("Опт. №{}: {}", i + 1, report.status()), c, 7.0, alpha(color, 0.95), chosen);
if chosen {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
}
// The contact it watches: its own last clear sighting, else the network cue's forecast.
let own = report.seen.is_some();
let point = report
.seen
.or_else(|| report.target.and_then(|id| picture.get(&id).map(|t| t.est(now))));
if let Some(p) = point {
let pc = ui.to_screen(p.x, p.z);
s.push(line(c, pc, 1.0, alpha(color, if chosen { 0.9 } else if own { 0.55 } else { 0.3 })));
let label = match (own, report.observation) {
(true, Some(o)) => format!("вероятно {} · {:.0}%", o.class.name(), (1.0 - o.uncertainty) * 100.0),
(true, None) => "контакт в поле зрения".into(),
(false, _) => "цель по подсказке".into(),
};
add_lab(ui, labs, label, pc, 5.0, alpha(color, 0.95), chosen);
}
}
}
/// The radars' coverage edges. A radar's edge is where the land first hides a low flyer along each ray round it;
/// each is worked out from the sim's own horizon (`low_rim`), a few a redraw, and kept a while. The selected
/// one shows its dead zones filled.
fn map_rims(&self, ui: &mut MapUi, s: &mut Vec<Shape>, draft: &Draft, picked: Option<DVec3>) {
let editing = ui.mode == Mode::Editor;
let now = self.sim.tick;
// (the unit it is, kind, radar)
let list: Vec<(Option<u32>, SamKind, LowSensor, DVec3)> = if editing {
draft
.sams
.iter()
.filter(|d| !d.gone)
.filter_map(|d| {
// A unit that stays where it is keeps its horizon; a new or moved one has none yet.
let live = d.id.filter(|&id| self.sim.sams.iter().any(|x| x.id == id && x.pos.distance(d.pos) < 0.01));
self.sim.low_sensor(d.kind, d.pos, live).map(|ls| (live, d.kind, ls, d.pos))
})
.collect()
} else {
self.sim.sams.iter().filter(|x| x.radar_up()).filter_map(|x| self.sim.low_sensor(x.kind, x.pos, Some(x.id)).map(|ls| (Some(x.id), x.kind, ls, x.pos))).collect()
};
let list: Vec<_> = list.into_iter().filter(|v| ui.sclass[sys_class(v.1)] || picked.is_some_and(|p| p.distance(v.3) < 1.0)).collect();
let (w, h) = ui.size;
let mid = (w / 2.0, h / 2.0);
let reach_px = mid.0.hypot(mid.1);
// Whether the circle comes near the screen at all.
let near_view = |ui: &MapUi, pos: DVec3, reach: f64| {
let c = ui.to_screen(pos.x, pos.z);
let r = (reach * ui.scale) as f32;
let far = (c.0 - mid.0).hypot(c.1 - mid.1);
r >= 3.0 && far - r <= reach_px && r - far <= reach_px
};
// Work out the oldest few that are on the screen.
let mut stale: Vec<(u64, usize)> = Vec::new();
for (i, (id, _, ls, pos)) in list.iter().enumerate() {
let Some(id) = id else { continue };
if !near_view(ui, *pos, ls.reach) {
continue;
}
match ui.rims.get(id) {
Some(c) if c.pos == *pos && (c.reach - ls.reach).abs() < 0.5 && c.terrain == ls.terrain && now.saturating_sub(c.tick) < RIM_REFRESH => {}
Some(c) => stale.push((now.saturating_sub(c.tick) + if c.pos == *pos { 0 } else { 100_000 }, i)),
None => stale.push((u64::MAX, i)),
}
}
stale.sort_by(|a, b| b.0.cmp(&a.0));
for (_, i) in stale.into_iter().take(RIMS_PER_FRAME) {
let (id, _, ls, pos) = &list[i];
let d = self.sim.low_rim(&self.ground, ls);
ui.rims.insert(id.unwrap_or(u32::MAX), Rim { tick: now, pos: *pos, reach: ls.reach, terrain: ls.terrain, d });
}
if ui.rims.len() > list.len() + 64 {
let live: std::collections::HashSet<u32> = self.sim.sams.iter().map(|x| x.id).collect();
ui.rims.retain(|id, _| live.contains(id));
}
// Draw.
let many = list.len() > 16;
let mut dashes = 0usize;
for (id, kind, ls, pos) in &list {
if !near_view(ui, *pos, ls.reach) {
continue;
}
let chosen = picked.is_some_and(|p| p.distance(*pos) < 1.0);
// A crowd of systems: only the selected one and the long-range radars show their edge.
if many && !chosen && sys_class(*kind) != 2 {
continue;
}
let cached = id.and_then(|i| ui.rims.get(&i)).filter(|c| c.pos == *pos && (c.reach - ls.reach).abs() < 0.5);
let full;
let d: &[f32] = match cached {
Some(c) => &c.d,
None => {
full = vec![ls.reach as f32; sim::RIM_RAYS];
&full
}
};
let base = match sys_class(*kind) {
2 => 0x80FF90,
1 => 0xFFC060,
_ => 0x60B0FF,
};
let col = alpha(base, if chosen { 0.95 } else if many { 0.35 } else { 0.55 });
let o = ui.to_screen(pos.x, pos.z);
let n = sim::RIM_RAYS;
let sub = if chosen || (!many && ls.reach * ui.scale > 160.0) { 2 } else { 1 };
let at = |k: f32| {
// Ray k (fractional): the distance between the two rays it lies between.
let i = k.floor() as usize % n;
let j = (i + 1) % n;
let f = k - k.floor();
let dist = (d[i] + (d[j] - d[i]) * f) as f64 * ui.scale;
let a = k as f64 / n as f64 * std::f64::consts::TAU;
(o.0 + (a.sin() * dist) as f32, o.1 + (a.cos() * dist) as f32)
};
// A dead zone: the part of the circle the land takes away, filled, for the one in hand.
if chosen {
for i in 0..n {
let (j, r0, r1) = ((i + 1) % n, d[i], d[(i + 1) % n]);
let full_r = ls.reach as f32;
if r0 >= full_r - 1.0 && r1 >= full_r - 1.0 {
continue;
}
let edge = |k: usize, r: f32| {
let a = k as f64 / n as f64 * std::f64::consts::TAU;
(o.0 + (a.sin() * r as f64 * ui.scale) as f32, o.1 + (a.cos() * r as f64 * ui.scale) as f32)
};
let (a0, a1, b0, b1) = (edge(i, r0), edge(i, full_r), edge(j, full_r), edge(j, r1));
if ui.on_screen(a1, 80.0) || ui.on_screen(b1, 80.0) || ui.on_screen(a0, 80.0) {
s.push(Shape::Quad(QuadShape { corners: (pt(a0.0, a0.1), pt(a1.0, a1.1), pt(b0.0, b0.1), pt(b1.0, b1.1)), color: alpha(0xFF4040, 0.2) }));
}
}
}
for step in (0..n * sub).step_by(2) {
if dashes >= RIM_DASHES {
break;
}
let (k0, k1) = (step as f32 / sub as f32, (step + 1) as f32 / sub as f32);
let (p0, p1) = (at(k0), at(k1));
if ui.on_screen(p0, 30.0) || ui.on_screen(p1, 30.0) {
s.push(line(p0, p1, if chosen { 1.5 } else { 1.0 }, col));
dashes += 1;
}
}
}
}
/// The coverage tint: a cell is green where a weapon reaches and a radar sees a low flyer over the land, amber where a
/// weapon reaches but no radar sees (the land hides it), blue where a radar sees and no weapon reaches. Kept while the
/// view and the layout stay the same.
fn map_tint(&self, ui: &mut MapUi, s: &mut Vec<Shape>, draft: &Draft, armed: &[(SamKind, DVec3)]) {
let editing = ui.mode == Mode::Editor;
let (w, h) = ui.size;
let sensors: Vec<LowSensor> = if editing {
draft
.sams
.iter()
.filter(|d| !d.gone)
.filter_map(|d| {
let live = d.id.filter(|&id| self.sim.sams.iter().any(|x| x.id == id && x.pos.distance(d.pos) < 0.01));
self.sim.low_sensor(d.kind, d.pos, live)
})
.collect()
} else {
self.sim.low_sensors()
};
let mut key = 0xcbf29ce484222325u64;
for v in [ui.centre.0.round().to_bits(), ui.centre.1.round().to_bits(), ui.scale.to_bits(), w.to_bits() as u64, h.to_bits() as u64, self.sim.tick / 20, editing as u64, armed.len() as u64, sensors.len() as u64] {
key = (key ^ v).wrapping_mul(0x100000001b3);
}
for (_, p) in armed {
key = (key ^ p.x.to_bits() ^ p.z.to_bits().rotate_left(21)).wrapping_mul(0x100000001b3);
}
for ls in &sensors {
key = (key ^ ls.ant.x.to_bits() ^ ls.ant.z.to_bits().rotate_left(21) ^ ls.terrain as u64).wrapping_mul(0x100000001b3);
}
if ui.tint.key != key {
let cell = ((w * h / TINT_CELLS).sqrt()).max(14.0);
let tl = ui.to_world((0.0, 0.0));
let br = ui.to_world((w, h));
let near = |x: f64, z: f64, r: f64| x + r >= tl.0 && x - r <= br.0 && z + r >= tl.1 && z - r <= br.1;
let weap: Vec<(f64, f64, f64)> = armed.iter().filter(|(k, p)| near(p.x, p.z, k.range())).map(|(k, p)| (p.x, p.z, k.range() * k.range())).collect();
let sens: Vec<&LowSensor> = sensors.iter().filter(|l| near(l.ant.x, l.ant.z, l.reach)).collect();
let mut runs: Vec<([f32; 4], u32)> = Vec::new();
let mut asks = 0usize;
let mut y = 0.0f32;
while y < h {
let mut x = 0.0f32;
let mut cur: Option<([f32; 4], u32)> = None;
while x < w {
let c = ui.to_world((x + cell / 2.0, y + cell / 2.0));
let a = weap.iter().any(|(wx, wz, r2)| (wx - c.0).powi(2) + (wz - c.1).powi(2) <= *r2);
let mut b = false;
for l in &sens {
if (l.ant.x - c.0).powi(2) + (l.ant.z - c.1).powi(2) > l.reach * l.reach {
continue;
}
asks += 1;
if asks > TINT_ASKS {
break;
}
if self.sim.low_sees(&self.ground, l, c.0, c.1) {
b = true;
break;
}
}
let col = match (a, b) {
(true, true) => Some(alpha(0x40FF60, 0.12)),
(true, false) => Some(alpha(0xFFB030, 0.24)),
(false, true) => Some(alpha(0x4090FF, 0.07)),
_ => None,
};
match (col, &mut cur) {
(Some(c), Some((r, rc))) if *rc == c => r[2] += cell,
(col, cur_run) => {
if let Some(done) = cur_run.take() {
runs.push(done);
}
if let Some(c) = col {
*cur_run = Some(([x, y, cell, cell], c));
}
}
}
x += cell;
}
if let Some(done) = cur {
runs.push(done);
}
y += cell;
}
ui.tint = Tint { key, runs };
}
for (r, c) in &ui.tint.runs {
s.push(fill(r[0], r[1], r[2], r[3], *c));
}
}
fn map_terrain(&mut self, ui: &MapUi, s: &mut Vec<Shape>) {
let (w, h) = ui.size;
let tl = ui.to_world((0.0, 0.0));
let br = ui.to_world((w, h));
let mut bpt = 1u32;
loop {
let span = 128.0 * bpt as f64;
let nx = ((br.0 - tl.0) / span).ceil() as i64 + 1;
let nz = ((br.1 - tl.1) / span).ceil() as i64 + 1;
if (nx * nz <= 20 && 128.0 * bpt as f64 * ui.scale >= 64.0) || bpt >= 64 {
break;
}
bpt *= 2;
}
let span = 128 * bpt as i32;
let (x0, z0) = ((tl.0.floor() as i32).div_euclid(span) * span, (tl.1.floor() as i32).div_euclid(span) * span);
let px = (span as f64 * ui.scale) as f32;
let mut z = z0;
let mut n = 0;
while (z as f64) < br.1 && n < 24 {
let mut x = x0;
while (x as f64) < br.0 && n < 24 {
let a = ui.to_screen(x as f64, z as f64);
s.push(Shape::Terrain(TerrainShape { rect: Rect { x: a.0, y: a.1, w: px, h: px }, x, z, blocks_per_texel: bpt }));
n += 1;
x += span;
}
z += span;
}
}
fn map_grid(&self, ui: &MapUi, s: &mut Vec<Shape>) {
let (w, h) = ui.size;
// A square of 1, 2, 5... x 10^n blocks that is at least 70 pixels wide.
let mut step = 10.0f64;
for m in [1.0, 2.0, 5.0].iter().cycle().zip(0..30).map(|(m, i)| m * 10f64.powi(1 + i / 3)) {
step = m;
if m * ui.scale >= 70.0 {
break;
}
}
let tl = ui.to_world((0.0, 0.0));
let br = ui.to_world((w, h));
let mut x = (tl.0 / step).floor() * step;
while x < br.0 {
let sx = ui.to_screen(x, 0.0).0;
s.push(fill(sx, 0.0, 1.0, h, 0x18FFFFFF));
x += step;
}
let mut z = (tl.1 / step).floor() * step;
while z < br.1 {
let sy = ui.to_screen(0.0, z).1;
s.push(fill(0.0, sy, w, 1.0, 0x18FFFFFF));
z += step;
}
// The scale bar.
let bar = (step * ui.scale) as f32;
s.push(fill(12.0, h - 16.0, bar, 2.0, WHITE));
s.push(fill(12.0, h - 20.0, 1.0, 6.0, WHITE));
s.push(fill(12.0 + bar, h - 20.0, 1.0, 6.0, WHITE));
s.push(text(distance(step), 14.0, h - 30.0, WHITE));
}
fn map_sector(&self, ui: &MapUi, s: &mut Vec<Shape>, pos: DVec3, d: &Doctrine, reach: f64) {
let Some((c, half)) = d.sector else { return };
let o = ui.to_screen(pos.x, pos.z);
let r = (reach * ui.scale) as f32;
let n = ((half * 2.0 / 0.15) as usize).clamp(4, 48);
let at = |a: f64| {
let (dx, dz) = dir_of(a);
(o.0 + dx as f32 * r, o.1 + dz as f32 * r)
};
let col = alpha(0xFFB040, 0.16);
for i in 0..n {
let a0 = c - half + half * 2.0 * i as f64 / n as f64;
let a1 = c - half + half * 2.0 * (i + 1) as f64 / n as f64;
s.push(Shape::Quad(QuadShape { corners: (pt(o.0, o.1), pt(at(a0).0, at(a0).1), pt(at(a1).0, at(a1).1), pt(o.0, o.1)), color: col }));
}
s.push(line(o, at(c - half), 1.0, alpha(0xFFB040, 0.8)));
s.push(line(o, at(c + half), 1.0, alpha(0xFFB040, 0.8)));
}
fn map_sites(&self, ui: &mut MapUi, s: &mut Vec<Shape>, labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
let (w, h) = ui.size;
for k in &self.sim.strikes.known {
let Some(e) = k.est else { continue };
let gone = matches!(k.state, SiteState::Destroyed(_));
let col = if gone { 0xFF707070 } else { ORANGE };
let chosen = ui.sel == Some(Sel::Site(k.site));
if e.fix {
let c = ui.to_screen(e.pos.x, e.pos.y);
// The circle of error: the place is somewhere in it.
ring(ui, s, c, (e.radius * ui.scale) as f32, 1.0, alpha(col & 0xFFFFFF, 0.8));
if ui.on_screen(c, 20.0) {
s.push(diamond(c.0, c.1, 5.0, col));
s.push(diamond(c.0, c.1, 2.5, 0xFF101010));
taken.push([c.0 - 6.0, c.1 - 6.0, 12.0, 12.0]);
add_lab(ui, labs, format!("ПУ {}{}", k.site, if gone { " ×" } else { "" }), c, 7.0, col, chosen);
if chosen {
s.extend(frame(c.0 - 9.0, c.1 - 9.0, 18.0, 18.0, 1.0, GREEN));
}
}
} else {
// Only a bearing: a ray from where it was seen.
let o = ui.to_screen(e.origin.x, e.origin.y);
let (dx, dz) = (e.bearing.sin(), -e.bearing.cos());
let len = (w.max(h) * 2.0) as f64;
let b = (o.0 + (dx * len) as f32, o.1 + (dz * len) as f32);
s.push(line(o, b, 1.0, alpha(0xFFA040, 0.35)));
// The ray's label near the origin when that is on the screen, else clamped to the rim.
let at = ((o.0 + dx as f32 * 40.0).clamp(30.0, w - 30.0), (o.1 + dz as f32 * 40.0).clamp(10.0, h - 10.0));
add_lab(ui, labs, format!("ПУ {}: {:.0}°", k.site, e.bearing.to_degrees()), at, 0.0, alpha(0xFFA040, 0.9), chosen);
}
}
}
fn map_tracks(&self, ui: &mut MapUi, s: &mut Vec<Shape>, labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
let now = self.sim.tick;
let pic = self.sim.picture();
// Only the classes asked for (the selected one and the unidentified always).
let shown: Vec<(&u32, &Track)> = pic.iter().filter(|(id, t)| tclass_shown(t, &ui.tclass) || ui.sel == Some(Sel::Track(**id))).collect();
for (id, t) in &shown {
let chosen = ui.sel == Some(Sel::Track(**id));
if ui.filters[F_TRAILS]
&& let Some(trail) = ui.trails.get(*id)
{
let col = alpha(0xFF6060, if chosen { 1.0 } else { 0.7 });
let mut prev: Option<(f32, f32)> = None;
for p in trail {
let c = ui.to_screen(p.0 as f64, p.1 as f64);
if let Some(a) = prev
&& (ui.on_screen(a, 0.0) || ui.on_screen(c, 0.0))
{
s.push(line(a, c, if chosen { 2.2 } else { 1.6 }, col));
}
prev = Some(c);
}
}
if !ui.filters[F_TRACKS] {
continue;
}
let forecast = t.forecast(now);
let e = t.est(now);
let c = ui.to_screen(e.x, e.z);
let m = ui.to_screen(t.pos.x, t.pos.z);
// The last measurement and the forecast from it: dashes, never drawn as a certainty.
if forecast {
s.push(line(m, c, 1.4, alpha(0xFFB0B0, 0.45)));
let r = (t.uncertainty(now) * ui.scale) as f32;
ring(ui, s, c, r.min(300.0), 1.0, alpha(0xFFB0B0, 0.5));
}
if chosen {
// Ahead along the course for 30 s, dashed.
let v = t.vel;
let ahead = ui.to_screen(e.x + v.x * 600.0, e.z + v.z * 600.0);
dashed(s, c, ahead, 1.5, alpha(0xFF8080, 0.85));
}
}
if !ui.filters[F_TRACKS] {
return;
}
let vis: Vec<(u32, &Track, (f32, f32))> = shown
.iter()
.map(|(id, t)| {
let e = t.est(now);
(**id, *t, ui.to_screen(e.x, e.z))
})
.filter(|v| ui.on_screen(v.2, 12.0))
.collect();
let pos: Vec<(f32, f32)> = vis.iter().map(|v| v.2).collect();
let solo: Vec<bool> = vis.iter().map(|v| ui.sel == Some(Sel::Track(v.0))).collect();
for grp in groups_of(&pos, &solo, TRACK_CLUSTER_R, true) {
if grp.len() > 1 {
let members: Vec<(f32, f32)> = grp.iter().map(|&k| vis[k].2).collect();
draw_cluster(ui, s, taken, &members, RED);
continue;
}
let (id, t, c) = vis[grp[0]];
let chosen = ui.sel == Some(Sel::Track(id));
let forecast = t.forecast(now);
let age = t.age(now);
// 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 - 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, 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));
}
}
}
// ------------------------------------------------------------------ the panels
fn map_panels(&mut self, ui: &mut MapUi, s: &mut Vec<Shape>, draft: &Draft) {
let (w, h) = ui.size;
let now = self.sim.tick;
let editing = ui.mode == Mode::Editor;
let u = ui.u;
// Rows and buttons grow with the window; the text can't, so only the room round it does.
let bh = (14.0 * u).round();
let lh = (11.0 * u).round();
let narrow = w < 520.0;
// The top bar: what the map shows, always said.
s.push(fill(0.0, 0.0, w, bh, PANEL));
ui.blocked.push([0.0, 0.0, w, bh]);
let tail = {
let cw = ui.to_world(ui.cursor);
format!("x {:.0} z {:.0}", cw.0, cw.1)
};
let tail_w = ui.tw(&tail);
let heads: [&str; 2] = if self.sim.truth {
["КАРТА · ИСТИНА (песочница): белые рамки — дроны, жёлтое — их цели и маршруты", "КАРТА · ИСТИНА (песочница)"]
} else {
["КАРТА · режим: данные сети РЛС", "КАРТА · сеть РЛС"]
};
let room = w - tail_w - 20.0;
let head = if ui.tw(heads[0]) <= room { heads[0] } else { heads[1] };
s.push(text(head, 6.0, (bh - 8.0) / 2.0, if self.sim.truth { YELLOW } else { GREEN }));
if ui.tw(head) + tail_w + 20.0 <= w {
s.push(text(tail, w - tail_w - 6.0, (bh - 8.0) / 2.0, GREY));
}
// The left panel: pages of layers, filters and scenarios.
let top = bh + 4.0;
let tabs_w = 14.0 + ["Слои", "Фильтр", "Сцена"].iter().map(|t| ui.tw(t) + 14.0).sum::<f32>();
let lw = (if narrow { 150.0 } else { (w * 0.2).clamp(150.0, 190.0) }).max(tabs_w + 12.0);
let mut inner: Vec<Shape> = Vec::new();
let mut y = top;
if ui.folded {
let mut bx = 4.0;
bx += draw_btn(ui, &mut inner, "Панель", Act::Panel, false, bx, y, bh);
bx += draw_btn(ui, &mut inner, "Выход (M)", Act::Close, false, bx, y, bh);
ui.blocked.push([4.0, y, bx, bh]);
s.extend(inner);
} else {
let x0 = 8.0;
let iw = lw - 8.0;
let mut bx = x0;
bx += draw_btn(ui, &mut inner, "<", Act::Panel, false, bx, y, bh);
for (i, name) in ["Слои", "Фильтр", "Сцена"].iter().enumerate() {
bx += draw_btn(ui, &mut inner, name, Act::Tab(i), ui.tab == i, bx, y, bh);
}
y += bh + 5.0;
match ui.tab {
0 => {
inner.push(text("Слои (клавиши 1–9)", x0, y, GREY));
y += lh;
for (i, name) in FILTERS.iter().enumerate() {
let on = ui.filters[i];
let r = [x0 - 2.0, y - 1.0, iw, lh];
if hovered(ui, r) {
inner.push(fill(r[0], r[1], r[2], r[3], 0x30FFFFFF));
}
inner.push(text(format!("{} {} {}", if on { "[x]" } else { "[ ]" }, i + 1, name), x0 + 1.0, y, if on { WHITE } else { GREY }));
ui.buttons.push(Btn { rect: r, act: Act::Filter(i) });
y += lh;
}
}
1 => {
let mut sc = [0usize; 4];
for x in &self.sim.sams {
sc[sys_class(x.kind)] += 1;
}
// By the estimated class; the unidentified are counted apart.
let mut tc = [0usize; 5];
let mut unknown = 0usize;
for t in self.sim.picture().values() {
match t.class.class() {
Some(c) => tc[c as usize] += 1,
None => unknown += 1,
}
}
inner.push(text("Системы по классу", x0, y, GREY));
y += lh;
let mut x = x0;
for i in 0..SYS_CLASSES.len() {
let label = format!("{} {}", SYS_CLASSES[i], sc[i]);
let bw = ui.tw(&label) + 10.0;
if x + bw > lw {
x = x0;
y += bh + 3.0;
}
x += draw_btn(ui, &mut inner, &label, Act::SysClass(i), ui.sclass[i], x, y, bh);
}
y += bh + 6.0;
inner.push(text("Цели сети по классу", x0, y, GREY));
y += lh;
x = x0;
for i in 0..TGT_CLASSES.len() {
let label = format!("{} {}", TGT_CLASSES[i], tc[i]);
let bw = ui.tw(&label) + 10.0;
if x + bw > lw {
x = x0;
y += bh + 3.0;
}
x += draw_btn(ui, &mut inner, &label, Act::TgtClass(i), ui.tclass[i], x, y, bh);
}
// The unidentified: a count, not a filter (they are always shown).
inner.push(text(format!("? {unknown} (не опознано)"), x, y + 2.0, GREY));
y += bh + 5.0;
for l in ["ЗРК ракеты · ЗАК пушки · тыл", "Д дроны · Г реактивные · К крылатые", "С сверхзвук · Б баллистика"] {
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));
y += lh;
let r = [x0 - 2.0, y, iw, bh];
inner.push(fill(r[0], r[1], r[2], r[3], if ui.name_focus { 0xE0302810 } else { 0xE0101814 }));
inner.extend(frame(r[0], r[1], r[2], r[3], 1.0, if ui.name_focus { YELLOW } else { 0x60FFFFFF }));
let shown = format!("{}{}", ui.name, if ui.name_focus { "_" } else { "" });
inner.push(text(shown, x0 + 3.0, y + (bh - 8.0) / 2.0, WHITE));
ui.buttons.push(Btn { rect: r, act: Act::NameFocus });
y += bh + 3.0;
let over = matches!(&ui.confirm, Some((Act::SaveScn, _)));
let save = if over { "Перезаписать?" } else { "Сохранить" };
draw_btn(ui, &mut inner, save, Act::SaveScn, over, x0 - 2.0, y, bh);
y += bh + 5.0;
if ui.scn.is_empty() {
inner.push(text("Сохранённых нет", x0, y, GREY));
y += lh;
} else {
inner.push(text(format!("Сохранённые: {}", ui.scn.len()), x0, y, GREY));
y += lh;
let first = ui.scn_page * SCN_ROWS;
for i in first..(first + SCN_ROWS).min(ui.scn.len()) {
let nm = ui.scn[i].clone();
let load = matches!(&ui.confirm, Some((Act::LoadScn(k), _)) if *k == i);
let r = [x0 - 2.0, y, iw, bh];
let hv = hovered(ui, r);
inner.push(fill(r[0], r[1], r[2], r[3], if load { 0xE0806020 } else if hv { 0xE0304038 } else { 0xE0182420 }));
inner.extend(frame(r[0], r[1], r[2], r[3], 1.0, if load { YELLOW } else { 0x60FFFFFF }));
let label = if load { "ещё раз".to_string() } else { nm };
inner.push(text(label, r[0] + 4.0, y + (bh - 8.0) / 2.0, WHITE));
ui.buttons.push(Btn { rect: r, act: Act::LoadScn(i) });
y += bh + 2.0;
}
if ui.scn.len() > SCN_ROWS {
let pages = ui.scn.len().div_ceil(SCN_ROWS);
let mut bx = x0 - 2.0;
bx += draw_btn(ui, &mut inner, "<", Act::ScnPage(-1), false, bx, y, bh);
bx += draw_btn(ui, &mut inner, ">", Act::ScnPage(1), false, bx, y, bh);
inner.push(text(format!("{}/{}", ui.scn_page + 1, pages), bx + 4.0, y + (bh - 8.0) / 2.0, GREY));
y += bh + 2.0;
}
}
}
}
y += 6.0;
// The mode buttons, in rows that wrap.
let mut bx = x0 - 2.0;
for (label, act, on) in [("Правка (E)", Act::Editor, editing), ("Истина (T)", Act::Truth, self.sim.truth), ("Игрок (C)", Act::Player, false), ("Выход (M)", Act::Close, false)] {
let bw = ui.tw(label) + 10.0;
if bx + bw > lw + 2.0 {
bx = x0 - 2.0;
y += bh + 3.0;
}
bx += draw_btn(ui, &mut inner, label, act, on, bx, y, bh);
}
y += bh + 4.0;
let panel = [4.0, top - 3.0, lw, y - top + 3.0];
s.push(fill(panel[0], panel[1], panel[2], panel[3], PANEL));
s.extend(inner);
ui.blocked.push(panel);
}
// The keys.
let helps: [&str; 3] = if editing {
["ЛКМ: ставить/переносить · ПКМ: убрать · R · Z · Enter · Esc", "ЛКМ ставить · ПКМ убрать · Enter · Esc", "Enter · Esc"]
} else {
["ЛКМ: выбор, тянуть: сдвиг · колесо: масштаб · T: данные · Esc", "ЛКМ выбор · колесо масштаб · T данные · Esc", "Esc"]
};
for help in helps {
let hw = ui.tw(help);
if hw + 12.0 <= w - 24.0 {
let r = [w / 2.0 - hw / 2.0 - 6.0, h - bh - 2.0, hw + 12.0, bh];
s.push(fill(r[0], r[1], r[2], r[3], PANEL));
s.push(text_c(help, w / 2.0, r[1] + (bh - 8.0) / 2.0, GREY));
ui.blocked.push(r);
break;
}
}
// The note.
if let Some((n, until)) = ui.note.clone() {
if now < until {
let nw = ui.tw(&n).min(w - 20.0);
let r = [w / 2.0 - nw / 2.0 - 8.0, top, nw + 16.0, bh + 2.0];
s.push(fill(r[0], r[1], r[2], r[3], 0xE0302010));
s.push(text_c(n, w / 2.0, top + (bh - 6.0) / 2.0, YELLOW));
ui.blocked.push(r);
} else {
ui.note = None;
}
}
// The right card.
let card_w = if narrow { 150.0 } else { (w * 0.2).clamp(170.0, 250.0) };
let cx = w - card_w - 2.0;
let mut lines: Vec<(String, u32)> = Vec::new();
let mut btns: Vec<(String, Act, bool)> = Vec::new();
if editing {
self.editor_card(ui, draft, &mut lines, &mut btns);
} else {
self.sel_card(ui, &mut lines, &mut btns);
}
// Long lines break at the card's width.
let lines = wrap_lines(ui, lines, card_w);
if !lines.is_empty() || !btns.is_empty() {
let mut y = top;
let ch = lines.len() as f32 * lh + 10.0;
// Buttons go in rows that wrap.
let mut rows: Vec<Vec<(String, Act, bool, f32)>> = vec![Vec::new()];
let mut used = 0.0;
for (l, a, on) in btns {
let bw = ui.tw(&l) + 10.0;
if used + bw > card_w - 6.0 && !rows.last().unwrap().is_empty() {
rows.push(Vec::new());
used = 0.0;
}
rows.last_mut().unwrap().push((l, a, on, bw));
used += bw + 4.0;
}
let total = ch + rows.iter().filter(|r| !r.is_empty()).count() as f32 * (bh + 4.0) + 4.0;
let panel = [cx - 3.0, y - 3.0, card_w + 2.0, total];
s.push(fill(panel[0], panel[1], panel[2], panel[3], PANEL));
ui.blocked.push(panel);
for (l, c) in &lines {
s.push(text(l.as_str(), cx, y, *c));
y += lh;
}
y += 6.0;
for row in rows {
let mut x = cx;
for (l, a, on, _) in row {
x += draw_btn(ui, s, &l, a, on, x, y, bh);
}
y += bh + 4.0;
}
}
// The editor's palette along the bottom.
if editing {
let mut kinds: Vec<(String, Pick)> = SamKind::ALL.iter().map(|k| (short_name(*k).to_string(), Pick::Sam(*k))).collect();
kinds.push(("Объект".into(), Pick::Object));
// Rows first, so the palette sits just above the help line.
let mut rows = 1;
let mut used = 6.0;
for (label, _) in &kinds {
let bw = ui.tw(label) + 10.0;
if used + bw > w - 4.0 {
rows += 1;
used = 6.0;
}
used += bw + 4.0;
}
let mut x = 6.0;
let mut y = h - bh - 4.0 - rows as f32 * (bh + 2.0);
let panel = [0.0, y - 3.0, w, rows as f32 * (bh + 2.0) + 4.0];
s.push(fill(panel[0], panel[1], panel[2], panel[3], PANEL));
ui.blocked.push(panel);
for (label, pick) in kinds {
let bw = ui.tw(&label) + 10.0;
if x + bw > w - 4.0 {
x = 6.0;
y += bh + 2.0;
}
let on = ui.pick == pick;
let r = [x, y, bw, bh];
let hv = hovered(ui, r);
s.push(fill(r[0], r[1], r[2], r[3], if on { 0xE0806020 } else if hv { 0xE0304038 } else { 0xE0182420 }));
s.extend(frame(r[0], r[1], r[2], r[3], 1.0, if on { YELLOW } else { 0x60FFFFFF }));
s.push(text(label, x + 5.0, y + (bh - 8.0) / 2.0, WHITE));
ui.buttons.push(Btn { rect: r, act: Act::Pick(pick) });
x += bw + 4.0;
}
}
}
fn editor_card(&self, ui: &MapUi, d: &Draft, lines: &mut Vec<(String, u32)>, btns: &mut Vec<(String, Act, bool)>) {
lines.push(("РАССТАНОВКА ДО БОЯ".into(), YELLOW));
lines.push(("Пока не подтвердите, ничего не строится.".into(), GREY));
let new_s = d.sams.iter().filter(|s| s.id.is_none() && !s.gone).count();
let gone_s = d.sams.iter().filter(|s| s.id.is_some() && s.gone).count();
let new_o = d.objs.iter().filter(|o| o.idx.is_none() && !o.gone).count();
let gone_o = d.objs.iter().filter(|o| o.idx.is_some() && o.gone).count();
lines.push((format!("Новых: комплексов {new_s}, объектов {new_o}"), WHITE));
lines.push((format!("Убрать: комплексов {gone_s}, объектов {gone_o}"), WHITE));
if self.draft_changed(ui) {
lines.push(("Есть неподтверждённые изменения".into(), ORANGE));
}
// The gaps: objects no system reaches.
let bare = d
.objs
.iter()
.filter(|o| !o.gone)
.filter(|o| !d.sams.iter().any(|s| !s.gone && reaches(s.kind, s.pos, o.pos)))
.count();
lines.push((if bare == 0 { "Все объекты в зоне поражения".into() } else { format!("Без прикрытия: объектов {bare} (красные)") }, if bare == 0 { GREEN } else { RED }));
lines.push(("Зелёное: зона огня, тёмное: дыра".into(), GREY));
match ui.pick {
Pick::Sam(k) => {
let reach = if k == SamKind::Optical {
format!("оптика {}", distance(sim::OPTICAL_RANGE))
} else {
format!("дальность {}", distance(k.range()))
};
lines.push((format!("В руке: {}, {reach}", k.name()), YELLOW));
}
Pick::Object => lines.push(("В руке: объект (его будут защищать)".into(), YELLOW)),
Pick::None => lines.push(("Выберите тип внизу".into(), GREY)),
}
btns.push(("Готово (Enter)".into(), Act::Confirm, false));
btns.push(("Отмена".into(), Act::Cancel, false));
btns.push(("Назад (Z)".into(), Act::Undo, false));
btns.push(("Поворот (R)".into(), Act::Rotate, false));
btns.push(("Убрать (Del)".into(), Act::Delete, false));
}
fn sel_card(&self, ui: &MapUi, lines: &mut Vec<(String, u32)>, btns: &mut Vec<(String, Act, bool)>) {
let now = self.sim.tick;
match ui.sel {
Some(Sel::Sam(id)) => {
let Some((n, sam)) = self.sim.sams.iter().enumerate().find(|(_, s)| s.id == id) else { return };
let k = sam.kind;
lines.push((format!("{} №{}", k.name(), n + 1), CYAN));
if k == SamKind::Radar {
let profile = sam.radar_profile();
lines.push((format!("Профиль РЛС: {} [{}]", profile.name, profile.id), WHITE));
lines.push((crate::battery_view::radar_profile_line(profile), GREY));
lines.push((format!("Ограничение: {}", profile.limit), GREY));
lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(now), profile.channels), GREY));
} else if sam.mode == sim::battery::SamMode::LauncherOnly {
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
}
if k.spec().sensor > 0.0 && sam.mode != sim::battery::SamMode::LauncherOnly {
lines.push((format!("Излучение РЛС: {}", if sam.radar_on { "вкл" } else { "выкл" }), WHITE));
btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on));
}
lines.push((crate::battery_view::sam_status(sam, now), WHITE));
if k == SamKind::Optical
&& let Some(r) = self.sim.optical_report(sam.id)
{
lines.push((r.line(), WHITE));
if let Some(o) = r.observation {
lines.push((format!("Последнее наблюдение: {} · {} с назад", o.class.name(), o.age(now) / 20), WHITE));
}
lines.push(("Пассивный пост: не излучает и не ведёт огневой трек".into(), GREY));
if r.target.is_some() {
lines.push(("Выбранный контакт показан линией".into(), GREY));
}
}
lines.push((format!("Исправен {:.0}% · {:.0} {:.0}", sam.health * 100.0, sam.pos.x, sam.pos.z), GREY));
if k == SamKind::Depot {
lines.push((format!("Ударные RM48U: {} · снятые 48Н6: {}", sam.ground_stock, sam.air_48n6_stock), WHITE));
lines.push((format!("Обычный БК ПВО: {} перезарядок", sam.cargo), WHITE));
if sam.ground_stock == 0 { lines.push((format!("Начальный запас: /airdef ground-stock {} <число>", n + 1), GREY)); }
} else if k == SamKind::Tzm {
lines.push((format!("Груз RM48U: {} · 48Н6: {}{}", sam.ground_stock, sam.air_48n6_stock, if sam.return_cargo { " · возврат на склад" } else { "" }), WHITE));
}
if k.armed() {
if sam.kind == SamKind::S400 { lines.push((format!("Ударных RM48U: {} (общие ячейки с ПВО){}", sam.ground_rounds, if sam.ground_return { " · ожидает вывоза" } else if sam.ground_request { " · ожидает доставки" } else { "" }), WHITE)); }
lines.push((format!("Боезапас: {} ракет, {} очередей{}", sam.missiles, sam.bursts, if sam.reloading > 0 { format!(" · перезарядка {} с", sam.reloading / 20) } else { String::new() }), WHITE));
lines.push((format!("Дальность огня: {}", distance(k.range())), WHITE));
}
if let Some(sensor) = sam.radar_up().then(|| self.sim.low_sensor(k, sam.pos, Some(sam.id))).flatten() {
lines.push((format!("Свой обзор для низкой цели: {} (зелёное кольцо)", distance(sensor.reach)), WHITE));
}
if let Some(t) = sam.gun_target.or(sam.target) {
lines.push((format!("Ведёт цель: трек №{t}"), YELLOW));
}
if k.armed() {
lines.push(("Роли (кнопки): Д дроны, Г реактивные, К крылатые, С сверхзвук, Б баллистика".into(), GREY));
lines.push((format!("Доктрина: {}", sam.doctrine.text(&self.sim.targets)), WHITE));
for c in Class::ALL {
btns.push((c.letter().to_string(), Act::Role(c.bit()), sam.roles & c.bit() != 0));
}
btns.push(("Охрана".into(), Act::Guard, matches!(ui.mode, Mode::Guard(i) if i == id)));
btns.push(("Сектор".into(), Act::Sector, matches!(ui.mode, Mode::Sector(i, _) if i == id)));
btns.push(("Без сектора".into(), Act::SectorOff, false));
btns.push((format!("Резерв {}", sam.doctrine.reserve), Act::Reserve, false));
btns.push((format!("Залп: {}", sam.doctrine.salvo.name()), Act::Salvo, false));
btns.push(("Сброс".into(), Act::ResetDoc, false));
match ui.mode {
Mode::Guard(_) => lines.push(("Нажимайте объекты на карте: охранять / не охранять. Esc — готово.".into(), YELLOW)),
Mode::Sector(_, None) => lines.push(("Сектор: щёлкните в сторону центра сектора.".into(), YELLOW)),
Mode::Sector(_, Some(_)) => lines.push(("Сектор: щёлкните, чтобы задать ширину.".into(), YELLOW)),
_ => {}
}
}
if k.mobile() {
lines.push(("ПКМ по земле — отправить на марш".into(), GREY));
}
}
Some(Sel::Object(i)) => {
let Some(p) = self.sim.targets.get(i) else { return };
lines.push((format!("Объект №{}", i + 1), WHITE));
lines.push((format!("Прочность: {:.0}% {:.0} {:.0}", self.sim.target_health.get(i).copied().unwrap_or(100.0), p.x, p.z), GREY));
let cover: Vec<String> = self.sim.sams.iter().filter(|s| s.alive() && reaches(s.kind, s.pos, *p)).map(|s| s.kind.name().to_string()).collect();
if cover.is_empty() {
lines.push(("НЕ ПРИКРЫТ: ни один комплекс не достаёт".into(), RED));
} else {
lines.push((format!("Прикрыт: {}", cover.join(", ")), GREEN));
}
let guards = self.sim.sams.iter().filter(|s| s.doctrine.guards.iter().any(|g| g.distance(*p) < 16.0)).count();
if guards > 0 {
lines.push((format!("Охраняют по доктрине: {guards}"), WHITE));
}
}
Some(Sel::Site(id)) => {
let Some(k) = self.sim.strikes.get(id) else { return };
lines.push((format!("Пусковая №{id}: {}", class_name(k.class)), ORANGE));
match (&k.est, k.state) {
(Some(e), st) => {
if e.fix {
lines.push((format!("Место известно: {:.0} {:.0} ± {}", e.pos.x, e.pos.y, distance(e.radius)), WHITE));
} else {
lines.push((format!("Места не знаем, только азимут {:.0}°", e.bearing.to_degrees()), YELLOW));
}
lines.push((format!("Точность: {}", sim::strike::accuracy(e)), WHITE));
lines.push((
match st {
SiteState::Active => "Состояние: действует".to_string(),
SiteState::Stunned(t) => format!("Состояние: подавлена ещё {} с", t.saturating_sub(now) / 20),
SiteState::Destroyed(_) => "Состояние: уничтожена".to_string(),
},
WHITE,
));
}
(None, _) => lines.push(("Данных нет".into(), GREY)),
}
lines.push((format!("Пусков замечено: {}; последний {} с назад", k.launches, now.saturating_sub(k.last) / 20), GREY));
lines.push(("Для удара нужен готовый С-400 с RM48U".into(), GREY));
if k.aimed {
lines.push(("Ракета по ней уже в полёте".into(), YELLOW));
}
if k.est.is_some_and(|e| e.fix) && !matches!(k.state, SiteState::Destroyed(_)) {
btns.push(("Нанести удар".into(), Act::Strike(id), false));
}
btns.push(("В центр".into(), Act::Centre, false));
}
Some(Sel::Track(id)) => {
let pic = self.sim.picture();
let Some(t) = pic.get(&id) else {
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));
lines.push(("пунктир — прогноз курса.".into(), GREY));
if let Some(trail) = ui.trails.get(&id) {
lines.push((format!("Точек измерений: {}", trail.len()), GREY));
}
btns.push(("В центр".into(), Act::Centre, false));
btns.push(("Следить (F)".into(), Act::Follow, ui.follow));
}
None => {
let live = self.sim.strikes.known.iter().filter(|k| !matches!(k.state, SiteState::Destroyed(_))).count();
lines.push(("Ничего не выбрано".into(), GREY));
lines.push((format!("Комплексов: {} · объектов: {}", self.sim.sams.len(), self.sim.targets.len()), WHITE));
lines.push((format!("Целей у сети: {} · известных ПУ: {live}", self.sim.picture().len()), WHITE));
if self.sim.truth {
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));
}
}
}
}
}
fn remove_dsam(d: &mut Draft, i: usize) {
if let Some(s) = d.sams.get_mut(i) {
if s.id.is_some() {
s.gone = true;
} else {
d.sams.remove(i);
}
}
}
fn remove_dobj(d: &mut Draft, i: usize) {
if let Some(o) = d.objs.get_mut(i) {
if o.idx.is_some() {
o.gone = true;
} else {
d.objs.remove(i);
}
}
}
fn sim_angle_diff(from: f64, to: f64) -> f64 {
(to - from + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
}
/// A button at (x, y) as high as `bh`; registers its click and returns the room it takes (with the gap after it).
fn draw_btn(ui: &mut MapUi, s: &mut Vec<Shape>, label: &str, act: Act, on: bool, x: f32, y: f32, bh: f32) -> f32 {
let bw = ui.tw(label) + 10.0;
let r = [x, y, bw, bh];
let hv = hovered(ui, r);
s.push(fill(r[0], r[1], r[2], r[3], if on { 0xE0306040 } else if hv { 0xE0304038 } else { 0xE0182420 }));
s.extend(frame(r[0], r[1], r[2], r[3], 1.0, if on { GREEN } else { 0x60FFFFFF }));
s.push(text(label, x + 5.0, y + (bh - 8.0) / 2.0, WHITE));
ui.buttons.push(Btn { rect: r, act });
bw + 4.0
}
fn hovered(ui: &MapUi, r: [f32; 4]) -> bool {
ui.cursor.0 >= r[0] && ui.cursor.0 <= r[0] + r[2] && ui.cursor.1 >= r[1] && ui.cursor.1 <= r[1] + r[3]
}
/// A circle of `r` pixels round `c`, only the parts on the screen.
fn ring(ui: &MapUi, s: &mut Vec<Shape>, c: (f32, f32), r: f32, w: f32, color: u32) {
if !r.is_finite() || r < 2.0 {
return;
}
// Wholly off the screen: the nearest the circle comes is |distance to the middle - r|.
let mid = (ui.size.0 / 2.0, ui.size.1 / 2.0);
let far = (c.0 - mid.0).hypot(c.1 - mid.1);
let reach = mid.0.hypot(mid.1);
if far - r > reach || r - far > reach {
return;
}
let n = ((r / 5.0) as usize).clamp(16, 120);
let mut prev = (c.0, c.1 - r);
for i in 1..=n {
let a = i as f32 / n as f32 * TAU;
let p = (c.0 + a.sin() * r, c.1 - a.cos() * r);
if ui.on_screen(p, 40.0) || ui.on_screen(prev, 40.0) {
s.push(line(prev, p, w, color));
}
prev = p;
}
}
fn dashed(s: &mut Vec<Shape>, a: (f32, f32), b: (f32, f32), w: f32, color: u32) {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = dx.hypot(dy);
let n = ((len / 8.0) as usize).min(200);
for i in (0..n).step_by(2) {
let (t0, t1) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
s.push(line((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1), w, color));
}
}
/// A coarser dash for the truth mode's routes: many drones at once, so fewer, longer dashes.
fn route_dashed(s: &mut Vec<Shape>, a: (f32, f32), b: (f32, f32), color: u32) {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = dx.hypot(dy);
let n = ((len / 24.0) as usize).clamp(2, 24);
for i in (0..n).step_by(2) {
let (t0, t1) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
s.push(line((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1), 1.2, color));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn labels(n: usize) -> (Vec<Lab>, Vec<(f32, f32)>) {
// 128 systems of a polygon in a few clumps, each with the long name that overlapped before.
let pos: Vec<(f32, f32)> = (0..n).map(|i| (300.0 + (i % 16) as f32 * 14.0 + (i / 64) as f32 * 3.0, 200.0 + (i / 16) as f32 * 13.0)).collect();
let labs = pos
.iter()
.enumerate()
.map(|(i, p)| Lab { text: "РЛС дальнего обнаружения".into(), w: 24.0 * 6.0, at: *p, r: 7.0, col: WHITE, prio: ((p.0 - 400.0).hypot(p.1 - 250.0)) + i as f32 * 0.001 })
.collect();
(labs, pos)
}
#[test]
fn labels_never_overlap_and_are_capped() {
let (labs, pos) = labels(128);
let mut taken: Vec<[f32; 4]> = pos.iter().map(|p| [p.0 - 5.0, p.1 - 5.0, 10.0, 10.0]).collect();
taken.push([0.0, 0.0, 1000.0, 14.0]);
let mut out = Vec::new();
let t = std::time::Instant::now();
place_labels((1000.0, 560.0), labs, taken.clone(), &mut out);
eprintln!("128 labels placed in {:?}, {} shown", t.elapsed(), out.len());
assert!(out.len() <= MAX_LABELS);
let rects: Vec<[f32; 4]> = out
.iter()
.map(|s| match s {
Shape::Text(t) => [t.at.x, t.at.y, 144.0, LH],
_ => unreachable!(),
})
.collect();
for (i, a) in rects.iter().enumerate() {
assert!(taken.iter().all(|m| !overlap(*a, *m)), "label {i} covers a marker or panel");
for b in &rects[i + 1..] {
assert!(!overlap(*a, *b), "two labels overlap");
}
}
}
#[test]
fn crowded_markers_merge_and_the_selected_one_stays_alone() {
let pos: Vec<(f32, f32)> = (0..128).map(|i| (300.0 + (i % 16) as f32 * 3.0, 200.0 + (i / 16) as f32 * 3.0)).collect();
let mut solo = vec![false; 128];
solo[40] = true;
let t = std::time::Instant::now();
let g = groups_of(&pos, &solo, CLUSTER_R, true);
eprintln!("128 markers grouped in {:?} into {}", t.elapsed(), g.len());
assert!(g.len() < 20 && g.iter().any(|x| x == &vec![40]));
assert_eq!(g.iter().map(Vec::len).sum::<usize>(), 128);
// Zoomed in, they stand apart.
let far: Vec<(f32, f32)> = (0..128).map(|i| (i as f32 * 30.0, 0.0)).collect();
assert_eq!(groups_of(&far, &vec![false; 128], CLUSTER_R, true).len(), 128);
}
/// A drone over the map's middle and a system that has not measured anything yet.
fn hover_fixture() -> (Sim, u32, MapUi) {
let mut sim = Sim::new(1);
sim.launch(sim::DroneKind::Shahed, DVec3::new(0.0, 64.0, 0.0), DVec3::ZERO, DVec3::ZERO, &mut sim::Out::default());
let id = sim.drones[0].id;
let sid = sim.id();
sim.sams.push(Sam::new(sid, SamKind::Buk, DVec3::new(0.0, 64.0, 500.0), 0.0));
let ui = MapUi { size: (800.0, 600.0), centre: (0.0, 0.0), scale: 1.0, cursor: (400.0, 300.0), ..Default::default() };
(sim, id, ui)
}
#[test]
fn hover_reads_the_network_and_only_the_truth_mode_adds_drones() {
let (mut sim, id, ui) = hover_fixture();
// The system holds no track: the drone is not in the network's picture and is not hoverable.
assert_eq!(hover_at(&sim, &ui), None);
sim.truth = true;
assert_eq!(hover_at(&sim, &ui), Some(Hover::Drone(id)));
// A measured track is hoverable in the honest picture too.
sim.truth = false;
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: sim::battery::Measure::Search, quality: 40, own_product: sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: false };
sim.sams[0].tracks.push(t);
assert_eq!(hover_at(&sim, &ui), Some(Hover::Track(id)));
// Away from the marker there is nothing.
let mut away = ui;
away.cursor = (20.0, 20.0);
assert_eq!(hover_at(&sim, &away), None);
}
#[test]
fn the_network_card_never_claims_a_target_and_lists_its_status_and_interception() {
let (mut sim, id, _) = hover_fixture();
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::new(0.0, 0.0, 0.5), tick: 0, own_tick: 0, source: 0, product: sim::battery::Measure::Search, quality: 40, own_product: sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: true };
sim.sams[0].tracks.push(t);
let mut lines = Vec::new();
track_lines(&sim, &t, Some(DVec3::ZERO), &mut lines);
let all: String = lines.iter().map(|l| l.0.as_str()).collect::<Vec<_>>().join(" | ");
for must in ["Трек №", "Статус:", "Источник: сеть", "Скорость:", "Дистанция:", "Огневой захват", "Перехват: ракет нет", "Держат: 1 комплексов"] {
assert!(all.contains(must), "the track card lacks {must}: {all}");
}
assert!(!all.contains("Цель:"), "the network's card claims a target: {all}");
}
#[test]
fn the_truth_card_names_the_type_aim_route_and_interception() {
let (sim, _, ui) = hover_fixture();
let mut lines = Vec::new();
truth_lines(&sim, &sim.drones[0], Some(DVec3::ZERO), &mut lines);
let all: String = lines.iter().map(|l| l.0.as_str()).collect::<Vec<_>>().join(" | ");
for must in ["ИСТИНА", "Шахед", "вне картины сети", "Цель:", "Маршрут:", "До цели:", "Перехват:"] {
assert!(all.contains(must), "the truth card lacks {must}: {all}");
}
assert_eq!(hover_at(&sim, &ui), None, "the truth-off map revealed the drone");
}
#[test]
fn the_truth_layer_draws_white_frames_and_yellow_routes() {
let (mut sim, id, mut ui) = hover_fixture();
sim.truth = true;
// The label's width is cached so the test needs no GUI host call.
let label = format!("{} №{}", sim.drones[0].kind.spec().name, id);
ui.widths.insert(label.clone(), 60.0);
let mut shapes = Vec::new();
let mut labs = Vec::new();
let mut taken = Vec::new();
map_truth(&sim, &mut ui, Some(Hover::Drone(id)), &mut shapes, &mut labs, &mut taken);
assert!(shapes.iter().any(|s| matches!(s, Shape::Fill(f) if f.color == alpha(WHITE, 0.95))), "no white frame for the true drone");
assert!(shapes.iter().any(|s| matches!(s, Shape::Quad(q) if q.color & 0xFFFFFF == 0xFFE070)), "no yellow route or aim");
assert!(labs.iter().any(|l| l.text.contains("Шахед")), "the true drone has no label");
assert!(!taken.is_empty());
}
#[test]
fn the_truth_trail_never_mixes_into_the_network_trail() {
let (mut sim, id, mut ui) = hover_fixture();
sim.tick = SAMPLE;
ui.sample(&sim);
assert!(ui.trails.is_empty() && ui.seen.is_empty(), "the network got the truth's trail");
sim.truth = true;
sim.tick = SAMPLE * 2;
ui.sample(&sim);
assert_eq!(ui.truth_trails.get(&id).map(Vec::len), Some(1));
assert!(ui.trails.is_empty(), "the truth's trail was filed as the network's");
assert!(ui.truth_seen.contains_key(&id) && !ui.seen.contains_key(&id));
}
}