forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

hud.rs1318 lines, 41.4 KiBHistoryRawDownload
1//! Military HUD: a top bar (clock, speed, one pill per front sector), a bottom
2//! strip (selected node, its supply lines, last news lines), hover tooltips and
3//! the help overlay. Nothing here blocks the map except the bars themselves.
4
5use std::collections::VecDeque;
6
7use bevy::ecs::hierarchy::ChildSpawnerCommands;
8use bevy::ecs::query::Has;
9use bevy::picking::hover::Hovered;
10use bevy::prelude::*;
11use bevy::ui::{Display, UiTransform};
12use bevy::ui_widgets::{Activate, Button};
13
14use bevy::window::PrimaryWindow;
15
16use crate::front::hourly_need;
17use crate::map::{MapHover, good_color};
18use crate::menu::Menu;
19use crate::model::{
20 CarKind, FrontState, GOODS, Good, MIN_USABLE_CONDITION, Network, NodeClicked, NodeId,
21 NodeKind, Notify, REPAIR_COST, SLOW_CONDITION, Selected, SimClock, Tool, Train, Treasury,
22 UiPassThrough, stock_text,
23};
24use crate::routes::{AddCar, AddTrain, RemoveCar, Scrap, cargo_good};
25use crate::seasons::SeasonState;
26use crate::supply::produces;
27use crate::trains::{TrainNo, train_center};
28
29const PANEL: Color = Color::srgba(0.18, 0.2, 0.14, 0.92);
30/// Opaque, so nothing of the map shows through the bottom strip.
31const STRIP: Color = Color::srgb(0.15, 0.17, 0.12);
32const CHIP: Color = Color::srgb(0.1, 0.11, 0.08);
33const PARCH: Color = Color::srgb(0.92, 0.88, 0.76);
34const AMBER: Color = Color::srgb(0.95, 0.68, 0.2);
35const ALERT: Color = Color::srgb(0.9, 0.3, 0.25);
36const DARK_RED: Color = Color::srgb(0.4, 0.12, 0.1);
37const GREEN: Color = Color::srgb(0.35, 0.62, 0.28);
38const DIM: Color = Color::srgb(0.5, 0.48, 0.42);
39const BTN: Color = Color::srgba(0.27, 0.29, 0.21, 0.95);
40const BTN_HOVER: Color = Color::srgba(0.35, 0.37, 0.27, 0.98);
41const BTN_ACTIVE: Color = Color::srgb(0.6, 0.4, 0.12);
42const BAR_BG: Color = Color::srgba(0.07, 0.08, 0.05, 0.9);
43
44pub(crate) const TOP_H: f32 = 44.0;
45pub(crate) const BOTTOM_H: f32 = 128.0;
46/// Width of the selected node card in the bottom strip.
47const CARD_W: f32 = 300.0;
48/// Preferred width of the news column; it shrinks before the window does.
49const NEWS_W: f32 = 360.0;
50const NEWS_LINES: usize = 3;
51/// Stock value that fills a bar completely.
52const BAR_FULL: f32 = 30.0;
53/// World units from a train's centre within which the cursor picks it.
54const TRAIN_PICK_RADIUS: f32 = 14.0;
55/// World units from a damaged track within which the cursor picks it.
56const TRACK_PICK_RADIUS: f32 = 8.0;
57
58/// Goods a front sector consumes every game hour, with their hourly need.
59const SUPPLIED: [Good; 3] = [Good::Ammo, Good::Food, Good::Troops];
60
61/// Icon shapes for the help overlay.
62#[derive(Clone, Copy)]
63enum Shape {
64 Round,
65 Square,
66 Diamond,
67}
68
69/// Help overlay rows: icon, its colour, and a label of one to three words.
70const HELP_ROWS: [(Shape, Color, &str); 8] = [
71 (Shape::Round, PARCH, "City or capital"),
72 (Shape::Square, PARCH, "Factory (Ammo)"),
73 (Shape::Diamond, PARCH, "Farm (Food)"),
74 (Shape::Round, ALERT, "Front: needs supply"),
75 (Shape::Square, Color::srgb(0.27, 0.51, 0.71), "Light train"),
76 (Shape::Square, Color::srgb(0.08, 0.08, 0.09), "Heavy train"),
77 (Shape::Square, ALERT, "Damaged track: click"),
78 (Shape::Square, Color::srgb(0.85, 0.6, 0.2), "Stock level"),
79];
80
81/// One start hint, shown in the news log when the game starts.
82const WELCOME_LINES: [&str; 1] = ["D1 Drag a source onto a front"];
83
84pub struct HudPlugin;
85
86impl Plugin for HudPlugin {
87 fn build(&self, app: &mut App) {
88 app.init_resource::<NewsLog>()
89 .init_resource::<HelpShown>()
90 .add_systems(Startup, (spawn_hud, welcome))
91 .add_observer(on_speed_button)
92 .add_observer(on_help_toggle)
93 .add_observer(on_front_pill)
94 .add_systems(
95 Update,
96 (
97 handle_keys,
98 handle_node_clicks,
99 collect_news,
100 update_button_visuals,
101 update_texts,
102 sync_front_pills,
103 update_front_pills,
104 update_card,
105 update_sections,
106 update_gauges,
107 update_stock_rows,
108 update_stock_bars,
109 sync_line_chips,
110 render_news,
111 update_help,
112 update_tooltip,
113 ),
114 );
115 }
116}
117
118/// Whether the help overlay is shown. H and the [?] button toggle it; starts hidden.
119#[derive(Resource, Default)]
120struct HelpShown(bool);
121
122/// Marks the help overlay.
123#[derive(Component)]
124struct HelpPanel;
125
126/// Hover tooltip box, moved to the cursor each frame.
127#[derive(Component)]
128struct TooltipRoot;
129
130#[derive(Component)]
131struct TooltipText;
132
133fn welcome(mut log: ResMut<NewsLog>) {
134 log.0.extend(WELCOME_LINES.iter().map(|s| s.to_string()));
135}
136
137/// Last `NEWS_LINES` log lines, already prefixed with the day ("D12 ...").
138#[derive(Resource, Default)]
139struct NewsLog(VecDeque<String>);
140
141#[derive(Component, Clone, Copy)]
142struct SpeedButton(u32);
143
144/// The [?] button in the top bar.
145#[derive(Component, Clone, Copy)]
146struct HelpToggle;
147
148/// Front sector pill in the top bar. Clicking it selects the front.
149#[derive(Component, Clone, Copy)]
150struct FrontPill(NodeId);
151
152/// The small square inside a front pill, coloured by the front's health.
153#[derive(Component, Clone, Copy)]
154struct FrontSquare(NodeId);
155
156/// Container of the front pills, rebuilt when the set of fronts changes.
157#[derive(Component)]
158struct FrontPillRow;
159
160/// Container of the supply line chips, rebuilt when its content changes.
161#[derive(Component)]
162struct ChipRow;
163
164/// The selected node card, and the one-line hint shown when nothing is selected.
165#[derive(Component)]
166struct CardRoot;
167
168#[derive(Component)]
169struct HintText;
170
171/// Text fields whose content is refreshed from the game state each frame.
172#[derive(Component, Clone, Copy, PartialEq, Eq)]
173enum Field {
174 Day,
175 Treasury,
176 NodeName,
177 Stock(usize),
178 Hunger,
179 FrontLine,
180 Supply,
181}
182
183/// Groups of the card shown only for matching node kinds.
184#[derive(Component, Clone, Copy, PartialEq, Eq)]
185enum Section {
186 Settlement,
187 Front,
188}
189
190/// One stock row of the card, shown only for goods the node kind makes or takes.
191#[derive(Component, Clone, Copy)]
192struct StockRow(Good);
193
194/// Fill bar for one stock good (index = `Good::idx()`).
195#[derive(Component, Clone, Copy)]
196struct StockBar(usize);
197
198/// Fill of the hunger bar of a settlement.
199#[derive(Component)]
200struct HungerFill;
201
202/// Marker on the front-line gauge, from -1 (pushed back) to +1 (right edge).
203#[derive(Component)]
204struct LineMarker;
205
206#[derive(Component)]
207struct NewsList;
208
209/// One chip of the bottom strip: the supply lines between two nodes.
210#[derive(Clone, PartialEq)]
211struct LineGroup {
212 from: NodeId,
213 to: NodeId,
214 good: Option<Good>,
215 count: usize,
216 /// One of the trains of the group; [✕] scraps it.
217 train: Entity,
218 /// Cars of that train, front to back. Shown as icons and edited in place.
219 cars: Vec<CarKind>,
220}
221
222fn label(text: &str, size: f32, color: Color) -> impl Bundle {
223 (
224 Text::new(text),
225 TextFont::from_font_size(size),
226 TextColor(color),
227 )
228}
229
230fn row(gap: f32) -> Node {
231 Node {
232 align_items: AlignItems::Center,
233 column_gap: Val::Px(gap),
234 ..default()
235 }
236}
237
238/// Mini button for the supply chips: a 24 px square.
239fn spawn_mini_button(parent: &mut ChildSpawnerCommands, text: &str, marker: impl Bundle) {
240 parent
241 .spawn((
242 Button,
243 Node {
244 width: Val::Px(24.0),
245 height: Val::Px(24.0),
246 align_items: AlignItems::Center,
247 justify_content: JustifyContent::Center,
248 flex_shrink: 0.0,
249 ..default()
250 },
251 BackgroundColor(BTN),
252 Hovered::default(),
253 marker,
254 ))
255 .with_children(|b| {
256 b.spawn(label(text, 14.0, PARCH));
257 });
258}
259
260fn spawn_button(parent: &mut ChildSpawnerCommands, text: &str, marker: impl Bundle) {
261 parent
262 .spawn((
263 Button,
264 Node {
265 height: Val::Px(26.0),
266 padding: UiRect::axes(Val::Px(10.0), Val::Px(2.0)),
267 align_items: AlignItems::Center,
268 justify_content: JustifyContent::Center,
269 ..default()
270 },
271 BackgroundColor(BTN),
272 Hovered::default(),
273 marker,
274 ))
275 .with_children(|b| {
276 b.spawn(label(text, 14.0, PARCH));
277 });
278}
279
280fn bar_color(g: Good) -> Color {
281 match g {
282 Good::Ammo => Color::srgb(0.85, 0.6, 0.2),
283 Good::Food => Color::srgb(0.5, 0.7, 0.3),
284 Good::Troops => Color::srgb(0.5, 0.6, 0.7),
285 Good::Wounded => Color::srgb(0.8, 0.3, 0.25),
286 }
287}
288
289fn spawn_hud(mut commands: Commands) {
290 // Top bar: title, clock, speed, front pills, then the help toggle.
291 commands
292 .spawn((
293 Node {
294 position_type: PositionType::Absolute,
295 top: Val::Px(0.0),
296 left: Val::Px(0.0),
297 right: Val::Px(0.0),
298 height: Val::Px(TOP_H),
299 padding: UiRect::horizontal(Val::Px(14.0)),
300 align_items: AlignItems::Center,
301 column_gap: Val::Px(16.0),
302 ..default()
303 },
304 BackgroundColor(PANEL),
305 ))
306 .with_children(|bar| {
307 bar.spawn(label("IRON LIFELINE", 16.0, AMBER));
308 bar.spawn((label("", 14.0, PARCH), Field::Day));
309 crate::seasons::spawn_badge(bar);
310 bar.spawn((label("", 14.0, PARCH), Field::Treasury));
311 bar.spawn(row(4.0)).with_children(|s| {
312 spawn_button(s, "II", SpeedButton(0));
313 spawn_button(s, "1x", SpeedButton(1));
314 spawn_button(s, "2x", SpeedButton(2));
315 spawn_button(s, "4x", SpeedButton(4));
316 });
317 bar.spawn((
318 Node {
319 flex_grow: 1.0,
320 min_width: Val::Px(0.0),
321 ..row(6.0)
322 },
323 FrontPillRow,
324 ));
325 spawn_button(bar, "?", HelpToggle);
326 });
327
328 // Bottom strip: selected node card | supply lines | news. Every child is
329 // clipped, so nothing can run past the strip or the window edge.
330 commands
331 .spawn((
332 Node {
333 position_type: PositionType::Absolute,
334 bottom: Val::Px(0.0),
335 left: Val::Px(0.0),
336 right: Val::Px(0.0),
337 height: Val::Px(BOTTOM_H),
338 padding: UiRect::all(Val::Px(8.0)),
339 column_gap: Val::Px(10.0),
340 overflow: Overflow::clip(),
341 ..default()
342 },
343 BackgroundColor(STRIP),
344 ))
345 .with_children(|s| {
346 spawn_card(s);
347
348 // Supply lines touching the selected node, or all of them, as wrapping chips.
349 s.spawn((
350 Node {
351 flex_grow: 1.0,
352 min_width: Val::Px(0.0),
353 height: Val::Percent(100.0),
354 flex_wrap: FlexWrap::Wrap,
355 align_content: AlignContent::Start,
356 align_items: AlignItems::Start,
357 column_gap: Val::Px(6.0),
358 row_gap: Val::Px(6.0),
359 overflow: Overflow::clip(),
360 ..default()
361 },
362 ChipRow,
363 ));
364
365 // Last news lines, newest on top. Lines wrap inside the column.
366 s.spawn((
367 Node {
368 flex_basis: Val::Px(NEWS_W),
369 flex_shrink: 1.0,
370 min_width: Val::Px(0.0),
371 height: Val::Percent(100.0),
372 padding: UiRect::all(Val::Px(8.0)),
373 flex_direction: FlexDirection::Column,
374 row_gap: Val::Px(3.0),
375 overflow: Overflow::clip(),
376 ..default()
377 },
378 NewsList,
379 ));
380 });
381
382 // Help overlay: icons with short labels. Top right, under the bar, never blocks the map.
383 commands
384 .spawn((
385 Node {
386 position_type: PositionType::Absolute,
387 top: Val::Px(TOP_H + 6.0),
388 right: Val::Px(8.0),
389 padding: UiRect::all(Val::Px(10.0)),
390 flex_direction: FlexDirection::Column,
391 row_gap: Val::Px(6.0),
392 display: Display::None,
393 ..default()
394 },
395 BackgroundColor(PANEL),
396 GlobalZIndex(40),
397 HelpPanel,
398 UiPassThrough,
399 ))
400 .with_children(|h| {
401 for (shape, color, text) in HELP_ROWS {
402 h.spawn(row(8.0)).with_children(|r| {
403 spawn_swatch(r, shape, color);
404 r.spawn(label(text, 13.0, PARCH));
405 });
406 }
407 });
408
409 // Hover tooltip, moved to the cursor by `update_tooltip`.
410 commands.spawn((
411 Node {
412 position_type: PositionType::Absolute,
413 display: Display::None,
414 padding: UiRect::all(Val::Px(8.0)),
415 ..default()
416 },
417 GlobalZIndex(60),
418 BackgroundColor(PANEL),
419 TooltipRoot,
420 UiPassThrough,
421 children![(label("", 13.0, PARCH), TooltipText)],
422 ));
423}
424
425/// The left part of the bottom strip: a hint, or the selected node. Compact:
426/// name and kind on one row, stock bars in a 2x2 grid, then one row for the
427/// settlement hunger or the front line gauge with its supply.
428fn spawn_card(s: &mut ChildSpawnerCommands) {
429 s.spawn(Node {
430 width: Val::Px(CARD_W),
431 flex_shrink: 0.0,
432 height: Val::Percent(100.0),
433 padding: UiRect::axes(Val::Px(10.0), Val::Px(6.0)),
434 flex_direction: FlexDirection::Column,
435 overflow: Overflow::clip(),
436 ..default()
437 })
438 .with_children(|c| {
439 c.spawn((label("Drag from a source to a front", 14.0, DIM), HintText));
440 c.spawn((
441 Node {
442 flex_direction: FlexDirection::Column,
443 row_gap: Val::Px(4.0),
444 display: Display::None,
445 ..default()
446 },
447 CardRoot,
448 ))
449 .with_children(|card| {
450 card.spawn((label("", 14.0, PARCH), Field::NodeName));
451
452 // 2x2 stock grid. A cell hides when the node does not use that good.
453 card.spawn(Node {
454 flex_direction: FlexDirection::Row,
455 flex_wrap: FlexWrap::Wrap,
456 row_gap: Val::Px(4.0),
457 ..default()
458 })
459 .with_children(|grid| {
460 for g in GOODS {
461 grid.spawn((
462 Node {
463 display: Display::None,
464 width: Val::Percent(50.0),
465 padding: UiRect::right(Val::Px(8.0)),
466 ..row(4.0)
467 },
468 StockRow(g),
469 ))
470 .with_children(|r| {
471 r.spawn((
472 label(g.name(), 12.0, PARCH),
473 Node {
474 width: Val::Px(56.0),
475 ..default()
476 },
477 ));
478 r.spawn((
479 label("", 12.0, PARCH),
480 Node {
481 width: Val::Px(24.0),
482 ..default()
483 },
484 Field::Stock(g.idx()),
485 ));
486 r.spawn((
487 Node {
488 flex_grow: 1.0,
489 min_width: Val::Px(0.0),
490 height: Val::Px(6.0),
491 ..default()
492 },
493 BackgroundColor(BAR_BG),
494 ))
495 .with_children(|bg| {
496 bg.spawn((
497 Node {
498 width: Val::Percent(0.0),
499 height: Val::Percent(100.0),
500 ..default()
501 },
502 BackgroundColor(bar_color(g)),
503 StockBar(g.idx()),
504 ));
505 });
506 });
507 }
508 });
509
510 // Settlement: hunger text and bar on one row.
511 card.spawn((row(6.0), Section::Settlement))
512 .with_children(|b| {
513 b.spawn((
514 label("", 12.0, PARCH),
515 Node {
516 width: Val::Px(84.0),
517 ..default()
518 },
519 Field::Hunger,
520 ));
521 b.spawn((
522 Node {
523 flex_grow: 1.0,
524 min_width: Val::Px(0.0),
525 height: Val::Px(5.0),
526 ..default()
527 },
528 BackgroundColor(BAR_BG),
529 ))
530 .with_children(|bg| {
531 bg.spawn((
532 Node {
533 width: Val::Percent(0.0),
534 height: Val::Percent(100.0),
535 ..default()
536 },
537 BackgroundColor(ALERT),
538 HungerFill,
539 ));
540 });
541 });
542
543 // Front: front line text, gauge and supply % on one row.
544 card.spawn((row(6.0), Section::Front)).with_children(|b| {
545 b.spawn((
546 label("", 12.0, PARCH),
547 Node {
548 width: Val::Px(84.0),
549 ..default()
550 },
551 Field::FrontLine,
552 ));
553 b.spawn((
554 Node {
555 flex_grow: 1.0,
556 min_width: Val::Px(0.0),
557 height: Val::Px(6.0),
558 ..default()
559 },
560 BackgroundColor(BAR_BG),
561 ))
562 .with_children(|bg| {
563 bg.spawn((
564 Node {
565 position_type: PositionType::Absolute,
566 left: Val::Percent(50.0),
567 top: Val::Px(-2.0),
568 width: Val::Px(4.0),
569 height: Val::Px(10.0),
570 ..default()
571 },
572 BackgroundColor(PARCH),
573 LineMarker,
574 ));
575 });
576 b.spawn((label("", 12.0, PARCH), Field::Supply));
577 });
578 });
579 });
580}
581
582/// A small icon for the help overlay: round, square or diamond.
583fn spawn_swatch(r: &mut ChildSpawnerCommands, shape: Shape, color: Color) {
584 let mut node = Node {
585 width: Val::Px(12.0),
586 height: Val::Px(12.0),
587 ..default()
588 };
589 let mut transform = UiTransform::default();
590 match shape {
591 Shape::Round => node.border_radius = BorderRadius::MAX,
592 Shape::Square => {}
593 Shape::Diamond => transform.rotation = Rot2::degrees(45.0),
594 }
595 r.spawn((node, transform, BackgroundColor(color)));
596}
597
598/// A front pill: a button with the front's name and a health square.
599fn spawn_pill(p: &mut ChildSpawnerCommands, id: NodeId, name: &str) {
600 p.spawn((
601 Button,
602 FrontPill(id),
603 Node {
604 height: Val::Px(26.0),
605 padding: UiRect::axes(Val::Px(10.0), Val::Px(2.0)),
606 align_items: AlignItems::Center,
607 column_gap: Val::Px(6.0),
608 ..default()
609 },
610 BackgroundColor(BTN),
611 Hovered::default(),
612 ))
613 .with_children(|b| {
614 b.spawn((
615 Node {
616 width: Val::Px(10.0),
617 height: Val::Px(10.0),
618 ..default()
619 },
620 BackgroundColor(GREEN),
621 FrontSquare(id),
622 ));
623 b.spawn(label(name, 14.0, PARCH));
624 });
625}
626
627/// Health colour of a front: green supplied, amber short, red starving.
628/// A front pushed back past -0.6 pulses red.
629fn front_color(front: &FrontState, blink: bool) -> Color {
630 if front.line < -0.6 {
631 return if blink { ALERT } else { DARK_RED };
632 }
633 if front.supply >= 0.7 {
634 GREEN
635 } else if front.supply >= 0.4 {
636 AMBER
637 } else {
638 ALERT
639 }
640}
641
642/// Hours of supply left in a front-line sector, as "12 h" or "4.2 days".
643fn lasts_text(hours: f32) -> String {
644 if hours < 48.0 {
645 format!("{:.0} h", hours)
646 } else {
647 format!("{:.1} days", hours / 24.0)
648 }
649}
650
651/// Formats a treasury amount, e.g. `$4,000` or `-$120`.
652fn money(v: i64) -> String {
653 let digits = v.unsigned_abs().to_string();
654 let mut out = String::new();
655 for (i, c) in digits.chars().enumerate() {
656 if i > 0 && (digits.len() - i).is_multiple_of(3) {
657 out.push(',');
658 }
659 out.push(c);
660 }
661 if v < 0 {
662 format!("-${out}")
663 } else {
664 format!("${out}")
665 }
666}
667
668/// Help hotkey. Space and 1/2/3 are handled by `economy.rs`, Esc by `menu.rs`.
669/// Nothing here runs while a menu is open.
670fn handle_keys(keys: Res<ButtonInput<KeyCode>>, menu: Res<Menu>, mut help: ResMut<HelpShown>) {
671 if menu.is_open() {
672 return;
673 }
674 if keys.just_pressed(KeyCode::KeyH) {
675 help.0 = !help.0;
676 }
677}
678
679fn on_speed_button(ev: On<Activate>, buttons: Query<&SpeedButton>, mut clock: ResMut<SimClock>) {
680 if let Ok(btn) = buttons.get(ev.entity)
681 && clock.speed != btn.0
682 {
683 clock.speed = btn.0;
684 }
685}
686
687fn on_help_toggle(
688 ev: On<Activate>,
689 toggles: Query<(), With<HelpToggle>>,
690 mut help: ResMut<HelpShown>,
691) {
692 if toggles.get(ev.entity).is_ok() {
693 help.0 = !help.0;
694 }
695}
696
697fn on_front_pill(ev: On<Activate>, pills: Query<&FrontPill>, mut selected: ResMut<Selected>) {
698 if let Ok(FrontPill(id)) = pills.get(ev.entity) {
699 selected.0 = Some(*id);
700 }
701}
702
703fn handle_node_clicks(
704 mut clicks: MessageReader<NodeClicked>,
705 tool: Res<Tool>,
706 mut selected: ResMut<Selected>,
707) {
708 for click in clicks.read() {
709 if matches!(*tool, Tool::Inspect) && selected.0 != Some(click.0) {
710 selected.0 = Some(click.0);
711 }
712 }
713}
714
715fn collect_news(mut notes: MessageReader<Notify>, clock: Res<SimClock>, mut log: ResMut<NewsLog>) {
716 let day = clock.day() + 1;
717 let fresh: Vec<String> = notes.read().map(|n| format!("D{day} {}", n.0)).collect();
718 if fresh.is_empty() {
719 return;
720 }
721 let queue = &mut log.0;
722 queue.extend(fresh);
723 while queue.len() > NEWS_LINES {
724 queue.pop_front();
725 }
726}
727
728#[allow(
729 clippy::type_complexity,
730 reason = "one-off query tuple for button colours"
731)]
732fn update_button_visuals(
733 clock: Res<SimClock>,
734 help: Res<HelpShown>,
735 mut buttons: Query<
736 (
737 &Hovered,
738 &mut BackgroundColor,
739 Option<&SpeedButton>,
740 Has<HelpToggle>,
741 ),
742 Or<(With<SpeedButton>, With<HelpToggle>, With<FrontPill>)>,
743 >,
744) {
745 for (hovered, mut bg, speed, is_help) in &mut buttons {
746 let active = match speed {
747 Some(s) => clock.speed == s.0,
748 None => is_help && help.0,
749 };
750 let target = if active {
751 BTN_ACTIVE
752 } else if hovered.get() {
753 BTN_HOVER
754 } else {
755 BTN
756 };
757 if bg.0 != target {
758 bg.0 = target;
759 }
760 }
761}
762
763fn update_texts(
764 clock: Res<SimClock>,
765 treasury: Res<Treasury>,
766 selected: Res<Selected>,
767 net: Res<Network>,
768 mut texts: Query<(&Field, &mut Text, &mut TextColor)>,
769) {
770 let node = selected.0.and_then(|id| net.nodes.get(id.0));
771 for (field, mut text, mut color) in &mut texts {
772 let (value, tint): (String, Color) = match *field {
773 Field::Day => (
774 format!("Day {} (Week {})", clock.day() + 1, clock.week() + 1),
775 PARCH,
776 ),
777 Field::Treasury => (
778 format!("Treasury {}", money(treasury.0)),
779 if treasury.0 < 0 { ALERT } else { PARCH },
780 ),
781 Field::NodeName => (
782 node.map_or(String::new(), |n| {
783 format!("{} | {}", n.name, n.kind.name())
784 }),
785 PARCH,
786 ),
787 Field::Stock(i) => (
788 node.map_or(String::new(), |n| format!("{:.0}", n.stock[i])),
789 PARCH,
790 ),
791 Field::Hunger => match node {
792 Some(n) if is_settlement(n.kind) => (
793 format!("Hunger {}%", (n.hunger * 100.0).round() as i32),
794 if n.hunger > 0.5 { ALERT } else { PARCH },
795 ),
796 _ => (String::new(), PARCH),
797 },
798 Field::FrontLine => (
799 node.and_then(|n| n.front.as_ref())
800 .map_or(String::new(), |f| format!("Front {:+.2}", f.line)),
801 PARCH,
802 ),
803 Field::Supply => (
804 node.and_then(|n| n.front.as_ref())
805 .map_or(String::new(), |f| {
806 format!("Supply {}%", (f.supply * 100.0).round() as i32)
807 }),
808 PARCH,
809 ),
810 };
811 if text.0 != value {
812 text.0 = value;
813 }
814 if color.0 != tint {
815 color.0 = tint;
816 }
817 }
818}
819
820fn is_settlement(kind: NodeKind) -> bool {
821 matches!(kind, NodeKind::Capital | NodeKind::City)
822}
823
824/// Rebuilds the front pills when the set of fronts changes.
825fn sync_front_pills(
826 mut commands: Commands,
827 net: Res<Network>,
828 rows: Query<Entity, With<FrontPillRow>>,
829 mut shown: Local<Option<Vec<NodeId>>>,
830) {
831 let fronts: Vec<NodeId> = net
832 .nodes
833 .iter()
834 .enumerate()
835 .filter(|(_, n)| n.kind == NodeKind::Front)
836 .map(|(i, _)| NodeId(i))
837 .collect();
838 if shown.as_ref() == Some(&fronts) {
839 return;
840 }
841 let Ok(row) = rows.single() else {
842 return;
843 };
844 commands
845 .entity(row)
846 .despawn_related::<Children>()
847 .with_children(|p| {
848 for id in &fronts {
849 spawn_pill(p, *id, &net.nodes[id.0].name);
850 }
851 });
852 *shown = Some(fronts);
853}
854
855/// Colours the health square of each front pill. The red pulse alternates each frame.
856fn update_front_pills(
857 time: Res<Time>,
858 net: Res<Network>,
859 mut squares: Query<(&FrontSquare, &mut BackgroundColor)>,
860) {
861 let blink = (time.elapsed_secs() * 6.0).sin() > 0.0;
862 for (square, mut bg) in &mut squares {
863 let color = net
864 .nodes
865 .get(square.0.0)
866 .and_then(|n| n.front.as_ref())
867 .map_or(DIM, |f| front_color(f, blink));
868 if bg.0 != color {
869 bg.0 = color;
870 }
871 }
872}
873
874/// Shows the card for the selected node, or the hint when nothing is selected.
875#[allow(clippy::type_complexity, reason = "one-off query for card and hint")]
876fn update_card(
877 selected: Res<Selected>,
878 mut cards: Query<(&mut Node, Has<CardRoot>), Or<(With<CardRoot>, With<HintText>)>>,
879) {
880 let has = selected.0.is_some();
881 for (mut node, is_card) in &mut cards {
882 let shown = if is_card { has } else { !has };
883 let target = if shown { Display::Flex } else { Display::None };
884 if node.display != target {
885 node.display = target;
886 }
887 }
888}
889
890fn update_sections(
891 selected: Res<Selected>,
892 net: Res<Network>,
893 mut sections: Query<(&Section, &mut Node)>,
894) {
895 let kind = selected
896 .0
897 .and_then(|id| net.nodes.get(id.0))
898 .map(|n| n.kind);
899 for (section, mut node) in &mut sections {
900 let shown = match (section, kind) {
901 (Section::Settlement, Some(k)) => is_settlement(k),
902 (Section::Front, Some(k)) => k == NodeKind::Front,
903 _ => false,
904 };
905 let target = if shown { Display::Flex } else { Display::None };
906 if node.display != target {
907 node.display = target;
908 }
909 }
910}
911
912/// Shows a stock row only when the selected node makes or takes that good.
913fn update_stock_rows(
914 selected: Res<Selected>,
915 net: Res<Network>,
916 mut rows: Query<(&StockRow, &mut Node)>,
917) {
918 let node = selected.0.and_then(|id| net.nodes.get(id.0));
919 for (StockRow(good), mut ui) in &mut rows {
920 let relevant =
921 node.is_some_and(|n| n.kind.accepts(*good) || produces(n.kind) == Some(*good));
922 let target = if relevant {
923 Display::Flex
924 } else {
925 Display::None
926 };
927 if ui.display != target {
928 ui.display = target;
929 }
930 }
931}
932
933/// Fills the hunger bar of a settlement and moves the front-line marker.
934fn update_gauges(
935 selected: Res<Selected>,
936 net: Res<Network>,
937 mut gauges: Query<(&mut Node, Has<HungerFill>, Has<LineMarker>)>,
938) {
939 let node = selected.0.and_then(|id| net.nodes.get(id.0));
940 for (mut ui, is_hunger, is_line) in &mut gauges {
941 if is_hunger {
942 let fill = node
943 .filter(|n| is_settlement(n.kind))
944 .map_or(0.0, |n| (n.hunger * 100.0).clamp(0.0, 100.0));
945 let target = Val::Percent(fill);
946 if ui.width != target {
947 ui.width = target;
948 }
949 }
950 if is_line {
951 let at = node
952 .and_then(|n| n.front.as_ref())
953 .map_or(50.0, |f| ((f.line + 1.0) / 2.0 * 100.0).clamp(0.0, 100.0));
954 let target = Val::Percent(at);
955 if ui.left != target {
956 ui.left = target;
957 }
958 }
959 }
960}
961
962fn update_stock_bars(
963 selected: Res<Selected>,
964 net: Res<Network>,
965 mut bars: Query<(&StockBar, &mut Node)>,
966) {
967 let node = selected.0.and_then(|id| net.nodes.get(id.0));
968 for (bar, mut ui) in &mut bars {
969 let fill = node.map_or(0.0, |n| {
970 (n.stock[bar.0] / BAR_FULL * 100.0).clamp(0.0, 100.0)
971 });
972 let target = Val::Percent(fill);
973 if ui.width != target {
974 ui.width = target;
975 }
976 }
977}
978
979/// Rebuilds the supply line chips when the lines shown change. Shows the lines
980/// that touch the selected node, or all lines when nothing is selected.
981fn sync_line_chips(
982 mut commands: Commands,
983 net: Res<Network>,
984 selected: Res<Selected>,
985 trains: Query<(Entity, &Train)>,
986 rows: Query<Entity, With<ChipRow>>,
987 mut shown: Local<Option<Vec<LineGroup>>>,
988) {
989 let mut groups: Vec<LineGroup> = Vec::new();
990 for (entity, train) in &trains {
991 let (Some(first), Some(last)) = (train.route.first(), train.route.last()) else {
992 continue;
993 };
994 let (from, to) = (first.node, last.node);
995 if selected.0.is_some_and(|id| id != from && id != to) {
996 continue;
997 }
998 match groups.iter_mut().find(|g| g.from == from && g.to == to) {
999 Some(g) => g.count += 1,
1000 None => groups.push(LineGroup {
1001 from,
1002 to,
1003 good: cargo_good(train),
1004 count: 1,
1005 train: entity,
1006 cars: train.cars.clone(),
1007 }),
1008 }
1009 }
1010 groups.sort_by_key(|g| (g.from.0, g.to.0));
1011
1012 if shown.as_ref() == Some(&groups) {
1013 return;
1014 }
1015 let Ok(row) = rows.single() else {
1016 return;
1017 };
1018 commands
1019 .entity(row)
1020 .despawn_related::<Children>()
1021 .with_children(|p| {
1022 if groups.is_empty() {
1023 let text = if selected.0.is_some() {
1024 "No supply lines here"
1025 } else {
1026 "No supply lines yet"
1027 };
1028 p.spawn(label(text, 14.0, DIM));
1029 }
1030 for g in &groups {
1031 spawn_chip(p, g, &net);
1032 }
1033 });
1034 *shown = Some(groups);
1035}
1036
1037/// Colour of a car icon: its good's colour, or grey for a flat car.
1038fn car_color(car: CarKind) -> Color {
1039 car.good()
1040 .map_or(Color::srgb(0.55, 0.53, 0.50), good_color)
1041}
1042
1043/// One chip: good dot, "From > To", train count, [+] and [✕], then the consist of
1044/// the line's first train: a coloured icon per car (click to remove it), and a
1045/// coloured button per car type (click to add one).
1046fn spawn_chip(p: &mut ChildSpawnerCommands, g: &LineGroup, net: &Network) {
1047 let name = |id: NodeId| net.nodes.get(id.0).map_or("?", |n| n.name.as_str());
1048 p.spawn((
1049 Node {
1050 height: Val::Px(32.0),
1051 flex_shrink: 0.0,
1052 align_items: AlignItems::Center,
1053 column_gap: Val::Px(5.0),
1054 padding: UiRect::horizontal(Val::Px(6.0)),
1055 ..default()
1056 },
1057 BackgroundColor(CHIP),
1058 ))
1059 .with_children(|c| {
1060 c.spawn((
1061 Node {
1062 width: Val::Px(8.0),
1063 height: Val::Px(8.0),
1064 ..default()
1065 },
1066 BackgroundColor(g.good.map_or(DIM, bar_color)),
1067 ));
1068 c.spawn(label(
1069 &format!("{} > {}", name(g.from), name(g.to)),
1070 13.0,
1071 PARCH,
1072 ));
1073 c.spawn(label(&format!("x{}", g.count), 13.0, AMBER));
1074 spawn_mini_button(
1075 c,
1076 "+",
1077 AddTrain {
1078 from: g.from,
1079 to: g.to,
1080 },
1081 );
1082 spawn_mini_button(c, "x", Scrap(g.train));
1083 for (index, car) in g.cars.iter().enumerate() {
1084 c.spawn((
1085 Button,
1086 Node {
1087 width: Val::Px(10.0),
1088 height: Val::Px(14.0),
1089 flex_shrink: 0.0,
1090 ..default()
1091 },
1092 BackgroundColor(car_color(*car)),
1093 RemoveCar {
1094 entity: g.train,
1095 index,
1096 },
1097 ));
1098 }
1099 for car in CarKind::ALL {
1100 c.spawn((
1101 Button,
1102 Node {
1103 width: Val::Px(12.0),
1104 height: Val::Px(12.0),
1105 flex_shrink: 0.0,
1106 ..default()
1107 },
1108 BackgroundColor(car_color(car)),
1109 AddCar {
1110 entity: g.train,
1111 car,
1112 },
1113 ));
1114 }
1115 });
1116}
1117
1118/// Rebuilds the news list when the log changes. Older lines fade out.
1119fn render_news(log: Res<NewsLog>, lists: Query<Entity, With<NewsList>>, mut commands: Commands) {
1120 if !log.is_changed() {
1121 return;
1122 }
1123 let Ok(list) = lists.single() else {
1124 return;
1125 };
1126 commands
1127 .entity(list)
1128 .despawn_related::<Children>()
1129 .with_children(|p| {
1130 // Long entries wrap inside the column; the column clips what does not fit.
1131 for (age, line) in log.0.iter().rev().take(NEWS_LINES).enumerate() {
1132 let alpha = (1.0 - 0.3 * age as f32).max(0.35);
1133 p.spawn((
1134 label(line, 13.0, Color::srgba(0.92, 0.88, 0.76, alpha)),
1135 ));
1136 }
1137 });
1138}
1139
1140/// Shows or hides the help overlay to match `HelpShown`.
1141fn update_help(help: Res<HelpShown>, mut panels: Query<&mut Node, With<HelpPanel>>) {
1142 let target = if help.0 { Display::Flex } else { Display::None };
1143 for mut node in &mut panels {
1144 if node.display != target {
1145 node.display = target;
1146 }
1147 }
1148}
1149
1150/// Keeps the tooltip at the cursor, describing the node, train or track under it.
1151#[allow(clippy::too_many_arguments, reason = "bevy system parameters")]
1152fn update_tooltip(
1153 hover: Res<MapHover>,
1154 net: Res<Network>,
1155 windows: Query<&Window, With<PrimaryWindow>>,
1156 trains: Query<(&Train, &TrainNo)>,
1157 routes: Query<&Train>,
1158 season: Res<SeasonState>,
1159 mut roots: Query<&mut Node, With<TooltipRoot>>,
1160 mut texts: Query<&mut Text, With<TooltipText>>,
1161) {
1162 let (Ok(mut root), Ok(mut text)) = (roots.single_mut(), texts.single_mut()) else {
1163 return;
1164 };
1165 let cursor = windows.single().ok().and_then(|w| w.cursor_position());
1166 let route_refs: Vec<&Train> = routes.iter().collect();
1167 let content = match (hover.node, hover.world) {
1168 (Some(id), _) => node_tip(&net, &route_refs, id, season.season.food_mult()),
1169 (None, Some(world)) => train_tip(&net, world, hover.zoom, &trains)
1170 .or_else(|| track_tip(&net, world, hover.zoom)),
1171 (None, None) => None,
1172 };
1173 match (content, cursor) {
1174 (Some(s), Some(c)) => {
1175 if text.0 != s {
1176 text.0 = s;
1177 }
1178 root.display = Display::Flex;
1179 root.left = Val::Px(c.x + 16.0);
1180 root.top = Val::Px(c.y + 16.0);
1181 }
1182 _ => root.display = Display::None,
1183 }
1184}
1185
1186/// Tooltip lines for a node: name and kind, what it makes, stock. A front adds its status.
1187fn node_tip(net: &Network, trains: &[&Train], id: NodeId, food_mult: f32) -> Option<String> {
1188 let n = net.nodes.get(id.0)?;
1189 let mut text = format!("{} ({})", n.name, n.kind.name());
1190 if n.kind.makes_text() != "nothing" {
1191 text.push_str(&format!("\nMakes {}", n.kind.makes_text()));
1192 }
1193 text.push_str(&format!("\nStock: {}", stock_text(&n.stock)));
1194 if n.kind == NodeKind::Front {
1195 text.push('\n');
1196 text.push_str(&front_problem(net, trains, id, food_mult));
1197 }
1198 Some(text)
1199}
1200
1201/// One-line reason a front is short, highest priority first: rail, delivery, then goods.
1202fn front_problem(net: &Network, trains: &[&Train], id: NodeId, food_mult: f32) -> String {
1203 let capital = net
1204 .nodes
1205 .iter()
1206 .position(|n| n.kind == NodeKind::Capital)
1207 .map(NodeId);
1208 let connected = capital.is_some_and(|c| net.shortest_path(c, id).is_some());
1209 if !connected {
1210 let cut = net
1211 .tracks
1212 .iter()
1213 .any(|t| (t.a == id || t.b == id) && t.condition < MIN_USABLE_CONDITION);
1214 return if cut {
1215 "Rail cut: repair the track"
1216 } else {
1217 "No rail: drag to lay track"
1218 }
1219 .to_string();
1220 }
1221 if !trains.iter().any(|t| t.route.iter().any(|s| s.node == id)) {
1222 return "No train delivers here".to_string();
1223 }
1224 let node = &net.nodes[id.0];
1225 let mut short: Vec<&str> = Vec::new();
1226 let mut lowest: Option<(f32, &str)> = None;
1227 for good in SUPPLIED {
1228 let hours = node.stock[good.idx()].max(0.0) / hourly_need(good, food_mult);
1229 if hours < 1.0 {
1230 short.push(good.name());
1231 }
1232 if lowest.is_none_or(|(h, _)| hours < h) {
1233 lowest = Some((hours, good.name()));
1234 }
1235 }
1236 match lowest {
1237 Some((hours, _)) if !short.is_empty() => {
1238 format!("Short: {} ({} left)", short.join(", "), lasts_text(hours))
1239 }
1240 _ => "Well supplied".to_string(),
1241 }
1242}
1243
1244/// Tooltip lines for the train nearest the cursor, if one is close enough.
1245fn train_tip(
1246 net: &Network,
1247 world: Vec2,
1248 zoom: f32,
1249 trains: &Query<(&Train, &TrainNo)>,
1250) -> Option<String> {
1251 let (train, no) = trains
1252 .iter()
1253 .map(|(t, no)| (train_center(net, t).distance(world), t, no))
1254 .filter(|(d, _, _)| *d <= TRAIN_PICK_RADIUS * zoom)
1255 .min_by(|a, b| a.0.total_cmp(&b.0))
1256 .map(|(_, t, no)| (t, no))?;
1257
1258 let carried: Vec<String> = GOODS
1259 .iter()
1260 .filter(|g| train.cargo[g.idx()] >= 0.5)
1261 .map(|g| format!("{} {:.0}", g.name(), train.cargo[g.idx()]))
1262 .collect();
1263 let cargo = if carried.is_empty() {
1264 "empty".to_string()
1265 } else {
1266 carried.join(", ")
1267 };
1268 let dest = train
1269 .route
1270 .get(train.stop_idx)
1271 .and_then(|s| net.nodes.get(s.node.0))
1272 .map_or("-", |n| n.name.as_str());
1273 let mut lines = vec![format!(
1274 "{} train #{}: {} to {}",
1275 train.loco.name(),
1276 no.0,
1277 cargo,
1278 dest
1279 )];
1280 if train.stalled {
1281 lines.push("Stalled: no track".to_string());
1282 } else if let Some(next) = train.path.first()
1283 && let Some(i) = net.track_between(train.at, *next)
1284 && net.tracks[i].condition < SLOW_CONDITION
1285 {
1286 lines.push("Slowed: damaged track".to_string());
1287 }
1288 Some(lines.join("\n"))
1289}
1290
1291/// Distance from a point to a straight track segment.
1292fn segment_distance(p: Vec2, a: Vec2, b: Vec2) -> f32 {
1293 let ab = b - a;
1294 let t = ((p - a).dot(ab) / ab.length_squared().max(f32::EPSILON)).clamp(0.0, 1.0);
1295 p.distance(a + ab * t)
1296}
1297
1298/// Tooltip for the damaged track nearest the cursor: its state and the repair price.
1299fn track_tip(net: &Network, world: Vec2, zoom: f32) -> Option<String> {
1300 let track = net
1301 .tracks
1302 .iter()
1303 .filter(|t| t.condition < 1.0)
1304 .map(|t| {
1305 let d = segment_distance(world, net.nodes[t.a.0].pos, net.nodes[t.b.0].pos);
1306 (d, t)
1307 })
1308 .filter(|(d, _)| *d <= TRACK_PICK_RADIUS * zoom)
1309 .min_by(|a, b| a.0.total_cmp(&b.0))
1310 .map(|(_, t)| t)?;
1311 let mut text = format!("Damaged track\nRepair ${REPAIR_COST}");
1312 if track.condition < MIN_USABLE_CONDITION {
1313 text.push_str("\nBlocked");
1314 } else if track.condition < SLOW_CONDITION {
1315 text.push_str("\nSlow");
1316 }
1317 Some(text)
1318}