//! The simulation: drones, interceptors, air-defence systems and effects, //! one step a game tick. It knows nothing of the game: what it needs from //! the world comes in (`ground`, the player's position), what it wants to //! happen goes out as [`Out`] (models, particles, sounds, commands). //! //! Every kind of drone, missile and air-defence system is a row of numbers //! (`DroneKind::spec`, `MissileKind::spec`, `SamKind::spec`) plus how its //! parts are drawn (`Sim::draw_sam`). use glam::{DQuat, DVec3}; use std::collections::HashMap; mod damage; mod raid; pub mod record; mod sight; mod ew; mod lights; mod logistics; mod orders; mod units; mod why; #[cfg(test)] mod regress; pub use ew::EW_RADIUS; pub use units::{Family, SamKind}; use units::Muzzle; pub use raid::{Approach, Aim, RaidOrder}; pub const TAU: f64 = std::f64::consts::TAU; const HALF_PI: f64 = std::f64::consts::FRAC_PI_2; // ---------------------------------------------------------------- output /// A model to draw this tick (the mod turns these into `render.set-models`). pub struct Model { pub id: u32, pub name: &'static str, pub at: DVec3, pub rotation: DQuat, pub scale: f32, pub glow: bool, } pub struct Particle { pub kind: &'static str, pub at: DVec3, pub spread: [f32; 3], pub velocity: DVec3, pub speed: f32, pub count: u32, pub color: u32, pub scale: f32, } /// A blast the post-processing shader draws as a fireball, flash and shock. #[derive(Clone, Copy)] pub struct Blast { /// Never reused while the simulation lives: the HD light keeps its identity through the blast's life. pub id: u32, pub at: DVec3, /// Fireball radius in blocks. pub size: f32, /// The tick it went off. pub start: u64, pub life: u32, } #[derive(Default)] pub struct Out { pub models: Vec, pub particles: Vec, pub sounds: Vec<(&'static str, DVec3, f32, f32)>, pub commands: Vec, /// Camera jolt (strength, seconds), the strongest this tick. pub shake: Option<(f32, f32)>, pub messages: Vec, } impl Out { fn model(&mut self, id: u32, name: &'static str, at: DVec3, rotation: DQuat, scale: f64, glow: bool) { self.models.push(Model { id, name, at, rotation, scale: scale as f32, glow }); } fn particles(&mut self, kind: &'static str, at: DVec3, spread: f32, velocity: DVec3, speed: f32, count: u32) { self.particles.push(Particle { kind, at, spread: [spread; 3], velocity, speed, count, color: 0, scale: 1.0 }); } fn dust(&mut self, at: DVec3, color: u32, scale: f32, spread: f32, count: u32) { self.particles.push(Particle { kind: "minecraft:dust", at, spread: [spread; 3], velocity: DVec3::ZERO, speed: 0.0, count, color, scale, }); } pub fn sound(&mut self, event: &'static str, at: DVec3, volume: f32, pitch: f32) { self.sounds.push((event, at, volume, pitch)); } fn jolt(&mut self, strength: f32, seconds: f32) { if self.shake.is_none_or(|(s, _)| s < strength) { self.shake = Some((strength.min(1.0), seconds)); } } } // ---------------------------------------------------------------- maths /// A small xorshift: the simulation's own randomness. pub struct Rng(u64); impl Rng { pub fn new(seed: u64) -> Self { Self(seed | 1) } /// The generator's state: `new(state())` continues the same sequence. pub fn state(&self) -> u64 { self.0 } pub fn next(&mut self) -> u64 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 7; self.0 ^= self.0 << 17; self.0 } /// 0..1 pub fn f(&mut self) -> f64 { (self.next() >> 11) as f64 / (1u64 << 53) as f64 } /// -1..1 pub fn s(&mut self) -> f64 { self.f() * 2.0 - 1.0 } pub fn chance(&mut self, p: f64) -> bool { self.f() < p } } /// The models' noses point north (-z): the rotation that points one along /// `dir`, rolled by `roll` (radians, right wing down positive). pub fn look(dir: DVec3, roll: f64) -> DQuat { let d = dir.normalize_or(DVec3::NEG_Z); DQuat::from_rotation_y(heading_of(d)) * DQuat::from_rotation_x(d.y.clamp(-1.0, 1.0).asin()) * DQuat::from_rotation_z(-roll) } /// The yaw `look` gives a direction (0 = north, radians). pub fn heading_of(d: DVec3) -> f64 { (-d.x).atan2(-d.z) } /// `from` turned towards `to` by at most `max` radians. fn turn(from: DVec3, to: DVec3, max: f64) -> DVec3 { let a = from.normalize_or(DVec3::NEG_Z); let b = to.normalize_or(a); let angle = a.angle_between(b); if angle <= max || angle < 1e-9 { return b; } let axis = a.cross(b); let axis = if axis.length_squared() < 1e-12 { a.any_orthonormal_vector() } else { axis.normalize() }; DQuat::from_axis_angle(axis, max) * a } pub fn horizontal(v: DVec3) -> DVec3 { DVec3::new(v.x, 0.0, v.z) } /// Turns `from` towards `to` (angles, radians) by at most `rate`. fn slew(from: f64, to: f64, rate: f64) -> f64 { from + angle_diff(from, to).clamp(-rate, rate) } /// One axis of a drive: speeds up towards `err` (the angle still to turn), brakes in time to stop on it, /// and returns the turn this tick. Arriving takes the last bit at once, so there is no overshoot or jitter. fn drive(vel: &mut f64, err: f64, speed: f64, accel: f64) -> f64 { // The fastest it may go and still stop within what is left. let fastest = (2.0 * accel * err.abs()).sqrt().min(speed); let want = fastest.copysign(err); *vel = (*vel + (want - *vel).clamp(-accel, accel)).clamp(-speed, speed); if vel.abs() >= err.abs() && vel.signum() == err.signum() { *vel = 0.0; return err; } *vel } /// Moves one system's claim from the drone it had to the one it has, in a count of claims per drone. fn retarget(counts: &mut HashMap, from: Option, to: Option) { if from == to { return; } if let Some(n) = from.and_then(|id| counts.get_mut(&id)) { *n = n.saturating_sub(1); } if let Some(id) = to { *counts.entry(id).or_insert(0) += 1; } } fn angle_diff(from: f64, to: f64) -> f64 { (to - from + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI } // ---------------------------------------------------------------- the world /// Ground heights the game answered (`render.ground`), by column. #[derive(Default)] pub struct Ground { known: HashMap<(i32, i32), (i32, u64)>, wanted: Vec<(i32, i32)>, asked: std::collections::HashSet<(i32, i32)>, /// The tick of the last full clean-up (a big cache would otherwise be scanned on every answer). swept: u64, } /// Ticks between full clean-ups of a big ground cache. const SWEEP_EVERY: u64 = 200; impl Ground { /// One above the highest solid block, if known; the column is asked for /// when it isn't (or is old). pub fn at(&mut self, p: DVec3, now: u64) -> Option { let key = (p.x.floor() as i32, p.z.floor() as i32); match self.known.get(&key) { Some(&(y, when)) => { // Refreshes of known columns take at most a quarter of the questions: the rest // stay free for columns never seen, or those would starve. if now.saturating_sub(when) > 200 && self.wanted.len() < 64 && self.asked.insert(key) { self.wanted.push(key); } (y > -64).then_some(f64::from(y)) } None => { if self.wanted.len() < 256 && self.asked.insert(key) { self.wanted.push(key); } None } } } pub fn answer(&mut self, answers: Vec<(i32, i32, i32)>, now: u64) { for (x, z, y) in answers { self.known.insert((x, z), (y, now)); } if self.known.len() > 300_000 && now.saturating_sub(self.swept) >= SWEEP_EVERY { self.swept = now; self.known.retain(|_, (_, when)| now.saturating_sub(*when) < 2000); } } pub fn take_wanted(&mut self) -> Vec<(i32, i32)> { self.asked.clear(); std::mem::take(&mut self.wanted) } /// Explosions change the land: forget what was known round them. fn forget(&mut self, at: DVec3, radius: i32) { let (cx, cz) = (at.x.floor() as i32, at.z.floor() as i32); self.known.retain(|&(x, z), _| (x - cx).abs() > radius || (z - cz).abs() > radius); } } // ---------------------------------------------------------------- drones /// What kind of target it is, for air defence's roles. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Class { /// Slow propeller drones. Drone, /// Jet drones. Jet, /// Subsonic cruise missiles. Cruise, /// Supersonic and hypersonic missiles. Supersonic, /// Ballistic and aeroballistic missiles. Ballistic, } impl Class { pub const ALL: [Class; 5] = [Class::Drone, Class::Jet, Class::Cruise, Class::Supersonic, Class::Ballistic]; pub fn bit(self) -> u8 { 1 << self as u8 } pub fn key(self) -> &'static str { match self { Class::Drone => "drone", Class::Jet => "jet", Class::Cruise => "cruise", Class::Supersonic => "supersonic", Class::Ballistic => "ballistic", } } pub fn name(self) -> &'static str { match self { Class::Drone => "дроны", Class::Jet => "реакт. дроны", Class::Cruise => "крылатые", Class::Supersonic => "сверхзвуковые", Class::Ballistic => "баллистика", } } /// A short mark for the summary. pub fn letter(self) -> &'static str { match self { Class::Drone => "Д", Class::Jet => "Г", Class::Cruise => "К", Class::Supersonic => "С", Class::Ballistic => "Б", } } pub fn from_key(key: &str) -> Option { Self::ALL.into_iter().find(|c| c.key() == key) } } /// Roles as a mask of [`Class::bit`]s, from `drone,jet,...` or `all`. pub fn parse_roles(text: &str) -> Option { if text == "all" { return Some(0x1F); } let mut mask = 0; for word in text.split(',') { mask |= Class::from_key(word.trim())?.bit(); } Some(mask) } pub fn roles_text(mask: u8) -> String { Class::ALL.iter().filter(|c| mask & c.bit() != 0).map(|c| c.letter()).collect::>().join("") } /// Ballistic flight's gravity, blocks a tick². const GRAVITY: f64 = 0.05; #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] pub enum DroneKind { Shahed, Geran3, Lancet, Gerbera, Kh101, Kalibr, Kh22, Zircon, Iskander, Kinzhal, /// An IRBM: its bus releases six blocks high over the target. Oreshnik, /// One of the Oreshnik's blocks: it splits into six glowing submunitions. OreshnikBlock, OreshnikSub, } /// What a drone carries on its tail. #[derive(Clone, Copy)] enum Engine { /// A pusher propeller this far behind the centre (model blocks), this big. Prop(f64, f64), /// A jet's flame at (up, back) model blocks, this big. Jet(f64, f64, f64), /// A rocket motor's long flame this far behind the centre, this big. Rocket(f64, f64), } pub struct DroneSpec { pub name: &'static str, pub key: &'static str, model: &'static str, speed: f64, turn: f64, /// Height over the target it cruises at. cruise: f64, /// Height it keeps over the land it flies over. clearance: f64, /// Horizontal distance from the target where it dives. dive: f64, /// Primed TNT on impact. warhead: u32, scale: f64, engine: Engine, /// No warhead: it only draws fire. pub decoy: bool, /// How hard it is to hit (1 normal). stealth: f64, /// Its sound: event, pitch, every n ticks. sound: (&'static str, f32, u32), pub class: Class, /// Ballistic: launched this far away on a raid, flying an arc. pub ballistic: Option, } impl DroneKind { pub const ALL: [DroneKind; 13] = [ DroneKind::Shahed, DroneKind::Geran3, DroneKind::Lancet, DroneKind::Gerbera, DroneKind::Kh101, DroneKind::Kalibr, DroneKind::Kh22, DroneKind::Zircon, DroneKind::Iskander, DroneKind::Kinzhal, DroneKind::Oreshnik, DroneKind::OreshnikBlock, DroneKind::OreshnikSub, ]; /// The sound of a launch from the ground: a light catapult shot, a rocket booster, a heavy ballistic launch. pub fn launch_sound(self) -> &'static str { match self { DroneKind::Shahed | DroneKind::Geran3 | DroneKind::Lancet | DroneKind::Gerbera => "airdef:launch.s400_eject", DroneKind::Kh101 | DroneKind::Kalibr | DroneKind::Kh22 => "airdef:launch.patriot", DroneKind::Zircon => "airdef:launch.s400", DroneKind::Iskander | DroneKind::Kinzhal | DroneKind::Oreshnik | DroneKind::OreshnikBlock | DroneKind::OreshnikSub => { "airdef:launch.s500" } } } pub fn spec(self) -> &'static DroneSpec { match self { DroneKind::Shahed => &DroneSpec { name: "Шахед-136", key: "shahed", model: "airdef:shahed", speed: 0.6, turn: 0.035, cruise: 45.0, clearance: 18.0, dive: 32.0, warhead: 3, scale: 1.3, engine: Engine::Prop(1.34, 1.0), decoy: false, stealth: 1.0, sound: ("airdef:drone.shahed", 1.0, 48), class: Class::Drone, ballistic: None, }, DroneKind::Geran3 => &DroneSpec { name: "Герань-3", key: "geran3", model: "airdef:geran3", speed: 1.6, turn: 0.03, cruise: 60.0, clearance: 18.0, dive: 50.0, warhead: 2, scale: 1.15, engine: Engine::Jet(0.34, 1.55, 1.0), decoy: false, stealth: 1.1, sound: ("airdef:drone.geran3", 1.0, 40), class: Class::Jet, ballistic: None, }, DroneKind::Lancet => &DroneSpec { name: "Ланцет-3", key: "lancet", model: "airdef:lancet", speed: 1.1, turn: 0.07, cruise: 25.0, clearance: 10.0, dive: 38.0, warhead: 1, scale: 0.9, engine: Engine::Prop(0.93, 0.55), decoy: false, stealth: 1.4, sound: ("airdef:drone.lancet", 1.0, 32), class: Class::Drone, ballistic: None, }, DroneKind::Gerbera => &DroneSpec { name: "Гербера", key: "gerbera", model: "airdef:gerbera", speed: 0.5, turn: 0.04, cruise: 40.0, clearance: 15.0, dive: 30.0, warhead: 0, scale: 1.1, engine: Engine::Prop(1.03, 0.9), decoy: true, stealth: 0.9, sound: ("airdef:drone.shahed", 1.3, 40), class: Class::Drone, ballistic: None, }, DroneKind::Kh101 => &DroneSpec { name: "Х-101", key: "kh101", model: "airdef:kh101", speed: 2.4, turn: 0.025, cruise: 0.0, clearance: 12.0, dive: 26.0, warhead: 6, scale: 1.6, engine: Engine::Jet(-0.27, 1.4, 0.6), decoy: false, stealth: 1.5, sound: ("airdef:drone.cruise", 1.0, 50), class: Class::Cruise, ballistic: None, }, DroneKind::Kalibr => &DroneSpec { name: "Калибр", key: "kalibr", model: "airdef:kalibr", speed: 2.1, turn: 0.025, cruise: 0.0, clearance: 15.0, dive: 26.0, warhead: 5, scale: 1.5, engine: Engine::Jet(-0.2, 1.5, 0.6), decoy: false, stealth: 1.3, sound: ("airdef:drone.cruise", 1.2, 50), class: Class::Cruise, ballistic: None, }, DroneKind::Kh22 => &DroneSpec { name: "Х-22", key: "kh22", model: "airdef:kh22", speed: 4.0, turn: 0.03, cruise: 140.0, clearance: 40.0, dive: 150.0, warhead: 7, scale: 1.8, engine: Engine::Rocket(1.5, 1.3), decoy: false, stealth: 1.4, sound: ("airdef:drone.rocket", 0.8, 46), class: Class::Supersonic, ballistic: None, }, DroneKind::Zircon => &DroneSpec { name: "Циркон", key: "zircon", model: "airdef:zircon", speed: 5.5, turn: 0.025, cruise: 90.0, clearance: 30.0, dive: 110.0, warhead: 6, scale: 1.4, engine: Engine::Rocket(1.5, 1.1), decoy: false, stealth: 2.0, sound: ("airdef:drone.rocket", 1.35, 46), class: Class::Supersonic, ballistic: None, }, DroneKind::Iskander => &DroneSpec { name: "Искандер-М", key: "iskander", model: "airdef:iskander", speed: 5.0, turn: 0.04, cruise: 0.0, clearance: 0.0, dive: 0.0, warhead: 8, scale: 1.8, engine: Engine::Rocket(1.5, 1.6), decoy: false, stealth: 1.6, sound: ("airdef:drone.rocket", 0.7, 46), class: Class::Ballistic, ballistic: Some(1000.0), }, DroneKind::Kinzhal => &DroneSpec { name: "Кинжал", key: "kinzhal", model: "airdef:kinzhal", speed: 7.5, turn: 0.03, cruise: 0.0, clearance: 0.0, dive: 0.0, warhead: 8, scale: 1.7, engine: Engine::Rocket(1.5, 1.5), decoy: false, stealth: 2.2, sound: ("airdef:drone.rocket", 0.6, 46), class: Class::Ballistic, ballistic: Some(1500.0), }, DroneKind::Oreshnik => &DroneSpec { name: "Орешник", key: "oreshnik", model: "airdef:iskander", speed: 9.0, turn: 0.0, cruise: 0.0, clearance: 0.0, dive: 0.0, warhead: 0, scale: 2.6, engine: Engine::Rocket(1.5, 2.4), decoy: false, stealth: 3.0, sound: ("airdef:drone.rocket", 0.5, 46), class: Class::Ballistic, ballistic: Some(2600.0), }, DroneKind::OreshnikBlock => &DroneSpec { name: "Орешник: блок", key: "oreshnik_block", model: "airdef:reentry", speed: 9.0, turn: 0.0, cruise: 0.0, clearance: 0.0, dive: 0.0, warhead: 4, scale: 1.6, engine: Engine::Rocket(1.0, 1.0), decoy: false, stealth: 3.5, sound: ("airdef:drone.ballistic", 0.8, 9999), class: Class::Ballistic, ballistic: None, }, DroneKind::OreshnikSub => &DroneSpec { name: "Орешник: суббоеприпас", key: "oreshnik_sub", model: "airdef:reentry", speed: 9.0, turn: 0.05, cruise: 0.0, clearance: 0.0, dive: 0.0, warhead: 3, scale: 1.1, engine: Engine::Rocket(1.0, 1.0), decoy: false, stealth: 4.0, sound: ("airdef:drone.ballistic", 1.0, 9999), class: Class::Ballistic, ballistic: None, }, } } pub fn from_key(key: &str) -> Option { Self::ALL.into_iter().find(|k| k.spec().key == key) } /// Its radar cross-section, a Shahed's 0.3: radars see it from as far as its fourth root allows. pub fn rcs(self) -> f64 { match self { DroneKind::Shahed => 0.3, DroneKind::Geran3 => 0.4, DroneKind::Lancet => 0.08, // Corner reflectors make the decoy look as big as a Shahed. DroneKind::Gerbera => 0.4, DroneKind::Kh101 => 0.05, DroneKind::Kalibr => 0.15, DroneKind::Kh22 => 1.0, DroneKind::Zircon => 0.4, DroneKind::Iskander => 0.6, DroneKind::Kinzhal => 0.5, DroneKind::Oreshnik => 2.0, DroneKind::OreshnikBlock => 0.4, DroneKind::OreshnikSub => 0.08, } } } /// Height over the target where the Oreshnik's blocks release their submunitions. const BLOCK_SPLIT: f64 = 300.0; #[derive(PartialEq, Clone, Copy)] enum Flight { Cruise, Dive, /// An arc under gravity; the motor burns for the first ticks. Ballistic, /// Shot down: spinning down, burning. Falling, } #[derive(Clone)] pub struct Drone { pub id: u32, pub kind: DroneKind, pub pos: DVec3, pub vel: DVec3, target: DVec3, flight: Flight, roll: f64, spin: f64, age: u32, /// Interceptors on their way to it. pub engaged: u32, /// Points it flies by on its way (a planned raid), the next first. route: Vec, /// Hugs the land all the way, under the radars. low: bool, /// Its navigation is being jammed. pub jammed: bool, /// The approach sector it came from (the enemy keeps score). sector: u8, /// Sent by the smart enemy: it may be turned on systems that give themselves away. smart: bool, } impl Drone { pub fn alive(&self) -> bool { self.flight != Flight::Falling } /// How much a system wants to shoot it: fast and heavy first, decoys look real. fn threat(&self, from: DVec3) -> f64 { let s = self.kind.spec(); let warhead = if s.decoy { 3.0 } else { s.warhead as f64 }; (1.0 + warhead) * (1.0 + s.speed) / (1.0 + self.pos.distance(from) * 0.02) } } // ---------------------------------------------------------------- interceptors #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum MissileKind { Pac3, M57e6, M48n6, M77n6, IrisT, Amraam, M9m317, M9m338, /// Not a missile: an interceptor drone, slow and cheap, that rams Shaheds. P1sun, } struct MissileSpec { model: &'static str, speed: f64, accel: f64, turn: f64, /// Ticks of straight flight before guidance. boost: u32, /// Thrown out of the tube by gas first; the motor lights this many ticks later. cold: u32, pk: f64, fuse: f64, life: u32, scale: f64, flame: f64, /// The nozzle, model units behind the centre (z). rear: f64, } impl MissileKind { /// The sound of its launch. pub fn launch_sound(self) -> &'static str { match self { MissileKind::Pac3 => "airdef:launch.patriot", MissileKind::M57e6 => "airdef:launch.pantsir", MissileKind::M48n6 => "airdef:launch.s400_eject", MissileKind::M77n6 => "airdef:launch.s500_eject", MissileKind::IrisT | MissileKind::M9m338 => "airdef:launch.s400_eject", MissileKind::Amraam | MissileKind::M9m317 => "airdef:launch.patriot", MissileKind::P1sun => "airdef:drone.lancet", } } fn spec(self) -> &'static MissileSpec { match self { MissileKind::Pac3 => &MissileSpec { model: "airdef:pac3", speed: 5.5, accel: 0.35, turn: 0.3, boost: 8, cold: 0, pk: 0.9, fuse: 4.0, life: 240, scale: 1.0, flame: 1.0, rear: 28.0, }, MissileKind::M57e6 => &MissileSpec { model: "airdef:m57e6", speed: 5.0, accel: 0.5, turn: 0.32, boost: 5, cold: 0, pk: 0.82, fuse: 3.0, life: 160, scale: 0.85, flame: 0.65, rear: 28.0, }, MissileKind::M48n6 => &MissileSpec { model: "airdef:m48n6", speed: 7.0, accel: 0.5, turn: 0.22, boost: 8, cold: 5, pk: 0.9, fuse: 5.0, life: 300, scale: 1.5, flame: 1.4, rear: 30.0, }, MissileKind::M77n6 => &MissileSpec { model: "airdef:m77n6", speed: 9.0, accel: 0.6, turn: 0.22, boost: 8, cold: 5, pk: 0.95, fuse: 6.0, life: 320, scale: 1.7, flame: 1.6, rear: 32.0, }, MissileKind::IrisT => &MissileSpec { model: "airdef:irist_missile", speed: 7.0, accel: 0.5, turn: 0.35, boost: 6, cold: 4, pk: 0.9, fuse: 4.0, life: 260, scale: 0.95, flame: 0.9, rear: 28.0, }, MissileKind::Amraam => &MissileSpec { model: "airdef:amraam_missile", speed: 6.0, accel: 0.45, turn: 0.3, boost: 6, cold: 0, pk: 0.85, fuse: 4.0, life: 260, scale: 0.9, flame: 0.9, rear: 28.0, }, MissileKind::M9m317 => &MissileSpec { model: "airdef:m48n6", speed: 6.5, accel: 0.5, turn: 0.25, boost: 8, cold: 0, pk: 0.85, fuse: 5.0, life: 300, scale: 1.1, flame: 1.2, rear: 32.0, }, MissileKind::M9m338 => &MissileSpec { model: "airdef:m57e6", speed: 5.5, accel: 0.6, turn: 0.4, boost: 4, cold: 4, pk: 0.9, fuse: 3.0, life: 160, scale: 1.0, flame: 0.8, rear: 28.0, }, MissileKind::P1sun => &MissileSpec { model: "airdef:p1sun", speed: 2.8, accel: 0.12, turn: 0.3, boost: 4, cold: 0, pk: 0.8, fuse: 3.0, life: 900, scale: 0.8, // Electric: no flame. flame: 0.0, rear: 10.0, }, } } } pub struct Missile { pub id: u32, pub kind: MissileKind, pub pos: DVec3, vel: DVec3, target: u32, /// The system that fired it. sam: u32, age: u32, } // ---------------------------------------------------------------- air defence /// What a system is doing, for the monitor. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum SamState { Search, Track, Slew, Lock, Launch, Fire, Reload, Hold, Destroyed, /// A move order: packing up, on the march, deploying again. Packing, Moving, Deploying, /// Out of missiles, waiting for a reload truck (logistics on: a depot stands). Waiting, } impl SamState { pub fn name(self) -> &'static str { match self { SamState::Search => "ПОИСК", SamState::Track => "СОПРОВОЖДЕНИЕ", SamState::Slew => "ДОВОРОТ", SamState::Lock => "ЗАХВАТ", SamState::Launch => "ПУСК", SamState::Fire => "ОГОНЬ", SamState::Reload => "ПЕРЕЗАРЯДКА", SamState::Hold => "ОГОНЬ ЗАПРЕЩЁН", SamState::Destroyed => "УНИЧТОЖЕН", SamState::Packing => "СВЁРТЫВАНИЕ", SamState::Moving => "НА МАРШЕ", SamState::Deploying => "РАЗВЁРТЫВАНИЕ", SamState::Waiting => "ЖДЁТ БК", } } pub fn color(self) -> u32 { match self { SamState::Search => 0x60FF80, SamState::Track => 0xFFE060, SamState::Slew => 0xFFB040, SamState::Lock => 0xFF5040, SamState::Launch | SamState::Fire => 0xFFFFFF, SamState::Reload => 0x80A0FF, SamState::Hold => 0xA0A0A0, SamState::Destroyed => 0xFF2020, SamState::Packing | SamState::Moving | SamState::Deploying => 0xC0A0FF, SamState::Waiting => 0xFF9040, } } } pub struct Sam { pub state: SamState, /// Ticks the monitor keeps showing a launch. launched: u32, pub id: u32, pub kind: SamKind, /// The vehicle's centre on the ground. pub pos: DVec3, /// Where its nose points (radians, as `look`'s yaw). pub heading: f64, yaw: f64, pitch: f64, /// How fast the mount turns now (radians a tick); not saved, a loaded system starts at rest. yaw_vel: f64, pitch_vel: f64, pub missiles: u32, pub bursts: u32, cooldown: u32, gun_cooldown: u32, pub reloading: u32, /// What its missiles are after, and what its guns track. pub target: Option, pub gun_target: Option, dish: f64, recoil: f64, flash: u32, pub kills: u32, pub fired: u32, /// The classes of target it engages (`Class::bit`s). pub roles: u8, /// 1 whole, 0 destroyed: a damaged system turns slower, sees less and hits worse. pub health: f64, /// Ticks its wreck still burns. burn: u32, /// The drones it has tracks of this tick: its own radar's and the network's. pub seen: Vec, /// The drones its own radar (or optics) holds: guns need these. pub own: Vec, /// What it just shot down, where, and till when its camera stays on it. pub kill_view: Option<(u32, DVec3, u64)>, /// A move order's destination, and ticks left packing up or deploying. pub dest: Option, march: u32, /// A depot's reloads in stock; a reload truck's on board. pub cargo: u32, /// A reload truck's job: the system it is driving to, or a depot. job: Option, /// Out of ammunition, waiting for a reload (logistics on). pub empty: bool, /// An EW station: jamming, and its transmitter's heat (0 cold, 1 forced off). pub ew_on: bool, pub heat: f64, /// Overheated: off until it cools. pub ew_lock: bool, /// Ticks till a gun fires its next illumination flare. flare_cd: u32, } impl Sam { pub fn new(id: u32, kind: SamKind, pos: DVec3, heading: f64) -> Self { let spec = kind.spec(); Self { id, kind, pos, heading, yaw: heading, pitch: spec.rest_pitch, yaw_vel: 0.0, pitch_vel: 0.0, missiles: spec.missile.as_ref().map_or(0, |m| m.magazine), bursts: spec.gun.as_ref().map_or(0, |g| g.bursts), cooldown: 40, gun_cooldown: 0, reloading: 0, target: None, gun_target: None, dish: 0.0, recoil: 0.0, flash: 0, kills: 0, fired: 0, roles: spec.roles, state: SamState::Search, launched: 0, health: 1.0, burn: 0, seen: Vec::new(), own: Vec::new(), kill_view: None, dest: None, march: 0, cargo: match kind { SamKind::Depot => 30, SamKind::Tzm => 2, _ => 0, }, job: None, empty: false, ew_on: false, heat: 0.0, ew_lock: false, flare_cd: 0, } } pub fn alive(&self) -> bool { self.health > 0.0 } /// How well it still works: turning, aiming, its radar's reach. /// Turns the mount towards `yaw` (and `pitch`, if it elevates) under its drive's limits; a damaged /// system has the less of both speed and acceleration. fn aim_towards(&mut self, yaw: f64, pitch: Option) { let d = self.kind.spec().drive(); let fit = self.fitness(); self.yaw += drive(&mut self.yaw_vel, angle_diff(self.yaw, yaw), d.yaw.0 * fit, d.yaw.1 * fit); if let Some(pitch) = pitch { self.pitch += drive(&mut self.pitch_vel, pitch - self.pitch, d.pitch.0 * fit, d.pitch.1 * fit); } } /// The mount stops where it is (a march, a deployment: the vehicle drives it directly). pub(super) fn halt_mount(&mut self) { self.yaw_vel = 0.0; self.pitch_vel = 0.0; } fn fitness(&self) -> f64 { 0.45 + 0.55 * self.health.clamp(0.0, 1.0) } pub fn status(&self) -> String { let spec = self.kind.spec(); let mut text = spec.name.to_string(); if !self.alive() { return text + " УНИЧТОЖЕН"; } if self.moving() { return text + " " + &self.state.name().to_lowercase(); } match self.kind { SamKind::Depot => return format!("{text}: запас {} перезарядок", self.cargo), SamKind::Tzm => return format!("{text}: на борту {}/2{}", self.cargo, if self.job.is_some() { ", в пути" } else { "" }), SamKind::Ew => { let state = if self.ew_on { "ГЛУШИТ" } else if self.ew_lock { "остывает" } else { "готова" }; return format!("{text}: {state}, нагрев {:.0}%", self.heat * 100.0); } SamKind::Radar => return format!("{text}: целей {}", self.own.len()), SamKind::Light => return format!("{text}{}", if self.target.is_some() { ": в луче цель" } else { "" }), _ => {} } if self.empty && self.missiles == 0 { text += " ЖДЁТ БК"; } if self.health < 1.0 { text += &format!(" ({:.0}%)", self.health * 100.0); } if self.reloading > 0 { text += &format!(" перезарядка {}с", self.reloading.div_ceil(20)); } else { if let Some(m) = &spec.missile { text += &format!(" ракеты {}/{}", self.missiles, m.magazine); } if spec.gun.is_some() { text += &format!(" снаряды {}", self.bursts); } } text } } // ---------------------------------------------------------------- effects enum Fx { /// A glowing fireball growing then shrinking (when the shader can't draw it). Fireball { pos: DVec3, size: f64, age: u32, life: u32, spin: DQuat }, /// A falling piece of a drone. Debris { pos: DVec3, vel: DVec3, rot: DQuat, spin: DQuat, age: u32 }, /// A glowing red tracer round. Tracer { pos: DVec3, vel: DVec3, life: u32 }, } // ---------------------------------------------------------------- the simulation pub struct Sim { /// Roles set for a kind of system (`/airdef roles`), new ones included. pub roles: HashMap, pub drones: Vec, pub missiles: Vec, pub sams: Vec, pub targets: Vec, fx: Vec<(u32, Fx)>, /// Blasts for the post-processing shader. pub blasts: Vec, /// The next blast's id (separate from `next`, so the other units' ids stay as they were). blast_seq: u32, next: u32, pub rng: Rng, pub tick: u64, pub kills: u32, pub hits: u32, pub launched: u32, /// Explosions damage the land (primed TNT through commands). pub damage: bool, /// The shader draws fireballs: no glowing cubes. pub shader: bool, /// Air defence holds fire. pub hold: bool, /// What the land hides round each system's radar, by system id. horizons: HashMap, /// Blasts to come: (tick, where, TNT, small) — a magazine cooking off. later: Vec<(u64, DVec3, u32, bool)>, /// A planned raid's drones waiting for their launch tick. pub queue: Vec<(u64, Drone)>, /// A raid being planned. plan: Option, /// Each marked object's health, 0 to 100 (`targets`' order). pub target_health: Vec, /// The raid in progress, for its report. wave: Option, /// The raid being recorded, the last ones recorded, and how many have been. rec: Option, pub replays: Vec, recordings: u32, /// What went wrong for the air defence, counted for the raid report and the recordings. pub tally: record::Tally, /// What the enemy has learned. intel: ew::Intel, /// Night: guns need light (the mod sets it from the game's clock). pub night: bool, /// Illumination flares in the sky, and the drones lit this tick. pub flares: Vec, pub lit: Vec, } /// Ids: objects get multiples of 16, their parts the low bits. const PARTS: u32 = 16; impl Sim { pub fn new(seed: u64) -> Self { Self { roles: HashMap::new(), drones: Vec::new(), missiles: Vec::new(), sams: Vec::new(), targets: Vec::new(), fx: Vec::new(), blasts: Vec::new(), blast_seq: 0, next: 1, rng: Rng::new(seed), tick: 0, kills: 0, hits: 0, launched: 0, damage: true, shader: false, hold: false, horizons: HashMap::new(), later: Vec::new(), queue: Vec::new(), plan: None, target_health: Vec::new(), wave: None, rec: None, replays: Vec::new(), recordings: 0, tally: record::Tally::default(), intel: ew::Intel::default(), night: false, flares: Vec::new(), lit: Vec::new(), } } pub fn id(&mut self) -> u32 { self.next += 1; self.next * PARTS } /// What a system's camera follows: its guns' or missiles' target, else what its missiles in /// flight are after. pub fn watched(&self, sam: &Sam) -> Option<&Drone> { // A kill stays in view a few seconds: the wreck falling, before the next target. if let Some((id, _, until)) = sam.kill_view && self.tick < until { return self.drones.iter().find(|d| d.id == id); } let id = sam .gun_target .or(sam.target) .or_else(|| self.missiles.iter().find(|m| m.sam == sam.id).map(|m| m.target))?; self.drones.iter().find(|d| d.id == id) } /// Where a system's camera looks: what it watches, or where its last kill was while that /// stays in view (the wreck may be gone). pub fn focus(&self, sam: &Sam) -> Option { if let Some((_, at, until)) = sam.kill_view && self.tick < until { return Some(self.watched(sam).map_or(at, |d| d.pos)); } self.watched(sam).map(|d| d.pos) } /// Whether a system's camera is showing its kill. pub fn showing_kill(&self, sam: &Sam) -> bool { sam.kill_view.is_some_and(|(_, _, until)| self.tick < until) } pub fn nearest_target(&self, to: DVec3) -> Option { self.targets.iter().copied().min_by(|a, b| a.distance_squared(to).total_cmp(&b.distance_squared(to))) } fn add_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) { let id = self.id(); let spec = kind.spec(); let (vel, flight) = if spec.ballistic.is_some() { // An arc from `from` to `target` at the kind's horizontal speed. let flat = horizontal(target - from); let time = (flat.length() / spec.speed).max(30.0); let up = (target.y - from.y + 0.5 * GRAVITY * time * time) / time; (flat / time + DVec3::Y * up, Flight::Ballistic) } else { (dir.normalize_or(DVec3::NEG_Z) * spec.speed, Flight::Cruise) }; self.drones.push(Drone { id, kind, pos: from, vel, target, flight, roll: 0.0, spin: 0.0, age: 0, engaged: 0, route: Vec::new(), low: false, jammed: false, sector: 0, smart: false, }); self.launched += 1; } /// Launches a drone from `from`, heading `dir`, for `target`. pub fn launch(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3, out: &mut Out) { let dir = DVec3::new(dir.x, dir.y.max(0.35), dir.z).normalize_or(DVec3::Y); let from = if kind.spec().ballistic.is_some() { from + DVec3::Y * 2.0 } else { from }; self.add_drone(kind, from, dir, target); out.sound(kind.launch_sound(), from, 1.0, 1.3); out.particles("minecraft:large_smoke", from, 0.6, DVec3::ZERO, 0.05, 30); out.particles("minecraft:flame", from, 0.3, -dir * 0.2, 0.05, 12); } /// A raid: `count` drones from random bearings `dist` blocks out. pub fn raid(&mut self, kind: DroneKind, target: DVec3, count: u32, dist: f64, out: &mut Out) { let spec = kind.spec(); // A raid comes from one sector, spread over ±40°. let centre = self.rng.f() * TAU; for _ in 0..count { let a = centre + self.rng.s() * 0.7; let d = spec.ballistic.map_or(dist, |far| far.max(dist)) + self.rng.f() * 60.0; let height = if spec.ballistic.is_some() { 10.0 } else if spec.cruise > 0.0 { spec.cruise } else { 25.0 }; let from = target + DVec3::new(a.sin() * d, height + self.rng.s() * 8.0, a.cos() * d); let aim = target + DVec3::new(self.rng.s() * 5.0, 0.0, self.rng.s() * 5.0); self.add_drone(kind, from, horizontal(target - from), aim); } out.messages.push(format!("ВОЗДУШНАЯ ТРЕВОГА: {count} × {}", spec.name)); out.sound("minecraft:event.raid.horn", target, 64.0, 1.0); } pub fn clear(&mut self) { self.drones.clear(); self.missiles.clear(); self.fx.clear(); self.blasts.clear(); self.queue.clear(); self.plan = None; self.wave = None; // Ammunition still to cook off, flares in the sky. self.later.clear(); self.flares.clear(); self.lit.clear(); } /// One game tick. pub fn step(&mut self, ground: &mut Ground, player: Option, out: &mut Out) { self.tick += 1; self.plan_step(out); self.adapt(); self.release_queue(); self.step_drones(ground, player, out); self.step_later(ground, player, out); self.step_moves(ground, out); self.step_supply(out); self.step_ew(out); self.update_sight(ground); self.step_lights(out); self.step_sams(out); self.step_missiles(out); self.step_fx(ground, out); self.draw_targets(out); self.step_wrecks(out); self.report_wave(out); self.record(); let now = self.tick; self.blasts.retain(|b| now - b.start < b.life as u64); } // ------------------------------------------------ drones fn step_drones(&mut self, ground: &mut Ground, player: Option, out: &mut Out) { let now = self.tick; let mut boom: Vec<(DVec3, u32, bool)> = Vec::new(); let mut removed: Vec = Vec::new(); // Oreshnik pieces released this tick: kind, at, velocity, target, the parent's sector (what they teach the enemy). let mut released: Vec<(DroneKind, DVec3, DVec3, DVec3, u8)> = Vec::new(); // Warheads that reached their aim (for the replays): drone, kind, where, TNT; and splits. let mut impacts: Vec<(u32, DroneKind, DVec3, u32)> = Vec::new(); let mut splits: Vec<(u32, DVec3)> = Vec::new(); for d in &mut self.drones { d.age += 1; let spec = d.kind.spec(); let below = ground.at(d.pos, now); // Near its aim it looks at the land there again: a platform or hilltop blown away // meanwhile, it goes for what is left below, not for the air where it stood. if d.flight != Flight::Falling && horizontal(d.target - d.pos).length() < 250.0 && let Some(g) = ground.at(d.target, now) && g < d.target.y - 1.5 { d.target.y = g; } if d.flight == Flight::Falling { d.vel.y -= 0.05; d.vel *= 0.985; d.spin += 0.35; d.pos += d.vel; if self.rng.chance(0.5) { out.particles("minecraft:large_smoke", d.pos, 0.2, DVec3::new(0.0, 0.05, 0.0), 0.02, 1); } out.particles("minecraft:flame", d.pos, 0.25, DVec3::ZERO, 0.02, 2); if below.is_some_and(|g| d.pos.y <= g + 0.3) || d.age > 600 { // The wreck's warhead may still go off where it lands. let warhead = if spec.decoy || !self.rng.chance(0.35) { 0 } else { spec.warhead.min(2) }; boom.push((d.pos, warhead, true)); removed.push(d.id); } continue; } if d.flight == Flight::Ballistic { // The motor burns for 3 s; then the arc, and the warhead steers in at the end. let burning = d.age < 60; match d.kind { // A block glides to its point high over the target; its submunitions fall from there // nearly straight down, braked by the air: a rain of fire for seconds. DroneKind::OreshnikBlock => d.vel = (d.target + DVec3::Y * BLOCK_SPLIT - d.pos).normalize_or(DVec3::NEG_Y) * 6.5, DroneKind::OreshnikSub => d.vel = (d.target - d.pos).normalize_or(DVec3::NEG_Y) * 3.2, _ => d.vel.y -= GRAVITY, } if d.vel.y < 0.0 && d.pos.distance(d.target) < 260.0 { let sp = d.vel.length(); d.vel = turn(d.vel, d.target - d.pos, spec.turn) * sp; } d.pos += d.vel; let speed = d.vel.length(); let hit = d.pos.distance(d.target) < speed.max(2.0) || below.is_some_and(|g| d.pos.y <= g + 0.2) || (d.vel.y < 0.0 && d.pos.y < d.target.y - 1.0 && horizontal(d.target - d.pos).length() < speed * 2.0) || d.age > 4000; if hit { boom.push((d.pos, spec.warhead, false)); impacts.push((d.id, d.kind, d.pos, spec.warhead)); removed.push(d.id); self.hits += 1; continue; } // The bus releases its six blocks over the target, each block its six submunitions lower down. let split = match d.kind { DroneKind::Oreshnik => (d.vel.y < 0.0 && horizontal(d.target - d.pos).length() < 900.0) .then_some((DroneKind::OreshnikBlock, 45.0)), DroneKind::OreshnikBlock => (d.pos.distance(d.target + DVec3::Y * BLOCK_SPLIT) < 8.0) .then_some((DroneKind::OreshnikSub, 9.0)), _ => None, }; if let Some((piece, spread)) = split { let turn0 = self.rng.f() * TAU; for i in 0..6 { let a = turn0 + i as f64 * TAU / 6.0; let r = spread * (0.6 + 0.4 * self.rng.f()); let aim = d.target + DVec3::new(a.sin() * r, 0.0, a.cos() * r); // Straight down at the aim point, at the bus's speed. let v = (aim - d.pos).normalize_or(DVec3::NEG_Y) * 3.0; released.push((piece, d.pos + v.normalize_or_zero() * (i as f64 * 0.3), v, aim, d.sector)); } out.sound("airdef:boom.sonic", d.pos, 1.0, 0.7); splits.push((d.id, d.pos)); // Its pieces count as launched instead of it. self.launched += 5; out.particles("minecraft:firework", d.pos, 1.5, DVec3::ZERO, 0.3, 40); if d.kind == DroneKind::OreshnikBlock && self.rng.chance(0.5) { out.sound("airdef:drone.ballistic", d.pos, 1.0, 1.1); } removed.push(d.id); continue; } let dir = d.vel.normalize_or_zero(); if d.kind == DroneKind::OreshnikSub || d.kind == DroneKind::OreshnikBlock { out.particles("minecraft:flame", d.pos - dir * 1.5, 0.1, DVec3::ZERO, 0.0, 1); out.particles("minecraft:white_smoke", d.pos - dir * 3.0, 0.15, DVec3::ZERO, 0.0, 1); } else if burning { out.particles("minecraft:flame", d.pos - dir * 2.5 * spec.scale, 0.15, -dir * 0.2, 0.02, 3); out.particles("minecraft:cloud", d.pos - dir * 3.5 * spec.scale, 0.4, DVec3::ZERO, 0.01, 3); } else if d.vel.y < -2.0 { // Re-entry: the nose glows, a thin trail. out.particles("minecraft:small_flame", d.pos + dir * spec.scale, 0.1, DVec3::ZERO, 0.0, 1); out.particles("minecraft:white_smoke", d.pos - dir * spec.scale, 0.1, DVec3::ZERO, 0.0, 1); } let (event, pitch, every) = spec.sound; if burning && d.age % every == 0 { out.sound(event, d.pos, 1.0, pitch); } // The scream of the warhead coming down, once, and its shock wave. if d.vel.y < -1.0 && d.spin == 0.0 && d.pos.distance(d.target) < d.vel.length() * 80.0 { d.spin = 1.0; let p = if d.kind == DroneKind::Kinzhal { 0.85 } else { 1.0 }; out.sound("airdef:drone.ballistic", d.pos, 1.0, p); out.sound("airdef:boom.sonic", d.pos, 1.0, p); } continue; } if d.flight == Flight::Cruise && d.route.len() <= 1 && horizontal(d.target - d.pos).length() < spec.dive { d.flight = Flight::Dive; } // An interceptor coming: drones drop to the treetops (radars lose them sooner). if d.engaged > 0 && matches!(spec.class, Class::Drone | Class::Jet) { d.low = true; } // A planned route: the next point, then the next. // Reached when near (as near as it can turn), or passed: behind it and close. let radius = (spec.speed / spec.turn.max(0.01)).max(24.0); while d.route.len() > 1 && d.route.first().is_some_and(|w| { let to = horizontal(*w - d.pos); to.length() < radius * 0.8 || (to.dot(horizontal(d.vel)) < 0.0 && to.length() < radius * 2.5) }) { d.route.remove(0); } let goal = if d.flight == Flight::Dive { d.target } else { // Cruise height over the target, and `clearance` over the land ahead. let ahead = ground.at(d.pos + horizontal(d.vel).normalize_or_zero() * 20.0, now); let floor = match (below, ahead) { (Some(a), Some(b)) => a.max(b) + spec.clearance, (Some(g), None) | (None, Some(g)) => g + spec.clearance, (None, None) => d.target.y + spec.clearance, }; let to = d.route.first().copied().unwrap_or(d.target); // Under the radars: as low as the land lets it, all the way. let height = if d.low { floor.max(d.target.y + 4.0) } else { (d.target.y + spec.cruise).max(floor) }; DVec3::new(to.x, height, to.z) }; let rate = if d.flight == Flight::Dive { spec.turn * 3.5 } else { spec.turn }; let old = d.vel.normalize_or(DVec3::NEG_Z); let new = turn(old, goal - d.pos, rate); let side = old.cross(new).y; d.roll += ((side * 40.0).clamp(-0.8, 0.8) - d.roll) * 0.15; let speed = if d.flight == Flight::Dive { spec.speed * 1.35 } else { spec.speed }; d.vel = new * speed; d.pos += d.vel; let at_target = d.pos.distance(d.target) < speed.max(1.5); let in_ground = below.is_some_and(|g| d.pos.y <= g + 0.2); if at_target || in_ground || d.age > 8000 { boom.push((d.pos, spec.warhead, spec.decoy)); if !spec.decoy { impacts.push((d.id, d.kind, d.pos, spec.warhead)); } removed.push(d.id); if !spec.decoy { self.hits += 1; } continue; } let back = d.pos - d.vel.normalize_or_zero() * 1.5 * spec.scale; match spec.engine { Engine::Prop(..) => { if d.age % 2 == 0 { out.particles("minecraft:smoke", back, 0.05, DVec3::ZERO, 0.01, 1); } } Engine::Jet(..) => out.particles("minecraft:smoke", back, 0.08, DVec3::ZERO, 0.01, 1), Engine::Rocket(..) => { out.particles("minecraft:flame", back, 0.08, -d.vel * 0.05, 0.01, 1); out.particles("minecraft:cloud", back - d.vel.normalize_or_zero() * 1.5, 0.15, DVec3::ZERO, 0.005, 1); } } let (event, pitch, every) = spec.sound; if d.age % every == 0 { out.sound(event, d.pos, 1.0, pitch); } } for (drone, pos) in splits { self.log(pos, record::EventKind::Split { drone }); } for (drone, kind, pos, tnt) in impacts { if let Some(sector) = self.drones.iter().find(|x| x.id == drone).map(|x| x.sector as usize) { self.learn(sector, false); } let power = match tnt { 0 => 0, 1 | 2 => 1, 3..=5 => 2, 6 | 7 => 3, _ => 4, }; let object = self.targets.iter().position(|t| t.distance(pos) < 16.0); let sam = self.sams.iter().enumerate().find(|(_, s)| s.alive() && s.pos.distance(pos) < 12.0).map(|(i, s)| (s.kind, i)); self.log(pos, record::EventKind::Hit { drone, kind, power, object, sam }); } for (pos, warhead, small) in boom { self.explode(pos, warhead, small, ground, player, out); } self.drones.retain(|d| !removed.contains(&d.id)); for (kind, pos, vel, target, sector) in released { let id = self.id(); self.drones.push(Drone { id, kind, pos, vel, target, flight: Flight::Ballistic, roll: 0.0, spin: 1.0, age: 60, engaged: 0, route: Vec::new(), low: false, jammed: false, sector, smart: false, }); } for d in &self.drones { let spec = d.kind.spec(); let s = spec.scale; let mut rot = look(d.vel, d.roll); if d.flight == Flight::Falling { rot = rot * DQuat::from_rotation_z(d.spin) * DQuat::from_rotation_x(-0.6); } if !matches!(d.kind, DroneKind::OreshnikBlock | DroneKind::OreshnikSub) || !d.alive() { out.model(d.id, spec.model, d.pos, rot, s, false); } if !d.alive() { continue; } match spec.engine { Engine::Prop(back, size) => { let at = d.pos + rot * DVec3::new(0.0, 0.0, back * s); let spin = DQuat::from_rotation_z(d.age as f64 * 1.1); out.model(d.id + 1, "airdef:shahed_prop", at, rot * spin, s * size, false); } Engine::Jet(up, back, size) => { let at = d.pos + rot * DVec3::new(0.0, up * s, back * s); let flicker = 0.7 + 0.3 * self.rng.f(); out.model(d.id + 1, "airdef:geran3_flame", at, rot, s * size * flicker, true); } Engine::Rocket(back, size) => { // Ballistic missiles fly far and high: their glow keeps a size on screen, so they are seen // all the way (the motor while it burns, then the hot body). let far = player.map_or(1.0, |p| (d.pos.distance(p) / 140.0).max(1.0)); let flicker = 0.8 + 0.2 * self.rng.f(); if d.flight != Flight::Ballistic || d.age < 60 { let size = if d.flight == Flight::Ballistic { size * far.sqrt() } else { size }; let at = d.pos + rot * DVec3::new(0.0, 0.0, back * s + size * flicker); out.model(d.id + 1, "airdef:flame", at, rot, size * flicker, true); } else if !matches!(d.kind, DroneKind::OreshnikBlock | DroneKind::OreshnikSub) { out.model(d.id + 1, "airdef:reentry", d.pos, rot, s * 0.6 * far.sqrt() * flicker, true); } else { out.model(d.id + 1, "airdef:reentry", d.pos, rot, s * far.sqrt().min(4.0) * flicker, true); } } } } } /// A blast: a fireball, smoke, sound, a jolt for a near player, and (with /// `damage`) primed TNT for the land. fn explode(&mut self, pos: DVec3, tnt: u32, small: bool, ground: &mut Ground, player: Option, out: &mut Out) { let big = tnt >= 3; // Power: 0 air burst, 1 small, 2 drone, 3 cruise missile, 4 ballistic. let power = match tnt { 0 => 0, 1 | 2 => 1, 3..=5 => 2, 6 | 7 => 3, _ => 4, }; let size = [2.5, 4.5, 7.0, 10.0, 13.0][power]; self.fireball(pos, size, [11, 11, 18, 22, 26][power]); out.particles("minecraft:explosion_emitter", pos, 0.5 + power as f32, DVec3::ZERO, 0.0, [1, 1, 3, 5, 8][power]); // The shader draws the fireball and smoke; particles add sparks and debris. let n = if self.shader { 12 } else { 40 }; out.particles("minecraft:large_smoke", pos, size as f32 * 0.4, DVec3::new(0.0, 0.1, 0.0), 0.08, n); out.particles("minecraft:flame", pos, size as f32 * 0.3, DVec3::ZERO, 0.2, n); out.particles("minecraft:lava", pos, 1.0, DVec3::ZERO, 0.0, 16); out.particles("minecraft:campfire_signal_smoke", pos, 1.2, DVec3::new(0.0, 0.04, 0.0), 0.01, if big { 30 } else { 10 }); let pitch = 0.9 + self.rng.f() as f32 * 0.2; let event = ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][power]; out.sound(event, pos, 1.0, if small { pitch * 1.15 } else { pitch }); if power >= 3 { // A heavy warhead throws a column of dirt and a ring of dust. out.particles("minecraft:campfire_cosy_smoke", pos, size as f32 * 0.5, DVec3::new(0.0, 0.15, 0.0), 0.05, 20 * power as u32); out.particles("minecraft:explosion", pos, size as f32 * 0.6, DVec3::ZERO, 0.0, 10 * power as u32); } if let Some(p) = player { let d = p.distance(pos); let reach = [45.0, 45.0, 100.0, 160.0, 240.0][power]; if d < reach { let strength = [0.4, 0.4, 0.9, 1.3, 1.8][power]; out.jolt((1.0 - d / reach) as f32 * strength, [0.8, 0.8, 1.6, 2.2, 3.0][power]); } } self.blast_damage(pos, power, out); if self.damage && tnt > 0 { for i in 0..tnt { out.commands.push(format!( "summon tnt {:.2} {:.2} {:.2} {{fuse:0s}}", pos.x + self.rng.s() * 0.8, pos.y + i as f64 * 0.5, pos.z + self.rng.s() * 0.8 )); } ground.forget(pos, 8); } } fn fireball(&mut self, pos: DVec3, size: f64, life: u32) { self.blast_seq = self.blast_seq.wrapping_add(1); self.blasts.push(Blast { id: self.blast_seq, at: pos, size: size as f32, start: self.tick, life: life * 9 }); if self.blasts.len() > 48 { self.blasts.remove(0); } if self.shader { return; } let id = self.id(); let spin = DQuat::from_euler(glam::EulerRot::XYZ, self.rng.s() * 0.2, self.rng.s() * 0.2, self.rng.s() * 0.2); self.fx.push((id, Fx::Fireball { pos, size, age: 0, life, spin })); } /// A drone hit by air defence: a flash, pieces, and it falls burning. fn shoot_down(&mut self, idx: usize, by: u32, missile: Option, out: &mut Out) { if !self.drones[idx].alive() { return; } let sector = self.drones[idx].sector as usize; self.learn(sector, true); let until = self.tick + 70; if let Some(s) = self.sams.iter_mut().find(|s| s.id == by) { s.kill_view = Some((self.drones[idx].id, self.drones[idx].pos, until)); } if let Some((i, s)) = self.sams.iter().enumerate().find(|(_, s)| s.id == by) { let (drone, kind, pos) = (self.drones[idx].id, self.drones[idx].kind, self.drones[idx].pos); let kill = record::EventKind::Kill { drone, kind, sam: by, sam_kind: s.kind, sam_index: i, missile }; self.log(pos, kill); } let d = &mut self.drones[idx]; d.flight = Flight::Falling; d.age = 0; d.vel = d.vel * 0.6 + DVec3::new(0.0, 0.15, 0.0); let pos = d.pos; let vel = d.vel; self.kills += 1; if let Some(s) = self.sams.iter_mut().find(|s| s.id == by) { s.kills += 1; } self.fireball(pos, 3.5, 8); out.particles("minecraft:explosion", pos, 0.6, DVec3::ZERO, 0.0, 4); out.particles("minecraft:large_smoke", pos, 1.0, DVec3::ZERO, 0.06, 25); out.particles("minecraft:firework", pos, 0.3, DVec3::ZERO, 0.35, 30); out.sound("airdef:blast.air", pos, 1.0, 1.0 + self.rng.f() as f32 * 0.2); for _ in 0..5 { let id = self.id(); let v = vel + DVec3::new(self.rng.s(), self.rng.f() * 0.8, self.rng.s()) * 0.35; let spin = DQuat::from_euler(glam::EulerRot::XYZ, self.rng.s() * 0.4, self.rng.s() * 0.4, self.rng.s() * 0.4); self.fx.push((id, Fx::Debris { pos, vel: v, rot: DQuat::IDENTITY, spin, age: 0 })); } } // ------------------------------------------------ air defence fn step_sams(&mut self, out: &mut Out) { if self.hold { for i in 0..self.sams.len() { if self.sams[i].alive() && !self.sams[i].moving() { self.sams[i].state = SamState::Hold; } self.draw_sam(i, out); } return; } let logistics = self.logistics(); // Drones by id (none come or go while the systems act), and how many systems have each as their // missile target and as their gun target: counted once, then kept up to date as targets change. let drone_at: HashMap = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect(); let (mut missile_on, mut guns_on) = why::engagement_counts(&self.sams); // For the raid's report: tracks dropped and systems that ran dry and wait for a truck. let (mut tracks_lost, mut ammo_waits) = (0u32, 0u32); let mut launches: Vec<(MissileKind, DVec3, DVec3, u32, u32)> = Vec::new(); let mut gun_hits: Vec<(u32, u32)> = Vec::new(); let mut tracers: Vec<(u32, DVec3, DVec3, u32)> = Vec::new(); for i in 0..self.sams.len() { let spec = self.sams[i].kind.spec(); if !self.sams[i].alive() { let sam = &mut self.sams[i]; sam.state = SamState::Destroyed; retarget(&mut missile_on, sam.target.take(), None); retarget(&mut guns_on, sam.gun_target.take(), None); continue; } let fit = self.sams[i].fitness(); { let sam = &mut self.sams[i]; sam.cooldown = sam.cooldown.saturating_sub(1); sam.gun_cooldown = sam.gun_cooldown.saturating_sub(1); sam.flash = sam.flash.saturating_sub(1); sam.recoil *= 0.6; sam.dish = (sam.dish + 0.15) % TAU; if sam.reloading > 0 { sam.reloading -= 1; if sam.reloading == 0 { sam.missiles = spec.missile.as_ref().map_or(0, |m| m.magazine); sam.bursts = spec.gun.as_ref().map_or(0, |g| g.bursts); out.sound("minecraft:block.piston.extend", sam.pos, 2.0, 0.6); } } } if self.sams[i].moving() { continue; } if !self.sams[i].kind.armed() { let sam = &mut self.sams[i]; sam.state = SamState::Search; // A searchlight's target is its beam's (step_lights): kept for its spot of light. if sam.kind != SamKind::Light { retarget(&mut missile_on, sam.target.take(), None); } retarget(&mut guns_on, sam.gun_target.take(), None); continue; } let pos = self.sams[i].pos; let roles = self.sams[i].roles; let (had_target, had_gun) = (self.sams[i].target, self.sams[i].gun_target); let (target, gun_target) = { let (seen, own) = (&self.sams[i].seen, &self.sams[i].own); // The conditions are `why`'s, shared with the diagnostic. let allowed = |d: &Drone| why::allowed(roles, seen, d); let claimed = |d: &Drone| why::claimed(d, &missile_on, had_target); let needed = why::needed; let target = spec.missile.as_ref().map(|load| { let in_reach = |d: &Drone, k: f64| why::in_reach(load.min, load.max, k, pos, d); let keep = had_target.filter(|t| { drone_at.get(t).is_some_and(|&k| allowed(&self.drones[k]) && in_reach(&self.drones[k], 1.1)) }); keep.or_else(|| { self.drones .iter() .filter(|d| allowed(d) && in_reach(d, 1.0) && claimed(d) < needed(d)) .max_by(|a, b| a.threat(pos).total_cmp(&b.threat(pos))) .map(|d| d.id) }) }); // Guns: the nearest, spread over the targets the other guns and missiles aren't on. let gun_target = spec.gun.as_ref().map(|gun| { let on_it = |d: &Drone| { (guns_on.get(&d.id).copied().unwrap_or(0) - u32::from(had_gun == Some(d.id))) as f64 }; self.drones .iter() .filter(|d| why::gun_candidate(roles, seen, own, gun.track, pos, d)) .map(|d| { let busy = 1.0 + 2.0 * on_it(d) + if d.engaged > 0 { 1.5 } else { 0.0 }; (d.pos.distance(pos) * busy, d.id) }) .min_by(|a, b| a.0.total_cmp(&b.0)) .map(|(_, id)| id) }); (target, gun_target) }; if let Some(target) = target { // A target still in the sky that the system had and now doesn't: its track was lost. if let Some(h) = had_target && target != Some(h) && drone_at.get(&h).is_some_and(|&k| self.drones[k].alive()) { tracks_lost += 1; } retarget(&mut missile_on, had_target, target); self.sams[i].target = target; } if let Some(gun_target) = gun_target { retarget(&mut guns_on, had_gun, gun_target); self.sams[i].gun_target = gun_target; } let sam = &mut self.sams[i]; // What the turret or launcher points at: guns first when a target is close. let aim = sam.gun_target.or(sam.target).and_then(|t| drone_at.get(&t).map(|&k| &self.drones[k])); sam.launched = sam.launched.saturating_sub(1); let Some(aim) = aim else { // Out of missiles or of shells, and nothing to shoot: reload now (both, as a // combined system's crew would), not only once both are spent. let spent = (spec.missile.is_some() && sam.missiles == 0) || (spec.gun.is_some() && sam.bursts == 0); if spent && sam.reloading == 0 && !sam.empty { if logistics { sam.empty = true; ammo_waits += 1; } else { sam.reloading = spec.reload } } sam.state = if sam.reloading > 0 { SamState::Reload } else if sam.empty { SamState::Waiting } else { SamState::Search }; // Back to the rest position, under the drive's limits like any other turn. sam.aim_towards(sam.heading, Some(spec.rest_pitch)); continue; }; let (mount, _) = sam.mount(); let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell); let (lead, want_yaw, want_pitch) = why::aim_wants(mount, aim, lead_speed); let cells = matches!(spec.muzzle, Muzzle::Cells); match spec.family { // Vertical launch: no aiming (the Tor's turret turns its radar to the target). Family::Vertical if cells => sam.aim_towards(want_yaw, None), Family::Vertical => {} // The launcher's elevation is fixed (the missile turns after its boost): only the training is aimed. Family::Trainable => sam.aim_towards(want_yaw, None), _ => sam.aim_towards(want_yaw, Some(want_pitch)), } // How far the mount still is from the aim, over the axes this family aims. let aim_error = why::aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch); let vertical = spec.family == Family::Vertical; sam.state = if sam.reloading > 0 { SamState::Reload } else if sam.empty && sam.missiles == 0 && sam.bursts == 0 { SamState::Waiting } else if sam.launched > 0 { SamState::Launch } else if sam.flash > 0 { SamState::Fire } else if !vertical && aim_error > 0.15 { SamState::Slew } else if aim.pos.distance(mount) < self::SamKind::range(sam.kind) { SamState::Lock } else { SamState::Track }; // Guns. if let (Some(gun), Some(gt)) = (&spec.gun, sam.gun_target) { if let Some(t) = drone_at.get(>).map(|&k| &self.drones[k]) { let dist = t.pos.distance(mount); if why::gun_blocks(sam, aim.id, gt, aim_error, dist, gun.range) == 0 { sam.gun_cooldown = 2; sam.bursts -= 1; sam.flash = 2; sam.recoil = 1.0; if sam.bursts == 0 && sam.missiles == 0 { if logistics { sam.empty = true; ammo_waits += 1; } else { sam.reloading = spec.reload } } let (_, rot) = sam.mount(); let s = spec.scale; let barrels: &[DVec3] = match sam.kind { SamKind::Pantsir => &[DVec3::new(-0.95, 0.33, -1.5), DVec3::new(0.95, 0.33, -1.5)], _ => &[DVec3::new(-0.92, -0.11, -1.55), DVec3::new(0.92, -0.11, -1.55)], }; for b in barrels { let muzzle = mount + rot * *b * s; let dir = (lead - muzzle).normalize_or(DVec3::NEG_Z); let len = muzzle.distance(lead).min(gun.range * 1.2); // Every round is a red tracer flying out at the shell's speed. let scatter = DVec3::new(self.rng.s(), self.rng.s(), self.rng.s()) * 0.012; let id = self.next * PARTS + 0x0800_0000; self.next += 1; tracers.push((id, muzzle + dir * 1.5, (dir + scatter).normalize() * gun.shell, (len / gun.shell) as u32 + 2)); out.particles("minecraft:smoke", muzzle, 0.1, dir * 0.05, 0.01, 2); } // A gun sound holds a few shots: one every other burst. if sam.bursts % 2 == 0 { let event = if sam.kind == SamKind::Pantsir { "airdef:gun.pantsir" } else { "airdef:gun.gepard" }; out.sound(event, mount, 1.0, 0.95 + self.rng.f() as f32 * 0.1); } // At night a gun sees what is lit (a searchlight, a flare) and little else. let dark = if self.night && !self.lit.contains(&t.id) { lights::DARK_HITS } else { 1.0 }; let p = gun.p * fit * dark / t.kind.spec().stealth * (1.0 - dist / (gun.range * 1.3)).max(0.35); if self.rng.chance(p) { gun_hits.push((gt, sam.id)); } else { out.particles("minecraft:crit", t.pos, 1.2, DVec3::ZERO, 0.2, 4); } } } } // Missiles. if let (Some(load), Some(mt)) = (&spec.missile, sam.target) { let ready = why::missile_blocks(sam) == 0; // The missile turns after its boost, but the launcher must point near the target. let t = drone_at.get(&mt).map(|&k| &self.drones[k]); let aligned = why::missile_aligned(spec.family, sam.yaw, mount, t, aim.id, mt, aim_error); if ready && aligned { let n = load.magazine - sam.missiles; let (muzzle, dir) = sam.muzzle(n); launches.push((load.kind, muzzle, dir, mt, sam.id)); // Its missile is on it from now, so the systems after this one this tick see // the target taken; this one's next launch looks for another. if let Some(&k) = drone_at.get(&mt) { self.drones[k].engaged += 1; } sam.target = None; retarget(&mut missile_on, Some(mt), None); sam.launched = 12; sam.missiles -= 1; sam.fired += 1; sam.cooldown = load.interval; if sam.missiles == 0 && (spec.gun.is_none() || sam.bursts == 0) { if logistics { sam.empty = true; ammo_waits += 1; } else { sam.reloading = spec.reload } } } } } self.note(|t| { t.tracks_lost += tracks_lost; t.ammo_waits += ammo_waits; }); for (kind, muzzle, dir, target, sam) in launches { // A launch gives the system away. if let Some(s) = self.sams.iter().find(|s| s.id == sam) { self.intel.revealed.push((sam, s.pos, self.tick)); } let spec = kind.spec(); let id = self.id(); let v0 = if spec.cold > 0 { 0.7 } else { 0.8 }; self.missiles.push(Missile { id, kind, pos: muzzle, vel: dir * v0, target, sam, age: 0 }); if spec.cold > 0 { // Thrown out by gas: a puff, a thump; the motor lights later. out.particles("minecraft:cloud", muzzle, 0.6, dir * 0.05, 0.05, 30); let event = if kind == MissileKind::M77n6 { "airdef:launch.s500_eject" } else { "airdef:launch.s400_eject" }; out.sound(event, muzzle, 1.0, 1.0); } else { out.particles("minecraft:flash", muzzle, 0.0, DVec3::ZERO, 0.0, 1); out.particles("minecraft:cloud", muzzle - dir * 2.0, 1.4, DVec3::new(0.0, 0.02, 0.0), 0.06, 70); out.particles("minecraft:campfire_cosy_smoke", muzzle - dir * 3.0, 1.2, DVec3::ZERO, 0.02, 20); let event = if kind == MissileKind::M57e6 { "airdef:launch.pantsir" } else { "airdef:launch.patriot" }; out.sound(event, muzzle, 1.0, 0.95 + self.rng.f() as f32 * 0.1); } } for (id, pos, vel, life) in tracers { self.fx.push((id, Fx::Tracer { pos, vel, life })); } for (t, by) in gun_hits { if let Some(i) = self.drones.iter().position(|d| d.id == t) { self.shoot_down(i, by, None, out); } } for i in 0..self.sams.len() { self.draw_sam(i, out); } } // ------------------------------------------------ interceptors fn step_missiles(&mut self, out: &mut Out) { let mut done: Vec<(u32, Option, bool, u32)> = Vec::new(); // (missile, target, kill, sam) let (mut missed, mut expired, mut orphaned) = (0u32, 0u32, 0u32); let sams_fit: HashMap = self.sams.iter().map(|s| (s.id, s.fitness())).collect(); for m in &mut self.missiles { m.age += 1; let spec = m.kind.spec(); let target = self.drones.iter().find(|d| d.id == m.target && d.alive()); let lit = m.age > spec.cold; let speed = if !lit { (m.vel.length() * 0.97).max(0.4) } else { (m.vel.length() + spec.accel).min(spec.speed) }; let dir = m.vel.normalize_or(DVec3::Y); let new = match target { Some(t) if m.age >= spec.boost => { // Time to go by the closing speed: head-on targets come to meet it. let los = (t.pos - m.pos).normalize_or_zero(); let closing = (speed - t.vel.dot(los)).max(1.0); let tgo = t.pos.distance(m.pos) / closing; turn(dir, t.pos + t.vel * tgo - m.pos, spec.turn) } // After a cold launch it tips over towards the target while the motor burns. Some(t) if lit && spec.cold > 0 => turn(dir, t.pos - m.pos, spec.turn * 0.5), _ => dir, }; let before = m.pos; m.vel = new * speed; m.pos += m.vel; if let Some(t) = target { // Closest approach this tick, both moving (fast targets cross a fuse in a tick). let rel0 = (t.pos - t.vel) - before; let rel1 = t.pos - m.pos; let delta = rel1 - rel0; let k = (-rel0.dot(delta) / delta.length_squared().max(1e-9)).clamp(0.0, 1.0); if (rel0 + delta * k).length() < spec.fuse { // A target faster than the interceptor is hard to hit. let ratio = (spec.speed / t.vel.length().max(0.1)).min(1.0).powf(1.5); let fit = sams_fit.get(&m.sam).copied().unwrap_or(1.0); let kill = self.rng.chance(spec.pk * fit * ratio / t.kind.spec().stealth.sqrt()); missed += u32::from(!kill); done.push((m.id, Some(t.id), kill, m.sam)); continue; } } if m.age > spec.life || (target.is_none() && m.age > 30) { // Its target gone (shot down by another, or lost), or its life spent chasing one. if target.is_none() { orphaned += 1; } else { expired += 1; } done.push((m.id, None, false, m.sam)); continue; } if lit && spec.flame == 0.0 { if m.age % 20 == 1 { out.sound("airdef:drone.lancet", m.pos, 0.8, 1.6); } } else if lit { if (m.age - spec.cold) % 46 == 1 { let pitch = match m.kind { MissileKind::Pac3 => 1.0, MissileKind::M57e6 => 1.12, MissileKind::M48n6 => 0.88, MissileKind::M77n6 => 0.8, MissileKind::IrisT | MissileKind::Amraam => 1.05, MissileKind::M9m317 => 0.9, MissileKind::M9m338 => 1.15, MissileKind::P1sun => 1.7, }; out.sound("airdef:missile.flight", m.pos, 1.0, pitch); } let back = m.pos - new * 1.4 * spec.scale; out.particles("minecraft:flame", back, 0.05, -new * 0.1, 0.01, 2); if m.age % 2 == 0 { out.particles("minecraft:cloud", back - new * 0.5, 0.12 * spec.scale as f32, DVec3::ZERO, 0.005, if m.age < 30 { 3 } else { 1 }); } if m.age == spec.cold + 1 && spec.cold > 0 { let event = if m.kind == MissileKind::M77n6 { "airdef:launch.s500" } else { "airdef:launch.s400" }; out.sound(event, m.pos, 1.0, 1.0); out.particles("minecraft:cloud", m.pos, 1.0, DVec3::ZERO, 0.08, 40); } } } self.note(|t| { t.missed += missed; t.expired += expired; t.orphaned += orphaned; }); for (mid, target, kill, sam) in done { if let Some(i) = self.missiles.iter().position(|m| m.id == mid) { let m = self.missiles.swap_remove(i); self.fireball(m.pos, 2.5 * m.kind.spec().scale, 7); out.particles("minecraft:explosion", m.pos, 0.4, DVec3::ZERO, 0.0, 3); out.sound("airdef:blast.air", m.pos, 1.0, 1.25); if let Some(t) = target.and_then(|t| self.drones.iter().position(|d| d.id == t)) { self.drones[t].engaged = self.drones[t].engaged.saturating_sub(1); if kill { self.shoot_down(t, sam, Some(mid), out); } } // A missile that lost its target frees it for others. if target.is_none() && let Some(d) = self.drones.iter_mut().find(|d| d.id == m.target) { d.engaged = d.engaged.saturating_sub(1); } } } for m in &self.missiles { let spec = m.kind.spec(); let rot = look(m.vel, 0.0) * DQuat::from_rotation_z(m.age as f64 * 0.3); out.model(m.id, spec.model, m.pos, rot, spec.scale, false); if m.age > spec.cold && spec.flame > 0.0 { let back = (spec.rear - 8.0) / 16.0 * spec.scale + spec.flame; let size = spec.flame * if m.age < 40 { 1.2 } else { 0.8 } * (0.85 + 0.15 * self.rng.f()); out.model(m.id + 1, "airdef:flame", m.pos + rot * DVec3::new(0.0, 0.0, back), rot, size, true); } } } // ------------------------------------------------ effects fn step_fx(&mut self, ground: &mut Ground, out: &mut Out) { let now = self.tick; let mut keep = Vec::with_capacity(self.fx.len()); for (id, mut fx) in std::mem::take(&mut self.fx) { let alive = match &mut fx { Fx::Fireball { pos, size, age, life, spin } => { *age += 1; let t = *age as f64 / *life as f64; let s = if t < 0.25 { *size * t / 0.25 } else { *size * (1.0 - (t - 0.25) / 0.75).max(0.0) }; let rot = DQuat::from_rotation_y(*age as f64 * 0.2) * *spin; out.model(id, "airdef:fireball", *pos + DVec3::Y * (*age as f64 * 0.05), rot, s.max(0.01), true); *age < *life } Fx::Debris { pos, vel, rot, spin, age } => { *age += 1; vel.y -= 0.05; *vel *= 0.98; *pos += *vel; *rot = *spin * *rot; out.model(id, "airdef:debris", *pos, *rot, 0.7, false); if *age % 2 == 0 { out.particles("minecraft:smoke", *pos, 0.05, DVec3::ZERO, 0.0, 1); } let landed = ground.at(*pos, now).is_some_and(|g| pos.y <= g); !landed && *age < 200 } Fx::Tracer { pos, vel, life } => { *pos += *vel; vel.y -= 0.02; *life = life.saturating_sub(1); out.model(id, "airdef:tracer", *pos, look(*vel, 0.0), 1.0, true); *life > 0 } }; if alive { keep.push((id, fx)); } } self.fx = keep; } fn draw_targets(&mut self, out: &mut Out) { for (i, t) in self.targets.iter().enumerate() { let bob = (self.tick as f64 * 0.1 + i as f64).sin() * 0.25; let rot = DQuat::from_rotation_y(self.tick as f64 * 0.08); out.model(0x7000_0000 + i as u32 * PARTS, "airdef:target", *t + DVec3::Y * (1.6 + bob), rot, 0.8, true); if self.tick % 10 == 0 { out.dust(*t + DVec3::Y * 0.2, 0xFF2020, 1.5, 0.4, 3); } } } }