//! Game clock, home-front production and consumption, and the weekly budget. use std::collections::HashMap; use bevy::input::ButtonInput; use bevy::prelude::*; use bevy::time::{Real, Time}; use crate::menu::Menu; use crate::model::{ Good, HourTick, Network, NodeKind, Notify, Outcome, SECS_PER_HOUR, SimClock, Train, Treasury, }; use crate::seasons::SeasonState; /// Stock cap per good per node. const STOCK_CAP: f32 = 200.0; /// Food eaten per hour by Capital and City. const FOOD_PER_HOUR: f32 = 0.5; /// Hunger relief per hour when fed, and gain per hour when starving. const HUNGER_RECOVER: f32 = 0.02; const HUNGER_GAIN: f32 = 0.03; /// Hunger level at which a city's production warning fires. const HUNGER_ALARM: f32 = 0.5; /// Minimum game hours between two bread-line warnings for the same city. const ALARM_COOLDOWN_HOURS: u32 = 24; /// Wounded treated per hour per hospital node. const TREAT_PER_HOUR: f32 = 1.0; /// Troops returned per wounded treated. const TROOPS_PER_TREATED: f32 = 0.5; /// Weekly budget period in game hours. const WEEK_HOURS: u32 = 24 * 7; const BASE_INCOME: i64 = 2000; const FRONT_LINE_BONUS: i64 = 500; pub struct EconomyPlugin; impl Plugin for EconomyPlugin { fn build(&self, app: &mut App) { app.add_systems(Update, (clock_controls, advance_clock).chain()) .add_systems(Update, economy_tick.after(advance_clock)); } } /// Space toggles pause (restoring the previous speed on unpause). /// Digit1/2/3 select speed 1, 2 or 4. fn clock_controls( keys: Res>, menu: Res, mut clock: ResMut, mut prev_speed: Local, ) { if menu.is_open() { return; } if keys.just_pressed(KeyCode::Space) { if clock.speed == 0 { clock.speed = if *prev_speed == 0 { 1 } else { *prev_speed }; } else { *prev_speed = clock.speed; clock.speed = 0; } } let digits = [ (KeyCode::Digit1, 1), (KeyCode::Digit2, 2), (KeyCode::Digit3, 4), ]; for (key, speed) in digits { if keys.just_pressed(key) { clock.speed = speed; } } } /// Advances game time by real time times speed, emitting one `HourTick` per whole hour. pub fn advance_clock( time: Res>, outcome: Res, mut clock: ResMut, mut ticks: MessageWriter, ) { if *outcome != Outcome::Ongoing { return; } clock.acc += time.delta_secs() * clock.speed as f32; while clock.acc >= SECS_PER_HOUR { clock.acc -= SECS_PER_HOUR; clock.hour += 1; ticks.write(HourTick); } } /// Runs the hourly production, consumption and budget for every `HourTick` read this frame. /// Ticks are ordered after `advance_clock`, so the tick hours are the last `n` hours of the clock. #[allow(clippy::too_many_arguments, reason = "bevy system parameters")] pub(crate) fn economy_tick( mut ticks: MessageReader, clock: Res, season: Res, mut net: ResMut, mut treasury: ResMut, trains: Query<&Train>, mut notes: MessageWriter, mut alarm_hours: Local>, ) { let n = ticks.read().count() as u32; if n == 0 { return; } let first_hour = (clock.hour + 1).saturating_sub(n); for k in 0..n { let hour = first_hour + k; for text in run_hour(&mut net.nodes, hour, season.season.food_mult(), &mut alarm_hours) { notes.write(Notify(text)); } if is_budget_hour(hour) { let front_lines = net .nodes .iter() .filter(|node| node.front.is_some_and(|f| f.line > 0.0)) .count(); let upkeep: i64 = trains.iter().map(|t| t.upkeep_per_week()).sum(); let income = budget_income(front_lines); treasury.0 += income - upkeep; notes.write(Notify(format!( "War Ministry allocation: +${income}, upkeep -${upkeep}" ))); } } } /// One hour of home-front simulation. Returns the news lines to publish. fn run_hour( nodes: &mut [crate::model::Node], hour: u32, food_mult: f32, alarm_hours: &mut HashMap, ) -> Vec { let mut news = Vec::new(); let (hunger_sum, hunger_count) = nodes .iter() .filter(|n| !n.captured && matches!(n.kind, NodeKind::Capital | NodeKind::City)) .fold((0.0_f32, 0_usize), |(s, c), n| (s + n.hunger, c + 1)); let avg_hunger = if hunger_count > 0 { hunger_sum / hunger_count as f32 } else { 0.0 }; let p = productivity(avg_hunger); for (i, node) in nodes.iter_mut().enumerate() { // Captured sites are gone; evacuating sites produce nothing until the evacuation ends. if node.captured { continue; } let before = node.hunger; let output = if node.evac.is_some() { 0.0 } else { node.output }; match node.kind { NodeKind::Factory => { add_capped(&mut node.stock[Good::Ammo.idx()], 2.0 * p * output); } NodeKind::Farm => { add_capped(&mut node.stock[Good::Food.idx()], 3.0 * output); } NodeKind::Capital => { add_capped(&mut node.stock[Good::Troops.idx()], 0.8 * p * output); } NodeKind::City => { add_capped(&mut node.stock[Good::Troops.idx()], city_troops(before) * output); } NodeKind::Depot | NodeKind::Front => {} } if matches!(node.kind, NodeKind::Capital | NodeKind::City) { let (hunger, eaten) = feed(before, node.stock[Good::Food.idx()], FOOD_PER_HOUR * food_mult); node.stock[Good::Food.idx()] = (node.stock[Good::Food.idx()] - eaten).max(0.0); node.hunger = hunger; let wounded = node.stock[Good::Wounded.idx()]; let treated = wounded.min(TREAT_PER_HOUR); node.stock[Good::Wounded.idx()] = (wounded - treated).max(0.0); add_capped( &mut node.stock[Good::Troops.idx()], treated * TROOPS_PER_TREATED, ); if node.kind == NodeKind::City && before < HUNGER_ALARM && node.hunger >= HUNGER_ALARM && alarm_due(alarm_hours, i, hour) { news.push(format!("Bread lines in {}: production falling", node.name)); } } } news } /// Returns true and records `hour` when the city's warning is off cooldown. /// A last warning later than `hour` came from before a restart, so it does not count. fn alarm_due(alarm_hours: &mut HashMap, node: usize, hour: u32) -> bool { match alarm_hours.get(&node) { Some(&last) if hour >= last && hour - last < ALARM_COOLDOWN_HOURS => false, _ => { alarm_hours.insert(node, hour); true } } } /// Output multiplier from average city hunger: 1.0 when fed, 0.4 at full hunger. pub fn productivity(avg_hunger: f32) -> f32 { 1.0 - 0.6 * avg_hunger } /// Troops a city adds per hour, scaled by its own hunger. pub fn city_troops(hunger: f32) -> f32 { 0.3 * (1.0 - hunger) } /// One hour of eating a `ration`. Returns (new hunger, food consumed). pub fn feed(hunger: f32, food: f32, ration: f32) -> (f32, f32) { if food >= ration { ((hunger - HUNGER_RECOVER).max(0.0), ration) } else { ((hunger + HUNGER_GAIN).min(1.0), 0.0) } } /// Adds `amount` to a stock, clamped to the per-node cap. pub fn add_capped(stock: &mut f32, amount: f32) { *stock = (*stock + amount).min(STOCK_CAP); } pub fn is_budget_hour(hour: u32) -> bool { hour > 0 && hour.is_multiple_of(WEEK_HOURS) } pub fn budget_income(front_lines_advancing: usize) -> i64 { BASE_INCOME + FRONT_LINE_BONUS * front_lines_advancing as i64 } #[cfg(test)] mod tests { use super::*; #[test] fn feed_eats_when_fed_and_starves_without_food() { // Enough food: eat one hour's ration and recover hunger. let (h, eaten) = feed(0.5, 1.0, FOOD_PER_HOUR); assert!((h - 0.48).abs() < 1e-6); assert_eq!(eaten, FOOD_PER_HOUR); // No food: eat nothing and hunger rises, capped at 1. let (h, eaten) = feed(0.5, 0.49, FOOD_PER_HOUR); assert!((h - 0.53).abs() < 1e-6); assert_eq!(eaten, 0.0); let (h, _) = feed(0.99, 0.0, FOOD_PER_HOUR); assert_eq!(h, 1.0); } }