Compare commits

..

1 Commits

Author SHA1 Message Date
Codex 9d904335b1 Ignore wrecks and silent emitters in recon reports
build / mod (push) Failing after 39s
Refs #139

Co-Authored-By: Codex <codex@openai.com>
2026-11-21 05:30:38 +00:00
10 changed files with 151 additions and 918 deletions
+1 -3
View File
@@ -193,9 +193,7 @@ API мода `render.set-lights` (до 512, плавно интерполиру
трек-прогноз оранжевый и помечен возрастом. Свои перехватчики — маленькие жёлтые квадраты. Это данные сети
РЛС, как на радаре и карте; в режиме «Истина» (`/airdef truth on`, T на карте) добавляются белые рамки
реальных дронов с их настоящим типом — отдельно от сетевых оценок, чтобы видеть расхождение. Отпустил
клавишу — метки исчезли. Метки достаются ближайшим из видимых целей: цель за камерой или за краем
экрана бюджет кадра не тратит, а заголовок показывает, сколько целей в кадре, сколько за кадром и сколько
не поместилось в бюджет. Метки проектируются через камеру последнего отрисованного кадра (`render.project`,
клавишу — метки исчезли. Метки проектируются через камеру последнего отрисованного кадра (`render.project`,
API 31 форка) и следуют за взглядом покадрово; поверх повтора, сетки J, монитора K и карты M обзор не рисуется.
**Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто
+38 -175
View File
@@ -5,22 +5,14 @@
//! network's. The player's own interceptors wear small yellow squares, as the radar shows them.
//! Letting the key go hides everything. The markers are projected through the camera the last
//! drawn frame used (`render.project`, API 31), so they sit on the world as it is drawn.
//! Visibility comes before the draw budget (#141): each layer projects at most a bounded number
//! of its nearest candidates, keeps the markers of the nearest visible ones, and counts a target
//! that leaves the frame without spending a slot.
use crate::panel::distance;
use crate::sim::{ClassEst, Sim, Track};
use glam::DVec3;
use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape};
/// The most markers of one picture (the network's, the truth's and the interceptors' each): a full
/// raid still fits the HUD's 1024 shapes — a marker is four sides and a label.
/// The most markers of one picture (the network's and the truth's each): a full raid still fits
/// the HUD's 1024 shapes — a marker is four sides and a label.
const MAX_MARKERS: usize = 64;
/// The most candidates of one layer the frame looks at: the nearest ones by distance. The draw
/// budget is spent on what is in frame, but the projection work stays bounded — a crowd the frame
/// does not hold cannot buy an unbounded scan, and what the scan never reaches counts as past the
/// budget rather than out of the frame.
const MAX_SCAN: usize = 4 * MAX_MARKERS;
/// A marker's side thickness, pixels.
const LINE: f32 = 1.0;
/// A label line's height (the HUD font with its shadow).
@@ -94,50 +86,6 @@ fn label_y(y: f32, half: f32, gui_h: f32, above: bool) -> f32 {
}
}
/// What one layer shows this frame: the markers to draw (the nearest visible candidates), how
/// many of the scanned candidates left the frame, and how many the budgets left out.
struct Pick<T> {
marks: Vec<(T, Point, f32)>,
offscreen: usize,
capped: usize,
}
/// The markers one layer gets this frame. The candidates are ordered nearest the player first and
/// at most [`MAX_SCAN`] of them are projected; a candidate the frame does not hold (behind the
/// camera or past an edge) is counted and its slot stays free for the next, so the nearest
/// [`MAX_MARKERS`] visible candidates are drawn. Work stays bounded by the scan, not the picture.
fn pick<T: Copy>(
items: impl Iterator<Item = T>,
at: impl Fn(T) -> DVec3,
half_at: impl Fn(T) -> f32,
player: DVec3,
gui: (f32, f32),
project: &impl Fn(DVec3) -> Option<Point>,
) -> Pick<T> {
let near = |a: &T, b: &T| at(*a).distance(player).total_cmp(&at(*b).distance(player));
let mut items: Vec<T> = items.collect();
let total = items.len();
// Only the nearest candidates are ever projected: no sort of the whole picture is needed.
if items.len() > MAX_SCAN {
items.select_nth_unstable_by(MAX_SCAN, near);
items.truncate(MAX_SCAN);
}
items.sort_by(near);
let mut marks = Vec::new();
let mut offscreen = 0usize;
for it in items {
if marks.len() >= MAX_MARKERS {
break;
}
let h = half_at(it);
match project(at(it)) {
Some(p) if p.x >= h && p.x <= gui.0 - h && p.y >= h && p.y <= gui.1 - h => marks.push((it, p, h)),
_ => offscreen += 1,
}
}
Pick { capped: total - marks.len() - offscreen, marks, offscreen }
}
/// The overlay's shapes for this frame. `project` is the game's `render.project` (the last drawn
/// frame's camera); a point behind the camera projects to None, a point off the screen still
/// projects past its edges — both are counted, not drawn. Drawn only while the key is held.
@@ -149,17 +97,20 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -
let pic = sim.air_picture();
let now = pic.now;
let truth = sim.truth && !pic.unaided;
// The frame's counts: what got a marker and what did not — out of the frame (behind the camera
// or past an edge) or past the budget. The header keeps the two apart (#141).
// The network's tracks, nearest first: a full raid keeps the closest markers.
let mut tracks: Vec<&Track> = pic.tracks.iter().collect();
tracks.sort_by(|a, b| a.est(now).distance(player).total_cmp(&b.est(now).distance(player)));
let mut shown = 0usize;
let mut offscreen = 0usize;
let mut capped = 0usize;
// The network's tracks: the nearest visible keep the markers; a target behind the camera no
// longer spends one, so a crowd behind cannot crowd out the target in frame.
let net = pick(pic.tracks.iter(), |t| t.est(now), |t| half(t.est(now).distance(player)), player, gui, &project);
offscreen += net.offscreen;
capped += net.capped;
for (t, p, h) in net.marks {
let mut hidden = tracks.len().saturating_sub(MAX_MARKERS);
for t in tracks.into_iter().take(MAX_MARKERS) {
let e = t.est(now);
let dist = e.distance(player);
let Some(p) = project(e) else { hidden += 1; continue };
let h = half(dist);
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
hidden += 1;
continue;
}
// Fresh: red; a forecast: orange, fading as it ages towards the track's drop (the radar's colours).
let (color, a) = if pic.unaided {
(RED, 1.0)
@@ -177,17 +128,16 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -
// with the actual type the network never shows. A tracked drone wears both: the network's
// estimate under the square, the truth over it — the offset between them is the point.
if truth {
let real = pick(
sim.drones.iter().filter(|d| d.alive()),
|d| d.pos,
|d| half(d.pos.distance(player)) + 2.0,
player,
gui,
&project,
);
offscreen += real.offscreen;
capped += real.capped;
for (d, p, h) in real.marks {
let mut drones: Vec<_> = sim.drones.iter().filter(|d| d.alive()).collect();
drones.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
hidden += drones.len().saturating_sub(MAX_MARKERS);
for d in drones.into_iter().take(MAX_MARKERS) {
let Some(p) = project(d.pos) else { hidden += 1; continue };
let h = half(d.pos.distance(player)) + 2.0;
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
hidden += 1;
continue;
}
s.extend(square_outline(p.x, p.y, h, WHITE));
let label = format!("{} {}", d.kind.spec().name, distance(d.pos.distance(player)));
s.push(text(label, p.x, label_y(p.y, h, gui.1, true), WHITE, true));
@@ -195,18 +145,24 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -
}
}
// The player's own interceptors: small yellow squares, no label — they are not targets, and
// the network never hid them (the radar has always shown them). They keep their own budget.
let own = pick(sim.missiles.iter(), |m| m.pos, |_| MISSILE_HALF, player, gui, &project);
for (_, p, h) in own.marks {
// the network never hid them (the radar has always shown them).
let mut missiles: Vec<_> = sim.missiles.iter().collect();
missiles.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
for m in missiles.into_iter().take(MAX_MARKERS) {
let Some(p) = project(m.pos) else { continue };
let h = MISSILE_HALF;
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
continue;
}
s.extend(square_outline(p.x, p.y, h, MISSILE));
}
// The mode, named as the map names it: the network's data by default, the sandbox's truth
// explicitly marked. The counts say what the frame holds, what left it, and what the budget cut.
let counts = format!("в кадре {shown}, за кадром {offscreen}, сверх бюджета {capped}");
// explicitly marked. The counts say what the frame holds and what stayed behind the camera
// or past the edges.
let head = if truth {
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · {counts}")
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре {shown}, за кадром {hidden}")
} else {
format!("ОБЗОР · данные сети РЛС · {counts}")
format!("ОБЗОР · данные сети РЛС · в кадре {shown}, за кадром {hidden}")
};
s.push(text(head, gui.0 / 2.0, 2.0, if truth { YELLOW } else { GREEN }, true));
s
@@ -245,17 +201,6 @@ mod tests {
}).collect()
}
fn head(shapes: &[Shape]) -> String {
texts(shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).expect("no header").text.clone()
}
/// `n` targets in a row right behind the camera, each nearer than anything the tests put ahead.
fn crowd_behind(sim: &mut Sim, n: u32) {
for i in 0..n {
sim.launch(DroneKind::Shahed, DVec3::new(i as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
}
}
#[test]
fn a_visible_target_gets_a_square_and_a_short_line() {
let sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
@@ -337,88 +282,6 @@ mod tests {
assert!(fills(&shapes, RED) / 4 <= MAX_MARKERS);
}
/// #141: 64 targets behind the camera and one in frame. The budget used to be spent on the
/// crowd before the visibility check, so the picture came out empty; the target in frame must
/// keep its marker, and the crowd is out of frame, not past the budget.
#[test]
fn a_crowd_behind_the_camera_leaves_the_network_budget_to_the_target_in_frame() {
let mut sim = Sim::new(1);
crowd_behind(&mut sim, 64);
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, RED), 4, "the target in frame got no marker");
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 1, за кадром 64, сверх бюджета 0");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The truth layer keeps its own budget the same way: the real drone in frame is drawn, the
/// crowd behind the camera costs no white marker.
#[test]
fn a_crowd_behind_the_camera_leaves_the_truth_budget_to_the_target_in_frame() {
let mut sim = Sim::new(1);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0));
sim.truth = true;
crowd_behind(&mut sim, 64);
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, WHITE), 4, "the drone in frame got no truth marker");
assert_eq!(fills(&shapes, RED), 0, "the network drew a track it does not hold");
assert_eq!(head(&shapes), "ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре 1, за кадром 64, сверх бюджета 0");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The interceptors keep their own budget too: a salvo behind the camera leaves the marker
/// to the one in frame.
#[test]
fn a_crowd_behind_the_camera_leaves_the_interceptor_budget_to_the_one_in_frame() {
let mut sim = Sim::new(1);
for i in 0..64 {
sim.missiles.push(crate::sim::Missile::test_at(i + 1, DVec3::new(i as f64, 64.0, -50.0), 0));
}
sim.missiles.push(crate::sim::Missile::test_at(100, DVec3::new(0.0, 64.0, 100.0), 0));
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, MISSILE), 4, "the interceptor in frame got no marker");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The header tells what really left the frame from what the draw budget cut, and the markers
/// go to the nearest of the visible: 64 behind the camera, 65 in frame.
#[test]
fn the_header_separates_the_frames_edge_from_the_draw_budget() {
let mut sim = Sim::new(1);
crowd_behind(&mut sim, 64);
for i in 0..65 {
let z = 100.0 + i as f64 * 10.0;
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, z), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
}
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
// The 64 nearest in frame are drawn; the farthest one is past the draw budget, not out of frame.
assert_eq!(fills(&shapes, RED), 4 * MAX_MARKERS);
assert!(texts(&shapes).iter().any(|t| t.text.contains("100 м")), "the nearest visible lost its marker");
assert!(!texts(&shapes).iter().any(|t| t.text.contains("740 м")), "the farthest visible took a nearer one's marker");
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 64, за кадром 64, сверх бюджета 1");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The projection work itself is bounded: with more candidates than the scan budget, only the
/// nearest `MAX_SCAN` are looked at, and the rest are counted as past the budget.
#[test]
fn the_projection_work_is_bounded_by_the_scan_budget() {
let mut sim = Sim::new(1);
for i in 0..1000 {
sim.launch(DroneKind::Shahed, DVec3::new((i % 100) as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
}
let calls = std::cell::Cell::new(0usize);
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, |p| {
calls.set(calls.get() + 1);
ahead(p)
});
assert_eq!(calls.get(), MAX_SCAN, "one layer projected more than its scan budget");
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 0, за кадром 256, сверх бюджета 744");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
#[test]
fn interceptors_wear_small_yellow_squares_without_labels() {
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
+4 -8
View File
@@ -403,7 +403,7 @@ impl Sim {
);
for l in &s.pending {
body += &format!(
"airrecobs {} {} {} {} {} {} {} {} {} {} {}\n",
"airrecobs {} {} {} {} {} {} {} {} {} {}\n",
l.truth,
coord(l.area.x),
coord(l.area.y),
@@ -414,7 +414,6 @@ impl Sim {
l.quality.name(),
l.source.name(),
l.observed,
l.wreck,
);
}
for z in &s.zones {
@@ -716,8 +715,8 @@ impl Sim {
recon_expect.push((pending, zones));
}
"airrecobs" => {
if w.len() != 11 && w.len() != 12 {
return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник, такт и признак остова"));
if w.len() != 11 {
return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник и такт"));
}
let Some(at) = recon_sortie_at else {
return Err(l.bad("наблюдение разведки", "строка без разведчика"));
@@ -740,10 +739,7 @@ impl Sim {
let quality = recon::Quality::from_key(l.word(8, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?;
let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?;
let observed = l.int(10, "такт наблюдения", 0, tick as i64)? as u64;
// An older save has no wreck flag: every pending look it holds is of a unit
// that was alive when it was seen.
let wreck = if w.len() > 11 { l.flag(11, "остов")? } else { false };
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed, wreck });
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed });
}
"airreczone" => {
if w.len() != 5 {
-3
View File
@@ -1416,8 +1416,6 @@ pub struct Sim {
/// The next blast's id (separate from `next`, so the other units' ids stay as they were).
blast_seq: u32,
next: u32,
/// The optical probe sequence: a ready post is served oldest-probe first (fair queue, #138).
optical_seq: u64,
/// The combat randomness: what is rolled for aim, hits, damage and raids. Drawing, sound and camera never
/// spend it (#85).
pub rng: Rng,
@@ -1531,7 +1529,6 @@ impl Sim {
blasts: Vec::new(),
blast_seq: 0,
next: 1,
optical_seq: 0,
rng: Rng::new(seed),
vis: Rng::new(seed ^ 0x5DEE_CE66_D1CE_4E5B),
fx_next: 0,
+38 -239
View File
@@ -16,12 +16,6 @@
//! 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.
//!
//! An automatic contact is kept while it is within the optics' own reach; after a few failed probes
//! it is let go and not picked again for a while, so a visible alternative can be tried without the
//! post thrashing between hopeless contacts. A player's explicit command is different: it waits
//! until the player changes it, and the status says so. Ready posts are served oldest-probe first,
//! so posts whose phases coincide all get their turn under the same per-tick probe budget.
//!
//! #133 owns the shared class-estimate contract. The observation stays an independent
//! [`OpticalObservation`] — never a [`Track`] — and the explicit adapter [`Sim::apply_optical_classes`]
//! feeds its [`OpticalClassEstimate`] into the class of the network's existing tracks through
@@ -54,14 +48,6 @@ const LOCAL_CANDIDATES: usize = 8;
const TERRAIN_SAMPLES: usize = 6;
/// A relayed track older than this is not worth turning the head for.
const CUE_MAX_AGE: u64 = 120;
/// Consecutive failed probes before an automatic contact is let go.
const MISS_LIMIT: u32 = 3;
/// Unknown world geometry is a wait, not a verdict: it takes longer to let a contact go.
const UNKNOWN_LIMIT: u32 = 8;
/// Ticks a contact let go after failures is not picked again (no constant switching).
const RETRY_AFTER: u64 = PERIOD * 20;
/// Let-go contacts remembered at once.
const AVOID_MAX: usize = 8;
/// What the post is doing, in the words the map and monitor use.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
@@ -206,12 +192,6 @@ pub struct Optical {
/// The freshest relayed track: a direction to look, never a measurement and never a track.
cue: Option<Track>,
checks: u64,
/// Consecutive failed probes of the current automatic contact.
misses: u32,
/// Automatic contacts let go after failures: not picked again before the tick (anti-thrash).
avoid: Vec<(u32, u64)>,
/// The probe sequence number this post was last served at: the fair queue serves the oldest.
served: Option<u64>,
}
impl Optical {
@@ -258,7 +238,6 @@ impl Optical {
fn clear_activity(&mut self) {
self.target = None;
self.held = 0;
self.misses = 0;
self.state = OpticalState::Searching;
self.block = None;
}
@@ -266,7 +245,6 @@ impl Optical {
self.target = None;
self.commanded = None;
self.held = 0;
self.misses = 0;
self.observations = 0;
self.seen = None;
self.state = OpticalState::Searching;
@@ -275,42 +253,18 @@ impl Optical {
fn select(&mut self, id: Option<u32>) {
if self.target != id {
self.held = 0;
self.misses = 0;
self.observations = 0;
self.seen = None;
// The old picture belongs to the old contact: it must not be read as this one's. Letting
// the contact go (None) or picking the same one again keeps it: it is a record and ages.
if let Some(id) = id {
if !self.observation.is_some_and(|o| o.target == id) {
self.observations = 0;
self.observation = None;
}
}
// The old picture belongs to the old contact: it must not be read as this one's.
self.observation = None;
}
self.target = id;
self.block = None;
self.state = if id.is_some() { OpticalState::Holding } else { OpticalState::Searching };
}
fn avoided(&self, id: u32, now: u64) -> bool {
self.avoid.iter().any(|&(other, until)| other == id && until > now)
}
/// Let an automatic contact go after its failed probes and keep it out of the next picks for a
/// while, so the post can try a visible alternative instead of thrashing on this one.
fn release(&mut self, id: u32, now: u64) {
self.target = None;
self.held = 0;
self.misses = 0;
self.state = OpticalState::Searching;
self.block = None;
self.seen = None;
self.avoid.retain(|&(_, until)| until > now);
self.avoid.push((id, now + RETRY_AFTER));
if self.avoid.len() > AVOID_MAX {
self.avoid.remove(0);
}
}
/// A short line for the panel and the monitor: status, class and uncertainty, never a model name.
pub fn status_text(&self) -> String {
let body = match self.state {
match self.state {
OpticalState::Searching => "ищет".into(),
OpticalState::Holding => "занят: удерживает контакт".into(),
OpticalState::Observing => match self.observation {
@@ -321,8 +275,7 @@ impl Optical {
Some(b) => format!("нет видимости: {}", b.name()),
None => "нет видимости".into(),
},
};
if self.commanded.is_some() { format!("по команде: {body}") } else { body }
}
}
fn report(&self, post: u32, index: usize, now: u64, night: bool) -> OpticalReport {
OpticalReport {
@@ -337,7 +290,6 @@ impl Optical {
required: self.required(night),
seen: self.seen(now).map(|(_, p)| p),
checks: self.checks,
commanded: self.commanded,
night,
}
}
@@ -353,8 +305,6 @@ pub struct OpticalReport {
pub state: OpticalState,
pub block: Option<SightBlock>,
pub target: Option<u32>,
/// The contact the player has pinned, if any: the post waits for it until the command changes.
pub commanded: Option<u32>,
pub observation: Option<OpticalObservation>,
pub observations: u32,
pub held: u32,
@@ -374,7 +324,7 @@ impl OpticalReport {
format!("оптический пост №{}", self.index)
}
pub fn line(&self) -> String {
let body = match self.state {
match self.state {
OpticalState::Searching => "ищет".into(),
OpticalState::Holding => format!("занят: удерживает контакт {}/{}", self.held, self.required),
OpticalState::Observing => match self.observation {
@@ -390,8 +340,7 @@ impl OpticalReport {
Some(b) => format!("нет видимости: {}", b.name()),
None => "нет видимости".into(),
},
};
if self.commanded.is_some() { format!("по команде: {body}") } else { body }
}
}
/// The observation's age, if it has one; an old observation only ages.
pub fn age(&self, now: u64) -> Option<u64> {
@@ -428,7 +377,6 @@ impl Sim {
if sam.optical.target != target {
sam.optical.target = None;
sam.optical.held = 0;
sam.optical.misses = 0;
sam.optical.observations = 0;
sam.optical.seen = None;
// An explicit switch drops the old contact's picture; it was never this contact's.
@@ -439,39 +387,33 @@ impl Sim {
true
}
/// The post's own pick: a manual command, the contact it already holds, a cue within reach or
/// the near sector, and only then a far cue that merely points the head. At most one contact.
/// 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<u32>) -> Option<u32> {
let sam = &self.sams[i];
let optical = &sam.optical;
let alive = |id: u32| alive.contains(&id);
// A player's command keeps its contact until the command changes, reachable or not.
if let Some(id) = optical.commanded() {
if alive(id) {
return Some(id);
}
}
// Keep the current contact while it is still within the optics' own reach: observations
// accumulate instead of the post hopping between equally good contacts.
if let Some(id) = optical.target()
&& alive(id)
&& !optical.avoided(id, now)
&& let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive())
&& d.pos.distance(sam.pos) <= RANGE
{
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);
}
}
}
// A cue within reach is a known contact: the head turns to it and the post measures it itself.
// The network's freshest cue: the post measures it itself, the relay only points the head.
if let Some(t) = optical.cue()
&& t.age(now) <= CUE_MAX_AGE
&& alive(t.id)
&& !optical.avoided(t.id, now)
&& t.est(now).distance(sam.pos) <= RANGE
&& t.est(now).distance(sam.pos) <= CUE_RANGE
{
return Some(t.id);
}
// Search a narrow near sector, nearest first, comparing no more than a few. The sector is
// the head's (`dish`, which turns while it searches), not the base's heading.
// Nothing cued: search a narrow near sector, nearest first, comparing no more than a few.
// The sector is the head's (`dish`, which turns while it searches), not the base's heading.
let mut local: Vec<(f64, u32)> = self
.drones
.iter()
@@ -479,7 +421,7 @@ impl Sim {
.filter_map(|d| {
let rel = d.pos - sam.pos;
let dist = rel.length();
if dist > RANGE || optical.avoided(d.id, now) {
if dist > RANGE {
return None;
}
let bearing = heading_of(rel);
@@ -488,19 +430,7 @@ impl Sim {
.collect();
local.sort_by(|a, b| a.0.total_cmp(&b.0));
local.truncate(LOCAL_CANDIDATES);
if let Some(&(_, id)) = local.first() {
return Some(id);
}
// A far cue points the head but never displaces a visible local contact above.
if let Some(t) = optical.cue()
&& t.age(now) <= CUE_MAX_AGE
&& alive(t.id)
&& !optical.avoided(t.id, now)
&& t.est(now).distance(sam.pos) <= CUE_RANGE
{
return Some(t.id);
}
None
local.first().map(|&(_, id)| id)
}
/// One tick of every optical post: age state, then spend the bounded line-of-sight budget.
@@ -551,31 +481,22 @@ impl Sim {
sam.dish = (sam.dish + 0.02) % TAU;
}
}
// A fair queue over the posts ready this tick: the post probed longest ago goes first, so
// posts whose phases coincide all get their turn. The per-tick probe budget still caps work.
let mut ready: Vec<usize> = posts
.iter()
.copied()
.filter(|&i| {
let sam = &self.sams[i];
sam.alive()
&& !sam.moving()
&& sam.part(Part::Sensor) > 0.0
&& now % PERIOD == (sam.id / PARTS) as u64 % PERIOD
})
.collect();
ready.sort_by(|&a, &b| {
self.sams[a]
.optical
.served
.cmp(&self.sams[b].optical.served)
.then(self.sams[a].id.cmp(&self.sams[b].id))
});
// 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 i in ready {
for k in 0..posts.len() {
if checks >= CHECKS_PER_TICK {
break;
}
let i = posts[(start + k) % posts.len()];
// A dead, moving or blinded post spends none of the tick's probe budget.
if !self.sams[i].alive() || self.sams[i].moving() || self.sams[i].part(Part::Sensor) <= 0.0 {
continue;
}
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;
@@ -595,14 +516,10 @@ impl Sim {
let night = self.night;
let sight = line_of_sight(ground, from, to, now, range, night);
checks += 1;
self.optical_seq = self.optical_seq.wrapping_add(1);
let seq = self.optical_seq;
let sam = &mut self.sams[i];
sam.optical.checks += 1;
sam.optical.served = Some(seq);
match sight {
Ok(()) => {
sam.optical.misses = 0;
sam.optical.block = None;
sam.optical.seen = Some((target, d.pos, d.vel, now));
sam.optical.held = sam.optical.held.saturating_add(1);
@@ -637,19 +554,11 @@ impl Sim {
sam.optical.held = 0;
sam.optical.block = Some(block);
sam.optical.state = OpticalState::NoSight;
// A player's pin waits for the player. An automatic contact that keeps failing
// is let go, then left out of the picks for a while so an alternative can win.
if sam.optical.commanded().is_none() {
sam.optical.misses = sam.optical.misses.saturating_add(1);
let limit = if block == SightBlock::UnknownGeometry { UNKNOWN_LIMIT } else { MISS_LIMIT };
if sam.optical.misses >= limit {
sam.optical.release(target, now);
}
}
}
}
// The post's own state is `OpticalState`: it never claims a fire-control track.
sam.state = SamState::Search;
sam.optical.target = Some(target);
}
self.apply_optical_classes();
}
@@ -798,8 +707,7 @@ mod tests {
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();
// Two night probes: beyond the reduced reach, before the post lets the contact go.
run(&mut sim, &mut ground, 2 * PERIOD);
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));
@@ -826,17 +734,11 @@ mod tests {
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, 2 * PERIOD);
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());
// With no alternative the post lets the blocked contact go after its failed probes; it does
// not sit on it for ever, and it may try again only after the retry delay.
run(&mut sim, &mut ground, MISS_LIMIT as u64 * PERIOD + 2);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, None);
assert_eq!(r.state, OpticalState::Searching);
// The same clear land and sky, but no answered sections: unknown, not clear.
let mut unknown = Sim::new(5);
@@ -850,15 +752,10 @@ mod tests {
}
}
ground.answer(cols, 0);
run(&mut unknown, &mut ground, 2 * PERIOD);
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());
// Waiting for the world is bounded too: the unknown line is not an eternal block.
run(&mut unknown, &mut ground, UNKNOWN_LIMIT as u64 * PERIOD + 2);
let r = unknown.optical_report(post).unwrap();
assert_eq!(r.target, None);
assert_eq!(r.state, OpticalState::Searching);
}
// Once the view is lost, the old observation only ages: no new observation is invented.
@@ -872,20 +769,13 @@ mod tests {
let first = sim.optical_report(post).unwrap().observation.expect("no day observation");
let count = sim.optical_report(post).unwrap().observations;
sim.night = true;
// The first night probes fail: the old picture is not refreshed.
run(&mut sim, &mut ground, 2 * PERIOD);
let mid = sim.optical_report(post).unwrap();
assert_eq!(mid.state, OpticalState::NoSight);
assert_eq!(mid.block, Some(SightBlock::Night));
assert_eq!(mid.observation.unwrap().tick, first.tick);
// The post lets the contact go and only rechecks it now and then; the old observation ages.
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_ne!(r.state, OpticalState::Observing);
assert_eq!(r.state, OpticalState::NoSight);
}
// The class comes from observable motion, never from DroneKind: two true models with the same
@@ -951,17 +841,12 @@ mod tests {
});
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, 2 * PERIOD);
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 far cue may point the head, but after a few failed probes the post lets it go.
run(&mut sim, &mut ground, MISS_LIMIT as u64 * PERIOD + 2);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, None);
assert_eq!(r.state, OpticalState::Searching);
}
// A searching post turns its head: a near contact outside the base heading comes into the sector.
@@ -1042,98 +927,12 @@ mod tests {
run(&mut sim, &mut ground, 60);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(far));
assert_eq!(r.commanded, Some(far));
assert!(r.line().starts_with("по команде"), "the pin is not in the status: {}", r.line());
// A manual pin is predictable: it waits even when the contact leaves the optics' reach.
sim.drones.iter_mut().find(|d| d.id == far).unwrap().pos = DVec3::new(0.0, 95.0, -500.0);
run(&mut sim, &mut ground, 60);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(far), "a manual pin was dropped when the contact left the reach");
assert_eq!(r.block, Some(SightBlock::OutOfRange));
assert!(r.line().starts_with("по команде"), "{}", r.line());
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, None));
run(&mut sim, &mut ground, 10);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.commanded, None);
assert!(!r.line().contains("по команде"), "{}", r.line());
assert!(!sim.assign_optical(post, Some(u32::MAX)), "a dead contact cannot be assigned");
}
// #138: a contact that leaves the optics' reach must not keep the post for ever. The visible
// alternative is picked instead, and it is observed once the post has had its bounded probes.
#[test]
fn an_unreachable_contact_yields_to_a_visible_alternative() {
let mut sim = Sim::new(21);
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
let gone = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -50.0), DVec3::ZERO);
let alt = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -90.0), DVec3::ZERO);
let mut ground = clear_ground();
run(&mut sim, &mut ground, 30);
assert_eq!(sim.optical_report(post).unwrap().target, Some(gone), "the near contact was not picked");
// The held contact is moved far outside the optics' own reach; the alternative stays visible.
sim.drones.iter_mut().find(|d| d.id == gone).unwrap().pos = DVec3::new(0.0, 95.0, -500.0);
run(&mut sim, &mut ground, 20);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(alt), "the post still sat on the unreachable contact");
assert_ne!(r.block, Some(SightBlock::OutOfRange));
run(&mut sim, &mut ground, 200);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(alt));
let obs = r.observation.expect("the visible alternative was never observed");
assert_eq!(obs.target, alt);
}
// #138: a contact hidden behind a wall is let go after its failed probes, not held for ever,
// and the post observes the visible alternative in the same sector.
#[test]
fn a_blocked_contact_yields_to_a_visible_alternative() {
let mut sim = Sim::new(22);
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
let hidden = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::ZERO);
let alt = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(20.0, 95.0, -100.0), DVec3::ZERO);
let mut ground = clear_ground();
// A wall on the hidden contact's line only: the alternative at x=20 clears it.
ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -6), fill: world::Fill::Full }], 0);
run(&mut sim, &mut ground, 300);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(alt), "the post never tried the visible alternative to {hidden}");
assert_eq!(r.state, OpticalState::Observing);
assert_eq!(r.observation.expect("no observation of the alternative").target, alt);
}
// #138: five posts whose phases coincide must all advance under the per-tick probe budget. The
// ready queue serves the post probed longest ago first, so the fifth is not starved for ever.
#[test]
fn five_posts_in_one_phase_each_get_their_turn() {
let mut sim = Sim::new(23);
let mut posts = Vec::new();
for k in 0..5 {
let x = k as f64 * 5.0;
let post = optical_at(&mut sim, x, 0.0, 0.0);
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(x, 95.0, -100.0), DVec3::ZERO);
posts.push(post);
// The contact consumed one id; three ordinary ids make four between deployments, so
// every post lands in the same `(id / PARTS) % PERIOD` phase.
for _ in 0..3 {
sim.id();
}
}
assert!(
posts.iter().all(|&post| (post / PARTS) as u64 % PERIOD == (posts[0] / PARTS) as u64 % PERIOD),
"the posts do not share a phase: {posts:?}"
);
let mut ground = clear_ground();
run(&mut sim, &mut ground, 500);
let counts: Vec<u32> = posts.iter().map(|&p| sim.optical_report(p).unwrap().observations).collect();
assert!(counts.iter().all(|&c| c > 0), "a post never got a probe in 500 ticks: {counts:?}");
let min = counts.iter().copied().min().unwrap();
let max = counts.iter().copied().max().unwrap();
assert!(max - min <= 1, "the phase collision starved a post: {counts:?}");
}
// A dead post neither probes nor invents an observation.
#[test]
fn a_dead_post_does_not_probe() {
+43 -250
View File
@@ -11,9 +11,7 @@
//! What is reported is memory, not truth. A hidden move, a switch-off, a re-role or a
//! kill does not rewrite a mark; only a later look can. A repeated report of the same
//! observation does not raise its confidence: confidence is the mark's age alone, and a
//! second independent look may refine the area and (for a radar) its role. A wreck a look
//! flies over is not a lead: a fresh one makes no mark, and one the picture already held is
//! radioed home as destroyed and its mark leaves the picture (#139).
//! second independent look may refine the area and (for a radar) its role.
use super::*;
use std::collections::BTreeMap;
@@ -242,8 +240,6 @@ pub(super) struct Look {
pub(super) quality: Quality,
pub(super) source: Source,
pub(super) observed: u64,
/// The unit was a wreck when it was seen: the report takes its mark out of the picture.
pub(super) wreck: bool,
}
#[derive(Clone, Debug, PartialEq)]
@@ -372,13 +368,6 @@ impl Recon {
if look.observed <= old.observed {
return;
}
// The flight saw the wreck itself: the station is off the planner's leads, and
// only the observation — never a hidden kill — takes the mark away (#139).
if look.wreck {
self.marks.remove(&id);
self.truth.remove(&id);
return;
}
let refine = look.observed.saturating_sub(old.observed) >= REFINE_GAP;
let m = self.marks.get_mut(&id).unwrap();
m.area = look.area;
@@ -394,10 +383,6 @@ impl Recon {
}
}
None => {
// A wreck is no target: a first look at one leaves no mark at all.
if look.wreck {
return;
}
if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 {
return;
}
@@ -454,36 +439,13 @@ pub(super) fn area_of(at: DVec3, cell: f64, salt: u32) -> DVec3 {
pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone, now: u64) -> Vec<Look> {
let mut out = Vec::new();
for s in sams {
if horizontal(s.pos - zone.center).length() > zone.radius {
if !s.alive() || horizontal(s.pos - zone.center).length() > zone.radius {
continue;
}
if out.len() >= MAX_OBSERVED {
break;
}
let old = state.mark_for_truth(s.id);
// The jitter is the zone's, not the unit's: the mark must not carry the unit id even
// indirectly.
let salt = (zone.center.x.round() as i64 as u32) ^ (zone.center.z.round() as i64 as u32).rotate_left(16);
// A wreck is no lead and no emitter (#139). A fresh one makes no mark; one the picture
// already held is reported as destroyed, and the report takes the old mark away. A
// hidden kill never passes through here, so it never rewrites the picture.
if !s.alive() {
if old.is_none() {
continue;
}
out.push(Look {
truth: s.id,
area: area_of(s.pos, COARSE_AREA, salt),
radius: COARSE_AREA,
category: Category::of(s.kind),
role: None,
quality: Quality::Coarse,
source: Source::Flyby,
observed: now,
wreck: true,
});
continue;
}
let refine = old.is_some_and(|m| now.saturating_sub(m.observed) >= REFINE_GAP);
let quality = if refine { Quality::Refined } else { Quality::Coarse };
let cell = if refine { REFINED_AREA } else { COARSE_AREA };
@@ -491,17 +453,17 @@ pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone,
// A launch is a public event already watched by the disclosure channel; a look that
// passes just after one can name that source too. Health, magazine and link never are.
let launched = intel.contacts().get(&s.id).is_some_and(|c| c.seen == ew::Seen::Launch && now.saturating_sub(c.tick) < 200);
// The switch is intent, not work: a radar is an emitter only while `radar_up`, a jammer
// only while the transmitter is really on the air. A silent, packed or failed one is
// just a unit the flyby saw.
let source = match s.kind {
SamKind::Ew if s.ew_up() => Source::Jamming,
SamKind::Ew if s.ew_on && !s.moving() && !s.ew_lock => Source::Jamming,
SamKind::Radar if s.radar_up() => Source::Emission,
_ if launched => Source::Launch,
_ => Source::Flyby,
};
// The role is a public radar configuration only when a close second look can tell it.
let role = (refine && s.kind == SamKind::Radar).then_some(s.radar_role);
// The jitter is the zone's, not the unit's: the mark must not carry the unit id even
// indirectly.
let salt = (zone.center.x.round() as i64 as u32) ^ (zone.center.z.round() as i64 as u32).rotate_left(16);
out.push(Look {
truth: s.id,
area: area_of(s.pos, cell, salt),
@@ -511,7 +473,6 @@ pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone,
quality,
source,
observed: now,
wreck: false,
});
}
out
@@ -834,7 +795,6 @@ mod tests {
quality: Quality::Refined,
source: before.source,
observed: before.observed,
wreck: false,
};
sim.recon.report(look, before.reported + 10_000);
let after = *sim.recon.marks.values().next().unwrap();
@@ -864,224 +824,60 @@ mod tests {
s.missiles = 0;
sim.tick += 1000;
assert_eq!(key(&sim.enemy_picture().recon), key(&before), "a hidden change rewrote the recon picture");
// A hidden kill does not take the mark away either: it is still a lead until its age
// runs out, and then it is forgotten like any other unrevisited mark (#139).
let mark = before.first().expect("the look made no mark").id;
let observed = sim.recon.marks.get(&mark).expect("the mark is gone").observed;
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark), "a hidden kill removed an active lead");
assert!(sim.recon.leads(observed + MARK_TTL - 1).iter().any(|m| m.id == mark), "a mark died before its age");
assert!(sim.recon.leads(observed + MARK_TTL).iter().all(|m| m.id != mark), "a mark outlived its age");
}
// #139: a look at a wreck is not a lead. A station destroyed before the flight arrives, with
// its switch still on, makes no mark and no lead; its report is an empty observation.
// #135: the channel matters. A silent radar is seen only by the flyby, a transmitting
// radar by its emission, a jamming station by its transmission, and a just-fired system
// by the launch the disclosure channel already watched. A hidden switch or magazine is
// not read: only what the game shows.
#[test]
fn a_fresh_wreck_makes_no_mark_and_no_lead() {
let mut sim = Sim::new(21);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
s.health = 0.0;
s.radar_on = true;
assert!(!s.radar_up(), "a destroyed radar still reported itself working");
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
assert!(sim.recon.marks.is_empty(), "a look at a fresh wreck reached the picture");
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
assert!(sim.recon.marks.is_empty(), "a fresh wreck made a mark");
assert!(sim.recon.leads(sim.tick).is_empty(), "a fresh wreck became an active lead");
}
// #139: a hidden kill leaves the mark as the picture remembers it, but a look that flies over
// the wreck reports the destruction and the mark leaves the leads. Nothing of it stays to
// aim at, and a mark no look revisits still ages out on its own.
#[test]
fn a_known_mark_leaves_the_leads_when_its_wreck_is_seen() {
let mut sim = Sim::new(22);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
let mark = sim.recon.mark_for_truth(id).expect("a live radar made no mark");
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark.id));
// A hidden kill is not an observation: the old assessment stands.
sim.sams.iter_mut().find(|s| s.id == id).unwrap().health = 0.0;
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark.id), "a hidden kill removed the mark");
// A look that sees the wreck names it as a flyby, and its report takes the mark away.
let zone = Zone { center: object, radius: ZONE_RADIUS };
let wreck = super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).expect("the wreck was not observed");
assert!(wreck.wreck);
assert_eq!(wreck.source, Source::Flyby, "a wreck named an emission");
sim.recon.report(wreck, sim.tick + REPORT_DELAY);
assert!(sim.recon.marks.is_empty(), "the wreck's report left a mark");
assert!(sim.recon.truth.iter().all(|(_, t)| *t != id), "the wreck's truth mapping stayed");
assert!(sim.recon.leads(sim.tick + REPORT_DELAY).is_empty(), "the wreck stayed an active lead");
}
// #139: a wreck observation still waiting for its report is durable. A restored flight takes
// the mark away on its tick, while an older save without the wreck flag reads as before.
#[test]
fn a_wreck_report_survives_a_save_and_removes_the_mark() {
let mut sim = Sim::new(23);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
let mark = sim.recon.mark_for_truth(id).expect("no mark to destroy");
// The radar dies unseen; a second flight looks at the wreck and its report is unsent
// when the save is taken.
sim.sams.iter_mut().find(|s| s.id == id).unwrap().health = 0.0;
sim.recon.sorties.clear();
sim.recon.checked.clear();
sim.start_recon(&[object], 0.0, 900.0, &mut Out::default());
let (_, seen_wreck) = look_once(&mut sim);
assert!(sim.recon.sorties.iter().flat_map(|s| &s.pending).any(|l| l.wreck), "the wreck was not pending");
let text = sim.air_text().expect("a wreck report is durable");
assert!(text.lines().any(|l| l.starts_with("airrecobs ") && l.ends_with(" true")), "the wreck flag was not written");
// An older save has no flag: the same look reads as a live re-observation.
let legacy: String = text
.lines()
.map(|l| {
if l.starts_with("airrecobs ") {
let mut w: Vec<&str> = l.split_whitespace().collect();
w.pop();
w.join(" ")
} else {
l.to_string()
}
})
.collect::<Vec<_>>()
.join("\n")
+ "\n";
let mut old = Sim::new(24);
old.restore_air(Sim::parse_air(&legacy).expect("an older save reads").expect("the air section is there"));
assert!(old.recon.sorties.iter().flat_map(|s| &s.pending).all(|l| !l.wreck), "an older save invented a wreck");
let mut back = Sim::new(25);
back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there"));
assert!(back.recon.marks.contains_key(&mark.id), "the save forgot the mark before its wreck report");
assert!(back.recon.sorties.iter().flat_map(|s| &s.pending).any(|l| l.wreck), "the save lost the wreck report");
back.tick = seen_wreck + REPORT_DELAY;
back.step_recon(&mut Out::default());
assert!(!back.recon.marks.contains_key(&mark.id), "a restored wreck report left the mark");
assert!(back.recon.leads(back.tick).is_empty(), "a restored wreck report stayed an active lead");
}
// #135/#139: the channel matters. A silent, packed or failed radar is only a flyby; so is a
// jammer whose transmitter is off, packed or destroyed. Only a station actually working shows
// its emission, and a wreck is no source at all. A just-fired system is still a launch the
// disclosure channel already watched. A hidden empty magazine is not read.
#[test]
fn the_source_is_the_channel_that_showed_a_working_unit() {
fn the_source_is_the_channel_that_showed_the_unit() {
let mut sim = Sim::new(8);
let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS };
let radar = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0));
let ew = sam(&mut sim, SamKind::Ew, DVec3::new(-10.0, 70.0, 0.0));
let s400 = sam(&mut sim, SamKind::S400, DVec3::new(0.0, 70.0, 10.0));
let source = |sim: &Sim, id: u32| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).map(|l| l.source);
fn unit(sim: &mut Sim, id: u32) -> &mut Sam {
sim.sams.iter_mut().find(|s| s.id == id).unwrap()
}
// Working: the radar emits and the jammer transmits.
assert_eq!(source(&sim, radar), Some(Source::Emission));
unit(&mut sim, ew).ew_on = true;
assert_eq!(source(&sim, ew), Some(Source::Jamming));
// Off: the switch is intent, not work.
unit(&mut sim, radar).radar_on = false;
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a silent radar was read as emitting");
unit(&mut sim, radar).radar_on = true;
unit(&mut sim, ew).ew_on = false;
assert_eq!(source(&sim, ew), Some(Source::Flyby), "a silent jammer was read as transmitting");
unit(&mut sim, ew).ew_on = true;
// Packed for a march: neither is on the air, whatever the switch says.
unit(&mut sim, radar).state = SamState::Moving;
unit(&mut sim, ew).state = SamState::Moving;
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a radar on the march was read as emitting");
assert_eq!(source(&sim, ew), Some(Source::Flyby), "a jammer on the march was read as transmitting");
unit(&mut sim, radar).state = SamState::Search;
unit(&mut sim, ew).state = SamState::Search;
// Cooling down: a jammer locked by heat is not transmitting either.
unit(&mut sim, ew).ew_lock = true;
assert_eq!(source(&sim, ew), Some(Source::Flyby), "an overheated jammer was read as transmitting");
unit(&mut sim, ew).ew_lock = false;
// Damage: a failed sensor is no radar; a damaged hull with a working sensor still emits.
unit(&mut sim, radar).comps.0[Part::Sensor as usize] = 0.0;
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a radar with a failed sensor was read as emitting");
unit(&mut sim, radar).comps.0[Part::Sensor as usize] = 1.0;
unit(&mut sim, radar).health = 0.5;
assert_eq!(source(&sim, radar), Some(Source::Emission), "a damaged but working radar lost its emission");
// Destroyed: a wreck is no source and makes no lead at all.
unit(&mut sim, radar).health = 0.0;
unit(&mut sim, ew).health = 0.0;
assert_eq!(source(&sim, radar), None, "a wreck was reported as a lead");
assert_eq!(source(&sim, ew), None, "a wrecked jammer was reported as transmitting");
sim.recon.checked.clear();
let source = |sim: &Sim, id: u32| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).unwrap().source;
sim.sams.iter_mut().find(|s| s.id == radar).unwrap().radar_on = false;
assert_eq!(source(&sim, radar), Source::Flyby, "a silent radar was read as emitting");
sim.sams.iter_mut().find(|s| s.id == radar).unwrap().radar_on = true;
assert_eq!(source(&sim, radar), Source::Emission);
sim.sams.iter_mut().find(|s| s.id == radar).unwrap().state = super::super::SamState::Moving;
assert_eq!(source(&sim, radar), Source::Flyby, "a moving radar is not emitting");
assert_eq!(source(&sim, ew), Source::Flyby, "a silent jammer was read as transmitting");
sim.sams.iter_mut().find(|s| s.id == ew).unwrap().ew_on = true;
assert_eq!(source(&sim, ew), Source::Jamming);
sim.sams.iter_mut().find(|s| s.id == ew).unwrap().ew_lock = true;
assert_eq!(source(&sim, ew), Source::Flyby, "an overheated jammer is not transmitting");
sim.intel.observe(sim.sams.iter().find(|s| s.id == s400).unwrap(), sim.tick, ew::Seen::Launch);
assert_eq!(source(&sim, s400), Some(Source::Launch));
assert_eq!(source(&sim, s400), Source::Launch);
// A hidden empty magazine does not change the source.
sim.sams.iter_mut().find(|s| s.id == s400).unwrap().missiles = 0;
assert_eq!(source(&sim, s400), Some(Source::Launch));
assert_eq!(source(&sim, s400), Source::Launch);
}
// #139: a station the picture already holds, seen off, packed or damaged, stays a flyby
// contact: the switch never turns its mark into an emitter, and a working station seen
// again still names its emission.
#[test]
fn a_known_station_that_stops_working_stays_a_flyby_contact() {
let mut sim = Sim::new(26);
let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS };
let id = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0));
let seen = |sim: &Sim, now: u64| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, now).into_iter().find(|l| l.truth == id).expect("the radar was not observed");
fn wrecks_do_not_create_targets_in_a_new_flyby_report() {
let mut sim = Sim::new(8);
let object = DVec3::new(0.0, 70.0, 0.0);
sam(&mut sim, SamKind::Radar, object);
sam(&mut sim, SamKind::Ew, object + DVec3::X * 10.0);
sim.sams[0].radar_on = true;
sim.sams[1].ew_on = true;
for s in &mut sim.sams { s.health = 0.0; }
sam(&mut sim, SamKind::Gepard, object + DVec3::X * 20.0);
let first = seen(&sim, 100);
assert_eq!(first.source, Source::Emission);
sim.recon.report(first, 100);
let mark = sim.recon.mark_for_truth(id).expect("the working look made no mark");
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, seen) = look_once(&mut sim);
sim.tick = seen + REPORT_DELAY;
sim.step_recon(&mut Out::default());
// Off, then packed for a march, then with a failed sensor: the contact stays, the
// channel is the flyby alone.
for (change, now) in [(0, 200), (1, 900), (2, 1600)] {
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
match change {
0 => s.radar_on = false,
1 => {
s.radar_on = true;
s.state = SamState::Moving;
}
_ => {
s.state = SamState::Search;
s.comps.0[Part::Sensor as usize] = 0.0;
}
}
let look = seen(&sim, now);
assert!(!look.wreck, "case {change}: a working station was read as a wreck");
assert_eq!(look.source, Source::Flyby, "case {change}: the switch was read as work");
sim.recon.report(look, now);
assert!(sim.recon.marks.contains_key(&mark.id), "case {change}: the contact was lost");
}
// Working again: the refined look names the emission.
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
s.comps.0[Part::Sensor as usize] = 1.0;
let look = seen(&sim, 2300);
assert_eq!(look.source, Source::Emission);
assert_eq!(look.quality, Quality::Refined);
sim.recon.report(look, 2300);
assert_eq!(sim.recon.mark_for_truth(id).unwrap().source, Source::Emission);
let leads = sim.recon.leads(sim.tick);
assert_eq!(leads.len(), 1);
assert_eq!(leads[0].category, Category::of(SamKind::Gepard));
}
// #135: the planner's order is the observed public role, freshness and quality, not the
@@ -1272,7 +1068,6 @@ mod tests {
quality: Quality::Coarse,
source: Source::Flyby,
observed: 100,
wreck: false,
};
r.report(coarse_look, 200);
let coarse = r.mark();
@@ -1301,7 +1096,6 @@ mod tests {
quality: Quality::Refined,
source: Source::Emission,
observed: 1000,
wreck: false,
};
sim.recon.report(look(1, battery::RadarRole::Search), 1000);
sim.recon.report(look(2, battery::RadarRole::Engagement), 1000);
@@ -1348,7 +1142,6 @@ mod tests {
quality: Quality::Coarse,
source: Source::Flyby,
observed: 100,
wreck: false,
},
100,
);
+25 -204
View File
@@ -30,9 +30,6 @@ pub struct SamKey {
spent_cells: u8,
cap_cell: u8,
cap_open: f32,
/// A discrete transition or a frame of a tube cover's opening rather than a pose sample (#142):
/// decimation keeps it, within its own budget.
event: bool,
}
impl SamKey {
@@ -54,7 +51,6 @@ impl SamKey {
spent_cells: sam.spent_cells,
cap_cell: sam.cap_cell,
cap_open: sam.cap_open,
event: false,
}
}
/// The same pose (to within what could be seen).
@@ -72,18 +68,6 @@ impl SamKey {
&& self.spent_cells == o.spent_cells && self.cap_cell == o.cap_cell
&& near(self.cap_open, o.cap_open, 0.001)
}
/// The states a replay reads as facts rather than as interpolated poses: which round is spent,
/// which tube the cover opens, whether the radar emits, and the mount's configuration.
fn discrete(&self) -> (battery::SamMode, battery::RadarRole, bool, u8, u8) {
(self.mode, self.radar_role, self.radar_on, self.spent_cells, self.cap_cell)
}
/// The tube cover's stage: shut, on its way open, or wide.
fn cover(&self) -> u8 { cover_stage(self.cap_open) }
}
/// The cover's stage an opening (`launch::OPEN_TICKS` long) passes through.
fn cover_stage(open: f32) -> u8 {
if open <= 0.0 { 0 } else if open < 1.0 { 1 } else { 2 }
}
/// A system through a recording: its poses (a new one only when it changed, with the
@@ -131,7 +115,6 @@ impl SamTrack {
spent_cells: a.spent_cells,
cap_cell: a.cap_cell,
cap_open: if a.cap_cell == b.cap_cell && a.spent_cells == b.spent_cells { l(a.cap_open, b.cap_open) } else { a.cap_open },
event: false,
})
}
/// The system as it stood at `t`, as a ghost to draw with the ids from `id`.
@@ -174,7 +157,6 @@ impl Recording {
sam_tracks: Vec::new(),
sam_index: HashMap::new(),
sam_keys: 0,
sam_events: 0,
sam_step: STEP,
ticks: Vec::new(),
times: Vec::new(),
@@ -208,10 +190,6 @@ const LONGEST: u32 = 12_000;
const KEPT: usize = 3;
/// SAM poses share a fixed memory budget; under pressure old poses are thinned and new ones slow down.
const MAX_SAM_KEYS: usize = 32_768;
/// Discrete transitions and cover-opening frames have their own small budget (#142): they are
/// facts a replay must not lose, but they may not spend the pose budget either. When it runs out
/// the oldest stop being critical (the newest are kept) and decimation may thin them as poses.
const MAX_SAM_EVENTS: usize = 4_096;
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum What {
@@ -409,8 +387,6 @@ pub struct Recording {
pub sam_tracks: Vec<SamTrack>,
sam_index: HashMap<u32, usize>,
sam_keys: usize,
/// How many of `sam_keys` are critical transitions (#142).
sam_events: usize,
sam_step: u32,
/// The game's tick number as sampled with the clock: (recording tick, game tick). A replay
/// shows the world's blocks as of this time.
@@ -621,70 +597,37 @@ impl Recording {
sam_tracks: Vec::new(),
sam_index: HashMap::new(),
sam_keys: 0,
sam_events: 0,
sam_step: STEP,
ticks: Vec::new(),
times: Vec::new(),
quiet: 0,
}
}
/// Halves each track's poses, keeping its critical transitions, its first and its last key (#142).
fn thin_sam_poses(&mut self) {
fn thin_sam_tracks(&mut self) {
for track in &mut self.sam_tracks {
let len = track.keys.len();
let mut kept = 0;
let mut poses = 0;
for read in 0..len {
let key = track.keys[read];
let keep = if key.event {
true
} else {
poses += 1;
poses % 2 == 1 || read + 1 == len
};
if keep {
track.keys[kept] = key;
kept += 1;
}
for read in (0..len).step_by(2) {
track.keys[kept] = track.keys[read];
kept += 1;
}
if len % 2 == 0 && len > 0 {
track.keys[kept] = track.keys[len - 1];
kept += 1;
}
track.keys.truncate(kept);
track.keys.shrink_to_fit();
}
self.count_sam_keys();
self.sam_step = self.sam_step.saturating_mul(2).min(LONGEST);
}
/// The transitions' budget ran out: the oldest stop being critical, so decimation may thin them
/// as poses. The newest transitions, which a replay is watched closest for, are kept (#142).
fn thin_sam_events(&mut self) {
let mut over = self.sam_events.saturating_sub(MAX_SAM_EVENTS);
while over > 0 {
let mut demoted = 0;
for track in &mut self.sam_tracks {
if over == 0 { break; }
if let Some(key) = track.keys.iter_mut().find(|key| key.event) {
key.event = false;
over -= 1;
demoted += 1;
}
}
if demoted == 0 { break; }
}
self.count_sam_keys();
}
fn count_sam_keys(&mut self) {
self.sam_keys = self.sam_tracks.iter().map(|track| track.keys.len()).sum();
self.sam_events = self.sam_tracks.iter().map(|track| track.keys.iter().filter(|key| key.event).count()).sum();
self.sam_step = self.sam_step.saturating_mul(2).min(LONGEST);
}
/// Notes the systems' poses at the recording's tick `now`: a pose only when it changed, with
/// the pose it held marked before it so a replay doesn't glide through the stillness.
///
/// Poses are sampled on the adaptive `sam_step` grid under its own budget, but the cover's
/// opening (`launch::OPEN_TICKS`, shorter than a decimated interval) and the discrete
/// transitions — a round ejected, a tube cancelled, the radar switched, the mount's
/// configuration — are facts: they are kept on the tick they happen, in their own budget (#142).
fn note_sams(&mut self, sams: &[Sam], now: u32) {
let pose_due = now % self.sam_step == 0;
if now % self.sam_step != 0 {
return;
}
for sam in sams {
let key = SamKey::of(sam, self.origin, now);
let i = *self.sam_index.entry(sam.id).or_insert_with(|| {
@@ -693,41 +636,20 @@ impl Recording {
});
let track = &mut self.sam_tracks[i];
let before = track.keys.len();
let Some(last) = track.keys.last().copied() else {
track.keys.push(key);
self.sam_keys += 1;
continue;
};
if last.same(&key) {
continue;
}
// The cover's opening is short: its first frame only differs from the shut pose by a
// fraction, so the stage's start is backdated to the tick it began (#142).
if last.cover() == 0 && key.cover() == 1 && now > last.at + 1 {
track.keys.push(SamKey { at: now - 1, cap_open: 0.0, event: true, ..key });
}
let transitioning = last.discrete() != key.discrete() || last.cover() != key.cover();
// Every frame of the cover's own movement is kept, so the stage's six ticks survive intact.
let moving = key.cover() == 1 && last.cap_open != key.cap_open;
if transitioning || moving {
let mut event = key;
event.event = true;
track.keys.push(event);
} else if pose_due {
if last.at + self.sam_step < now {
track.keys.push(SamKey { at: now - self.sam_step, event: false, ..last });
match track.keys.last().copied() {
None => track.keys.push(key),
Some(last) if last.same(&key) => {}
Some(last) => {
if last.at + self.sam_step < now {
track.keys.push(SamKey { at: now - self.sam_step, ..last });
}
track.keys.push(key);
}
track.keys.push(key);
}
let added = track.keys.len() - before;
self.sam_keys += added;
self.sam_events += track.keys[before..].iter().filter(|key| key.event).count();
self.sam_keys += track.keys.len() - before;
}
if self.sam_events > MAX_SAM_EVENTS {
self.thin_sam_events();
}
if self.sam_keys.saturating_sub(self.sam_events) > MAX_SAM_KEYS {
self.thin_sam_poses();
if self.sam_keys > MAX_SAM_KEYS {
self.thin_sam_tracks();
}
}
/// Actual launch, if observed during this recording. Missing is not proof of no launch:
@@ -952,10 +874,9 @@ impl Sim {
}
r.ticks.push((r.len, self.engine_tick));
}
// Poses share the adaptive grid inside; the discrete transitions and the cover's short
// opening must be seen on the tick they happen, whatever the grid (#142).
r.note_sams(&self.sams, r.len);
if r.len % STEP == 0 {
let now = r.len;
r.note_sams(&self.sams, now);
for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) {
r.point(d.id, What::Drone(d.kind), d.pos);
}
@@ -1168,7 +1089,6 @@ mod tests {
sam_tracks: Vec::new(),
sam_index: HashMap::new(),
sam_keys: 0,
sam_events: 0,
sam_step: STEP,
ticks: Vec::new(),
times: Vec::new(),
@@ -1324,7 +1244,6 @@ mod tests {
let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum();
let allocated: usize = r.sam_tracks.iter().map(|track| track.keys.capacity()).sum();
assert_eq!(keys, r.sam_keys);
assert_eq!(r.sam_events, 0, "a turning dish is a pose, not a transition");
assert!(keys <= MAX_SAM_KEYS, "a full recording retained {keys} SamKeys");
assert!(allocated <= 2 * MAX_SAM_KEYS, "SamKey allocations reached {} MiB", allocated * size_of::<SamKey>() / (1024 * 1024));
assert!(r.sam_step > STEP, "the rotating radars never engaged adaptive sampling");
@@ -1333,104 +1252,6 @@ mod tests {
assert!(last.dish > 100.0, "the final radar pose was not recorded");
}
// #142: sixty-four turning radars on a 16-tick pose grid plus a cold S-400 launch. The
// cover's six-tick opening, the ejection and the spent cell must survive the decimation, and
// so must the radar's switch and a cancelled cover, on the tick they happened.
#[test]
fn decimation_keeps_a_cold_launch_cover_ejection_and_the_radar_switch() {
let mut r = recording();
let mut sams: Vec<_> = (0..64).map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0)).collect();
sams.push(Sam::new(100, SamKind::S400, DVec3::ZERO, 0.0));
let turned_off = 5_usize;
// The pose budget of a long recording has already slowed the sampling down.
r.sam_step = 16;
let eject = 4103u32;
let start = eject - launch::OPEN_TICKS as u32;
let (reopen, close, switch) = (4120u32, 4122u32, 4131u32);
for now in 0..4_200 {
for sam in &mut sams[..64] {
sam.dish = now as f64 * 0.01;
}
let s400 = sams.len() - 1;
if now == start {
assert!(!sams[s400].prepare_tube(7, now as u64));
} else if (start + 1..=eject).contains(&now) {
if sams[s400].prepare_tube(7, now as u64) {
assert_eq!(now, eject);
sams[s400].eject_cell(0);
}
} else if (reopen..close).contains(&now) {
// A second opening, cancelled before it is wide: the cover closes.
sams[s400].prepare_tube(7, now as u64);
} else if now == close {
sams[s400].cancel_prepare();
}
if now == switch {
sams[turned_off].radar_on = false;
}
r.note_sams(&sams, now);
}
let track = |id: u32| r.sam_tracks.iter().find(|track| track.id == id).unwrap();
let pose = |id: u32, t: f64| track(id).pose(t).unwrap();
let s400 = track(100);
assert!(s400.keys.len() < 32, "the launch track kept {} keys", s400.keys.len());
// The cover was shut before the stage and opens exactly over `OPEN_TICKS` ticks.
assert_eq!(pose(100, f64::from(start - 1)).cap_open, 0.0);
for k in 1..launch::OPEN_TICKS as u32 {
let want = k as f32 / launch::OPEN_TICKS as f32;
let got = pose(100, f64::from(start + k)).cap_open;
assert!((got - want).abs() < 1e-5, "tick {} of the opening: {got} not {want}", start + k);
}
assert!(s400.keys.iter().any(|k| k.at == start && k.event && k.cap_open == 0.0), "the stage's start key is kept");
// The last tick before the ejection: the cover stands five sixths open, not shut.
assert!((pose(100, f64::from(eject - 1)).cap_open - 5.0 / 6.0).abs() < 1e-5);
// The ejection: the cell is spent on its own tick, not on the next pose sample.
assert_eq!(pose(100, f64::from(eject - 1)).spent_cells, 0);
assert_eq!(pose(100, f64::from(eject)).spent_cells, 1);
assert!(track(100).keys.iter().any(|k| k.at == eject && k.event));
// The cancelled opening closes the cover on the tick it was cancelled.
assert!(pose(100, f64::from(close - 1)).cap_open > 0.0);
assert_eq!(pose(100, f64::from(close)).cap_open, 0.0);
// The radar's switch is on its own tick, between two 16-tick pose samples.
assert!(pose(turned_off as u32, f64::from(switch - 1)).radar_on);
assert!(!pose(turned_off as u32, f64::from(switch)).radar_on);
assert!(track(turned_off as u32).keys.iter().any(|k| k.at == switch && k.event));
// Later decimation halves poses only: the recorded launch still reads as it did.
r.thin_sam_poses();
r.thin_sam_poses();
let track = |id: u32| r.sam_tracks.iter().find(|track| track.id == id).unwrap();
let pose = |id: u32, t: f64| track(id).pose(t).unwrap();
assert!((pose(100, f64::from(eject - 1)).cap_open - 5.0 / 6.0).abs() < 1e-5);
assert_eq!(pose(100, f64::from(eject)).spent_cells, 1);
assert!(!pose(turned_off as u32, f64::from(switch)).radar_on);
}
// #142: the transitions have their own explicit budget. A recording that chatters must stay
// bounded, and the newest transitions — what a replay is watched closest for — stay exact.
#[test]
fn critical_transitions_have_their_own_explicit_budget() {
let mut r = recording();
let mut sams: Vec<_> = (0..64).map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0)).collect();
let ticks = 1_500u32;
for now in 0..ticks {
for sam in &mut sams {
sam.radar_on = now % 2 == 0;
}
r.note_sams(&sams, now);
}
let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum();
assert_eq!(keys, r.sam_keys);
assert_eq!(r.sam_events, MAX_SAM_EVENTS, "the transitions' budget is explicit");
assert!(keys <= MAX_SAM_KEYS + MAX_SAM_EVENTS + sams.len(), "{keys} SamKeys retained");
assert!(keys - r.sam_events <= MAX_SAM_KEYS, "poses broke their own budget");
// The newest switch reads exactly; the oldest transitions were the ones let go.
let newest = r.sam_tracks[0].pose(f64::from(ticks - 1)).unwrap();
assert_eq!(newest.radar_on, (ticks - 1) % 2 == 0);
assert!(r.sam_tracks[0].keys.iter().any(|key| key.at == ticks - 1 && key.event));
let earliest = r.sam_tracks[0].keys.iter().position(|key| key.event);
assert!(earliest.is_none_or(|i| r.sam_tracks[0].keys[i].at > ticks / 2), "old transitions hold on to the budget");
}
#[test]
fn a_system_keeps_its_pose_through_stillness_and_moves_when_it_moved() {
let mut r = recording();
-5
View File
@@ -363,11 +363,6 @@ impl Sam {
pub fn radar_up(&self) -> bool {
self.radar_on && self.mode != battery::SamMode::LauncherOnly && self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0
}
/// Its jammer is really on the air: the switch, a live station and a deployed one. The same
/// state `step_ew` transmits in, so a look names jamming only while the transmitter works.
pub fn ew_up(&self) -> bool {
self.ew_on && !self.ew_lock && self.alive() && !self.moving()
}
pub fn track(&self, id: u32) -> Option<&Track> {
self.tracks.iter().find(|t| t.id == id)
}
+2 -4
View File
@@ -50,15 +50,13 @@ expect.feedback = "№2 С-400: режим launcher"
[[step]]
command = "airdef deploy radar_track"
# The profile is chosen at deployment (#134): the old role switch is refused,
# and says where the profile comes from instead of retuning the station.
[[step]]
command = "airdef radar 4 search"
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в search не меняет оборудование. Доступно on/off."
expect.feedback = "№4 РЛС: роль search"
[[step]]
command = "airdef radar 4 engagement"
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в engagement не меняет оборудование. Доступно on/off."
expect.feedback = "№4 РЛС: роль engagement"
[[step]]
command = "airdef radar 4 off"
-27
View File
@@ -33,33 +33,6 @@
137346889/300M, command 129151/1B, failures=0. Лимит памяти 64 MiB не увеличивался. Это
синтетический host без GPU и не приёмка Windows GUI.
### Прореживание не съедает короткие переходы (#142)
Прореживание #122 не различало непрерывную позу и дискретный факт: при большом числе меняющихся
РЛС оно пропускало целиком открытие крышки ТПК (`launch::OPEN_TICKS = 6` тиков, короче шага
sampling) и могло убрать уже записанный переход — ракета в реплее вылетала с нарисованной
закрытой крышкой, а `spent_cells` менялось только на следующем общем сэмпле.
Теперь `Recording::note_sams` вызывается каждый тик: позы по-прежнему снимаются на адаптивной
сетке `sam_step` из прежнего бюджета 32768, а дискретные переходы (`cap_cell`, `spent_cells`,
`radar_on`, режим и роль) и кадры открытия крышки пишутся на том тике, когда произошли, и
помечаются как события. Начало открытия дотягивается отдельным ключом на тик раньше, поэтому
ramp занимает ровно `OPEN_TICKS`, а не «примерно». Прореживание поз половинит только позы и
сохраняет события, первую и последнюю позу.
У событий свой явный бюджет — 4096 ключей на запись поверх 32768 поз; общий бюджет поз не
поднимался. При переполнении старые события перестают быть критическими (прореживаются как
позы), новейшие сохраняются: под записью с «болтливым» датчиком реплей остаётся ограниченным,
а свежий пуск — точным.
Проверки: `airdef-core` `sim::record::tests::decimation_keeps_a_cold_launch_cover_ejection_and_the_radar_switch`
— 64 вращающихся РЛС + С-400 при `sam_step = 16`, выброс на тике 4103: за тик до выброса
`cap_open = 0.8333333` (как в контрольной записи без давления на бюджет), `spent_cells = 0`
до и `1` на тике выброса, отмена/закрытие и `radar_on` читаются на своих тиках, повторное
прореживание их не убирает;
`critical_transitions_have_their_own_explicit_budget` — 64 РЛС, переключающихся каждый тик,
1500 тиков: событий ровно 4096, позы в своём бюджете, новейшее переключение точное.
## Второй налёт из UI: событие, не тик
Точный лог Windows: `Horizon: mod airdef stopped in UI event (fuel budget 1000000000,