Files
airdef/airdef-mod/src/sim/sight.rs
T

370 lines
16 KiB
Rust

//! What a system's radar holds. Small targets come up late (the radar's reach
//! goes with the fourth root of their cross-section), low ones later still
//! (over the curve of the earth, scaled to the game's distances), and the land
//! hides what flies behind hills and woods: each system keeps its horizon, the
//! highest the land rises seen from its antenna, ray by ray round it.
//!
//! A radar does not know where everything is all the time. Its beam sweeps round
//! (a period by the kind of radar; an electronic one also revisits what it holds
//! more often), a target is measured when the beam passes it, with a chance that
//! falls with range and size, and the measurement is kept as a *track*: where it
//! was and how fast it went then, and when. Between measurements the track is
//! carried on by that velocity (a forecast, shown as one), and after three missed
//! scans it is dropped. A fire-control lock on a target the system is engaging is
//! a dedicated channel: it measures every tick while the target is in reach and in
//! sight. The network passes tracks with the age of their measurement; relaying
//! makes none of them fresher.
use super::*;
/// Rays round a radar, and blocks between the land's samples along them.
const RAYS: usize = 48;
const STEP: f64 = 16.0;
/// How far units share their tracks (the network's data links).
pub(super) const LINK: f64 = 1500.0;
/// A launcher fires on a track no older than this (ticks); a gun needs its own radar's, newer than `GUN_AGE`.
pub(super) const MISSILE_AGE: u64 = 120;
pub(super) const GUN_AGE: u64 = 3;
/// A gun takes a target its radar measured this recently (then the lock refreshes it every tick).
pub(super) const GUN_PICK_AGE: u64 = 40;
/// A track older than this is shown as a forecast.
pub const FORECAST_AGE: u64 = 20;
/// Radio horizon: `HORIZON * (√mast + √height)` blocks.
const HORIZON: f64 = 35.0;
/// Anything this near is seen (and heard), whatever hides it.
const NEAR: f64 = 24.0;
pub(super) struct Horizon {
/// Per ray, per sample out: the steepest rise of the land so far (tan of its elevation).
pub(super) rays: Vec<Vec<f32>>,
}
impl Horizon {
fn build(antenna: DVec3, reach: f64, ground: &mut Ground, now: u64) -> Self {
let steps = (reach / STEP).ceil() as usize + 1;
let rays = (0..RAYS)
.map(|r| {
let a = r as f64 / RAYS as f64 * TAU;
let dir = DVec3::new(a.sin(), 0.0, a.cos());
let mut top = f32::NEG_INFINITY;
(1..=steps)
.map(|k| {
let d = k as f64 * STEP;
// Unknown land (not loaded, not answered yet) hides nothing.
if let Some(g) = ground.at(antenna + dir * d, now) {
top = top.max(((g - antenna.y) / d) as f32);
}
top
})
.collect()
})
.collect();
Self { rays }
}
/// Whether the land between the antenna and `p` rises over the line to it.
pub(super) fn hides(&self, antenna: DVec3, p: DVec3) -> bool {
let rel = p - antenna;
let flat = (rel.x * rel.x + rel.z * rel.z).sqrt();
let k = (flat / STEP) as usize;
if k == 0 {
return false;
}
let a = rel.x.atan2(rel.z).rem_euclid(TAU);
let ray = &self.rays[(a / TAU * RAYS as f64).round() as usize % RAYS];
let top = ray[(k - 1).min(ray.len() - 1)];
((rel.y / flat) as f32) < top
}
}
/// Where a unit's radar antenna is.
pub(super) fn antenna(sam: &Sam) -> DVec3 {
sam.pos + DVec3::Y * sam.kind.spec().mast
}
/// How far a system's search radar reaches for this kind at `height` over the land:
/// its own reach (worse when damaged) for the target's size, under the radio horizon.
pub(super) fn reach(sam: &Sam, kind: DroneKind, height: f64) -> f64 {
let spec = sam.kind.spec();
if spec.sensor <= 0.0 {
return 0.0;
}
let radar = spec.sensor * sam.radar_fit() * kind.rcs().powf(0.25);
let horizon = HORIZON * (spec.mast.sqrt() + height.max(0.0).sqrt());
radar.min(horizon).max(NEAR)
}
/// How a kind's radar looks round.
pub(super) struct Scan {
/// Ticks for the beam to go round.
pub period: u32,
/// An electronic radar: what it holds it revisits at once a third of the period, between the beam's passes.
pub agile: bool,
}
impl SamKind {
pub(super) fn scan(self) -> Scan {
let (period, agile) = match self {
SamKind::Patriot => (30, true),
SamKind::S400 => (36, true),
SamKind::S500 => (24, true),
SamKind::IrisT | SamKind::Nasams => (40, true),
SamKind::Buk => (50, false),
SamKind::Tor | SamKind::Pantsir => (40, false),
SamKind::Gepard => (50, false),
// The early-warning radar: a big antenna turning slowly.
SamKind::Radar => (140, false),
_ => (40, false),
};
Scan { period, agile }
}
}
/// How well a track says what it is.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Ident {
/// One measurement: something is there.
Unknown,
/// Measured again: a drone or missile by how it flies.
Probable,
/// Held by a lock or by several measurements.
Confirmed,
}
impl Ident {
pub fn name(self) -> &'static str {
match self {
Ident::Unknown => "неопознана",
Ident::Probable => "предположительно воздушная цель",
Ident::Confirmed => "подтверждена",
}
}
}
/// What a system knows of one target: the last measurement, not the target itself.
#[derive(Clone, Copy, Debug)]
pub struct Track {
pub id: u32,
/// Where it was and how it went when last measured (blocks, blocks a tick).
pub pos: DVec3,
pub vel: DVec3,
/// When that was, and when this system's own radar last measured it (0: never, the network's only).
pub tick: u64,
pub own_tick: u64,
/// Ticks the track lives without a new measurement.
pub ttl: u32,
pub hits: u8,
/// The last own measurement came from a fire-control lock.
pub locked: bool,
}
impl Track {
pub fn age(&self, now: u64) -> u64 {
now.saturating_sub(self.tick)
}
/// Where the target should be by now, carrying the last measurement on: the forecast, not a measurement.
pub fn est(&self, now: u64) -> DVec3 {
self.pos + self.vel * self.age(now) as f64
}
pub fn forecast(&self, now: u64) -> bool {
self.age(now) > FORECAST_AGE
}
/// Own radar measured it within `age` ticks.
pub fn own_within(&self, now: u64, age: u64) -> bool {
self.own_tick > 0 && now.saturating_sub(self.own_tick) <= age
}
pub fn ident(&self) -> Ident {
match self.hits {
0 | 1 => Ident::Unknown,
2 => Ident::Probable,
_ => Ident::Confirmed,
}
}
/// How far the forecast may be off, blocks: grows with the age.
pub fn uncertainty(&self, now: u64) -> f64 {
1.0 + self.age(now) as f64 * (0.05 + self.vel.length() * 0.1)
}
}
impl Sam {
/// Ticks for its beam to go round (longer when the radar is damaged).
pub(super) fn scan_ticks(&self) -> f64 {
self.kind.scan().period as f64 / self.radar_fit().max(0.2)
}
/// Its own radar works: it has one, it is not failed and the unit is deployed.
pub fn radar_up(&self) -> bool {
self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0
}
pub fn track(&self, id: u32) -> Option<&Track> {
self.tracks.iter().find(|t| t.id == id)
}
}
/// Whether a beam that moved from `from` by `w` radians this tick passed `bearing` (all angles taken round 2π,
/// so a beam crossing north between two ticks still passes a target there).
pub(super) fn swept(bearing: f64, from: f64, w: f64) -> bool {
(bearing - from).rem_euclid(TAU) < w
}
/// A new measurement into a list of tracks (the index maps ids to places): a fresher one replaces an older.
fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
match index.get(&t.id) {
Some(&k) => {
let mine = &mut tracks[k];
if t.tick > mine.tick {
let (own_tick, locked) = (mine.own_tick, if t.own_tick > 0 { t.locked } else { mine.locked });
let hits = mine.hits.max(t.hits);
*mine = Track { own_tick: if t.own_tick > 0 { t.own_tick } else { own_tick }, hits, locked, ..t };
}
}
None => {
index.insert(t.id, tracks.len());
tracks.push(t);
}
}
}
impl Sim {
/// Rebuilds the systems' horizons in turn, then lets each radar's beam pass the sky: new measurements
/// into the tracks, old tracks out, and the network's tracks shared.
pub(super) fn update_sight(&mut self, ground: &mut Ground) {
let now = self.tick;
// One horizon every few ticks: the land answers come in over time.
if !self.sams.is_empty() && now % 3 == 0 {
let radars: Vec<usize> =
(0..self.sams.len()).filter(|&i| self.sams[i].alive() && self.sams[i].kind.spec().sensor > 0.0).collect();
if !radars.is_empty() {
let i = radars[(now / 3) as usize % radars.len()];
let sam = &self.sams[i];
let h = Horizon::build(antenna(sam), sam.kind.spec().sensor, ground, now);
self.horizons.insert(sam.id, h);
}
}
let alive: std::collections::HashSet<u32> = self.sams.iter().filter(|s| s.alive()).map(|s| s.id).collect();
self.horizons.retain(|id, _| alive.contains(id));
// Each drone's height over the land under it (or over the systems' ground, unknown).
let heights: Vec<Option<f64>> =
self.drones.iter().map(|d| ground.at(d.pos, now).map(|g| d.pos.y - g)).collect();
let drone_at: HashMap<u32, usize> = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect();
let seed = self.seed;
let mut index: HashMap<u32, usize> = HashMap::new();
for sam in &mut self.sams {
// A track of a drone that is gone is dropped (the kill is seen), so is one not renewed for its time.
sam.tracks.retain(|t| now - t.tick <= t.ttl as u64 && drone_at.get(&t.id).is_some_and(|&k| self.drones[k].alive()));
if !sam.alive() || sam.moving() {
sam.tracks.clear();
continue;
}
if !sam.radar_up() {
continue;
}
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
let spec = sam.kind.spec();
let scan = sam.kind.scan();
let period = sam.scan_ticks();
let w = TAU / period;
let (b0, ttl) = (sam.beam, ((period * 3.0) as u32).max(60));
sam.beam = (b0 + w) % TAU;
let at = antenna(sam);
let horizon = self.horizons.get(&sam.id);
let mut fresh: Vec<Track> = Vec::new();
for (d, h) in self.drones.iter().zip(&heights) {
if !d.alive() {
continue;
}
let rel = d.pos - at;
let dist = rel.length();
if dist > spec.sensor * 1.2 {
continue;
}
let locked = sam.target == Some(d.id) || sam.gun_target == Some(d.id);
let held = index.get(&d.id).map(|&k| sam.tracks[k]);
// The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round).
let in_beam = swept(rel.x.atan2(-rel.z), b0, w);
let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64);
if !(in_beam || locked || revisit) {
continue;
}
let height = h.unwrap_or(d.pos.y - sam.pos.y);
let reach = reach(sam, d.kind, height);
if dist > reach || (dist > NEAR && horizon.is_some_and(|hz| hz.hides(at, d.pos))) {
continue;
}
let key = (sam.id as u64) << 32 | d.id as u64;
// A target in the beam is measured with a chance that falls towards the edge of reach and
// with the target's stealth; one the radar already follows is lost only now and then.
let p = if locked || revisit {
0.985
} else {
((0.97 - 0.5 * (dist / reach).powi(3)) / d.kind.spec().stealth.sqrt()).clamp(0.05, 0.97)
};
if dist > NEAR && dice(seed, now, key, 0) >= p {
continue;
}
let sigma = if locked { 0.3 } else { 0.8 + dist * 0.004 };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * 0.5, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
fresh.push(Track {
id: d.id,
pos: d.pos + noise,
vel: d.vel,
tick: now,
own_tick: now,
ttl,
hits: held.map_or(1, |t| t.hits.saturating_add(1)),
locked,
});
}
for t in fresh {
merge(&mut sam.tracks, &mut index, t);
}
}
// The network: every unit gets the tracks the radars within data-link range measured themselves,
// with the time they were measured: a relayed track is never fresher than its measurement.
let shared: Vec<(u32, DVec3, f64, Vec<Track>)> = self
.sams
.iter()
.filter(|s| s.alive() && !s.moving() && s.link_range() > 0.0)
.map(|s| (s.id, s.pos, s.link_range(), s.tracks.iter().filter(|t| t.own_tick == t.tick).copied().collect::<Vec<_>>()))
.filter(|s| !s.3.is_empty())
.collect();
for sam in &mut self.sams {
if sam.alive() && !sam.moving() && sam.kind.armed() && sam.link_range() > 0.0 && !shared.is_empty() {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
let mine = sam.link_range();
for (id, at, range, tracks) in &shared {
if *id != sam.id && at.distance(sam.pos) <= range.min(mine) {
for t in tracks {
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, ..*t });
}
}
}
}
sam.seen.clear();
sam.own.clear();
for t in &sam.tracks {
sam.seen.push(t.id);
if t.own_within(now, t.ttl as u64) {
sam.own.push(t.id);
}
}
}
}
/// Whether any system's radar holds this drone (the player's radar shows only those).
pub fn tracked(&self, id: u32) -> bool {
self.sams.iter().any(|s| s.seen.contains(&id))
}
/// The freshest track of each drone any system holds: the air picture.
pub fn picture(&self) -> HashMap<u32, Track> {
let mut best: HashMap<u32, Track> = HashMap::new();
for t in self.sams.iter().flat_map(|s| s.tracks.iter()) {
if best.get(&t.id).is_none_or(|b| t.tick > b.tick) {
best.insert(t.id, *t);
}
}
best
}
}