feat: add shared radar batteries and animated cold launch
build / mod (push) Failing after 18s

Separate search and engagement roles, support launcher-only SAMs, animate individual tube lids and delay ground strike spending until ejection. Preserve battery configuration and launch poses in saves and replay.

Co-authored-by: Codex <codex@openai.com>
This commit is contained in:
2026-11-02 23:40:40 +03:00
parent d4adbb1e47
commit 966b52f9fc
41 changed files with 2534 additions and 509 deletions
+257
View File
@@ -0,0 +1,257 @@
//! Game-only configuration for a launcher using shared radar tracks.
use super::*;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SamMode {
#[default]
Integrated,
LauncherOnly,
}
impl SamMode {
pub fn key(self) -> &'static str {
match self { Self::Integrated => "integrated", Self::LauncherOnly => "launcher" }
}
pub fn from_key(key: &str) -> Option<Self> {
match key { "integrated" => Some(Self::Integrated), "launcher" => Some(Self::LauncherOnly), _ => None }
}
}
/// Game roles for the generic shared radar; all parameters are fictional.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RadarRole {
#[default]
Multifunction,
Search,
Engagement,
Height,
}
impl RadarRole {
pub fn key(self) -> &'static str {
match self { Self::Multifunction => "multi", Self::Search => "search", Self::Engagement => "engagement", Self::Height => "height" }
}
pub fn from_key(key: &str) -> Option<Self> {
match key { "multi" => Some(Self::Multifunction), "search" => Some(Self::Search), "engagement" => Some(Self::Engagement), "height" => Some(Self::Height), _ => None }
}
pub fn name(self) -> &'static str {
match self { Self::Multifunction => "многофункциональная", Self::Search => "обзорная", Self::Engagement => "сопровождения", Self::Height => "мачтовая" }
}
pub fn authorizes(self) -> bool { matches!(self, Self::Multifunction | Self::Engagement) }
pub(super) fn reach_factor(self) -> f64 { match self { Self::Multifunction => 1.0, Self::Search => 1.15, Self::Engagement => 0.8, Self::Height => 1.05 } }
}
impl Sam {
pub fn set_radar_role(&mut self, role: RadarRole) -> bool {
if self.kind != SamKind::Radar { return false; }
if self.radar_role != role {
self.radar_role = role;
self.tracks.clear();
self.seen.clear();
self.own.clear();
}
true
}
/// Change the physical configuration. Invalid combinations leave the unit untouched.
pub fn set_mode(&mut self, mode: SamMode) -> bool {
if mode == SamMode::LauncherOnly && !matches!(self.kind, SamKind::S400 | SamKind::S500) { return false; }
if self.mode != mode {
self.mode = mode;
self.tracks.clear();
self.seen.clear();
self.own.clear();
self.target = None;
self.gun_target = None;
self.terrain.clear();
self.waits.clear();
}
true
}
}
impl Sim {
/// Current configurations and whether a launcher has an operational radar link.
pub fn battery_status(&self) -> Vec<String> {
self.sams.iter().enumerate().filter_map(|(i, sam)| {
if sam.kind == SamKind::Radar {
Some(format!("№{} РЛС: {}, {}", i + 1, sam.radar_role.name(), if sam.radar_up() && sam.link_range() > 0.0 { "работает" } else { "нет связи или РЛС не работает" }))
} else if matches!(sam.kind, SamKind::S400 | SamKind::S500) {
let linked = self.sams.iter().any(|r| r.kind == SamKind::Radar && r.radar_role.authorizes() && r.radar_up() && r.link_range() > 0.0 && sam.link_range() > 0.0 && r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range()));
Some(format!("№{} {}: {}{}", i + 1, sam.kind.name(), sam.mode.key(), if sam.mode == SamMode::LauncherOnly { if linked { ", РЛС связана" } else { ", нет связанной РЛС сопровождения" } } else { "" }))
} else { None }
}).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::{sight, why};
fn track(now: u64) -> Track {
Track { id: 42, kind: DroneKind::Kh101, pos: DVec3::new(0.0, 100.0, -200.0), vel: DVec3::ZERO, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }
}
#[test]
fn shared_radar_serves_multiple_launchers_and_failure_blocks_cue() {
let mut radar = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
let mut a = Sam::new(2, SamKind::S400, DVec3::new(10.0, 0.0, 0.0), 0.0);
let mut b = Sam::new(3, SamKind::S500, DVec3::new(20.0, 0.0, 0.0), 0.0);
assert!(a.set_mode(SamMode::LauncherOnly));
assert!(b.set_mode(SamMode::LauncherOnly));
assert!(!a.radar_up() && !b.radar_up());
radar.tracks.push(track(10));
radar.set_radar_role(RadarRole::Search);
radar.tracks.push(track(10));
assert!(!why::radar_cue(&a, &[&radar], 42, 10));
radar.set_radar_role(RadarRole::Height);
radar.tracks.push(track(10));
assert!(!why::radar_cue(&a, &[&radar], 42, 10));
radar.set_radar_role(RadarRole::Engagement);
radar.tracks.push(track(10));
assert!(why::radar_cue(&a, &[&radar], 42, 10));
assert!(why::radar_cue(&b, &[&radar], 42, 10));
assert!(!why::radar_cue(&a, &[&radar], 42, 10 + why::FAR_RADAR_AGE + 1));
radar.comps.0[Part::Comms as usize] = 0.0;
assert!(!why::radar_cue(&a, &[&radar], 42, 10));
radar.comps.0[Part::Comms as usize] = 1.0;
a.comps.0[Part::Comms as usize] = 0.0;
assert!(!why::radar_cue(&a, &[&radar], 42, 10));
a.comps.0[Part::Comms as usize] = 1.0;
a.pos.x = sight::LINK + 1.0;
assert!(!why::radar_cue(&a, &[&radar], 42, 10));
a.pos.x = 10.0;
radar.health = 0.0;
assert!(!why::radar_cue(&a, &[&radar], 42, 10));
}
#[test]
fn network_shares_a_measurement_to_both_launchers_without_fabricating_own_tracks() {
let mut sim = Sim::new(7);
sim.tick = 10;
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0));
for kind in [SamKind::S400, SamKind::S500] {
let id = sim.id();
let mut launcher = Sam::new(id, kind, DVec3::new(10.0, 0.0, 0.0), 0.0);
launcher.set_mode(SamMode::LauncherOnly);
launcher.roles = 0xff;
sim.sams.push(launcher);
}
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 100.0, -200.0), DVec3::Z, DVec3::ZERO);
let id = sim.drones[0].id;
let mut measurement = track(10);
measurement.id = id;
sim.sams[0].tracks.push(measurement);
sim.update_sight(&mut Ground::default());
for launcher in &sim.sams[1..] {
let received = launcher.track(id).expect("shared measurement");
assert_eq!(received.tick, 10);
assert_eq!(received.own_tick, 0);
assert!(why::radar_cue(launcher, &[&sim.sams[0]], id, 10));
let load = launcher.kind.spec().missile.as_ref().unwrap();
let opts = why::Opts { last_chance: false, far_shots: false };
assert!(why::basis(launcher, load, received, &sim.drones[0], 10, 0, 1.0, opts, true, false).is_some());
assert!(why::basis(launcher, load, received, &sim.drones[0], 10, 0, 1.0, opts, false, false).is_none());
}
sim.sams[0].health = 0.0;
for launcher in &sim.sams[1..] {
assert!(launcher.track(id).is_some());
assert!(!why::radar_cue(launcher, &[&sim.sams[0]], id, 10));
}
}
#[test]
fn search_cues_tracking_radar_but_only_its_own_measurement_authorizes_launch() {
for in_range in [true, false] {
let mut sim = Sim::new(71);
sim.tick = 10;
let mut search = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
search.set_radar_role(RadarRole::Search);
let mut fire_control = Sam::new(2, SamKind::Radar, DVec3::ZERO, 0.0);
fire_control.set_radar_role(RadarRole::Engagement);
let mut launcher = Sam::new(3, SamKind::S400, DVec3::ZERO, 0.0);
launcher.set_mode(SamMode::LauncherOnly);
launcher.roles = 0xff;
sim.sams.extend([search, fire_control, launcher]);
let distance = if in_range { 100.0 } else { 10000.0 };
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 70.0, -distance), DVec3::Z, DVec3::ZERO);
let id = sim.drones[0].id;
let mut measurement = track(10);
measurement.id = id;
measurement.pos = sim.drones[0].pos;
sim.sams[0].tracks.push(measurement);
sim.sams[0].beam = std::f64::consts::PI;
sim.sams[1].beam = std::f64::consts::PI;
let mut ground = Ground::default();
sim.update_sight(&mut ground);
assert_eq!(sim.sams[1].track(id).unwrap().own_tick, 0, "cue is not a measurement");
assert!(!why::radar_cue(&sim.sams[2], &[&sim.sams[1]], id, sim.tick));
for now in 11..40 {
sim.tick = now;
// Bearing is north (zero); force the ordinary beam away each tick.
sim.sams[1].beam = std::f64::consts::PI;
sim.update_sight(&mut ground);
if sim.sams[1].track(id).is_some_and(|t| t.own_tick > 0) { break; }
}
let got_own = sim.sams[1].track(id).is_some_and(|t| t.own_tick > 0);
assert_eq!(got_own, in_range);
assert_eq!(why::radar_cue(&sim.sams[2], &[&sim.sams[1]], id, sim.tick), in_range);
if in_range {
let tr = sim.sams[2].track(id).unwrap();
let load = sim.sams[2].kind.spec().missile.as_ref().unwrap();
let opts = why::Opts { last_chance: false, far_shots: false };
assert!(why::basis(&sim.sams[2], load, tr, &sim.drones[0], sim.tick, 0, 1.0, opts, true, false).is_some());
let mut out = Out::default();
for _ in 0..100 {
sim.step(&mut ground, None, &mut out);
if sim.sams[2].fired > 0 { break; }
}
assert!(sim.sams[2].fired > 0, "launcher never fired after its tracking radar measured the cue");
}
}
}
#[test]
fn fictional_roles_change_scan_and_height_and_coverage() {
let mut r = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
let base_mast = r.sensor_mast();
let base_scan = r.scan_ticks();
let base_reach = sight::reach(&r, DroneKind::Kh101, 5000.0);
r.set_radar_role(RadarRole::Height);
assert!(r.sensor_mast() > base_mast);
r.set_radar_role(RadarRole::Engagement);
assert!(r.scan_ticks() < base_scan && r.scan_profile().agile);
assert!(sight::reach(&r, DroneKind::Kh101, 5000.0) < base_reach);
r.set_radar_role(RadarRole::Search);
assert!(sight::reach(&r, DroneKind::Kh101, 5000.0) > base_reach);
}
#[test]
fn launcher_has_no_own_map_sensor_and_mode_switch_drops_stale_tracks() {
let mut sim = Sim::new(3);
sim.sams.push(Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0));
assert!(sim.low_sensor(SamKind::S400, DVec3::ZERO, Some(1)).is_some());
sim.sams[0].tracks.push(track(10));
sim.sams[0].terrain.insert(42, (10, 1));
assert!(sim.sams[0].set_mode(SamMode::LauncherOnly));
assert!(sim.low_sensor(SamKind::S400, DVec3::ZERO, Some(1)).is_none());
assert!(sim.low_sensors().is_empty());
assert!(sim.sams[0].track(42).is_none());
assert!(sim.sams[0].terrain.is_empty());
sim.sams[0].set_mode(SamMode::Integrated);
assert!(sim.low_sensor(SamKind::S400, DVec3::ZERO, Some(1)).is_some());
}
#[test]
fn configuration_clears_old_tracks_and_rejects_other_kinds() {
let mut sam = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0);
sam.tracks.push(track(10));
assert!(sam.set_mode(SamMode::LauncherOnly));
assert!(sam.tracks.is_empty());
assert!(sam.set_mode(SamMode::Integrated));
assert!(sam.radar_up());
let mut other = Sam::new(2, SamKind::Patriot, DVec3::ZERO, 0.0);
assert!(!other.set_mode(SamMode::LauncherOnly));
assert_eq!(other.mode, SamMode::Integrated);
}
}
+4
View File
@@ -66,6 +66,8 @@ pub fn bounds(id: &str) -> Option<([f64; 3], [f64; 3])> {
"airdef:patriot_trailer" => ([-9.06, 0.0, -16.0], [25.06, 16.0, 32.0]),
"airdef:patriot_trailer_burnt" => ([-9.06, 0.0, -16.0], [25.0, 16.0, 32.0]),
"airdef:patriot_truck" => ([-8.56, 0.0, -16.0], [24.56, 22.0, 32.0]),
"airdef:radar_mast" => ([4.0, 0.0, 4.0], [12.0, 32.0, 12.0]),
"airdef:radar_mast_burnt" => ([4.0, 0.0, 4.0], [12.0, 32.0, 12.0]),
"airdef:radar_panel" => ([-10.5, -6.0, 7.0], [26.5, 26.5, 12.0]),
"airdef:radar_trailer" => ([-9.0, -1.379664, -12.0], [25.0, 18.0, 26.379664]),
"airdef:radar_truck" => ([-8.56, 0.0, -16.0], [24.56, 20.0, 32.0]),
@@ -91,6 +93,8 @@ pub fn bounds(id: &str) -> Option<([f64; 3], [f64; 3])> {
"airdef:tor_chassis_burnt" => ([-13.3, 0.0, -16.0], [29.3, 15.7, 31.0]),
"airdef:tor_turret" => ([-4.0, 0.0, -11.0], [20.0, 17.5, 22.0]),
"airdef:tor_turret_burnt" => ([-4.0, 0.0, -11.0], [20.0, 17.5, 22.0]),
"airdef:tpk_cap" => ([0.0, 0.0, 7.7], [16.0, 16.0, 8.3]),
"airdef:tpk_cap_burnt" => ([0.0, 0.0, 7.7], [16.0, 16.0, 8.3]),
"airdef:tracer" => ([7.3, 7.3, -16.0], [8.7, 8.7, 32.0]),
"airdef:tzm_truck" => ([-8.56, 0.0, -16.0], [24.56, 26.0, 32.0]),
"airdef:tzm_truck_burnt" => ([-8.5, 0.0, -16.0], [24.56, 26.0, 32.0]),
+117
View File
@@ -0,0 +1,117 @@
//! Short, deliberately fictional cold-launch choreography and physical tube visuals.
//! Timing and geometry are Minecraft presentation settings, not weapon specifications.
use super::*;
pub const OPEN_TICKS: u64 = 6;
#[derive(Clone, Copy, Debug)]
pub(super) struct Prepare {
pub target: u32,
pub cell: u32,
pub start: u64,
pub ground: bool,
}
impl Sam {
pub fn animated_tubes(&self) -> bool { matches!(self.kind, SamKind::S400 | SamKind::S500) }
/// Reconcile visual occupancy with the actual shared magazine after load, repair or supply.
pub fn sync_tube_cells(&mut self) {
if !self.animated_tubes() { self.spent_cells = 0; return; }
let cells = self.kind.spec().missile.as_ref().map_or(0, |m| m.magazine);
let valid = ((1u16 << cells) - 1) as u8;
self.spent_cells &= valid;
let loaded = (self.missiles + self.ground_rounds).min(cells);
let desired = cells - loaded;
while self.spent_cells.count_ones() > desired {
let bit = self.spent_cells.trailing_zeros();
self.spent_cells &= !(1 << bit);
}
while self.spent_cells.count_ones() < desired {
let bit = ((!self.spent_cells) & valid).trailing_zeros();
self.spent_cells |= 1 << bit;
}
if self.preparing.is_none() { self.cap_open = 0.0; }
}
pub(super) fn next_tube_cell(&self) -> u32 {
let cells = self.kind.spec().missile.as_ref().map_or(1, |m| m.magazine);
(0..cells).find(|n| self.spent_cells & (1 << n) == 0).unwrap_or(0)
}
pub(super) fn cancel_prepare(&mut self) {
self.preparing = None;
self.cap_open = 0.0;
}
/// Opening reserves a particular cell; ammunition is consumed only at actual ejection.
pub(super) fn prepare_tube(&mut self, target: u32, now: u64) -> bool {
if !self.animated_tubes() { return true; }
if self.preparing.is_none_or(|p| p.target != target) {
self.preparing = Some(Prepare { target, cell: self.next_tube_cell(), start: now, ground: false });
}
let p = self.preparing.unwrap();
self.cap_cell = p.cell as u8;
self.cap_open = (now.saturating_sub(p.start) as f32 / OPEN_TICKS as f32).clamp(0.0, 1.0);
self.cap_open >= 1.0
}
pub(super) fn eject_cell(&mut self, cell: u32) {
if self.animated_tubes() { self.spent_cells |= 1 << cell; }
self.cancel_prepare();
}
}
/// A hinge is a readable game abstraction. No claim is made about the real cover mechanism.
pub(super) fn draw_caps(sam: &Sam, out: &mut Out) {
if !sam.animated_tubes() || !sam.alive() { return; }
let Muzzle::Grid(cols, rows, size) = sam.kind.spec().muzzle else { return };
let (_, basis) = sam.mount();
let side = size / 16.0 * sam.scale();
for cell in 0..cols * rows {
let open = if sam.spent_cells & (1 << cell) != 0 { 1.0 }
else if sam.cap_cell as u32 == cell { sam.cap_open } else { 0.0 };
// Grid muzzle includes TUBE_PIVOT and is exactly the front plane of the model.
let (closed, _) = sam.muzzle(cell);
let hinge = closed + basis * DVec3::new(-side * 0.5, 0.0, 0.0);
let rotation = basis * DQuat::from_rotation_y((open as f64) * 1.8);
let center = hinge + rotation * DVec3::new(side * 0.5, 0.0, 0.0);
out.model(sam.id + 8 + cell, "airdef:tpk_cap", center, rotation, side, false);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_animated_magazine_has_one_round_per_drawn_tube() {
for kind in [SamKind::S400, SamKind::S500] {
let sam = Sam::new(16, kind, DVec3::ZERO, 0.0);
let Muzzle::Grid(cols, rows, _) = kind.spec().muzzle else { panic!("tube grid") };
assert_eq!(sam.missiles, cols * rows);
let mut out = Out::default();
draw_caps(&sam, &mut out);
assert_eq!(out.models.len(), sam.missiles as usize);
for (cell, model) in out.models.iter().enumerate() {
assert!(model.at.distance(sam.muzzle(cell as u32).0) < 1e-9, "closed lid covers the real muzzle");
}
}
}
#[test]
fn opening_reserves_a_cell_and_abort_does_not_spend_rounds() {
let mut sam = Sam::new(16, SamKind::S400, DVec3::ZERO, 0.0);
assert!(!sam.prepare_tube(42, 10));
assert!(!sam.prepare_tube(42, 13));
assert_eq!(sam.cap_open, 0.5);
let cell = sam.preparing.unwrap().cell;
assert_eq!(sam.missiles, 4);
sam.cancel_prepare();
assert_eq!((sam.missiles, sam.spent_cells, sam.cap_open), (4, 0, 0.0));
assert!(!sam.prepare_tube(42, 20));
assert_eq!(sam.preparing.unwrap().cell, cell);
assert!(sam.prepare_tube(42, 20 + OPEN_TICKS));
sam.missiles -= 1;
sam.eject_cell(cell);
assert_ne!(sam.next_tube_cell(), cell);
sam.sync_tube_cells();
assert_eq!(sam.spent_cells.count_ones(), 1);
sam.missiles = 4;
sam.sync_tube_cells();
assert_eq!(sam.spent_cells, 0);
}
}
+2 -2
View File
@@ -23,7 +23,7 @@ impl Sim {
pub fn load_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
if s.kind != SamKind::S400 { return Err("Для этого комплекса нет игрового профиля RM48U".into()); }
if !s.alive() || s.moving() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 {
if !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 {
return Err("Комплекс должен быть исправен и развёрнут".into());
}
if s.ground_rounds >= s.cells() { return Err("Нет свободной ячейки для RM48U".into()); }
@@ -43,7 +43,7 @@ impl Sim {
/// Return a loaded ground round to a nearby depot; restore a previously removed air round if available.
pub fn unload_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
if s.kind != SamKind::S400 || !s.alive() || s.moving() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 || s.ground_rounds == 0 {
if s.kind != SamKind::S400 || !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 || s.ground_rounds == 0 {
return Err("Нужен исправный развёрнутый С-400 с загруженной RM48U".into());
}
let depot = self.sams.iter().enumerate().filter(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.pos.distance(s.pos) < DEPOT_REACH)
+43 -5
View File
@@ -9,6 +9,8 @@
use glam::{DQuat, DVec3};
use std::collections::HashMap;
pub mod battery;
pub mod launch;
pub mod catalog;
mod generated_bounds;
mod damage;
@@ -1278,6 +1280,11 @@ pub const MAX_COAST: u64 = 240;
/// Ticks the seeker keeps a target it lost sight of (it looks again round the last place).
const REACQUIRE: u64 = 12;
impl Missile {
/// Whether the main motor is running (cold ejection has no exhaust).
pub fn engine_lit(&self) -> bool { self.age > self.kind.spec().cold }
}
impl MissileKind {
/// How far its own seeker holds a target of average size (blocks); 0: command guidance only.
pub fn seeker(self) -> f64 {
@@ -1355,6 +1362,12 @@ pub struct Sam {
launched: u32,
pub id: u32,
pub kind: SamKind,
pub mode: battery::SamMode,
pub radar_role: battery::RadarRole,
pub spent_cells: u8,
preparing: Option<launch::Prepare>,
cap_cell: u8,
cap_open: f32,
/// The vehicle's centre on the ground.
pub pos: DVec3,
/// Where its nose points (radians, as `look`'s yaw).
@@ -1441,6 +1454,12 @@ impl Sam {
Self {
id,
kind,
mode: battery::SamMode::Integrated,
radar_role: battery::RadarRole::Multifunction,
spent_cells: 0,
preparing: None,
cap_cell: 0,
cap_open: 0.0,
pos,
heading,
yaw: heading,
@@ -1544,6 +1563,9 @@ impl Sam {
SamKind::Light => return format!("{text}{}", if self.target.is_some() { ": в луче цель" } else { "" }),
_ => {}
}
if let Some(p) = self.preparing {
text += &format!(" · открытие ТПК №{}", p.cell + 1);
}
if self.empty && self.missiles == 0 {
text += " ЖДЁТ БК";
}
@@ -1829,6 +1851,8 @@ impl Sim {
}
pub fn clear(&mut self) {
self.strikes.pending.clear();
for sam in &mut self.sams { sam.cancel_prepare(); }
self.drones.clear();
self.missiles.clear();
self.fx.clear();
@@ -1889,6 +1913,7 @@ impl Sim {
self.step_ew(out);
self.update_sight(ground);
self.step_lights(ground, out);
self.prepare_ground_strikes(out);
self.step_sams(ground, out);
self.step_missiles(ground, out);
self.step_strikes(ground, player, out);
@@ -2489,6 +2514,13 @@ impl Sim {
// ------------------------------------------------ air defence
fn step_sams(&mut self, ground: &mut Ground, out: &mut Out) {
for sam in &mut self.sams {
sam.sync_tube_cells();
if (self.hold && !sam.preparing.is_some_and(|p| p.ground)) || !sam.alive() || sam.moving() || sam.reloading > 0 || sam.part(Part::Launcher) <= 0.0 {
sam.cancel_prepare();
}
}
if self.hold {
for i in 0..self.sams.len() {
if self.sams[i].alive() && !self.sams[i].moving() {
@@ -2573,10 +2605,10 @@ impl Sim {
let opts = why::Opts { last_chance: self.last_chance, far_shots: self.far_shots };
let target = spec.missile.as_ref().map(|load| {
// A launcher with nothing to fire (reloading, empty, failed) claims no target: others take it.
if me.missiles == 0 || me.reloading > 0 || me.part(Part::Launcher) <= 0.0 {
if me.missiles == 0 || me.reloading > 0 || me.part(Part::Launcher) <= 0.0 || me.preparing.is_some_and(|p| p.ground) {
return None;
}
let radars: Vec<&Sam> = if me.kind.far_shooter() && opts.far_shots { self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect() } else { Vec::new() };
let radars: Vec<&Sam> = if me.mode == battery::SamMode::LauncherOnly || (me.kind.far_shooter() && opts.far_shots) { self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect() } else { Vec::new() };
let cued = |id: u32| !radars.is_empty() && why::radar_cue(me, &radars, id, now);
let basis = |tr: &Track, k: f64, role_in_reach: bool| {
drone(tr).filter(|_| open(tr.id)).and_then(|d| why::basis(me, load, tr, d, now, claimed(d), k, opts, cued(tr.id), role_in_reach))
@@ -2641,6 +2673,10 @@ impl Sim {
self.sams[i].gun_target = gun_target;
}
let sam = &mut self.sams[i];
if sam.preparing.is_some_and(|p| !p.ground && Some(p.target) != sam.target) { sam.cancel_prepare(); }
if let Some(p) = sam.preparing.filter(|p| !p.ground) {
sam.cap_open = (now.saturating_sub(p.start) as f32 / launch::OPEN_TICKS as f32).clamp(0.0, 1.0);
}
// What the turret or launcher points at: guns first when a target is close.
let aim = sam
.gun_target
@@ -2783,11 +2819,11 @@ impl Sim {
}
// Missiles.
if let (Some(load), Some(mt)) = (&spec.missile, sam.target) {
let ready = why::missile_blocks(sam) == 0;
let ready = why::missile_blocks(sam) == 0 && !sam.preparing.is_some_and(|p| p.ground);
// The missile turns after its boost, but the launcher must point near the target.
let t = sam.track(mt).filter(|_| drone_at.contains_key(&mt)).map(|tr| tr.est(now));
let aligned = why::missile_aligned(spec.family, sam.yaw, mount, t, aim_id, mt, aim_error);
let n = load.magazine - sam.missiles;
let n = if sam.animated_tubes() { sam.preparing.map_or_else(|| sam.next_tube_cell(), |p| p.cell) } else { load.magazine - sam.missiles };
let (muzzle, dir) = sam.muzzle(n);
// The land: a target behind a hill, or a path the hill closes, is not fired at; the system looks for another.
let land = if ready && aligned {
@@ -2816,9 +2852,11 @@ impl Sim {
if land == terrain::WAIT {
// The land under the shot is not known yet: it waits.
} else if land != 0 {
sam.cancel_prepare();
retarget(&mut missile_on, Some(mt), None);
sam.target = None;
} else if ready && aligned {
} else if ready && aligned && sam.prepare_tube(mt, now) {
sam.eject_cell(n);
// Past its normal reach: a long shot, and the next waits.
if sam.kind.far_shooter() && t.is_some_and(|t| t.distance(sam.pos) >= load.max) {
sam.far_cooldown = why::FAR_COOLDOWN;
+45 -2
View File
@@ -23,6 +23,11 @@ pub struct SamKey {
/// Hull and component health at the sampled tick.
health: f32,
parts: [f32; 6],
mode: battery::SamMode,
radar_role: battery::RadarRole,
spent_cells: u8,
cap_cell: u8,
cap_open: f32,
}
impl SamKey {
@@ -38,6 +43,11 @@ impl SamKey {
beam: if sam.beam_on { ((sam.beam_free / 8.0).round() * 8.0).max(8.0) as f32 } else { 0.0 },
health: sam.health as f32,
parts: sam.comps.0.map(|v| v as f32),
mode: sam.mode,
radar_role: sam.radar_role,
spent_cells: sam.spent_cells,
cap_cell: sam.cap_cell,
cap_open: sam.cap_open,
}
}
/// The same pose (to within what could be seen).
@@ -51,6 +61,9 @@ impl SamKey {
&& self.beam == o.beam
&& self.health == o.health
&& self.parts == o.parts
&& self.mode == o.mode && self.radar_role == o.radar_role
&& self.spent_cells == o.spent_cells && self.cap_cell == o.cap_cell
&& near(self.cap_open, o.cap_open, 0.001)
}
}
@@ -93,6 +106,11 @@ impl SamTrack {
beam: a.beam,
health: a.health,
parts: a.parts,
mode: a.mode,
radar_role: a.radar_role,
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 },
})
}
/// The system as it stood at `t`, as a ghost to draw with the ids from `id`.
@@ -107,6 +125,11 @@ impl SamTrack {
sam.beam_free = k.beam as f64;
sam.health = if self.lost.is_some_and(|l| t >= l as f64) { 0.0 } else { k.health as f64 };
sam.comps = Comps(k.parts.map(|v| v as f64));
sam.mode = k.mode;
sam.radar_role = k.radar_role;
sam.spent_cells = k.spent_cells;
sam.cap_cell = k.cap_cell;
sam.cap_open = k.cap_open;
Some(sam)
}
}
@@ -757,7 +780,7 @@ impl Sim {
/// Open before the combat update so transitions on the first active tick are not lost.
pub(super) fn begin_recording_if_active(&mut self) {
if self.rec.is_none() && (self.drones.iter().any(|d| d.alive()) || !self.strikes.flights.is_empty()) {
if self.rec.is_none() && (self.drones.iter().any(|d| d.alive()) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) {
self.recordings += 1;
self.rec = Some(Recording::new(self.recordings, self));
}
@@ -775,7 +798,7 @@ impl Sim {
pub(super) fn record(&mut self) {
// Wrecks still falling (far off they fall a long while) don't keep it going. A counter-strike is a recorded
// object in its own right (#109): it holds the recording open until it lands, whatever the sky is doing.
let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty();
let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty();
self.begin_recording_if_active();
let Some(r) = &mut self.rec else { return };
r.note_tracks(&self.sams);
@@ -1006,6 +1029,26 @@ mod tests {
}
}
#[test]
fn replay_preserves_launcher_configuration_and_individual_cover_poses() {
let mut r = recording();
let mut sam = sam_at(0.0, 0.0, 0.0);
sam.set_mode(battery::SamMode::LauncherOnly);
sam.cap_cell = 2;
sam.cap_open = 0.5;
sam.spent_cells = 1;
r.note_sams(&[sam], 10);
for t in [10.0, 40.0, 10.0] {
let ghost = r.sam_tracks[0].ghost(r.origin, t, 160).unwrap();
assert_eq!(ghost.mode, battery::SamMode::LauncherOnly);
assert_eq!((ghost.spent_cells, ghost.cap_cell, ghost.cap_open), (1, 2, 0.5));
let mut out = Out::default();
units::draw_sam_model(&ghost, &mut Rng::new(1), &mut out);
assert_eq!(out.models.iter().filter(|m| m.name == "airdef:tpk_cap").count(), 4);
assert!(!out.models.iter().any(|m| m.name == "airdef:radar_panel"));
}
}
fn physical_strike(record_len: Option<u32>) -> (Sim, u32, DVec3) {
use crate::sim::sites::{LaunchSite, SiteClass};
use crate::sim::strike::{Estimate, Known, SiteState};
+54 -20
View File
@@ -36,6 +36,8 @@ const NEAR: f64 = 24.0;
pub(super) struct Horizon {
/// Per ray, per sample out: the steepest rise of the land so far (tan of its elevation).
pub(super) rays: Vec<Vec<f32>>,
antenna: DVec3,
reach: f64,
}
impl Horizon {
@@ -58,9 +60,12 @@ impl Horizon {
.collect()
})
.collect();
Self { rays }
Self { rays, antenna, reach }
}
fn matches(&self, sam: &Sam) -> bool {
self.antenna == antenna(sam) && self.reach == sensor_span(sam)
}
/// Whether the land between the antenna and `p` rises over the line to it.
pub(super) fn hides(&self, antenna: DVec3, p: DVec3) -> bool {
let rel = p - antenna;
@@ -78,7 +83,11 @@ impl Horizon {
/// Where a unit's radar antenna is.
pub(super) fn antenna(sam: &Sam) -> DVec3 {
sam.pos + DVec3::Y * sam.kind.spec().mast
sam.pos + DVec3::Y * sam.sensor_mast()
}
fn sensor_span(sam: &Sam) -> f64 {
sam.kind.spec().sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 }
}
/// How far a system's search radar reaches for this kind at `height` over the land:
@@ -88,8 +97,8 @@ pub(super) fn reach(sam: &Sam, kind: DroneKind, height: f64) -> f64 {
if spec.sensor <= 0.0 {
return 0.0;
}
let radar = spec.sensor * sam.radar_fit() * kind.rcs().powf(0.25);
let horizon = HORIZON * (spec.mast.sqrt() + height.max(0.0).sqrt());
let radar = spec.sensor * sam.radar_fit() * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 } * kind.rcs().powf(0.25);
let horizon = HORIZON * (sam.sensor_mast().sqrt() + height.max(0.0).sqrt());
radar.min(horizon).max(NEAR)
}
@@ -127,15 +136,17 @@ impl Sim {
/// A radar for a unit of `kind` at `pos` as the map draws it; `id`: the unit it is (its parts and horizon), None for a ghost.
pub fn low_sensor(&self, kind: SamKind, pos: DVec3, id: Option<u32>) -> Option<LowSensor> {
let spec = kind.spec();
if spec.sensor <= 0.0 {
if spec.sensor <= 0.0 || id.and_then(|i| self.sams.iter().find(|s| s.id == i)).is_some_and(|s| s.mode == battery::SamMode::LauncherOnly) {
return None;
}
let fit = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_fit());
let height = LOW_KIND.spec().clearance;
let radar = spec.sensor * fit * LOW_KIND.rcs().powf(0.25);
let reach = radar.min(HORIZON * (spec.mast.sqrt() + height.sqrt())).max(NEAR);
let terrain = id.is_some_and(|i| self.horizons.contains_key(&i));
Some(LowSensor { id: id.unwrap_or(u32::MAX), ant: pos + DVec3::Y * spec.mast, base: pos.y, reach, terrain })
let mast = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(spec.mast, |s| s.sensor_mast());
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).filter(|s| s.kind == SamKind::Radar).map_or(1.0, |s| s.radar_role.reach_factor());
let radar = spec.sensor * fit * factor * LOW_KIND.rcs().powf(0.25);
let reach = radar.min(HORIZON * (mast.sqrt() + height.sqrt())).max(NEAR);
let terrain = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).is_some_and(|s| self.horizons.get(&s.id).is_some_and(|h| h.matches(s)));
Some(LowSensor { id: id.unwrap_or(u32::MAX), ant: pos + DVec3::Y * mast, base: pos.y, reach, terrain })
}
/// The radars that are up now.
@@ -297,13 +308,26 @@ impl Track {
}
impl Sam {
/// Fictional antenna height and scan characteristics for gameplay roles.
pub(super) fn sensor_mast(&self) -> f64 {
self.kind.spec().mast + if self.kind == SamKind::Radar && self.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 }
}
pub(super) fn scan_profile(&self) -> Scan {
if self.kind != SamKind::Radar { return self.kind.scan(); }
match self.radar_role {
battery::RadarRole::Multifunction => self.kind.scan(),
battery::RadarRole::Search => Scan { period: 170, agile: false },
battery::RadarRole::Engagement => Scan { period: 70, agile: true },
battery::RadarRole::Height => Scan { period: 140, agile: false },
}
}
/// Ticks for its beam to go round (longer when the radar is damaged).
pub(super) fn scan_ticks(&self) -> f64 {
self.kind.scan().period as f64 / self.radar_fit().max(0.2)
self.scan_profile().period as f64 / self.radar_fit().max(0.2)
}
/// Its own radar works: it has one, it is not failed and the unit is deployed.
pub fn radar_up(&self) -> bool {
self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0
self.mode != battery::SamMode::LauncherOnly && self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0
}
pub fn track(&self, id: u32) -> Option<&Track> {
self.tracks.iter().find(|t| t.id == id)
@@ -339,18 +363,24 @@ impl Sim {
/// into the tracks, old tracks out, and the network's tracks shared.
pub(super) fn update_sight(&mut self, ground: &mut Ground) {
let now = self.tick;
// A role, mast or location change invalidates the cached terrain immediately.
for sam in &self.sams {
if sam.radar_up() && self.horizons.get(&sam.id).is_some_and(|h| !h.matches(sam)) {
self.horizons.insert(sam.id, Horizon::build(antenna(sam), sensor_span(sam), ground, now));
}
}
// One horizon every few ticks: the land answers come in over time.
if !self.sams.is_empty() && now % 3 == 0 {
let radars: Vec<usize> =
(0..self.sams.len()).filter(|&i| self.sams[i].alive() && self.sams[i].kind.spec().sensor > 0.0).collect();
(0..self.sams.len()).filter(|&i| self.sams[i].radar_up()).collect();
if !radars.is_empty() {
let i = radars[(now / 3) as usize % radars.len()];
let sam = &self.sams[i];
let h = Horizon::build(antenna(sam), sam.kind.spec().sensor, ground, now);
let h = Horizon::build(antenna(sam), sensor_span(sam), ground, now);
self.horizons.insert(sam.id, h);
}
}
let alive: std::collections::HashSet<u32> = self.sams.iter().filter(|s| s.alive()).map(|s| s.id).collect();
let alive: std::collections::HashSet<u32> = self.sams.iter().filter(|s| s.radar_up()).map(|s| s.id).collect();
self.horizons.retain(|id, _| alive.contains(id));
// Each drone's height over the land under it (or over the systems' ground, unknown).
let heights: Vec<Option<f64>> =
@@ -371,7 +401,7 @@ impl Sim {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
let spec = sam.kind.spec();
let scan = sam.kind.scan();
let 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));
@@ -385,7 +415,7 @@ impl Sim {
}
let rel = d.pos - at;
let dist = rel.length();
if dist > spec.sensor * 1.2 {
if dist > spec.sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor().max(1.0) * 1.2 } else { 1.2 } {
continue;
}
let locked = sam.target == Some(d.id) || sam.gun_target == Some(d.id);
@@ -393,7 +423,11 @@ impl Sim {
// The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round).
let in_beam = swept(rel.x.atan2(-rel.z), b0, w);
let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64);
if !(in_beam || locked || revisit) {
// A search radar's network track cues this fictional tracking radar to look, but is
// never itself a measurement: reach, terrain, probability and noise still apply.
let cue = sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement
&& held.is_some_and(|t| t.own_tick == 0 && t.age(now) <= MISSILE_AGE);
if !(in_beam || locked || revisit || cue) {
continue;
}
let height = h.unwrap_or(d.pos.y - sam.pos.y);
@@ -412,7 +446,7 @@ impl Sim {
if dist > NEAR && dice(seed, now, key, 0) >= p {
continue;
}
let sigma = if locked { 0.3 } else { 0.8 + dist * 0.004 };
let sigma = if locked { 0.3 } else if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement { 0.45 + dist * 0.002 } else { 0.8 + dist * 0.004 };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * 0.5, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
fresh.push(Track {
id: d.id,
@@ -435,12 +469,12 @@ impl Sim {
let shared: Vec<(u32, DVec3, f64, Vec<Track>)> = self
.sams
.iter()
.filter(|s| s.alive() && !s.moving() && s.link_range() > 0.0)
.filter(|s| s.radar_up() && s.link_range() > 0.0)
.map(|s| (s.id, s.pos, s.link_range(), s.tracks.iter().filter(|t| t.own_tick == t.tick).copied().collect::<Vec<_>>()))
.filter(|s| !s.3.is_empty())
.collect();
for sam in &mut self.sams {
if sam.alive() && !sam.moving() && sam.kind.armed() && sam.link_range() > 0.0 && !shared.is_empty() {
if sam.alive() && !sam.moving() && (sam.kind.armed() || (sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement)) && sam.link_range() > 0.0 && !shared.is_empty() {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
let mine = sam.link_range();
+124 -27
View File
@@ -308,6 +308,13 @@ impl Flight {
}
}
#[derive(Clone, Copy, Debug)]
pub(super) struct PendingStrike {
carrier: u32,
site: u32,
aim: DVec2,
}
#[derive(Default)]
pub struct Strikes {
/// Strike missiles left, and ticks towards the next.
@@ -315,6 +322,7 @@ pub struct Strikes {
pub progress: u32,
pub known: Vec<Known>,
pub flights: Vec<Flight>,
pub(super) pending: Vec<PendingStrike>,
flown: Vec<Flown>,
next: u32,
/// Smoking wrecks: (where, until).
@@ -581,7 +589,10 @@ impl Sim {
let from = f.pos;
// Time spent waiting for world data must not accumulate into a faster step.
let delta = planned - from;
let want = from + delta.clamp_length_max(TUNE.speed);
let speed = if f.carrier.is_some() && age >= EJECT_TICKS {
TUNE.speed * (0.2 + 0.8 * ((age - EJECT_TICKS) as f64 / 20.0).clamp(0.0, 1.0))
} else { TUNE.speed };
let want = from + delta.clamp_length_max(speed);
// A missile that never reaches its point (the world never tells of the way) ends somewhere: it does
// not stay in the air for ever.
if now >= f.arrive + 600 {
@@ -671,6 +682,7 @@ impl Sim {
/// while these exist, and let go after.
pub(super) fn site_refs(&mut self) -> Vec<u32> {
let mut v: Vec<u32> = self.strikes.flights.iter().map(|f| f.site).collect();
v.extend(self.strikes.pending.iter().map(|p| p.site));
let alive: Vec<u32> = self.drones.iter().filter(|d| d.alive()).map(|d| d.id).collect();
v.extend(self.strikes.scouted(&alive));
v.extend(self.sites.flying_sites(&alive));
@@ -679,42 +691,77 @@ impl Sim {
v
}
/// Atomic manual launch from an already prepared, compatible carrier.
pub fn order_strike(&mut self, id: u32, _from: DVec3, out: &mut Out) -> Result<String, String> {
/// Reserve a physical carrier and its cell; ammunition is spent only on ejection.
pub fn order_strike(&mut self, id: u32, _from: DVec3, _out: &mut Out) -> Result<String, String> {
let k = self.strikes.get(id).ok_or_else(|| format!("ПУ №{id} не найдена"))?;
let est = k.est.filter(|e| e.fix).ok_or("Место ПУ неизвестно: нужна разведка")?;
if matches!(k.state, SiteState::Destroyed(_)) { return Err("ПУ уже уничтожена".into()); }
if self.strikes.flights.iter().any(|f| f.site == id) { return Err("По этой ПУ ракета уже в полёте".into()); }
let site = self.sites.get(id).ok_or("ПУ уже нет на карте")?;
let snap = Target { pos: DVec2::new(site.pos.x, site.pos.z), stock: site.stock, offmap: site.offmap, alive: site.alive };
let (i, dist) = self.sams.iter().enumerate().filter_map(|(i,s)| {
if self.strikes.flights.iter().any(|f| f.site == id) || self.strikes.pending.iter().any(|p| p.site == id) {
return Err("По этой ПУ ракета уже готовится или в полёте".into());
}
if !self.sites.get(id).is_some_and(|s| s.alive) { return Err("ПУ уже нет на карте".into()); }
let (i, _) = self.sams.iter().enumerate().filter_map(|(i,s)| {
let dist = (est.pos - DVec2::new(s.pos.x, s.pos.z)).length();
(matches!(catalog::unit(s.kind).ground_strike(), catalog::GroundStrike::Rm48uGame)
&& s.alive() && !s.moving() && s.reloading == 0 && s.cooldown == 0
&& s.part(Part::Launcher) > 0.0 && s.ground_rounds > 0 && dist <= TUNE.range)
&& s.part(Part::Launcher) > 0.0 && s.ground_rounds > 0 && s.preparing.is_none() && dist <= TUNE.range)
.then_some((i, dist))
}).min_by(|(i,a), (j,b)| self.sams[*j].ground_rounds.cmp(&self.sams[*i].ground_rounds)
.then(a.total_cmp(b)).then(self.sams[*i].id.cmp(&self.sams[*j].id)))
.ok_or("Нет готового С-400 с загруженной RM48U в игровой дальности; подготовьте боезапас у склада")?;
let sam = &mut self.sams[i];
let carrier = sam.id;
let (start, _) = sam.muzzle(4 - sam.ground_rounds);
sam.ground_rounds -= 1;
sam.cooldown = 20;
sam.launched = 12;
sam.fired += 1;
self.intel.revealed.push((carrier, sam.pos, self.tick));
self.strikes.fired += 1;
self.strikes.next += 1;
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, id as u64, 7), gauss(self.seed, self.strikes.next as u64, id as u64, 8));
self.strikes.flights.push(Flight { id: self.strikes.next, site: id, carrier: Some(carrier), from: start, pos: start, aim: est.pos,
land: est.pos + DVec2::new(gx, gz) * TUNE.cep, start: self.tick, arrive: self.tick + ticks, snap, hold: 0 });
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == id) { k.aimed = true; }
self.record_strike_launch(self.strikes.next, carrier, start);
out.sound("airdef:launch.s400_eject", start, 1.0, 1.0);
out.particles("minecraft:cloud", start, 0.6, DVec3::Y * 0.05, 0.05, 30);
Ok(format!("С-400 №{} запустил RM48U по ПУ №{id}; осталось ударных: {}", i + 1, self.sams[i].ground_rounds))
sam.sync_tube_cells();
let cell = sam.next_tube_cell();
sam.preparing = Some(launch::Prepare { target: id, cell, start: self.tick, ground: true });
sam.cap_cell = cell as u8;
sam.cap_open = 0.0;
self.strikes.pending.push(PendingStrike { carrier: sam.id, site: id, aim: est.pos });
Ok(format!("С-400 №{} готовит RM48U по ПУ №{id}", i + 1))
}
pub(super) fn prepare_ground_strikes(&mut self, out: &mut Out) {
let pending = std::mem::take(&mut self.strikes.pending);
for p in pending {
let Some(i) = self.sams.iter().position(|s| s.id == p.carrier) else { continue };
let valid_site = self.sites.get(p.site).is_some_and(|s| s.alive)
&& self.strikes.get(p.site).is_some_and(|k| !matches!(k.state, SiteState::Destroyed(_)));
let sam = &self.sams[i];
let valid = valid_site && sam.preparing.is_some_and(|q| q.ground && q.target == p.site)
&& sam.alive() && !sam.moving() && sam.reloading == 0 && sam.cooldown == 0
&& sam.part(Part::Launcher) > 0.0 && sam.ground_rounds > 0;
if !valid {
out.messages.push(format!("Подготовка RM48U по ПУ №{} отменена: изменилось состояние носителя или цели", p.site));
if self.sams[i].preparing.is_some_and(|q| q.ground && q.target == p.site) { self.sams[i].cancel_prepare(); }
continue;
}
let prep = self.sams[i].preparing.unwrap();
self.sams[i].cap_open = (self.tick.saturating_sub(prep.start) as f32 / launch::OPEN_TICKS as f32).clamp(0.0, 1.0);
if self.tick.saturating_sub(prep.start) < launch::OPEN_TICKS {
self.strikes.pending.push(p);
continue;
}
let site = self.sites.get(p.site).unwrap();
let snap = Target { pos: DVec2::new(site.pos.x, site.pos.z), stock: site.stock, offmap: site.offmap, alive: site.alive };
let sam = &mut self.sams[i];
let (start, _) = sam.muzzle(prep.cell);
sam.eject_cell(prep.cell);
sam.ground_rounds -= 1;
sam.cooldown = 20;
sam.launched = 12;
sam.fired += 1;
let dist = (p.aim - DVec2::new(sam.pos.x, sam.pos.z)).length();
self.intel.revealed.push((p.carrier, sam.pos, self.tick));
self.strikes.fired += 1;
self.strikes.next += 1;
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, p.site as u64, 7), gauss(self.seed, self.strikes.next as u64, p.site as u64, 8));
self.strikes.flights.push(Flight { id: self.strikes.next, site: p.site, carrier: Some(p.carrier), from: start, pos: start, aim: p.aim,
land: p.aim + DVec2::new(gx, gz) * TUNE.cep, start: self.tick, arrive: self.tick + ticks, snap, hold: 0 });
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == p.site) { k.aimed = true; }
self.record_strike_launch(self.strikes.next, p.carrier, start);
out.sound("airdef:launch.s400_eject", start, 1.0, 1.0);
out.particles("minecraft:cloud", start, 0.6, DVec3::Y * 0.05, 0.05, 30);
}
}
/// Synthetic launcher used only by flight/impact regression fixtures; absent from production builds.
@@ -1243,9 +1290,13 @@ mod tests {
sim.load_ground_round(a).unwrap();
sim.sams[a].cooldown = 0;
sim.sams[b].cooldown = 0;
let muzzle = sim.sams[b].muzzle(2).0;
let cell = sim.sams[b].next_tube_cell();
let muzzle = sim.sams[b].muzzle(cell).0;
let old_stock = sim.strikes.stock;
sim.order_strike(site, DVec3::new(99999.0, 0.0, 99999.0), &mut out).unwrap();
assert_eq!((sim.sams[a].ground_rounds, sim.sams[b].ground_rounds, sim.strikes.stock), (1, 2, old_stock));
assert!(sim.order_strike(site, DVec3::ZERO, &mut out).is_err());
run(&mut sim, &mut ground, &mut out, launch::OPEN_TICKS as u32 + 1);
assert_eq!((sim.sams[a].ground_rounds, sim.sams[b].ground_rounds, sim.strikes.stock), (1, 1, old_stock));
let f = sim.strikes.flights.last().unwrap();
assert_eq!((f.carrier, f.from), (Some(b_id), muzzle));
@@ -1256,6 +1307,52 @@ mod tests {
assert!(sim.sams[b].missiles + sim.sams[b].ground_rounds <= 4);
}
#[test]
fn ground_preparation_cancels_without_spending_when_carrier_or_site_changes() {
for reason in 0..6 {
let mut sim = Sim::new(11);
let site = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 300.0), 0);
let mut sam = Sam::new(123, SamKind::S400, DVec3::ZERO, 0.0);
sam.missiles = 2; sam.ground_rounds = 2; sam.cooldown = 0;
sim.sams.push(sam);
let mut out = Out::default();
sim.order_strike(site, DVec3::ZERO, &mut out).unwrap();
match reason {
0 => sim.sams[0].health = 0.0,
1 => sim.sams[0].state = SamState::Moving,
2 => sim.sams[0].reloading = 5,
3 => sim.sams[0].cooldown = 5,
4 => sim.sams[0].ground_rounds = 0,
_ => sim.sites.list.iter_mut().find(|s| s.id == site).unwrap().alive = false,
}
sim.tick += launch::OPEN_TICKS;
sim.prepare_ground_strikes(&mut out);
assert!(sim.strikes.pending.is_empty() && sim.strikes.flights.is_empty());
assert_eq!(sim.strikes.fired, 0);
assert_eq!(sim.sams[0].ground_rounds, if reason == 4 { 0 } else { 2 });
assert!(sim.sams[0].preparing.is_none());
}
}
#[test]
fn ground_orders_reserve_the_carrier_and_target_until_ejection() {
let mut sim = Sim::new(11);
let a = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 300.0), 0);
let b = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 400.0), 0);
let mut sam = Sam::new(123, SamKind::S400, DVec3::ZERO, 0.0);
sam.missiles = 2; sam.ground_rounds = 2; sam.cooldown = 0;
sim.sams.push(sam);
let mut out = Out::default();
sim.order_strike(a, DVec3::ZERO, &mut out).unwrap();
assert!(sim.order_strike(a, DVec3::ZERO, &mut out).is_err());
assert!(sim.order_strike(b, DVec3::ZERO, &mut out).is_err());
assert_eq!(sim.sams[0].ground_rounds, 2);
sim.tick += launch::OPEN_TICKS;
sim.prepare_ground_strikes(&mut out);
assert_eq!((sim.sams[0].ground_rounds, sim.strikes.fired, sim.strikes.flights.len()), (1, 1, 1));
assert!(sim.strikes.pending.is_empty());
}
#[test]
fn fully_loaded_ground_cells_do_not_consume_air_reload_cargo() {
let mut sim = Sim::new(1);
+14 -3
View File
@@ -279,7 +279,7 @@ impl SamKind {
const S: SamSpec = SamSpec {
name: "С-500",
key: "s500",
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 4, min: 40.0, max: 1050.0, interval: 20 }),
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1050.0, interval: 20 }),
gun: None,
reload: 520,
scale: 1.6,
@@ -681,6 +681,7 @@ pub(super) fn draw_sam_model(sam: &Sam, rng: &mut Rng, out: &mut Out) {
}
Family::Static | Family::Truck => {}
}
if sam.mode != battery::SamMode::LauncherOnly {
if let Some((model, h, f, tilt)) = parts.dish {
part(out, model, mount + turret * DVec3::new(0.0, h * s, f * s), DQuat::from_rotation_y(sam.dish) * DQuat::from_rotation_x(tilt), s);
}
@@ -688,9 +689,19 @@ pub(super) fn draw_sam_model(sam: &Sam, rng: &mut Rng, out: &mut Out) {
part(out, model, sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s), base, s);
}
if let Some((model, h, back, size, tilt)) = parts.spinner {
let at = sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s);
part(out, model, at, DQuat::from_rotation_y(sam.dish * 0.6) * DQuat::from_rotation_x(tilt), s * size);
let extra = if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 };
let foot = sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s);
for segment in 0..(extra as u32 / 2) {
part(out, "airdef:radar_mast", foot + DVec3::Y * (segment as f64 * 2.0 + 0.5), base, 1.0);
}
let at = foot + DVec3::Y * extra;
let heading = if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement {
sam.tracks.first().map_or(sam.dish * 0.6, |t| heading_of(t.pos - sam.pos))
} else { sam.dish * 0.6 };
part(out, model, at, DQuat::from_rotation_y(heading) * DQuat::from_rotation_x(tilt), s * size);
}
}
launch::draw_caps(sam, out);
if sam.flash > 0 {
let barrels: &[DVec3] = match sam.kind {
SamKind::Pantsir => &[DVec3::new(-0.95, 0.33, -1.7), DVec3::new(0.95, 0.33, -1.7)],
+68 -7
View File
@@ -92,11 +92,14 @@ impl SamKind {
/// A live big radar in data-link reach of `sam` that measured `id` recently.
pub(super) fn radar_cue(sam: &Sam, radars: &[&Sam], id: u32, now: u64) -> bool {
radars.iter().any(|r| {
r.alive()
r.radar_role.authorizes()
&& r.link_range() > 0.0
&& sam.link_range() > 0.0
&& r.alive()
&& !r.moving()
&& r.radar_up()
&& r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range())
&& r.track(id).is_some_and(|t| t.own_tick > 0 && t.age(now) <= FAR_RADAR_AGE)
&& r.track(id).is_some_and(|t| t.own_tick > 0 && now.saturating_sub(t.own_tick) <= if sam.mode == battery::SamMode::LauncherOnly { sight::MISSILE_AGE } else { FAR_RADAR_AGE })
})
}
@@ -134,6 +137,7 @@ pub(super) struct Opts {
/// `role_in_reach` that the system has a target of its roles in range anyway (no long shots then).
#[allow(clippy::too_many_arguments)]
pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Drone, now: u64, claimed: u32, k: f64, opts: Opts, cued: bool, role_in_reach: bool) -> Option<Basis> {
if sam.mode == battery::SamMode::LauncherOnly && !cued { return None; }
let blocks = target_blocks(sam.roles, Some(track), now, d);
if blocks & !ROLE != 0 {
return None;
@@ -390,12 +394,16 @@ impl Sim {
_ => "не обнаружена ни своей РЛС, ни сетью".to_string(),
};
v.push(check(blocks & (UNSEEN | STALE) == 0, detect));
if sam.kind.spec().sensor > 0.0 {
if sam.mode == battery::SamMode::LauncherOnly {
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
let connected = radar_cue(sam, &radars, t.id, now);
v.push(check(connected, if connected { "внешняя РЛС: свежий трек по связи" } else { "внешняя РЛС: нет свежего трека или связи" }.to_string()));
} else if sam.kind.spec().sensor > 0.0 {
let period = sam.scan_ticks();
v.push(check(
sam.radar_up(),
if sam.radar_up() {
format!("обзор: оборот {:.1} с{}, луч на {:.0}°", period / 20.0, if sam.kind.scan().agile { ", электронный, цели в треке чаще" } else { "" }, sam.beam.to_degrees())
format!("обзор: оборот {:.1} с{}, луч на {:.0}°", period / 20.0, if sam.scan_profile().agile { ", электронный, цели в треке чаще" } else { "" }, sam.beam.to_degrees())
} else {
"обзор: РЛС не работает".to_string()
},
@@ -427,7 +435,7 @@ impl Sim {
let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est);
// Beyond the normal reach, a heavy system may fire on a big radar's cue.
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
let cued = sam.kind.far_shooter() && radar_cue(sam, &radars, t.id, now);
let cued = radar_cue(sam, &radars, t.id, now);
let role_in_reach = self.drones.iter().any(|o| {
sam.track(o.id).is_some_and(|tr| allowed(sam.roles, tr, now, o) && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o))
});
@@ -483,7 +491,7 @@ impl Sim {
));
}
let doc_ok = chance || area | held_back == 0;
let grounds = blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok);
let grounds = (sam.mode != battery::SamMode::LauncherOnly || cued) && blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok);
fires |= grounds && free < need && mb == 0 && aligned && land == 0;
}
if let Some(gun) = &spec.gun {
@@ -516,6 +524,11 @@ impl Sim {
v.push(check(gb == 0, if gb == 0 { "орудие готово".to_string() } else { format!("орудие не стреляет: {}", why.join(", ")) }));
fires |= gb == 0 && cand;
}
if let Some(p) = sam.preparing {
let opening = p.ground || now.saturating_sub(p.start) < launch::OPEN_TICKS;
v.push(check(!opening, format!("подготовка пуска: открывается крышка ТПК №{}", p.cell + 1)));
fires &= !opening;
}
v.push(check(fires, if fires { "итог: готова стрелять" } else { "итог: стрелять сейчас не может" }));
v
}
@@ -686,7 +699,8 @@ mod tests {
let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4);
let far = sim.drones[0].id;
sim.add_drone(DroneKind::Kh101, DVec3::new(300.0, 120.0, 0.0), DVec3::NEG_X, DVec3::new(0.0, 70.0, 0.0));
for _ in 0..40 {
// The launcher must finish opening its TPK after the initial readiness cooldown.
for _ in 0..40 + launch::OPEN_TICKS {
radar_sees(&mut sim);
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
@@ -695,6 +709,53 @@ mod tests {
assert!(sim.sams[0].fired > 0, "the closer target was not fired at");
}
#[test]
fn cold_launch_opens_before_spending_and_lights_only_after_ejection() {
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
sim.last_chance = false;
sim.sams[0].cooldown = 0;
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 160.0, -300.0), DVec3::Z, DVec3::ZERO);
let initial = sim.sams[0].missiles;
for _ in 0..200 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
if sim.sams[0].preparing.is_some() { break; }
}
assert!(sim.sams[0].preparing.is_some(), "a real tracked target must open a TPK");
assert_eq!(sim.sams[0].missiles, initial);
assert!(sim.missiles.is_empty());
// Loss during opening cancels without creating or consuming a missile.
sim.sams[0].health = 0.0;
sim.step(&mut ground, None, &mut out);
assert!(sim.sams[0].preparing.is_none() && sim.missiles.is_empty());
assert_eq!(sim.sams[0].missiles, initial);
sim.sams[0].health = 1.0;
sim.sams[0].cooldown = 0;
for _ in 0..200 {
out = Out::default();
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
if !sim.missiles.is_empty() { break; }
}
let m = sim.missiles.first().expect("ejection after reopening");
let (id, kind) = (m.id, m.kind);
assert_eq!(sim.sams[0].missiles, initial - 1);
assert_eq!(sim.sams[0].spent_cells.count_ones(), 1);
assert!(!m.engine_lit());
assert!(!out.engines.iter().any(|e| e.key == 0x4000_0000 | id));
let mut last_speed = m.vel.length();
for _ in 0..kind.lit_after() + 3 {
out = Out::default();
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
let m = sim.missiles.iter().find(|m| m.id == id).expect("cold launch remains in flight");
let voice = out.engines.iter().any(|e| e.key == 0x4000_0000 | id);
assert_eq!(voice, m.engine_lit());
if m.engine_lit() { assert!(m.vel.length() > last_speed, "the lit motor must accelerate"); }
last_speed = m.vel.length();
}
}
#[test]
fn the_kill_chance_falls_to_half_at_the_far_end() {
assert_eq!(reach_fit(100.0, 80.0), 1.0);