//! Evacuation: a losing front sector threatens a nearby factory, farm or city. //! The player rails its crates to the rear with one drag. When the crates are //! out, the site is dismantled and rebuilt at the destination. When the clock //! runs out, the site is captured. A front that recovers cancels the threat. use std::f32::consts::{FRAC_PI_2, FRAC_PI_4, TAU}; use bevy::prelude::*; use bevy::time::{Real, Time}; use crate::front::front_hour_system; use crate::map::WorldText; use crate::model::{ CarKind, Evac, HourTick, LocoKind, Network, NodeId, NodeKind, Notify, Outcome, TrackSeg, node, }; /// A front at or below this line threatens buildings within `EVAC_RANGE`. const THREAT_LINE: f32 = -0.4; /// The threat lifts once the threatening front recovers above this line. const SAFE_LINE: f32 = -0.2; const EVAC_RANGE: f32 = 350.0; const EVAC_HOURS: u32 = 120; const EVAC_CRATES: u32 = 6; /// An evacuation destination lies at least this far west of the building. const REAR_GAP: f32 = 150.0; /// Distance from the destination to the rebuilt site, and the clearance it needs. const REBUILD_OFFSET: f32 = 45.0; const REBUILD_CLEAR: f32 = 35.0; const CRATE_FILL: Color = Color::srgb(0.55, 0.36, 0.16); const CRATE_EDGE: Color = Color::srgb(0.22, 0.15, 0.09); const ALARM: Color = Color::srgb(0.78, 0.12, 0.10); const AMBER: Color = Color::srgb(1.0, 0.70, 0.10); const CAPTION_SIZE: f32 = 15.0; pub struct EvacPlugin; impl Plugin for EvacPlugin { fn build(&self, app: &mut App) { app.add_systems(Update, evac_hour_system.after(front_hour_system)) .add_systems(Update, (sync_captions, draw_evac).chain()); } } /// Checks that `to` can take the crates of the evacuating building `from`. pub fn check_dest(net: &Network, from: NodeId, to: NodeId) -> Result<(), String> { let a = &net.nodes[from.0]; let b = &net.nodes[to.0]; let Some(evac) = a.evac else { return Err(format!("{} is not evacuating", a.name)); }; if b.kind == NodeKind::Front { return Err("Not a rear site".to_string()); } if b.captured { return Err(format!("{} is captured", b.name)); } if a.pos.x - b.pos.x < REAR_GAP { return Err("Too close to the front".to_string()); } if let Some(old) = evac.dest && old != to && evac.delivered > 0 { return Err("Crates already delivered".to_string()); } Ok(()) } /// The train that carries crates: a Light loco with three Flat cars. pub fn evac_consist() -> (LocoKind, Vec) { (LocoKind::Light, vec![CarKind::Flat; 3]) } /// True when an evacuation already threatens the spot `at`. fn in_reach(net: &Network, at: Vec2) -> bool { net.nodes .iter() .any(|n| n.evac.is_some() && n.pos.distance(at) <= EVAC_RANGE) } /// Founds a replacement of `kind` next to `dest`, linked to it by a short track. /// Its output is the share of crates that arrived. fn found_rebuild(net: &mut Network, name: &str, kind: NodeKind, dest: NodeId, delivered: u32) { let center = net.nodes[dest.0].pos; let dirs: Vec = (0..8) .map(|k| Vec2::from_angle(k as f32 * FRAC_PI_4)) .collect(); let dir = dirs .iter() .copied() .find(|d| { let at = center + *d * REBUILD_OFFSET; net.nodes .iter() .all(|n| n.pos.distance(at) >= REBUILD_CLEAR) }) .unwrap_or(Vec2::X); let pos = center + dir * REBUILD_OFFSET; let mut site = node(&format!("{name} II"), kind, pos.x, pos.y, [0.0; 4]); site.output = delivered as f32 / EVAC_CRATES as f32; net.nodes.push(site); net.tracks.push(TrackSeg { a: dest, b: NodeId(net.nodes.len() - 1), length: REBUILD_OFFSET, condition: 1.0, }); } /// Starts new threats and advances every evacuation one game hour. /// Returns the news lines. pub(crate) fn step_evacuations(net: &mut Network) -> Vec { let mut news = Vec::new(); let fronts: Vec<(usize, Vec2, f32)> = net .nodes .iter() .enumerate() .filter_map(|(i, n)| n.front.map(|f| (i, n.pos, f.line))) .collect(); for (fi, fpos, line) in fronts { if line > THREAT_LINE || in_reach(net, fpos) { continue; } let target = net .nodes .iter() .enumerate() .filter(|(_, n)| { matches!(n.kind, NodeKind::Factory | NodeKind::Farm | NodeKind::City) && !n.captured && n.evac.is_none() }) .map(|(i, n)| (i, n.pos.distance(fpos))) .filter(|(_, d)| *d <= EVAC_RANGE) .min_by(|a, b| a.1.total_cmp(&b.1)); if let Some((i, _)) = target { let site = &mut net.nodes[i]; site.evac = Some(Evac { hours_left: EVAC_HOURS, crates_left: EVAC_CRATES, dest: None, delivered: 0, threat: fi, }); news.push(format!("{} threatened!", site.name)); } } for i in 0..net.nodes.len() { let Some(mut evac) = net.nodes[i].evac else { continue; }; let name = net.nodes[i].name.clone(); let kind = net.nodes[i].kind; let threat_line = net .nodes .get(evac.threat) .and_then(|n| n.front) .map_or(-1.0, |f| f.line); // The front held: the site keeps what crates it still has. if threat_line > SAFE_LINE { net.nodes[i].evac = None; net.nodes[i].output = evac.crates_left as f32 / EVAC_CRATES as f32; news.push(format!("{name} is safe")); if let Some(dest) = evac.dest && evac.delivered > 0 { found_rebuild(net, &name, kind, dest, evac.delivered); } continue; } // Every crate got out: the old site was dismantled and is lost. if evac.delivered >= EVAC_CRATES { net.nodes[i].evac = None; net.capture(i); news.push(format!("{name} saved")); if let Some(dest) = evac.dest { found_rebuild(net, &name, kind, dest, evac.delivered); } continue; } // The deadline passed: the site is overrun. evac.hours_left = evac.hours_left.saturating_sub(1); if evac.hours_left == 0 { net.nodes[i].evac = None; net.capture(i); news.push(format!("{name} lost!")); if let Some(dest) = evac.dest { found_rebuild(net, &name, kind, dest, evac.delivered); } continue; } net.nodes[i].evac = Some(evac); } news } fn evac_hour_system( mut ticks: MessageReader, mut net: ResMut, outcome: Res, mut notify: MessageWriter, ) { for _ in ticks.read() { if *outcome != Outcome::Ongoing { continue; } for text in step_evacuations(&mut net) { notify.write(Notify(text)); } } } /// Marker for the "Drag to evacuate" caption beside a site. Holds the node index. #[derive(Component)] struct EvacCaption(usize); /// Keeps one caption per site that still needs a destination. fn sync_captions( mut commands: Commands, net: Res, captions: Query<(Entity, &EvacCaption)>, ) { let wanted = |i: usize| { net.nodes .get(i) .and_then(|n| n.evac) .is_some_and(|e| e.dest.is_none()) }; let mut have = vec![false; net.nodes.len()]; for (entity, caption) in &captions { if wanted(caption.0) { have[caption.0] = true; } else { commands.entity(entity).despawn(); } } for (i, site) in net.nodes.iter().enumerate() { if !wanted(i) || have[i] { continue; } commands.spawn(( EvacCaption(i), Text2d::new("Drag to evacuate"), WorldText { size: CAPTION_SIZE }, TextColor(ALARM), Transform::from_xyz(site.pos.x - 90.0, site.pos.y - 16.0, 21.0), )); } } /// Crate `k` of a stack sits north-west of its site, each one above the last. fn crate_at(pos: Vec2, k: u32) -> Vec2 { pos + Vec2::new(-36.0, 14.0 + k as f32 * 9.0) } fn draw_crate(gizmos: &mut Gizmos, c: Vec2) { gizmos.rect_2d( Isometry2d::from_translation(c), Vec2::new(8.0, 7.0), CRATE_EDGE, ); for dy in [-2.0_f32, 0.0, 2.0] { gizmos.line_2d(c + Vec2::new(-3.0, dy), c + Vec2::new(3.0, dy), CRATE_FILL); } } /// A line with a head at `to`. fn draw_arrow(gizmos: &mut Gizmos, from: Vec2, to: Vec2, color: Color) { gizmos.line_2d(from, to, color); let dir = (to - from).normalize_or_zero(); let side = Vec2::new(-dir.y, dir.x); gizmos.line_2d(to, to - dir * 7.0 + side * 4.0, color); gizmos.line_2d(to, to - dir * 7.0 - side * 4.0, color); } /// Countdown ring around a site: a faint full ring with the time left drawn over it. fn draw_countdown(gizmos: &mut Gizmos, pos: Vec2, frac: f32) { const RADIUS: f32 = 34.0; const STEPS: u32 = 48; gizmos.circle_2d( Isometry2d::from_translation(pos), RADIUS, Color::srgba(0.22, 0.15, 0.09, 0.25), ); let color = if frac < 0.3 { ALARM } else { AMBER }; let sweep = TAU * frac; for dr in [-0.6_f32, 0.0, 0.6] { let pts = (0..=STEPS).map(|k| { let ang = FRAC_PI_2 - sweep * k as f32 / STEPS as f32; pos + Vec2::from_angle(ang) * (RADIUS + dr) }); gizmos.linestrip_2d(pts, color); } } /// Everything shown for the evacuations: the flashing site, the countdown, crates on /// site, the piles at the destination, the hint to drag, and the threat arrow. fn draw_evac(mut gizmos: Gizmos, net: Res, time: Res>) { let t = time.elapsed_secs(); let blink = 0.5 + 0.5 * (t * 6.0).sin(); let pulse = 0.5 + 0.5 * (t * 4.0).sin(); for site in &net.nodes { let Some(evac) = site.evac else { continue; }; let pos = site.pos; let frac = evac.hours_left as f32 / EVAC_HOURS as f32; // Flashing outline around the threatened site. let flash = ALARM.with_alpha(0.35 + 0.65 * blink); gizmos.circle_2d(Isometry2d::from_translation(pos), 26.0, flash); gizmos.circle_2d(Isometry2d::from_translation(pos), 27.0, flash); draw_countdown(&mut gizmos, pos, frac); for k in 0..evac.crates_left { draw_crate(&mut gizmos, crate_at(pos, k)); } match evac.dest.and_then(|d| net.nodes.get(d.0)) { None => { // Hint pointing to the rear, until a destination is chosen. let hint = ALARM.with_alpha(0.4 + 0.6 * pulse); draw_arrow( &mut gizmos, pos + Vec2::new(-40.0, 0.0), pos + Vec2::new(-110.0, 0.0), hint, ); } Some(dest) => { for k in 0..evac.delivered { draw_crate(&mut gizmos, crate_at(dest.pos, k)); } } } // Threat: an arrow from the threatening front, longer as the deadline nears. if let Some(front) = net.nodes.get(evac.threat) { let east = (front.pos - pos).normalize_or_zero(); let progress = 1.0 - frac; let tip = pos + east * 40.0; let tail = pos + east * (60.0 + 70.0 * progress); draw_arrow(&mut gizmos, tail, tip, ALARM.with_alpha(0.5 + 0.5 * blink)); } } } #[cfg(test)] mod tests { use super::*; #[test] fn timeout_captures_site_and_rebuilds_with_delivered_share() { let mut net = Network::default(); // North Sector (node 9) collapses: Dornmark (node 12) is threatened. net.nodes[9].front.as_mut().unwrap().line = -0.6; step_evacuations(&mut net); assert!(net.nodes[12].evac.is_some()); // Half the crates reached Feldau (node 7) and the deadline hits. if let Some(e) = net.nodes[12].evac.as_mut() { e.dest = Some(NodeId(7)); e.delivered = 3; e.hours_left = 1; } step_evacuations(&mut net); assert!(net.nodes[12].captured); assert!(net.nodes[12].evac.is_none()); assert_eq!(net.nodes.len(), 15); assert!((net.nodes[14].output - 0.5).abs() < 1e-6); } }