//! A passive optical observation post (#136): a separate, stationary sensor that watches one //! already-known contact at a time and says what *class* of thing it is, without naming the model. //! //! It is deliberately not a radar and not a [`RadarRole`](battery::RadarRole): its spec has no //! radar reach (`sensor = 0`), so it never appears in the radar picture, never emits, and never feeds //! a fire-control track. It gets its contact either from the network's tracks (a cue) or by looking //! in its own narrow near sector; then it must hold that one contact in clear line of sight for a //! while. The result is an independent [`OpticalObservation`] with source, time, a wide [`Class`] //! and an uncertainty — not a fresh [`Track`], not a measurement added to a radar's, and not a new //! network emission. //! //! Line of sight is bounded work: one contact per post, one probe every few ticks, at most //! [`CHECKS_PER_TICK`] optical probes a tick in the whole simulation. An unknown block section or an //! unknown land column is *not* a clear line: the post keeps the old observation (which ages) and //! waits for the game to answer. Night shortens the reach and doubles the hold; there is no thermal //! mode in this first version. Weather/fog is not in the simulation API yet, so only the game's own //! day/night state and the world geometry are used here. //! //! #133 owns the shared class-estimate contract. This module keeps its own small //! [`OpticalObservation`]/[`OpticalClassEstimate`] types rather than inventing that contract silently: a //! future classifier can consume [`Sim::optical_reports`] or the observation's [`OpticalClassEstimate`] //! without this post pretending to be a [`Track`]. Nothing here reads [`DroneKind`] to classify. //! //! The catalog row currently reuses the existing `airdef:radar_truck` and `airdef:radar_panel` //! models, and the deploy item aliases the radar icon, until the optical post's own assets land. use super::*; use super::world::Sweep; /// How far the post's optics resolve a contact in clear daytime air, blocks. pub const RANGE: f64 = 300.0; /// How far a network cue may point the head; beyond `RANGE` it is only a direction to look. pub const CUE_RANGE: f64 = 800.0; /// Half-width of the local search sector, radians. const SECTOR_HALF: f64 = 70.0_f64.to_radians(); /// Ticks a contact must stay in clear sight: day, and night. const HOLD_DAY: u32 = 25; const HOLD_NIGHT: u32 = 60; /// Beyond this at night the optics resolve nothing. const NIGHT_RANGE: f64 = 150.0; /// A post probes its contact this often; the phase spreads posts over the period. const PERIOD: u64 = 5; /// Optical line-of-sight probes a tick, for the whole simulation. pub const CHECKS_PER_TICK: usize = 4; /// Nearest local candidates compared per look (one is selected). const LOCAL_CANDIDATES: usize = 8; /// Land samples a line is checked against (each may ask the game for its column). const TERRAIN_SAMPLES: usize = 6; /// A relayed track older than this is not worth turning the head for. const CUE_MAX_AGE: u64 = 120; /// Where the antenna sits over the post's base, blocks. const MAST: f64 = 2.5; /// What the post is doing, in the words the map and monitor use. #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] pub enum OpticalState { /// No contact selected. #[default] Searching, /// One contact selected, not yet held long enough (the post is "busy" with it). Holding, /// It has produced an observation and still watches the same contact. Observing, /// A contact is selected but the line is blocked or unresolved. NoSight, } impl OpticalState { pub fn name(self) -> &'static str { match self { Self::Searching => "ищет", Self::Holding => "занят", Self::Observing => "наблюдает", Self::NoSight => "нет видимости", } } } /// Why the selected contact cannot be confirmed now. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum SightBlock { /// Beyond the optics' reach (a cue may point farther than they resolve). OutOfRange, /// Too far for the reduced night reach. Night, /// The land itself rises into the line. Terrain, /// A known block stops the line (a wall, a building). Obstacle, /// Geometry along the line is not known: not a clean line of sight. UnknownGeometry, /// The sensor part has failed. Sensor, } impl SightBlock { pub fn name(self) -> &'static str { match self { Self::OutOfRange => "вне дальности", Self::Night => "ночь", Self::Terrain => "рельеф", Self::Obstacle => "препятствие", Self::UnknownGeometry => "геометрия неизвестна", Self::Sensor => "оптика отказала", } } } /// What can be observed of a contact's motion, without its true model or kind. #[derive(Clone, Copy, Debug, PartialEq)] pub struct OpticalObservable { /// Speed, blocks a tick. pub speed: f64, /// Vertical speed, blocks a tick (negative: descending). pub climb: f64, /// Distance from the post, blocks. pub range: f64, } /// A provisional wide class from observable motion alone. #133 will own the shared classifier; /// this function is the one place that provisional rule lives, and it never looks at `DroneKind`. /// Equal observable data therefore gives an equal answer for different true models. pub fn classify_optical(observable: OpticalObservable) -> Class { let speed = observable.speed; if speed >= 6.5 || (speed >= 3.0 && observable.climb <= -0.35) { Class::Ballistic } else if speed >= 3.0 { Class::Supersonic } else if speed >= 1.8 { Class::Cruise } else if speed >= 0.8 { Class::Jet } else { Class::Drone } } /// The minimum a future class-estimate consumer (#133) needs from one optical observation. /// Deliberately local: the shared contract is not invented here. #[derive(Clone, Copy, Debug, PartialEq)] pub struct OpticalClassEstimate { pub class: Class, /// 0 best, 1 worst. pub uncertainty: f64, } /// One independent optical observation: who saw it, when, what wide class, and how unsure. /// It contains no [`DroneKind`], no track hits and no fire-control state. #[derive(Clone, Copy, Debug, PartialEq)] pub struct OpticalObservation { /// The contact's track id (opaque to the player's data). pub target: u32, /// The post's unit id: the observation's source. pub source: u32, pub tick: u64, pub class: Class, /// 0 best, 1 worst. pub uncertainty: f64, pub range: f64, /// Bearing from the post, radians (as `heading_of`). pub bearing: f64, /// Ticks the contact was held before this observation. pub hold: u32, /// The observation was made at night. pub night: bool, } impl OpticalObservation { pub fn age(&self, now: u64) -> u64 { now.saturating_sub(self.tick) } /// The adapter to the future #133 contract. pub fn estimate(&self) -> OpticalClassEstimate { OpticalClassEstimate { class: self.class, uncertainty: self.uncertainty } } } /// One post's passive optics: the contact it is on, its line-of-sight state and its last observation. #[derive(Clone, Debug, Default)] pub struct Optical { target: Option, /// A player/network priority for a contact, when one is given. commanded: Option, state: OpticalState, block: Option, held: u32, observations: u32, observation: Option, /// The last clear sighting of the current contact: target, where it was, its velocity then, when. /// Only a clear line writes it; a blocked line leaves the old one to be forecast, never refreshed. seen: Option<(u32, DVec3, DVec3, u64)>, checks: u64, } impl Optical { pub fn state(&self) -> OpticalState { self.state } pub fn block(&self) -> Option { self.block } pub fn target(&self) -> Option { self.target } pub fn observation(&self) -> Option { self.observation } /// Where the current contact was last seen in clear sight, carried on by its velocity then. /// None when the post has not seen it, or its old sighting belongs to another contact. pub fn seen(&self, now: u64) -> Option<(u32, DVec3)> { let (id, pos, vel, tick) = self.seen?; (self.target == Some(id)).then(|| (id, pos + vel * now.saturating_sub(tick) as f64)) } pub fn observations(&self) -> u32 { self.observations } pub fn checks(&self) -> u64 { self.checks } fn commanded(&self) -> Option { self.commanded } fn required(&self, night: bool) -> u32 { if night { HOLD_NIGHT } else { HOLD_DAY } } fn clear_activity(&mut self) { self.target = None; self.held = 0; self.state = OpticalState::Searching; self.block = None; } fn drop_target(&mut self) { self.target = None; self.commanded = None; self.held = 0; self.observations = 0; self.seen = None; self.state = OpticalState::Searching; self.block = None; } fn select(&mut self, id: Option) { if self.target != id { self.held = 0; self.observations = 0; self.seen = None; } self.target = id; self.block = None; self.state = if id.is_some() { OpticalState::Holding } else { OpticalState::Searching }; } /// A short line for the panel and the monitor: status, class and uncertainty, never a model name. pub fn status_text(&self) -> String { match self.state { OpticalState::Searching => "ищет".into(), OpticalState::Holding => "занят: удерживает контакт".into(), OpticalState::Observing => match self.observation { Some(o) => format!("наблюдает: вероятно {} ({:.0}%)", o.class.name(), (1.0 - o.uncertainty) * 100.0), None => "наблюдает".into(), }, OpticalState::NoSight => match self.block { Some(b) => format!("нет видимости: {}", b.name()), None => "нет видимости".into(), }, } } fn report(&self, post: u32, index: usize, now: u64, night: bool) -> OpticalReport { OpticalReport { post, index, state: self.state, block: self.block, target: self.target, observation: self.observation, observations: self.observations, held: self.held, required: self.required(night), seen: self.seen(now).map(|(_, p)| p), checks: self.checks, night, } } } /// A post's state as the map, monitor and panel read it. #[derive(Clone, Copy, Debug, PartialEq)] pub struct OpticalReport { /// The unit id of the post (the source of its observations). pub post: u32, /// Its 1-based place among the systems, for the interface. pub index: usize, pub state: OpticalState, pub block: Option, pub target: Option, pub observation: Option, pub observations: u32, pub held: u32, pub required: u32, /// Where the current contact was last seen, forecast; None before the first clear sighting. pub seen: Option, pub checks: u64, pub night: bool, } impl OpticalReport { pub fn status(&self) -> &'static str { self.state.name() } /// "источник — оптический пост №N": the post itself, never a radar that cued it. pub fn source_text(&self) -> String { format!("оптический пост №{}", self.index) } pub fn line(&self) -> String { match self.state { OpticalState::Searching => "ищет".into(), OpticalState::Holding => format!("занят: удерживает контакт {}/{}", self.held, self.required), OpticalState::Observing => match self.observation { Some(o) => format!( "наблюдает: вероятно {} · {:.0}% · источник — {}", o.class.name(), (1.0 - o.uncertainty) * 100.0, self.source_text() ), None => "наблюдает".into(), }, OpticalState::NoSight => match self.block { Some(b) => format!("нет видимости: {}", b.name()), None => "нет видимости".into(), }, } } /// The observation's age, if it has one; an old observation only ages. pub fn age(&self, now: u64) -> Option { self.observation.map(|o| o.age(now)) } } impl Sim { /// Every live optical post's state, in deployment order (map/panel/monitor). pub fn optical_reports(&self) -> Vec { self.sams .iter() .enumerate() .filter(|(_, s)| s.kind == SamKind::Optical && s.alive()) .map(|(i, s)| s.optical.report(s.id, i + 1, self.tick, self.night)) .collect() } pub fn optical_report(&self, id: u32) -> Option { let (i, s) = self.sams.iter().enumerate().find(|(_, s)| s.id == id && s.kind == SamKind::Optical)?; Some(s.optical.report(s.id, i + 1, self.tick, self.night)) } /// A manual priority for the post: watch this contact, or (None) go back to cues and the local sector. /// False for a post that is not an optical post or a contact that is not in the air. pub fn assign_optical(&mut self, post: u32, target: Option) -> bool { if target.is_some_and(|id| !self.drones.iter().any(|d| d.id == id && d.alive())) { return false; } let Some(sam) = self.sams.iter_mut().find(|s| s.id == post && s.kind == SamKind::Optical && s.alive()) else { return false; }; sam.optical.commanded = target; if sam.optical.target != target { sam.optical.target = None; sam.optical.held = 0; sam.optical.observations = 0; sam.optical.state = OpticalState::Searching; sam.optical.block = None; } true } /// The post's own pick: a manual/network cue first, then its narrow near sector. At most one contact. fn optical_target(&self, i: usize, now: u64, alive: &std::collections::HashSet) -> Option { let sam = &self.sams[i]; let optical = &sam.optical; let alive = |id: u32| alive.contains(&id); if let Some(id) = optical.commanded() { if alive(id) { return Some(id); } } if let Some(id) = optical.target() { if let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive()) { if d.pos.distance(sam.pos) <= CUE_RANGE { return Some(id); } } } // The network's freshest cue: the post measures it itself, the relay only points the head. let mut cue: Option<(u64, f64, u32)> = None; for t in &sam.tracks { if t.own_tick != 0 || t.age(now) > CUE_MAX_AGE || !alive(t.id) { continue; } let dist = t.est(now).distance(sam.pos); if dist > CUE_RANGE { continue; } if cue.is_none_or(|(fresh, near, _)| t.tick > fresh || (t.tick == fresh && dist < near)) { cue = Some((t.tick, dist, t.id)); } } if let Some((_, _, id)) = cue { return Some(id); } // Nothing cued: search a narrow near sector, nearest first, comparing no more than a few. let mut local: Vec<(f64, u32)> = self .drones .iter() .filter(|d| d.alive()) .filter_map(|d| { let rel = d.pos - sam.pos; let dist = rel.length(); if dist > RANGE { return None; } let bearing = heading_of(rel); (angle_diff(sam.heading, bearing).abs() <= SECTOR_HALF).then_some((dist, d.id)) }) .collect(); local.sort_by(|a, b| a.0.total_cmp(&b.0)); local.truncate(LOCAL_CANDIDATES); local.first().map(|&(_, id)| id) } /// One tick of every optical post: age state, then spend the bounded line-of-sight budget. /// It never writes a [`Track`] and never calls the enemy-intel emission channel. pub(super) fn update_optics(&mut self, ground: &mut Ground) { let now = self.tick; let posts: Vec = self .sams .iter() .enumerate() .filter(|(_, s)| s.kind == SamKind::Optical) .map(|(i, _)| i) .collect(); if posts.is_empty() { return; } let alive: std::collections::HashSet = self.drones.iter().filter(|d| d.alive()).map(|d| d.id).collect(); for &i in &posts { let sam = &mut self.sams[i]; if !sam.alive() || sam.moving() { sam.optical.clear_activity(); continue; } if sam.part(Part::Sensor) <= 0.0 { sam.optical.clear_activity(); sam.optical.state = OpticalState::NoSight; sam.optical.block = Some(SightBlock::Sensor); continue; } if let Some(id) = sam.optical.target() { if !alive.contains(&id) { sam.optical.drop_target(); } } if let Some(id) = sam.optical.commanded() { if !alive.contains(&id) { sam.optical.commanded = None; } } // Searching posts keep their head turning; a post on a contact points at its forecast. if let Some(id) = sam.optical.target() { if let Some(d) = self.drones.iter().find(|d| d.id == id) { sam.dish = heading_of(d.pos - sam.pos); } } else { sam.dish = (sam.dish + 0.02) % TAU; } } // Fair round-robin: a crowd of posts does not starve the last ones for ever. let start = (now as usize) % posts.len(); let mut checks = 0usize; for k in 0..posts.len() { if checks >= CHECKS_PER_TICK { break; } let i = posts[(start + k) % posts.len()]; let phase = (self.sams[i].id / PARTS) as u64 % PERIOD; if now % PERIOD != phase { continue; } let Some(target) = self.optical_target(i, now, &alive) else { self.sams[i].optical.select(None); continue; }; if self.sams[i].optical.target() != Some(target) { self.sams[i].optical.select(Some(target)); } let sam = &self.sams[i]; let Some(d) = self.drones.iter().find(|d| d.id == target && d.alive()) else { continue; }; let from = sam.pos + DVec3::Y * MAST; let to = d.pos; let rel = to - from; let range = rel.length(); let bearing = heading_of(to - sam.pos); let night = self.night; let sight = line_of_sight(ground, from, to, now, range, night); checks += 1; let sam = &mut self.sams[i]; sam.optical.checks += 1; match sight { Ok(()) => { sam.optical.block = None; sam.optical.seen = Some((target, d.pos, d.vel, now)); sam.optical.held = sam.optical.held.saturating_add(1); let need = sam.optical.required(night); if sam.optical.held >= need { let samples = sam.optical.observations.saturating_add(1); let observable = OpticalObservable { speed: d.vel.length(), climb: d.vel.y, range }; let observation = OpticalObservation { target, source: sam.id, tick: now, class: classify_optical(observable), uncertainty: uncertainty(range, night, samples), range, bearing, hold: sam.optical.held, night, }; sam.optical.held = 0; sam.optical.observations = samples; sam.optical.observation = Some(observation); sam.optical.state = OpticalState::Observing; } else { sam.optical.state = if sam.optical.observation.is_some_and(|o| o.target == target) { OpticalState::Observing } else { OpticalState::Holding }; } } Err(block) => { sam.optical.held = 0; sam.optical.block = Some(block); sam.optical.state = OpticalState::NoSight; } } // The post's own state is `OpticalState`: it never claims a fire-control track. sam.state = SamState::Search; sam.optical.target = Some(target); } } } /// How unsure one observation is: range, night and the number of successful holds of the same contact. fn uncertainty(range: f64, night: bool, samples: u32) -> f64 { let r = (range / RANGE).clamp(0.0, 1.0); let base = 0.10 + 0.55 * r + if night { 0.15 } else { 0.0 }; let refine = 0.85_f64.powi(samples.saturating_sub(1).min(3) as i32); (base * refine).clamp(0.05, 0.95) } /// A bounded line of sight: land samples first, then one block probe. Unknown is never clear. fn line_of_sight(ground: &mut Ground, from: DVec3, to: DVec3, now: u64, range: f64, night: bool) -> Result<(), SightBlock> { if range > RANGE { return Err(SightBlock::OutOfRange); } if night && range > NIGHT_RANGE { return Err(SightBlock::Night); } for k in 1..TERRAIN_SAMPLES { let t = k as f64 / TERRAIN_SAMPLES as f64; let p = from + (to - from) * t; let Some(g) = ground.land(DVec3::new(p.x, 0.0, p.z)) else { return Err(SightBlock::UnknownGeometry); }; if g > p.y - 0.8 { return Err(SightBlock::Terrain); } } match ground.world.probe(from, to, now) { Sweep::Clear => Ok(()), Sweep::Hit { .. } => Err(SightBlock::Obstacle), Sweep::Unknown { .. } | Sweep::Wait { .. } => Err(SightBlock::UnknownGeometry), } } #[cfg(test)] mod tests { use super::*; use super::super::sight::Track; fn optical_at(sim: &mut Sim, x: f64, z: f64, heading: f64) -> u32 { let id = sim.id(); sim.sams.push(Sam::new(id, SamKind::Optical, DVec3::new(x, 70.0, z), heading)); id } /// Flat land at 70 and empty block sections along the line: a clear day. fn clear_ground() -> Ground { let mut ground = Ground::default(); let mut cols = Vec::new(); for x in -24..=24 { for z in -180..=24 { cols.push((x, z, 70)); } } ground.answer(cols, 0); let mut answers = Vec::new(); for x in -1..=1 { for y in 3..=7 { for z in -12..=1 { answers.push(world::SectionAnswer { sec: (x, y, z), fill: world::Fill::Empty }); } } } ground.world.answer(answers, 0); ground } fn flat_drone(sim: &mut Sim, kind: DroneKind, at: DVec3, vel: DVec3) -> u32 { sim.add_drone(kind, at, DVec3::NEG_Z, at + DVec3::NEG_Z * 100.0); let d = sim.drones.last_mut().unwrap(); d.pos = at; d.vel = vel; d.id } fn run(sim: &mut Sim, ground: &mut Ground, ticks: u64) { for _ in 0..ticks { sim.tick += 1; sim.update_optics(ground); } } // Day: one contact in the near sector is held and then classed. The source is the post itself. #[test] fn a_held_contact_gives_an_independent_class_observation() { let mut sim = Sim::new(1); let post = optical_at(&mut sim, 0.0, 0.0, 0.0); let id = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); let mut ground = clear_ground(); run(&mut sim, &mut ground, 200); let r = sim.optical_report(post).unwrap(); let obs = r.observation.expect("no class observation after a clear held contact"); assert_eq!(obs.source, post); assert_eq!(obs.target, id); assert_eq!(obs.class, Class::Drone); assert!(obs.uncertainty < 0.5, "uncertainty {}", obs.uncertainty); assert_eq!(r.state, OpticalState::Observing); // Another successful hold is another independent observation: it refines, never re-measures a relay. run(&mut sim, &mut ground, 250); let later = sim.optical_report(post).unwrap(); let again = later.observation.unwrap(); assert!(again.tick > obs.tick && later.observations > 1); assert!(again.uncertainty <= obs.uncertainty, "{} > {}", again.uncertainty, obs.uncertainty); } // Night blocks a contact beyond the reduced reach, and slows a close one: the day hold is not enough. #[test] fn night_shortens_the_reach_and_slows_the_hold() { let mut sim = Sim::new(2); sim.night = true; let post = optical_at(&mut sim, 0.0, 0.0, 0.0); flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -200.0), DVec3::new(0.5, 0.0, -0.6)); let mut ground = clear_ground(); run(&mut sim, &mut ground, 200); let r = sim.optical_report(post).unwrap(); assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.block, Some(SightBlock::Night)); assert!(r.observation.is_none()); let mut close = Sim::new(3); close.night = true; let post = optical_at(&mut close, 0.0, 0.0, 0.0); flat_drone(&mut close, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); let mut ground = clear_ground(); run(&mut close, &mut ground, HOLD_DAY as u64 * PERIOD as u64 + 10); assert!(close.optical_report(post).unwrap().observation.is_none(), "a night hold was as quick as a day one"); run(&mut close, &mut ground, (HOLD_NIGHT - HOLD_DAY) as u64 * PERIOD as u64 + 20); let r = close.optical_report(post).unwrap(); assert_eq!(r.state, OpticalState::Observing); assert!(r.observation.is_some()); } // A wall hides the contact; unknown block geometry is not a clean line of sight. #[test] fn a_wall_blocks_and_unknown_geometry_is_not_clear() { let mut sim = Sim::new(4); let post = optical_at(&mut sim, 0.0, 0.0, 0.0); flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); let mut ground = clear_ground(); ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -4), fill: world::Fill::Full }], 0); run(&mut sim, &mut ground, 200); let r = sim.optical_report(post).unwrap(); assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.block, Some(SightBlock::Obstacle)); assert!(r.observation.is_none()); // The same clear land and sky, but no answered sections: unknown, not clear. let mut unknown = Sim::new(5); let post = optical_at(&mut unknown, 0.0, 0.0, 0.0); flat_drone(&mut unknown, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); let mut ground = Ground::default(); let mut cols = Vec::new(); for x in -24..=24 { for z in -180..=24 { cols.push((x, z, 70)); } } ground.answer(cols, 0); run(&mut unknown, &mut ground, 200); let r = unknown.optical_report(post).unwrap(); assert_eq!(r.block, Some(SightBlock::UnknownGeometry)); assert!(r.observation.is_none()); } // Once the view is lost, the old observation only ages: no new observation is invented. #[test] fn an_old_observation_only_ages_after_the_view_is_lost() { let mut sim = Sim::new(6); let post = optical_at(&mut sim, 0.0, 0.0, 0.0); flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -180.0), DVec3::new(0.5, 0.0, -0.6)); let mut ground = clear_ground(); run(&mut sim, &mut ground, 300); let first = sim.optical_report(post).unwrap().observation.expect("no day observation"); let count = sim.optical_report(post).unwrap().observations; sim.night = true; run(&mut sim, &mut ground, 300); let r = sim.optical_report(post).unwrap(); let last = r.observation.expect("the old observation was thrown away"); assert_eq!(last.tick, first.tick, "a new observation was invented while the view was lost"); assert_eq!(r.observations, count); assert!(last.age(sim.tick) > 200); assert_eq!(r.state, OpticalState::NoSight); } // The class comes from observable motion, never from DroneKind: two true models with the same // pose and velocity get the same estimate and the same uncertainty. #[test] fn different_true_models_with_equal_observables_get_an_equal_estimate() { fn observe(kind: DroneKind) -> (OpticalObservation, String) { let mut sim = Sim::new(7); let post = optical_at(&mut sim, 0.0, 0.0, 0.0); flat_drone(&mut sim, kind, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.9, 0.0, -0.9)); let mut ground = clear_ground(); run(&mut sim, &mut ground, 200); let r = sim.optical_report(post).unwrap(); (r.observation.expect("no observation"), r.line()) } let (a, text_a) = observe(DroneKind::Shahed); let (b, text_b) = observe(DroneKind::Kinzhal); assert_eq!((a.class, a.uncertainty), (b.class, b.uncertainty)); assert_eq!(a.class, Class::Jet); for text in [text_a, text_b] { assert!(!text.contains("Шахед") && !text.contains("Кинжал"), "{text}"); assert!(text.contains("оптический пост"), "{text}"); } } // A network cue only points the head; it is not a measurement and does not raise confidence. #[test] fn a_network_cue_is_not_a_measurement() { let mut sim = Sim::new(8); let post = optical_at(&mut sim, 0.0, 0.0, 0.0); let id = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -500.0), DVec3::new(0.5, 0.0, -0.6)); sim.sams[0].tracks.push(Track { id, class: ClassEst::Probable(Class::Drone), pos: sim.drones[0].pos, vel: sim.drones[0].vel, tick: 0, own_tick: 0, source: u32::MAX, product: battery::Measure::Search, quality: 60, own_product: battery::Measure::Search, own_quality: 0, ttl: 100_000, hits: 3, locked: false, }); let mut ground = clear_ground(); // The cue is fresh only for its `CUE_MAX_AGE`; the contact is beyond the optics' own reach. run(&mut sim, &mut ground, 60); let r = sim.optical_report(post).unwrap(); assert_eq!(r.target, Some(id)); assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.block, Some(SightBlock::OutOfRange)); assert!(r.observation.is_none() && r.observations == 0, "a relayed track became a measurement"); } // A manual priority selects exactly one contact and is kept while it lives. #[test] fn a_manual_priority_selects_one_contact() { let mut sim = Sim::new(11); let post = optical_at(&mut sim, 0.0, 0.0, 0.0); let near = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -60.0), DVec3::new(0.5, 0.0, -0.6)); let far = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -120.0), DVec3::new(0.5, 0.0, -0.6)); assert!(sim.assign_optical(post, Some(far))); let mut ground = clear_ground(); run(&mut sim, &mut ground, 60); let r = sim.optical_report(post).unwrap(); assert_eq!(r.target, Some(far)); assert!(sim.assign_optical(post, Some(near))); run(&mut sim, &mut ground, 10); assert_eq!(sim.optical_report(post).unwrap().target, Some(near)); assert!(!sim.assign_optical(post, Some(u32::MAX)), "a dead contact cannot be assigned"); } // A failed optic is not a clear line: the state says so, and no observation is made. #[test] fn a_failed_sensor_stops_the_observation() { let mut sim = Sim::new(12); let post = optical_at(&mut sim, 0.0, 0.0, 0.0); flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); sim.sams[0].comps.0[Part::Sensor as usize] = 0.0; let mut ground = clear_ground(); run(&mut sim, &mut ground, 200); let r = sim.optical_report(post).unwrap(); assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.block, Some(SightBlock::Sensor)); assert!(r.observation.is_none()); } // Work is bounded: many posts and many contacts still spend only the per-tick probe budget. #[test] fn many_posts_and_contacts_keep_the_los_budget_bounded() { let mut sim = Sim::new(9); for i in 0..32 { optical_at(&mut sim, (i % 8) as f64 * 8.0, (i / 8) as f64 * 8.0, 0.0); } for i in 0..64 { flat_drone(&mut sim, DroneKind::Shahed, DVec3::new((i % 8) as f64, 95.0, -60.0 - (i / 8) as f64 * 4.0), DVec3::new(0.5, 0.0, -0.6)); } let mut ground = clear_ground(); sim.tick += 1; sim.update_optics(&mut ground); let checks: u64 = sim.sams.iter().filter(|s| s.kind == SamKind::Optical).map(|s| s.optical.checks()).sum(); assert!(checks > 0 && checks <= CHECKS_PER_TICK as u64, "checks {checks}"); } // The post is passive: no radar emission, no own track, no enemy emission contact. #[test] fn the_post_never_emits_or_makes_a_fire_control_track() { let mut sim = Sim::new(10); let post = optical_at(&mut sim, 0.0, 0.0, 0.0); flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); let mut ground = clear_ground(); run(&mut sim, &mut ground, 200); let sam = sim.sams.iter().find(|s| s.id == post).unwrap(); assert!(!sam.radar_up()); assert!(sam.own.is_empty()); assert!(sam.target.is_none() && sam.gun_target.is_none()); assert!(sam.tracks.is_empty()); assert!(sim.intel.contacts().is_empty(), "a passive post entered the enemy's emission picture"); } }