Tie a radar's refine/fire channel to its own plot's freshness (#140)
build / mod (push) Failing after 28s

A station counted any own plot, however old, as a busy refine/fire
channel: a network heartbeat kept a stale contact's track fresh, so two
long-expired own fire plots still held both channels of the engagement
radar and a new contact nearby got only a coarse search plot, even with
the search radar running.

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

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

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
2026-11-21 09:50:27 +03:00
parent 5f00a2a16b
commit f2bc8550f5
8 changed files with 105 additions and 34 deletions
+14 -14
View File
@@ -39,7 +39,7 @@ pub fn status(status: BatteryStatus) -> String {
}
/// One system's line in the summary panel and on the map.
pub fn sam_status(sam: &Sam) -> String {
pub fn sam_status(sam: &Sam, now: u64) -> String {
let spec = sam.kind.spec();
let mut text = spec.name.to_string();
if !sam.alive() {
@@ -67,7 +67,7 @@ pub fn sam_status(sam: &Sam) -> String {
let channels = if profile.channels == 0 {
"без уточнения".to_string()
} else {
format!("каналы {}/{}", sam.own_channels_used(), profile.channels)
format!("каналы {}/{}", sam.own_channels_used(now), profile.channels)
};
return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len());
}
@@ -126,20 +126,20 @@ mod tests {
let mut s400 = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0);
s400.missiles = 1;
s400.ground_rounds = 2;
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек");
assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек");
s400.ground_return = true;
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U");
assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U");
let mut pantsir = Sam::new(2, SamKind::Pantsir, DVec3::ZERO, 0.0);
pantsir.missiles = 7;
pantsir.bursts = 100;
assert_eq!(sam_status(&pantsir), "Панцирь-С1 ракеты 7/12 очереди 100");
assert_eq!(sam_status(&pantsir, 0), "Панцирь-С1 ракеты 7/12 очереди 100");
let mut worn = Sam::new(3, SamKind::Patriot, DVec3::ZERO, 0.0);
worn.health = 0.5;
worn.comps.0[Part::Sensor as usize] = 0.4;
worn.reloading = 21;
assert_eq!(sam_status(&worn), "Patriot (50%) [РЛС 40%] перезарядка 2с");
assert_eq!(sam_status(&worn, 0), "Patriot (50%) [РЛС 40%] перезарядка 2с");
}
#[test]
@@ -147,41 +147,41 @@ mod tests {
let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0);
radar.own.push(7);
radar.comps.0[Part::Sensor as usize] = 0.0;
assert_eq!(sam_status(&radar), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
assert_eq!(sam_status(&radar, 0), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
depot.cargo = 2;
depot.ground_stock = 3;
depot.air_48n6_stock = 1;
assert_eq!(sam_status(&depot), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1");
assert_eq!(sam_status(&depot, 0), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1");
let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0);
tzm.cargo = 1;
tzm.return_cargo = true;
assert_eq!(sam_status(&tzm), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад");
assert_eq!(sam_status(&tzm, 0), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад");
let mut ew = Sam::new(7, SamKind::Ew, DVec3::ZERO, 0.0);
ew.ew_on = true;
ew.heat = 0.5;
assert_eq!(sam_status(&ew), "Станция РЭБ: ГЛУШИТ, нагрев 50%");
assert_eq!(sam_status(&ew, 0), "Станция РЭБ: ГЛУШИТ, нагрев 50%");
let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0);
light.target = Some(1);
assert_eq!(sam_status(&light), "Прожектор: в луче цель");
assert_eq!(sam_status(&light, 0), "Прожектор: в луче цель");
let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0);
assert_eq!(sam_status(&optical), "Оптический пост: ищет");
assert_eq!(sam_status(&optical, 0), "Оптический пост: ищет");
}
#[test]
fn renders_moving_and_destroyed_systems_in_existing_format() {
let mut moving = Sam::new(9, SamKind::S400, DVec3::ZERO, 0.0);
moving.state = SamState::Moving;
assert_eq!(sam_status(&moving), "С-400 на марше");
assert_eq!(sam_status(&moving, 0), "С-400 на марше");
let mut dead = Sam::new(10, SamKind::S400, DVec3::ZERO, 0.0);
dead.health = 0.0;
assert_eq!(sam_status(&dead), "С-400 УНИЧТОЖЕН");
assert_eq!(sam_status(&dead, 0), "С-400 УНИЧТОЖЕН");
}
#[test]
+2 -2
View File
@@ -2732,7 +2732,7 @@ impl AirDef {
lines.push((format!("Профиль РЛС: {} [{}]", profile.name, profile.id), WHITE));
lines.push((crate::battery_view::radar_profile_line(profile), GREY));
lines.push((format!("Ограничение: {}", profile.limit), GREY));
lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(), profile.channels), GREY));
lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(now), profile.channels), GREY));
} else if sam.mode == sim::battery::SamMode::LauncherOnly {
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
}
@@ -2740,7 +2740,7 @@ impl AirDef {
lines.push((format!("Излучение РЛС: {}", if sam.radar_on { "вкл" } else { "выкл" }), WHITE));
btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on));
}
lines.push((crate::battery_view::sam_status(sam), WHITE));
lines.push((crate::battery_view::sam_status(sam, now), WHITE));
if k == SamKind::Optical
&& let Some(r) = self.sim.optical_report(sam.id)
{
+1 -1
View File
@@ -189,7 +189,7 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
format!("сеть · {seen}")
} else if radar_up {
let profile = sam.radar_profile();
let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(), profile.channels) };
let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(tick), profile.channels) };
format!("{} · {} · {}{channels}", profile.name, distance(reach), seen)
} else {
"РЛС ОТКАЗ".to_string()
+2 -2
View File
@@ -127,9 +127,9 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
}
for sam in sim.sams.iter().take(shown) {
let mut text = if sam.kind.armed() {
format!("{} [{}]", crate::battery_view::sam_status(sam), crate::sim::roles_text(sam.roles))
format!("{} [{}]", crate::battery_view::sam_status(sam, now), crate::sim::roles_text(sam.roles))
} else {
crate::battery_view::sam_status(sam)
crate::battery_view::sam_status(sam, now)
};
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) {
text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos)));
+57 -3
View File
@@ -496,7 +496,7 @@ fn run_profile_world(roles: &[RadarRole], ticks: u64) -> (ProfileStats, Sim, Vec
if sam.radar_profile().id == "radar_search" || sam.radar_profile().id == "radar_height" {
stats.search_or_height_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
}
stats.max_channels = stats.max_channels.max(sam.own_channels_used());
stats.max_channels = stats.max_channels.max(sam.own_channels_used(sim.tick));
}
}
(stats, sim, radars, ids)
@@ -633,11 +633,65 @@ fn tracked_channels_are_a_hard_limit_but_the_rest_keep_search_plots() {
let own: Vec<&Track> = sim.sams[engagement].tracks.iter().filter(|t| t.own_tick > 0).collect();
let precise = own.iter().filter(|t| t.own_product != Measure::Search).count();
assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}");
assert_eq!(sim.sams[engagement].own_channels_used(), 2);
assert_eq!(sim.sams[engagement].own_channels_used(sim.tick), 2);
assert_eq!(own.len(), 4, "a full station stopped giving coarse search plots: {own:?}");
assert!(own.iter().filter(|t| t.own_product == Measure::Search).all(|t| !t.own_authorizes(sim.tick)));
}
// #140: a network heartbeat keeps an old contact's track fresh, but never holds the station's
// channel: two stale own fire plots free the channels for a new contact, and the survey tracks
// of the old ones stay on the picture — with the search radar left running.
#[test]
fn stale_own_plots_free_their_channels_while_the_network_keeps_the_tracks() {
let mut sim = Sim::new(140);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 0.0);
let search = radar_with_role(&mut sim, RadarRole::Search, 1550.0);
for x in [100.0, 140.0] {
sim.add_drone(DroneKind::Gerbera, DVec3::new(x, 120.0, 0.0), DVec3::Z, DVec3::new(x, 120.0, 0.0));
}
let old: Vec<u32> = sim.drones.iter().map(|d| d.id).collect();
let mut ground = Ground::default();
let radars = [engagement, search];
for tick in 1..=40 {
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let frozen: Vec<u64> = old
.iter()
.map(|&id| {
let t = sim.sams[engagement].track(id).expect("the station took the contact");
assert_ne!(t.own_product, Measure::Search, "the station took no channel: {t:?}");
t.own_tick
})
.collect();
assert_eq!(sim.sams[engagement].own_channels_used(sim.tick), 2);
// The two contacts leave the station's reach for the search radar beside them; the new one
// arrives close to the station. Only the network keeps the old tracks alive now.
for (k, d) in sim.drones.iter_mut().enumerate() {
d.pos = DVec3::new(1600.0 + 20.0 * k as f64, 120.0, 0.0);
}
sim.add_drone(DroneKind::Gerbera, DVec3::new(180.0, 120.0, 0.0), DVec3::Z, DVec3::new(180.0, 120.0, 0.0));
let fresh = sim.drones.last().unwrap().id;
for tick in 41..=750 {
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let now = sim.tick;
let station = &sim.sams[engagement];
assert_eq!(station.own_channels_used(now), 1, "the stale channels still hold: {:?}", station.tracks);
for (&id, &own_tick) in old.iter().zip(&frozen) {
let t = station.track(id).expect("the survey track was thrown away with its channel");
assert_eq!(t.own_tick, own_tick, "the network renewed the station's own plot");
assert!(t.tick > 500, "the network stopped relaying the old contact: {t:?}");
assert_eq!(t.product, Measure::Search, "the relayed survey plot is gone: {t:?}");
assert!(!t.holds_channel(now, station.track_ttl() as u64), "an old own plot still holds a channel: {t:?}");
assert!(!t.own_authorizes(now));
}
let new = station.track(fresh).expect("the new contact is not held");
assert_eq!(new.own_product, Measure::Fire, "the new contact never got a channel: {new:?}");
assert!(new.own_authorizes(now), "the new contact's own fire plot does not authorize: {new:?}");
}
#[test]
fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() {
let mut sim = Sim::new(1342);
@@ -751,7 +805,7 @@ fn profiles_keep_their_jobs_over_a_ridge_on_one_seed_and_land() {
stats.high_marked |= t.id == ids[1];
}
if profile.id == "radar_track" {
stats.track_channels = stats.track_channels.max(sam.own_channels_used());
stats.track_channels = stats.track_channels.max(sam.own_channels_used(sim.tick));
}
if profile.id == "radar_search" || profile.id == "radar_height" {
stats.nonfire_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
+23 -8
View File
@@ -322,6 +322,15 @@ impl Track {
pub fn own_authorizes(&self, now: u64) -> bool {
self.own_fire_within(now, MISSILE_AGE)
}
/// The station's own refine/fire channel on this contact is still live: the plot is its own,
/// finer than a search, and no older than the station keeps a contact without a fresh
/// measurement. A relayed plot never holds a channel: the network's heartbeat keeps the
/// track fresh, not the station's own tracking (#140).
pub fn holds_channel(&self, now: u64, ttl: u64) -> bool {
self.own_tick > 0
&& self.own_product != battery::Measure::Search
&& now.saturating_sub(self.own_tick) <= ttl
}
/// Who measured the latest plot, as an ID (`0`: no station).
pub fn measured_by(&self) -> Option<u32> {
(self.source != 0).then_some(self.source)
@@ -371,9 +380,15 @@ impl Sam {
pub fn track(&self, id: u32) -> Option<&Track> {
self.tracks.iter().find(|t| t.id == id)
}
/// Refined/fire channels this station is currently using.
pub fn own_channels_used(&self) -> usize {
self.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count()
/// Ticks a contact stays this station's own without a fresh measurement: three missed turns, at least 60.
pub(super) fn track_ttl(&self) -> u32 {
((self.scan_ticks() * 3.0) as u32).max(60)
}
/// Refined/fire channels this station is currently using: the same test the planner applies,
/// so the panel and the allocation never disagree about a stale channel.
pub fn own_channels_used(&self, now: u64) -> usize {
let ttl = self.track_ttl() as u64;
self.tracks.iter().filter(|t| t.holds_channel(now, ttl)).count()
}
}
@@ -473,13 +488,14 @@ impl Sim {
let scan = sam.scan_profile();
let period = sam.scan_ticks();
let w = TAU / period;
let (b0, ttl) = (sam.beam, ((period * 3.0) as u32).max(60));
let (b0, ttl) = (sam.beam, sam.track_ttl());
sam.beam = (b0 + w) % TAU;
let at = antenna(sam);
let horizon = self.horizons.get(&sam.id);
let local = spec.sensor * profile.local;
// Channels already refining or holding fire plots. Search plots do not use one.
let mut used = sam.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count();
// Channels already refining or holding fire plots, by the same test the UI shows:
// a stale own plot (the network may keep the track) no longer occupies one.
let mut used = sam.own_channels_used(now);
let mut fresh: Vec<Track> = Vec::new();
for (d, h) in self.drones.iter().zip(&heights) {
if !d.alive() {
@@ -511,8 +527,7 @@ impl Sim {
// and a full station does not silently refine the whole sky. A station already
// refining a contact keeps its channel; a new refinement needs a free one, and
// without one the station still publishes its ordinary coarse search plot.
let own_held = held.is_some_and(|t| t.own_tick > 0);
let holds_channel = own_held && held.is_some_and(|t| t.own_product != battery::Measure::Search);
let holds_channel = held.is_some_and(|t| t.holds_channel(now, ttl as u64));
let mut product = if profile.allows(battery::Measure::Fire) {
battery::Measure::Fire
} else if profile.allows(battery::Measure::Refine) && held.is_some() {
+3 -3
View File
@@ -423,7 +423,7 @@ impl Sim {
let spec = sam.kind.spec();
let now = self.tick;
let channels = (spec.sensor > 0.0 && sam.mode != battery::SamMode::LauncherOnly && sam.radar_profile().channels > 0)
.then(|| (sam.own_channels_used(), sam.radar_profile().channels));
.then(|| (sam.own_channels_used(now), sam.radar_profile().channels));
let reason = |kind, block, target, mark| BattleReason {
kind,
block,
@@ -554,7 +554,7 @@ impl Sim {
});
if let Some((radar, tr)) = support {
let profile = radar.radar_profile();
let used = radar.own_channels_used();
let used = radar.own_channels_used(now);
if profile.channels > 0 && used >= profile.channels as usize && !tr.own_authorizes(now) {
let mut busy = reason(BattleKind::ChannelsBusy, None, Some(t.id), mark);
busy.channels = Some((used, profile.channels));
@@ -667,8 +667,8 @@ impl Sim {
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
)));
v.push(check(true, format!("ограничение: {}", profile.limit)));
v.push(check(true, format!("свои треки: {}, каналы {}/{}", sam.own.len(), sam.own_channels_used(), profile.channels)));
let now = self.tick;
v.push(check(true, format!("свои треки: {}, каналы {}/{}", sam.own.len(), sam.own_channels_used(now), profile.channels)));
let mut tracks: Vec<&Track> = sam.tracks.iter().filter(|t| t.own_tick > 0).collect();
tracks.sort_by_key(|t| std::cmp::Reverse(t.quality));
for t in tracks.into_iter().take(4) {
+3 -1
View File
@@ -65,7 +65,9 @@
Сеть передаёт трек вместе с измерившей станцией, возрастом и качеством. Повторная пересылка не
освежает измерение и не создаёт права на пуск. Уточнение применяется только к сопоставленному
контакту, а число каналов ограничено на каждом тике. Если РЛС сопровождения уничтожена, свёрнута,
контакту, а число каналов ограничено на каждом тике. Канал удерживает только собственное измерение
станции: когда оно устаревает (станция больше не измеряет контакт), канал освобождается для новой
цели, а сетевой обзорный трек остаётся на месте. Если РЛС сопровождения уничтожена, свёрнута,
потеряла связь или её измерение устарело, новые пуски прекращаются. Уже вылетевшие ракеты
продолжают штатную игровую логику связи/памяти/самонаведения.