//! Military HUD: a top bar (clock, speed, one pill per front sector), a bottom //! strip (selected node, its supply lines, last news lines), hover tooltips and //! the help overlay. Nothing here blocks the map except the bars themselves. use std::collections::VecDeque; use bevy::ecs::hierarchy::ChildSpawnerCommands; use bevy::ecs::query::Has; use bevy::picking::hover::Hovered; use bevy::prelude::*; use bevy::ui::{Display, UiTransform}; use bevy::ui_widgets::{Activate, Button}; use bevy::window::PrimaryWindow; use crate::front::hourly_need; use crate::map::{MapHover, good_color}; use crate::menu::Menu; use crate::model::{ CarKind, FrontState, GOODS, Good, MIN_USABLE_CONDITION, Network, NodeClicked, NodeId, NodeKind, Notify, REPAIR_COST, SLOW_CONDITION, Selected, SimClock, Tool, Train, Treasury, UiPassThrough, stock_text, }; use crate::routes::{AddCar, AddTrain, RemoveCar, Scrap, cargo_good}; use crate::seasons::SeasonState; use crate::supply::produces; use crate::trains::{TrainNo, train_center}; const PANEL: Color = Color::srgba(0.18, 0.2, 0.14, 0.92); /// Opaque, so nothing of the map shows through the bottom strip. const STRIP: Color = Color::srgb(0.15, 0.17, 0.12); const CHIP: Color = Color::srgb(0.1, 0.11, 0.08); const PARCH: Color = Color::srgb(0.92, 0.88, 0.76); const AMBER: Color = Color::srgb(0.95, 0.68, 0.2); const ALERT: Color = Color::srgb(0.9, 0.3, 0.25); const DARK_RED: Color = Color::srgb(0.4, 0.12, 0.1); const GREEN: Color = Color::srgb(0.35, 0.62, 0.28); const DIM: Color = Color::srgb(0.5, 0.48, 0.42); const BTN: Color = Color::srgba(0.27, 0.29, 0.21, 0.95); const BTN_HOVER: Color = Color::srgba(0.35, 0.37, 0.27, 0.98); const BTN_ACTIVE: Color = Color::srgb(0.6, 0.4, 0.12); const BAR_BG: Color = Color::srgba(0.07, 0.08, 0.05, 0.9); pub(crate) const TOP_H: f32 = 44.0; pub(crate) const BOTTOM_H: f32 = 128.0; /// Width of the selected node card in the bottom strip. const CARD_W: f32 = 300.0; /// Preferred width of the news column; it shrinks before the window does. const NEWS_W: f32 = 360.0; const NEWS_LINES: usize = 3; /// Stock value that fills a bar completely. const BAR_FULL: f32 = 30.0; /// World units from a train's centre within which the cursor picks it. const TRAIN_PICK_RADIUS: f32 = 14.0; /// World units from a damaged track within which the cursor picks it. const TRACK_PICK_RADIUS: f32 = 8.0; /// Goods a front sector consumes every game hour, with their hourly need. const SUPPLIED: [Good; 3] = [Good::Ammo, Good::Food, Good::Troops]; /// Icon shapes for the help overlay. #[derive(Clone, Copy)] enum Shape { Round, Square, Diamond, } /// Help overlay rows: icon, its colour, and a label of one to three words. const HELP_ROWS: [(Shape, Color, &str); 8] = [ (Shape::Round, PARCH, "City or capital"), (Shape::Square, PARCH, "Factory (Ammo)"), (Shape::Diamond, PARCH, "Farm (Food)"), (Shape::Round, ALERT, "Front: needs supply"), (Shape::Square, Color::srgb(0.27, 0.51, 0.71), "Light train"), (Shape::Square, Color::srgb(0.08, 0.08, 0.09), "Heavy train"), (Shape::Square, ALERT, "Damaged track: click"), (Shape::Square, Color::srgb(0.85, 0.6, 0.2), "Stock level"), ]; /// One start hint, shown in the news log when the game starts. const WELCOME_LINES: [&str; 1] = ["D1 Drag a source onto a front"]; pub struct HudPlugin; impl Plugin for HudPlugin { fn build(&self, app: &mut App) { app.init_resource::() .init_resource::() .add_systems(Startup, (spawn_hud, welcome)) .add_observer(on_speed_button) .add_observer(on_help_toggle) .add_observer(on_front_pill) .add_systems( Update, ( handle_keys, handle_node_clicks, collect_news, update_button_visuals, update_texts, sync_front_pills, update_front_pills, update_card, update_sections, update_gauges, update_stock_rows, update_stock_bars, sync_line_chips, render_news, update_help, update_tooltip, ), ); } } /// Whether the help overlay is shown. H and the [?] button toggle it; starts hidden. #[derive(Resource, Default)] struct HelpShown(bool); /// Marks the help overlay. #[derive(Component)] struct HelpPanel; /// Hover tooltip box, moved to the cursor each frame. #[derive(Component)] struct TooltipRoot; #[derive(Component)] struct TooltipText; fn welcome(mut log: ResMut) { log.0.extend(WELCOME_LINES.iter().map(|s| s.to_string())); } /// Last `NEWS_LINES` log lines, already prefixed with the day ("D12 ..."). #[derive(Resource, Default)] struct NewsLog(VecDeque); #[derive(Component, Clone, Copy)] struct SpeedButton(u32); /// The [?] button in the top bar. #[derive(Component, Clone, Copy)] struct HelpToggle; /// Front sector pill in the top bar. Clicking it selects the front. #[derive(Component, Clone, Copy)] struct FrontPill(NodeId); /// The small square inside a front pill, coloured by the front's health. #[derive(Component, Clone, Copy)] struct FrontSquare(NodeId); /// Container of the front pills, rebuilt when the set of fronts changes. #[derive(Component)] struct FrontPillRow; /// Container of the supply line chips, rebuilt when its content changes. #[derive(Component)] struct ChipRow; /// The selected node card, and the one-line hint shown when nothing is selected. #[derive(Component)] struct CardRoot; #[derive(Component)] struct HintText; /// Text fields whose content is refreshed from the game state each frame. #[derive(Component, Clone, Copy, PartialEq, Eq)] enum Field { Day, Treasury, NodeName, Stock(usize), Hunger, FrontLine, Supply, } /// Groups of the card shown only for matching node kinds. #[derive(Component, Clone, Copy, PartialEq, Eq)] enum Section { Settlement, Front, } /// One stock row of the card, shown only for goods the node kind makes or takes. #[derive(Component, Clone, Copy)] struct StockRow(Good); /// Fill bar for one stock good (index = `Good::idx()`). #[derive(Component, Clone, Copy)] struct StockBar(usize); /// Fill of the hunger bar of a settlement. #[derive(Component)] struct HungerFill; /// Marker on the front-line gauge, from -1 (pushed back) to +1 (right edge). #[derive(Component)] struct LineMarker; #[derive(Component)] struct NewsList; /// One chip of the bottom strip: the supply lines between two nodes. #[derive(Clone, PartialEq)] struct LineGroup { from: NodeId, to: NodeId, good: Option, count: usize, /// One of the trains of the group; [✕] scraps it. train: Entity, /// Cars of that train, front to back. Shown as icons and edited in place. cars: Vec, } fn label(text: &str, size: f32, color: Color) -> impl Bundle { ( Text::new(text), TextFont::from_font_size(size), TextColor(color), ) } fn row(gap: f32) -> Node { Node { align_items: AlignItems::Center, column_gap: Val::Px(gap), ..default() } } /// Mini button for the supply chips: a 24 px square. fn spawn_mini_button(parent: &mut ChildSpawnerCommands, text: &str, marker: impl Bundle) { parent .spawn(( Button, Node { width: Val::Px(24.0), height: Val::Px(24.0), align_items: AlignItems::Center, justify_content: JustifyContent::Center, flex_shrink: 0.0, ..default() }, BackgroundColor(BTN), Hovered::default(), marker, )) .with_children(|b| { b.spawn(label(text, 14.0, PARCH)); }); } fn spawn_button(parent: &mut ChildSpawnerCommands, text: &str, marker: impl Bundle) { parent .spawn(( Button, Node { height: Val::Px(26.0), padding: UiRect::axes(Val::Px(10.0), Val::Px(2.0)), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(BTN), Hovered::default(), marker, )) .with_children(|b| { b.spawn(label(text, 14.0, PARCH)); }); } fn bar_color(g: Good) -> Color { match g { Good::Ammo => Color::srgb(0.85, 0.6, 0.2), Good::Food => Color::srgb(0.5, 0.7, 0.3), Good::Troops => Color::srgb(0.5, 0.6, 0.7), Good::Wounded => Color::srgb(0.8, 0.3, 0.25), } } fn spawn_hud(mut commands: Commands) { // Top bar: title, clock, speed, front pills, then the help toggle. commands .spawn(( Node { position_type: PositionType::Absolute, top: Val::Px(0.0), left: Val::Px(0.0), right: Val::Px(0.0), height: Val::Px(TOP_H), padding: UiRect::horizontal(Val::Px(14.0)), align_items: AlignItems::Center, column_gap: Val::Px(16.0), ..default() }, BackgroundColor(PANEL), )) .with_children(|bar| { bar.spawn(label("IRON LIFELINE", 16.0, AMBER)); bar.spawn((label("", 14.0, PARCH), Field::Day)); crate::seasons::spawn_badge(bar); bar.spawn((label("", 14.0, PARCH), Field::Treasury)); bar.spawn(row(4.0)).with_children(|s| { spawn_button(s, "II", SpeedButton(0)); spawn_button(s, "1x", SpeedButton(1)); spawn_button(s, "2x", SpeedButton(2)); spawn_button(s, "4x", SpeedButton(4)); }); bar.spawn(( Node { flex_grow: 1.0, min_width: Val::Px(0.0), ..row(6.0) }, FrontPillRow, )); spawn_button(bar, "?", HelpToggle); }); // Bottom strip: selected node card | supply lines | news. Every child is // clipped, so nothing can run past the strip or the window edge. commands .spawn(( Node { position_type: PositionType::Absolute, bottom: Val::Px(0.0), left: Val::Px(0.0), right: Val::Px(0.0), height: Val::Px(BOTTOM_H), padding: UiRect::all(Val::Px(8.0)), column_gap: Val::Px(10.0), overflow: Overflow::clip(), ..default() }, BackgroundColor(STRIP), )) .with_children(|s| { spawn_card(s); // Supply lines touching the selected node, or all of them, as wrapping chips. s.spawn(( Node { flex_grow: 1.0, min_width: Val::Px(0.0), height: Val::Percent(100.0), flex_wrap: FlexWrap::Wrap, align_content: AlignContent::Start, align_items: AlignItems::Start, column_gap: Val::Px(6.0), row_gap: Val::Px(6.0), overflow: Overflow::clip(), ..default() }, ChipRow, )); // Last news lines, newest on top. Lines wrap inside the column. s.spawn(( Node { flex_basis: Val::Px(NEWS_W), flex_shrink: 1.0, min_width: Val::Px(0.0), height: Val::Percent(100.0), padding: UiRect::all(Val::Px(8.0)), flex_direction: FlexDirection::Column, row_gap: Val::Px(3.0), overflow: Overflow::clip(), ..default() }, NewsList, )); }); // Help overlay: icons with short labels. Top right, under the bar, never blocks the map. commands .spawn(( Node { position_type: PositionType::Absolute, top: Val::Px(TOP_H + 6.0), right: Val::Px(8.0), padding: UiRect::all(Val::Px(10.0)), flex_direction: FlexDirection::Column, row_gap: Val::Px(6.0), display: Display::None, ..default() }, BackgroundColor(PANEL), GlobalZIndex(40), HelpPanel, UiPassThrough, )) .with_children(|h| { for (shape, color, text) in HELP_ROWS { h.spawn(row(8.0)).with_children(|r| { spawn_swatch(r, shape, color); r.spawn(label(text, 13.0, PARCH)); }); } }); // Hover tooltip, moved to the cursor by `update_tooltip`. commands.spawn(( Node { position_type: PositionType::Absolute, display: Display::None, padding: UiRect::all(Val::Px(8.0)), ..default() }, GlobalZIndex(60), BackgroundColor(PANEL), TooltipRoot, UiPassThrough, children![(label("", 13.0, PARCH), TooltipText)], )); } /// The left part of the bottom strip: a hint, or the selected node. Compact: /// name and kind on one row, stock bars in a 2x2 grid, then one row for the /// settlement hunger or the front line gauge with its supply. fn spawn_card(s: &mut ChildSpawnerCommands) { s.spawn(Node { width: Val::Px(CARD_W), flex_shrink: 0.0, height: Val::Percent(100.0), padding: UiRect::axes(Val::Px(10.0), Val::Px(6.0)), flex_direction: FlexDirection::Column, overflow: Overflow::clip(), ..default() }) .with_children(|c| { c.spawn((label("Drag from a source to a front", 14.0, DIM), HintText)); c.spawn(( Node { flex_direction: FlexDirection::Column, row_gap: Val::Px(4.0), display: Display::None, ..default() }, CardRoot, )) .with_children(|card| { card.spawn((label("", 14.0, PARCH), Field::NodeName)); // 2x2 stock grid. A cell hides when the node does not use that good. card.spawn(Node { flex_direction: FlexDirection::Row, flex_wrap: FlexWrap::Wrap, row_gap: Val::Px(4.0), ..default() }) .with_children(|grid| { for g in GOODS { grid.spawn(( Node { display: Display::None, width: Val::Percent(50.0), padding: UiRect::right(Val::Px(8.0)), ..row(4.0) }, StockRow(g), )) .with_children(|r| { r.spawn(( label(g.name(), 12.0, PARCH), Node { width: Val::Px(56.0), ..default() }, )); r.spawn(( label("", 12.0, PARCH), Node { width: Val::Px(24.0), ..default() }, Field::Stock(g.idx()), )); r.spawn(( Node { flex_grow: 1.0, min_width: Val::Px(0.0), height: Val::Px(6.0), ..default() }, BackgroundColor(BAR_BG), )) .with_children(|bg| { bg.spawn(( Node { width: Val::Percent(0.0), height: Val::Percent(100.0), ..default() }, BackgroundColor(bar_color(g)), StockBar(g.idx()), )); }); }); } }); // Settlement: hunger text and bar on one row. card.spawn((row(6.0), Section::Settlement)) .with_children(|b| { b.spawn(( label("", 12.0, PARCH), Node { width: Val::Px(84.0), ..default() }, Field::Hunger, )); b.spawn(( Node { flex_grow: 1.0, min_width: Val::Px(0.0), height: Val::Px(5.0), ..default() }, BackgroundColor(BAR_BG), )) .with_children(|bg| { bg.spawn(( Node { width: Val::Percent(0.0), height: Val::Percent(100.0), ..default() }, BackgroundColor(ALERT), HungerFill, )); }); }); // Front: front line text, gauge and supply % on one row. card.spawn((row(6.0), Section::Front)).with_children(|b| { b.spawn(( label("", 12.0, PARCH), Node { width: Val::Px(84.0), ..default() }, Field::FrontLine, )); b.spawn(( Node { flex_grow: 1.0, min_width: Val::Px(0.0), height: Val::Px(6.0), ..default() }, BackgroundColor(BAR_BG), )) .with_children(|bg| { bg.spawn(( Node { position_type: PositionType::Absolute, left: Val::Percent(50.0), top: Val::Px(-2.0), width: Val::Px(4.0), height: Val::Px(10.0), ..default() }, BackgroundColor(PARCH), LineMarker, )); }); b.spawn((label("", 12.0, PARCH), Field::Supply)); }); }); }); } /// A small icon for the help overlay: round, square or diamond. fn spawn_swatch(r: &mut ChildSpawnerCommands, shape: Shape, color: Color) { let mut node = Node { width: Val::Px(12.0), height: Val::Px(12.0), ..default() }; let mut transform = UiTransform::default(); match shape { Shape::Round => node.border_radius = BorderRadius::MAX, Shape::Square => {} Shape::Diamond => transform.rotation = Rot2::degrees(45.0), } r.spawn((node, transform, BackgroundColor(color))); } /// A front pill: a button with the front's name and a health square. fn spawn_pill(p: &mut ChildSpawnerCommands, id: NodeId, name: &str) { p.spawn(( Button, FrontPill(id), Node { height: Val::Px(26.0), padding: UiRect::axes(Val::Px(10.0), Val::Px(2.0)), align_items: AlignItems::Center, column_gap: Val::Px(6.0), ..default() }, BackgroundColor(BTN), Hovered::default(), )) .with_children(|b| { b.spawn(( Node { width: Val::Px(10.0), height: Val::Px(10.0), ..default() }, BackgroundColor(GREEN), FrontSquare(id), )); b.spawn(label(name, 14.0, PARCH)); }); } /// Health colour of a front: green supplied, amber short, red starving. /// A front pushed back past -0.6 pulses red. fn front_color(front: &FrontState, blink: bool) -> Color { if front.line < -0.6 { return if blink { ALERT } else { DARK_RED }; } if front.supply >= 0.7 { GREEN } else if front.supply >= 0.4 { AMBER } else { ALERT } } /// Hours of supply left in a front-line sector, as "12 h" or "4.2 days". fn lasts_text(hours: f32) -> String { if hours < 48.0 { format!("{:.0} h", hours) } else { format!("{:.1} days", hours / 24.0) } } /// Formats a treasury amount, e.g. `$4,000` or `-$120`. fn money(v: i64) -> String { let digits = v.unsigned_abs().to_string(); let mut out = String::new(); for (i, c) in digits.chars().enumerate() { if i > 0 && (digits.len() - i).is_multiple_of(3) { out.push(','); } out.push(c); } if v < 0 { format!("-${out}") } else { format!("${out}") } } /// Help hotkey. Space and 1/2/3 are handled by `economy.rs`, Esc by `menu.rs`. /// Nothing here runs while a menu is open. fn handle_keys(keys: Res>, menu: Res, mut help: ResMut) { if menu.is_open() { return; } if keys.just_pressed(KeyCode::KeyH) { help.0 = !help.0; } } fn on_speed_button(ev: On, buttons: Query<&SpeedButton>, mut clock: ResMut) { if let Ok(btn) = buttons.get(ev.entity) && clock.speed != btn.0 { clock.speed = btn.0; } } fn on_help_toggle( ev: On, toggles: Query<(), With>, mut help: ResMut, ) { if toggles.get(ev.entity).is_ok() { help.0 = !help.0; } } fn on_front_pill(ev: On, pills: Query<&FrontPill>, mut selected: ResMut) { if let Ok(FrontPill(id)) = pills.get(ev.entity) { selected.0 = Some(*id); } } fn handle_node_clicks( mut clicks: MessageReader, tool: Res, mut selected: ResMut, ) { for click in clicks.read() { if matches!(*tool, Tool::Inspect) && selected.0 != Some(click.0) { selected.0 = Some(click.0); } } } fn collect_news(mut notes: MessageReader, clock: Res, mut log: ResMut) { let day = clock.day() + 1; let fresh: Vec = notes.read().map(|n| format!("D{day} {}", n.0)).collect(); if fresh.is_empty() { return; } let queue = &mut log.0; queue.extend(fresh); while queue.len() > NEWS_LINES { queue.pop_front(); } } #[allow( clippy::type_complexity, reason = "one-off query tuple for button colours" )] fn update_button_visuals( clock: Res, help: Res, mut buttons: Query< ( &Hovered, &mut BackgroundColor, Option<&SpeedButton>, Has, ), Or<(With, With, With)>, >, ) { for (hovered, mut bg, speed, is_help) in &mut buttons { let active = match speed { Some(s) => clock.speed == s.0, None => is_help && help.0, }; let target = if active { BTN_ACTIVE } else if hovered.get() { BTN_HOVER } else { BTN }; if bg.0 != target { bg.0 = target; } } } fn update_texts( clock: Res, treasury: Res, selected: Res, net: Res, mut texts: Query<(&Field, &mut Text, &mut TextColor)>, ) { let node = selected.0.and_then(|id| net.nodes.get(id.0)); for (field, mut text, mut color) in &mut texts { let (value, tint): (String, Color) = match *field { Field::Day => ( format!("Day {} (Week {})", clock.day() + 1, clock.week() + 1), PARCH, ), Field::Treasury => ( format!("Treasury {}", money(treasury.0)), if treasury.0 < 0 { ALERT } else { PARCH }, ), Field::NodeName => ( node.map_or(String::new(), |n| { format!("{} | {}", n.name, n.kind.name()) }), PARCH, ), Field::Stock(i) => ( node.map_or(String::new(), |n| format!("{:.0}", n.stock[i])), PARCH, ), Field::Hunger => match node { Some(n) if is_settlement(n.kind) => ( format!("Hunger {}%", (n.hunger * 100.0).round() as i32), if n.hunger > 0.5 { ALERT } else { PARCH }, ), _ => (String::new(), PARCH), }, Field::FrontLine => ( node.and_then(|n| n.front.as_ref()) .map_or(String::new(), |f| format!("Front {:+.2}", f.line)), PARCH, ), Field::Supply => ( node.and_then(|n| n.front.as_ref()) .map_or(String::new(), |f| { format!("Supply {}%", (f.supply * 100.0).round() as i32) }), PARCH, ), }; if text.0 != value { text.0 = value; } if color.0 != tint { color.0 = tint; } } } fn is_settlement(kind: NodeKind) -> bool { matches!(kind, NodeKind::Capital | NodeKind::City) } /// Rebuilds the front pills when the set of fronts changes. fn sync_front_pills( mut commands: Commands, net: Res, rows: Query>, mut shown: Local>>, ) { let fronts: Vec = net .nodes .iter() .enumerate() .filter(|(_, n)| n.kind == NodeKind::Front) .map(|(i, _)| NodeId(i)) .collect(); if shown.as_ref() == Some(&fronts) { return; } let Ok(row) = rows.single() else { return; }; commands .entity(row) .despawn_related::() .with_children(|p| { for id in &fronts { spawn_pill(p, *id, &net.nodes[id.0].name); } }); *shown = Some(fronts); } /// Colours the health square of each front pill. The red pulse alternates each frame. fn update_front_pills( time: Res