forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

supply.rs424 lines, 13.1 KiBHistoryRawDownload
1//! The drag gesture: left-drag from one node to another to run a supply line.
2//!
3//! The source sends the good it makes; the target must accept it. A straight
4//! track is laid when no usable rail path exists, and a train that carries the
5//! good is bought. Dragging the same pair again adds another train.
6
7use bevy::ecs::system::SystemParam;
8use bevy::prelude::*;
9use bevy::window::PrimaryWindow;
10
11use crate::audio::SoundEvent;
12use crate::build::{new_segments, segments_cost};
13use crate::evac;
14use crate::map::{MapHover, WorldText, dashed, good_color, picking};
15use crate::model::{
16 CarKind, Good, LocoKind, Network, NodeClicked, NodeId, NodeKind, Notify, Stop, Tool,
17 TrackSeg, Treasury, consist_cost,
18};
19use crate::trains::new_train;
20
21pub struct SupplyPlugin;
22
23impl Plugin for SupplyPlugin {
24 fn build(&self, app: &mut App) {
25 app.init_resource::<Drag>()
26 .add_systems(Startup, spawn_drag_label)
27 .add_systems(Update, (drag_gesture, draw_drag).chain().after(picking));
28 }
29}
30
31/// Pointer movement in logical pixels that turns a press into a drag.
32const DRAG_THRESHOLD: f32 = 6.0;
33/// Glyph size of the floating cost label, in world units (see `map::WorldText`).
34const LABEL_SIZE: f32 = 27.0;
35/// Offset of the floating label from the cursor.
36const LABEL_OFFSET: Vec2 = Vec2::new(14.0, 14.0);
37const DRAG_DASH: f32 = 12.0;
38const DRAG_GAP: f32 = 8.0;
39const RING_RADIUS: f32 = 24.0;
40
41const INK: Color = Color::srgb(0.22, 0.15, 0.09);
42const GREEN: Color = Color::srgb(0.1, 0.5, 0.1);
43const RED: Color = Color::srgb(0.8, 0.1, 0.1);
44const VALID_RING: Color = Color::srgb(1.0, 0.92, 0.45);
45
46/// The good a node sends out, if any. Depots only store.
47pub fn produces(kind: NodeKind) -> Option<Good> {
48 match kind {
49 NodeKind::Factory => Some(Good::Ammo),
50 NodeKind::Farm => Some(Good::Food),
51 NodeKind::Capital | NodeKind::City => Some(Good::Troops),
52 NodeKind::Front => Some(Good::Wounded),
53 NodeKind::Depot => None,
54 }
55}
56
57/// The good a drag from a `from` node to a `to` node sends, if `to` takes it.
58pub fn flow(from: NodeKind, to: NodeKind) -> Option<Good> {
59 let good = produces(from)?;
60 match good {
61 // Wounded only go home: to a Capital or City, never to a Depot.
62 Good::Wounded => matches!(to, NodeKind::Capital | NodeKind::City).then_some(good),
63 _ => to.accepts(good).then_some(good),
64 }
65}
66
67/// The default consist that carries a good: a locomotive and its cars.
68pub fn consist_for(good: Good) -> (LocoKind, Vec<CarKind>) {
69 match good {
70 Good::Ammo => (LocoKind::Heavy, vec![CarKind::Ammo; 4]),
71 Good::Food => (LocoKind::Light, vec![CarKind::Food; 2]),
72 Good::Troops => (LocoKind::Light, vec![CarKind::Troop; 2]),
73 Good::Wounded => (LocoKind::Light, vec![CarKind::Hospital; 3]),
74 }
75}
76
77/// Whole dollars with thousands separators: "$1,840".
78pub fn money(v: i64) -> String {
79 let digits = v.unsigned_abs().to_string();
80 let mut out = String::new();
81 for (i, c) in digits.chars().enumerate() {
82 if i > 0 && (digits.len() - i).is_multiple_of(3) {
83 out.push(',');
84 }
85 out.push(c);
86 }
87 if v < 0 {
88 format!("-${out}")
89 } else {
90 format!("${out}")
91 }
92}
93
94/// What a drag from one node to another would do and cost.
95#[derive(Debug, Clone, PartialEq)]
96pub struct Plan {
97 /// Good carried by the new train, if any.
98 pub good: Option<Good>,
99 /// True when the train carries evacuation crates from an evacuating site.
100 pub evac: bool,
101 /// Cost of the new track segments, if no usable rail path exists.
102 pub track: Option<i64>,
103 /// The new segments to lay, split at any node the straight line passes.
104 pub segments: Vec<TrackSeg>,
105 /// Total cost: track plus train.
106 pub total: i64,
107}
108
109/// Works out the plan for a drag, or the reason it cannot be done.
110pub fn plan(net: &Network, from: NodeId, to: NodeId) -> Result<Plan, String> {
111 let a = &net.nodes[from.0];
112 let b = &net.nodes[to.0];
113 if from == to {
114 return Err(format!("Drag from {} to another node", a.name));
115 }
116 if a.captured || b.captured {
117 let lost = if a.captured { a } else { b };
118 return Err(format!("{} is captured", lost.name));
119 }
120 let evac = a.evac.is_some();
121 if evac {
122 evac::check_dest(net, from, to)?;
123 }
124 let good = if evac { None } else { flow(a.kind, b.kind) };
125 let segments = if net.shortest_path(from, to).is_some() {
126 Vec::new()
127 } else {
128 let segs = new_segments(net, from, to);
129 if segs.is_empty() {
130 return Err(format!("{}-{} is cut: repair it first", a.name, b.name));
131 }
132 segs
133 };
134 let track = (!segments.is_empty()).then(|| segments_cost(&segments));
135 if good.is_none() && !evac && track.is_none() {
136 return Err(format!("Nothing to send from {} to {}", a.name, b.name));
137 }
138 let train_cost = if evac {
139 let (loco, cars) = evac::evac_consist();
140 consist_cost(loco, &cars)
141 } else {
142 good.map_or(0, |g| {
143 let (loco, cars) = consist_for(g);
144 consist_cost(loco, &cars)
145 })
146 };
147 let total = track.unwrap_or(0) + train_cost;
148 Ok(Plan {
149 good,
150 evac,
151 track,
152 segments,
153 total,
154 })
155}
156
157/// Load flags for a stop that loads exactly one good.
158fn load_of(good: Good) -> [bool; 4] {
159 let mut load = [false; 4];
160 load[good.idx()] = true;
161 load
162}
163
164/// State of the pointer press in progress.
165#[derive(Resource, Default)]
166struct Drag {
167 /// Node the press started on.
168 from: Option<NodeId>,
169 /// Cursor position at the press, in logical pixels.
170 press: Vec2,
171 /// True once the pointer moved past the threshold with the Inspect tool.
172 active: bool,
173 /// Last cursor position over the map, in world units.
174 world: Option<Vec2>,
175}
176
177/// Floating cost label that follows the cursor during a drag.
178#[derive(Component)]
179struct DragLabel;
180
181#[derive(SystemParam)]
182struct GestureParams<'w, 's> {
183 buttons: Res<'w, ButtonInput<MouseButton>>,
184 hover: Res<'w, MapHover>,
185 window: Single<'w, 's, &'static Window, With<PrimaryWindow>>,
186 tool: Res<'w, Tool>,
187 net: ResMut<'w, Network>,
188 treasury: ResMut<'w, Treasury>,
189 drag: ResMut<'w, Drag>,
190 commands: Commands<'w, 's>,
191 notify: MessageWriter<'w, Notify>,
192 sounds: MessageWriter<'w, SoundEvent>,
193 node_clicked: MessageWriter<'w, NodeClicked>,
194}
195
196fn spawn_drag_label(mut commands: Commands) {
197 commands.spawn((
198 DragLabel,
199 Text2d::new(""),
200 WorldText { size: LABEL_SIZE },
201 TextColor(INK),
202 Visibility::Hidden,
203 Transform::from_xyz(0.0, 0.0, 21.0),
204 ));
205}
206
207/// Press, drag and release on the map.
208///
209/// A press and release without movement is a plain click and sends `NodeClicked`
210/// on release, so selection and the B and R tools keep working. Movement with
211/// the Inspect tool turns it into a supply line dragged to the node under the cursor.
212fn drag_gesture(mut p: GestureParams) {
213 let cursor = p.window.cursor_position();
214 if p.buttons.just_pressed(MouseButton::Left) {
215 p.drag.from = p.hover.node;
216 p.drag.press = cursor.unwrap_or_default();
217 p.drag.active = false;
218 p.drag.world = None;
219 }
220
221 let inspect = matches!(*p.tool, Tool::Inspect);
222 if p.buttons.pressed(MouseButton::Left) && p.drag.from.is_some() && inspect {
223 if let Some(c) = cursor
224 && (c - p.drag.press).length() > DRAG_THRESHOLD
225 {
226 p.drag.active = true;
227 }
228 if p.drag.active
229 && let Some(w) = p.hover.world
230 {
231 p.drag.world = Some(w);
232 }
233 }
234
235 if !p.buttons.just_released(MouseButton::Left) {
236 return;
237 }
238 let Some(from) = p.drag.from.take() else {
239 return;
240 };
241 let active = std::mem::take(&mut p.drag.active);
242 p.drag.world = None;
243 if !active {
244 p.node_clicked.write(NodeClicked(from));
245 return;
246 }
247 if let Some(to) = p.hover.node
248 && to != from
249 {
250 buy_line(
251 &mut p.net,
252 &mut p.treasury,
253 &mut p.commands,
254 &mut p.notify,
255 &mut p.sounds,
256 from,
257 to,
258 );
259 }
260}
261
262/// Buys a supply line from `from` to `to`: charges, lays track if needed, buys the
263/// train that carries the good, and tells the player. Shared by the drag gesture and
264/// the [+] chip, so both behave the same.
265pub(crate) fn buy_line(
266 net: &mut Network,
267 treasury: &mut Treasury,
268 commands: &mut Commands,
269 notify: &mut MessageWriter<Notify>,
270 sounds: &mut MessageWriter<SoundEvent>,
271 from: NodeId,
272 to: NodeId,
273) {
274 let plan = match plan(net, from, to) {
275 Ok(plan) => plan,
276 Err(msg) => {
277 notify.write(Notify(msg));
278 return;
279 }
280 };
281 if plan.total > treasury.0 {
282 notify.write(Notify(format!("Need {}", money(plan.total))));
283 return;
284 }
285 treasury.0 -= plan.total;
286
287 let a = net.nodes[from.0].name.clone();
288 let b = net.nodes[to.0].name.clone();
289 net.tracks.extend(plan.segments.iter().copied());
290
291 let message = if plan.evac {
292 let (loco, cars) = evac::evac_consist();
293 commands.spawn(new_train(
294 loco,
295 cars,
296 vec![
297 Stop {
298 node: from,
299 load: [false; 4],
300 },
301 Stop {
302 node: to,
303 load: [false; 4],
304 },
305 ],
306 ));
307 if let Some(e) = net.nodes[from.0].evac.as_mut() {
308 e.dest = Some(to);
309 }
310 sounds.write(SoundEvent::TrainDeparts);
311 format!("Evacuating {a} -> {b}")
312 } else {
313 match plan.good {
314 Some(good) => {
315 let (loco, cars) = consist_for(good);
316 commands.spawn(new_train(
317 loco,
318 cars,
319 vec![
320 Stop {
321 node: from,
322 load: load_of(good),
323 },
324 Stop {
325 node: to,
326 load: [false; 4],
327 },
328 ],
329 ));
330 sounds.write(SoundEvent::TrainDeparts);
331 format!("{} line: {a} -> {b}", good.name())
332 }
333 None => {
334 sounds.write(SoundEvent::TrackLaid);
335 format!("Laid track {a}-{b} for {}", money(plan.total))
336 }
337 }
338 };
339 let message = if plan.track.is_some() && plan.good.is_some() {
340 format!("{message} (new track)")
341 } else {
342 message
343 };
344 notify.write(Notify(message));
345}
346
347/// Dashed line from the source to the cursor, ring on every node that takes the good,
348/// and the floating cost label.
349fn draw_drag(
350 mut gizmos: Gizmos,
351 drag: Res<Drag>,
352 net: Res<Network>,
353 treasury: Res<Treasury>,
354 hover: Res<MapHover>,
355 mut labels: Query<
356 (&mut Text2d, &mut TextColor, &mut Transform, &mut Visibility),
357 With<DragLabel>,
358 >,
359) {
360 let Ok((mut text, mut color, mut transform, mut visibility)) = labels.single_mut() else {
361 return;
362 };
363 let (Some(from), true) = (drag.from, drag.active) else {
364 *visibility = Visibility::Hidden;
365 return;
366 };
367 let source = &net.nodes[from.0];
368 let evacuating = source.evac.is_some();
369 let good = produces(source.kind);
370 let target = hover.node.filter(|t| *t != from);
371
372 for (i, node) in net.nodes.iter().enumerate() {
373 if NodeId(i) == from {
374 continue;
375 }
376 let valid = if evacuating {
377 evac::check_dest(&net, from, NodeId(i)).is_ok()
378 } else {
379 good.is_none() || flow(source.kind, node.kind).is_some()
380 };
381 if valid {
382 gizmos.circle_2d(Isometry2d::from_translation(node.pos), RING_RADIUS, VALID_RING);
383 }
384 }
385
386 let line_color = if evacuating {
387 RED
388 } else {
389 good.map_or(Color::srgba(0.2, 0.15, 0.1, 0.8), good_color)
390 };
391 let end = target.map(|t| net.nodes[t.0].pos).or(drag.world);
392 let planned = target.map(|t| plan(&net, from, t));
393 match &planned {
394 // New track: draw each segment, so the split at a passed node shows.
395 Some(Ok(p)) if !p.segments.is_empty() => {
396 for s in &p.segments {
397 let (start, stop) = (net.nodes[s.a.0].pos, net.nodes[s.b.0].pos);
398 dashed(&mut gizmos, start, stop, DRAG_DASH, DRAG_GAP, line_color);
399 }
400 }
401 _ => {
402 if let Some(end) = end {
403 dashed(&mut gizmos, source.pos, end, DRAG_DASH, DRAG_GAP, line_color);
404 }
405 }
406 }
407
408 let Some(result) = planned else {
409 *visibility = Visibility::Hidden;
410 return;
411 };
412 let (label, label_color) = match result {
413 Ok(plan) if plan.total > treasury.0 => (money(plan.total), RED),
414 Ok(plan) => (money(plan.total), GREEN),
415 Err(msg) => (msg, RED),
416 };
417 let at = drag.world.or(end).unwrap_or(source.pos) + LABEL_OFFSET;
418 if text.0 != label {
419 text.0 = label;
420 }
421 *color = TextColor(label_color);
422 transform.translation = at.extend(21.0);
423 *visibility = Visibility::Visible;
424}