//! The drag gesture: left-drag from one node to another to run a supply line. //! //! The source sends the good it makes; the target must accept it. A straight //! track is laid when no usable rail path exists, and a train that carries the //! good is bought. Dragging the same pair again adds another train. use bevy::ecs::system::SystemParam; use bevy::prelude::*; use bevy::window::PrimaryWindow; use crate::audio::SoundEvent; use crate::build::{new_segments, segments_cost}; use crate::evac; use crate::map::{MapHover, WorldText, dashed, good_color, picking}; use crate::model::{ CarKind, Good, LocoKind, Network, NodeClicked, NodeId, NodeKind, Notify, Stop, Tool, TrackSeg, Treasury, consist_cost, }; use crate::trains::new_train; pub struct SupplyPlugin; impl Plugin for SupplyPlugin { fn build(&self, app: &mut App) { app.init_resource::() .add_systems(Startup, spawn_drag_label) .add_systems(Update, (drag_gesture, draw_drag).chain().after(picking)); } } /// Pointer movement in logical pixels that turns a press into a drag. const DRAG_THRESHOLD: f32 = 6.0; /// Glyph size of the floating cost label, in world units (see `map::WorldText`). const LABEL_SIZE: f32 = 27.0; /// Offset of the floating label from the cursor. const LABEL_OFFSET: Vec2 = Vec2::new(14.0, 14.0); const DRAG_DASH: f32 = 12.0; const DRAG_GAP: f32 = 8.0; const RING_RADIUS: f32 = 24.0; const INK: Color = Color::srgb(0.22, 0.15, 0.09); const GREEN: Color = Color::srgb(0.1, 0.5, 0.1); const RED: Color = Color::srgb(0.8, 0.1, 0.1); const VALID_RING: Color = Color::srgb(1.0, 0.92, 0.45); /// The good a node sends out, if any. Depots only store. pub fn produces(kind: NodeKind) -> Option { match kind { NodeKind::Factory => Some(Good::Ammo), NodeKind::Farm => Some(Good::Food), NodeKind::Capital | NodeKind::City => Some(Good::Troops), NodeKind::Front => Some(Good::Wounded), NodeKind::Depot => None, } } /// The good a drag from a `from` node to a `to` node sends, if `to` takes it. pub fn flow(from: NodeKind, to: NodeKind) -> Option { let good = produces(from)?; match good { // Wounded only go home: to a Capital or City, never to a Depot. Good::Wounded => matches!(to, NodeKind::Capital | NodeKind::City).then_some(good), _ => to.accepts(good).then_some(good), } } /// The default consist that carries a good: a locomotive and its cars. pub fn consist_for(good: Good) -> (LocoKind, Vec) { match good { Good::Ammo => (LocoKind::Heavy, vec![CarKind::Ammo; 4]), Good::Food => (LocoKind::Light, vec![CarKind::Food; 2]), Good::Troops => (LocoKind::Light, vec![CarKind::Troop; 2]), Good::Wounded => (LocoKind::Light, vec![CarKind::Hospital; 3]), } } /// Whole dollars with thousands separators: "$1,840". pub 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}") } } /// What a drag from one node to another would do and cost. #[derive(Debug, Clone, PartialEq)] pub struct Plan { /// Good carried by the new train, if any. pub good: Option, /// True when the train carries evacuation crates from an evacuating site. pub evac: bool, /// Cost of the new track segments, if no usable rail path exists. pub track: Option, /// The new segments to lay, split at any node the straight line passes. pub segments: Vec, /// Total cost: track plus train. pub total: i64, } /// Works out the plan for a drag, or the reason it cannot be done. pub fn plan(net: &Network, from: NodeId, to: NodeId) -> Result { let a = &net.nodes[from.0]; let b = &net.nodes[to.0]; if from == to { return Err(format!("Drag from {} to another node", a.name)); } if a.captured || b.captured { let lost = if a.captured { a } else { b }; return Err(format!("{} is captured", lost.name)); } let evac = a.evac.is_some(); if evac { evac::check_dest(net, from, to)?; } let good = if evac { None } else { flow(a.kind, b.kind) }; let segments = if net.shortest_path(from, to).is_some() { Vec::new() } else { let segs = new_segments(net, from, to); if segs.is_empty() { return Err(format!("{}-{} is cut: repair it first", a.name, b.name)); } segs }; let track = (!segments.is_empty()).then(|| segments_cost(&segments)); if good.is_none() && !evac && track.is_none() { return Err(format!("Nothing to send from {} to {}", a.name, b.name)); } let train_cost = if evac { let (loco, cars) = evac::evac_consist(); consist_cost(loco, &cars) } else { good.map_or(0, |g| { let (loco, cars) = consist_for(g); consist_cost(loco, &cars) }) }; let total = track.unwrap_or(0) + train_cost; Ok(Plan { good, evac, track, segments, total, }) } /// Load flags for a stop that loads exactly one good. fn load_of(good: Good) -> [bool; 4] { let mut load = [false; 4]; load[good.idx()] = true; load } /// State of the pointer press in progress. #[derive(Resource, Default)] struct Drag { /// Node the press started on. from: Option, /// Cursor position at the press, in logical pixels. press: Vec2, /// True once the pointer moved past the threshold with the Inspect tool. active: bool, /// Last cursor position over the map, in world units. world: Option, } /// Floating cost label that follows the cursor during a drag. #[derive(Component)] struct DragLabel; #[derive(SystemParam)] struct GestureParams<'w, 's> { buttons: Res<'w, ButtonInput>, hover: Res<'w, MapHover>, window: Single<'w, 's, &'static Window, With>, tool: Res<'w, Tool>, net: ResMut<'w, Network>, treasury: ResMut<'w, Treasury>, drag: ResMut<'w, Drag>, commands: Commands<'w, 's>, notify: MessageWriter<'w, Notify>, sounds: MessageWriter<'w, SoundEvent>, node_clicked: MessageWriter<'w, NodeClicked>, } fn spawn_drag_label(mut commands: Commands) { commands.spawn(( DragLabel, Text2d::new(""), WorldText { size: LABEL_SIZE }, TextColor(INK), Visibility::Hidden, Transform::from_xyz(0.0, 0.0, 21.0), )); } /// Press, drag and release on the map. /// /// A press and release without movement is a plain click and sends `NodeClicked` /// on release, so selection and the B and R tools keep working. Movement with /// the Inspect tool turns it into a supply line dragged to the node under the cursor. fn drag_gesture(mut p: GestureParams) { let cursor = p.window.cursor_position(); if p.buttons.just_pressed(MouseButton::Left) { p.drag.from = p.hover.node; p.drag.press = cursor.unwrap_or_default(); p.drag.active = false; p.drag.world = None; } let inspect = matches!(*p.tool, Tool::Inspect); if p.buttons.pressed(MouseButton::Left) && p.drag.from.is_some() && inspect { if let Some(c) = cursor && (c - p.drag.press).length() > DRAG_THRESHOLD { p.drag.active = true; } if p.drag.active && let Some(w) = p.hover.world { p.drag.world = Some(w); } } if !p.buttons.just_released(MouseButton::Left) { return; } let Some(from) = p.drag.from.take() else { return; }; let active = std::mem::take(&mut p.drag.active); p.drag.world = None; if !active { p.node_clicked.write(NodeClicked(from)); return; } if let Some(to) = p.hover.node && to != from { buy_line( &mut p.net, &mut p.treasury, &mut p.commands, &mut p.notify, &mut p.sounds, from, to, ); } } /// Buys a supply line from `from` to `to`: charges, lays track if needed, buys the /// train that carries the good, and tells the player. Shared by the drag gesture and /// the [+] chip, so both behave the same. pub(crate) fn buy_line( net: &mut Network, treasury: &mut Treasury, commands: &mut Commands, notify: &mut MessageWriter, sounds: &mut MessageWriter, from: NodeId, to: NodeId, ) { let plan = match plan(net, from, to) { Ok(plan) => plan, Err(msg) => { notify.write(Notify(msg)); return; } }; if plan.total > treasury.0 { notify.write(Notify(format!("Need {}", money(plan.total)))); return; } treasury.0 -= plan.total; let a = net.nodes[from.0].name.clone(); let b = net.nodes[to.0].name.clone(); net.tracks.extend(plan.segments.iter().copied()); let message = if plan.evac { let (loco, cars) = evac::evac_consist(); commands.spawn(new_train( loco, cars, vec![ Stop { node: from, load: [false; 4], }, Stop { node: to, load: [false; 4], }, ], )); if let Some(e) = net.nodes[from.0].evac.as_mut() { e.dest = Some(to); } sounds.write(SoundEvent::TrainDeparts); format!("Evacuating {a} -> {b}") } else { match plan.good { Some(good) => { let (loco, cars) = consist_for(good); commands.spawn(new_train( loco, cars, vec![ Stop { node: from, load: load_of(good), }, Stop { node: to, load: [false; 4], }, ], )); sounds.write(SoundEvent::TrainDeparts); format!("{} line: {a} -> {b}", good.name()) } None => { sounds.write(SoundEvent::TrackLaid); format!("Laid track {a}-{b} for {}", money(plan.total)) } } }; let message = if plan.track.is_some() && plan.good.is_some() { format!("{message} (new track)") } else { message }; notify.write(Notify(message)); } /// Dashed line from the source to the cursor, ring on every node that takes the good, /// and the floating cost label. fn draw_drag( mut gizmos: Gizmos, drag: Res, net: Res, treasury: Res, hover: Res, mut labels: Query< (&mut Text2d, &mut TextColor, &mut Transform, &mut Visibility), With, >, ) { let Ok((mut text, mut color, mut transform, mut visibility)) = labels.single_mut() else { return; }; let (Some(from), true) = (drag.from, drag.active) else { *visibility = Visibility::Hidden; return; }; let source = &net.nodes[from.0]; let evacuating = source.evac.is_some(); let good = produces(source.kind); let target = hover.node.filter(|t| *t != from); for (i, node) in net.nodes.iter().enumerate() { if NodeId(i) == from { continue; } let valid = if evacuating { evac::check_dest(&net, from, NodeId(i)).is_ok() } else { good.is_none() || flow(source.kind, node.kind).is_some() }; if valid { gizmos.circle_2d(Isometry2d::from_translation(node.pos), RING_RADIUS, VALID_RING); } } let line_color = if evacuating { RED } else { good.map_or(Color::srgba(0.2, 0.15, 0.1, 0.8), good_color) }; let end = target.map(|t| net.nodes[t.0].pos).or(drag.world); let planned = target.map(|t| plan(&net, from, t)); match &planned { // New track: draw each segment, so the split at a passed node shows. Some(Ok(p)) if !p.segments.is_empty() => { for s in &p.segments { let (start, stop) = (net.nodes[s.a.0].pos, net.nodes[s.b.0].pos); dashed(&mut gizmos, start, stop, DRAG_DASH, DRAG_GAP, line_color); } } _ => { if let Some(end) = end { dashed(&mut gizmos, source.pos, end, DRAG_DASH, DRAG_GAP, line_color); } } } let Some(result) = planned else { *visibility = Visibility::Hidden; return; }; let (label, label_color) = match result { Ok(plan) if plan.total > treasury.0 => (money(plan.total), RED), Ok(plan) => (money(plan.total), GREEN), Err(msg) => (msg, RED), }; let at = drag.world.or(end).unwrap_or(source.pos) + LABEL_OFFSET; if text.0 != label { text.0 = label; } *color = TextColor(label_color); transform.translation = at.extend(21.0); *visibility = Visibility::Visible; }