forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

model.rs620 lines, 17.0 KiBHistoryRawDownload
1//! Shared types for Iron Lifeline. Every other module builds on these.
2
3use bevy::prelude::{Component, Message, Resource, Vec2};
4
5/// Marks a UI node (and its descendants) that never blocks map clicks, such as tooltips.
6#[derive(Component, Default, Clone, Copy)]
7pub struct UiPassThrough;
8
9/// Index into `Network::nodes`.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub struct NodeId(pub usize);
12
13/// Goods moved over the network. Index order matches `Node::stock`.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Good {
16 Ammo,
17 Food,
18 Troops,
19 Wounded,
20}
21
22pub const GOODS: [Good; 4] = [Good::Ammo, Good::Food, Good::Troops, Good::Wounded];
23
24impl Good {
25 pub fn idx(self) -> usize {
26 match self {
27 Good::Ammo => 0,
28 Good::Food => 1,
29 Good::Troops => 2,
30 Good::Wounded => 3,
31 }
32 }
33
34 pub fn name(self) -> &'static str {
35 match self {
36 Good::Ammo => "Ammo",
37 Good::Food => "Food",
38 Good::Troops => "Troops",
39 Good::Wounded => "Wounded",
40 }
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub enum NodeKind {
46 Capital,
47 City,
48 Factory,
49 Farm,
50 Depot,
51 Front,
52}
53
54impl NodeKind {
55 pub fn name(self) -> &'static str {
56 match self {
57 NodeKind::Capital => "Capital",
58 NodeKind::City => "City",
59 NodeKind::Factory => "Factory",
60 NodeKind::Farm => "Farm",
61 NodeKind::Depot => "Depot",
62 NodeKind::Front => "Front",
63 }
64 }
65
66 pub fn accepts(self, g: Good) -> bool {
67 match self {
68 NodeKind::Front => matches!(g, Good::Ammo | Good::Food | Good::Troops),
69 NodeKind::Capital | NodeKind::City => matches!(g, Good::Food | Good::Wounded),
70 NodeKind::Depot => true,
71 NodeKind::Factory | NodeKind::Farm => false,
72 }
73 }
74
75 /// What the node produces, in words, for tooltips.
76 pub fn makes_text(self) -> &'static str {
77 match self {
78 NodeKind::Capital | NodeKind::City => "Troops",
79 NodeKind::Factory => "Ammo",
80 NodeKind::Farm => "Food",
81 NodeKind::Depot | NodeKind::Front => "nothing",
82 }
83 }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct FrontState {
88 /// -1 collapse .. +1 breakthrough. Starts at 0.
89 pub line: f32,
90 /// 0..1 recent supply ratio.
91 pub supply: f32,
92}
93
94/// A building under threat, being railed to the rear one crate at a time.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub struct Evac {
97 /// Game hours until the building is overrun.
98 pub hours_left: u32,
99 /// Crates still on site, not yet loaded.
100 pub crates_left: u32,
101 /// Where the crates go. Set by the first drag.
102 pub dest: Option<NodeId>,
103 /// Crates that have arrived at `dest`.
104 pub delivered: u32,
105 /// Index of the front sector threatening the building.
106 pub threat: usize,
107}
108
109#[derive(Debug, Clone)]
110pub struct Node {
111 pub name: String,
112 pub kind: NodeKind,
113 pub pos: Vec2,
114 /// Indexed by `Good::idx()`: [ammo, food, troops, wounded].
115 pub stock: [f32; 4],
116 pub front: Option<FrontState>,
117 /// 0..1, cities only.
118 pub hunger: f32,
119 /// Production multiplier. 1.0 unless the site lost crates in an evacuation.
120 pub output: f32,
121 /// Overrun by the enemy: produces nothing and its rail is cut.
122 pub captured: bool,
123 pub evac: Option<Evac>,
124}
125
126#[derive(Debug, Clone, Copy, PartialEq)]
127pub struct TrackSeg {
128 pub a: NodeId,
129 pub b: NodeId,
130 pub length: f32,
131 /// 0..1; below `MIN_USABLE_CONDITION` the track is blocked.
132 pub condition: f32,
133}
134
135/// Tracks with condition below this value are blocked.
136pub const MIN_USABLE_CONDITION: f32 = 0.3;
137/// Tracks with condition below this value slow trains to half speed.
138pub const SLOW_CONDITION: f32 = 0.7;
139
140/// Speed multiplier for a train on track of the given condition.
141pub fn speed_factor(condition: f32) -> f32 {
142 if condition < SLOW_CONDITION { 0.5 } else { 1.0 }
143}
144
145#[derive(Resource, Debug, Clone)]
146pub struct Network {
147 pub nodes: Vec<Node>,
148 pub tracks: Vec<TrackSeg>,
149}
150
151impl Network {
152 /// Index of the track connecting `a` and `b` in either direction.
153 pub fn track_between(&self, a: NodeId, b: NodeId) -> Option<usize> {
154 self.tracks
155 .iter()
156 .position(|t| (t.a == a && t.b == b) || (t.a == b && t.b == a))
157 }
158
159 /// True when either end of the track is captured.
160 pub fn is_cut(&self, t: &TrackSeg) -> bool {
161 self.nodes[t.a.0].captured || self.nodes[t.b.0].captured
162 }
163
164 /// Marks a node captured and breaks the track touching it.
165 pub fn capture(&mut self, i: usize) {
166 self.nodes[i].captured = true;
167 for t in self.tracks.iter_mut() {
168 if t.a.0 == i || t.b.0 == i {
169 t.condition = 0.0;
170 }
171 }
172 }
173
174 /// Adjacent nodes over usable tracks (condition >= 0.3), with track length.
175 pub fn neighbors(&self, n: NodeId) -> Vec<(NodeId, f32)> {
176 self.tracks
177 .iter()
178 .filter(|t| t.condition >= MIN_USABLE_CONDITION && !self.is_cut(t))
179 .filter_map(|t| {
180 if t.a == n {
181 Some((t.b, t.length))
182 } else if t.b == n {
183 Some((t.a, t.length))
184 } else {
185 None
186 }
187 })
188 .collect()
189 }
190
191 /// Dijkstra over usable tracks. The returned path includes both endpoints.
192 pub fn shortest_path(&self, from: NodeId, to: NodeId) -> Option<Vec<NodeId>> {
193 let n = self.nodes.len();
194 if from.0 >= n || to.0 >= n {
195 return None;
196 }
197 let mut dist = vec![f32::INFINITY; n];
198 let mut prev: Vec<Option<usize>> = vec![None; n];
199 let mut done = vec![false; n];
200 dist[from.0] = 0.0;
201 loop {
202 let mut cur: Option<usize> = None;
203 for i in 0..n {
204 if !done[i] && dist[i].is_finite() && cur.is_none_or(|c| dist[i] < dist[c]) {
205 cur = Some(i);
206 }
207 }
208 let Some(u) = cur else { break };
209 if u == to.0 {
210 break;
211 }
212 done[u] = true;
213 for (v, w) in self.neighbors(NodeId(u)) {
214 let alt = dist[u] + w;
215 if alt < dist[v.0] {
216 dist[v.0] = alt;
217 prev[v.0] = Some(u);
218 }
219 }
220 }
221 if !dist[to.0].is_finite() {
222 return None;
223 }
224 let mut path = vec![to];
225 let mut c = to.0;
226 while let Some(p) = prev[c] {
227 path.push(NodeId(p));
228 c = p;
229 }
230 path.reverse();
231 Some(path)
232 }
233
234 /// Nearest node within `radius` of `pos`.
235 pub fn node_at(&self, pos: Vec2, radius: f32) -> Option<NodeId> {
236 self.nodes
237 .iter()
238 .enumerate()
239 .map(|(i, n)| (i, n.pos.distance(pos)))
240 .filter(|(_, d)| *d <= radius)
241 .min_by(|a, b| a.1.total_cmp(&b.1))
242 .map(|(i, _)| NodeId(i))
243 }
244}
245
246pub fn node(name: &str, kind: NodeKind, x: f32, y: f32, stock: [f32; 4]) -> Node {
247 let front = (kind == NodeKind::Front).then_some(FrontState {
248 line: 0.0,
249 supply: 0.7,
250 });
251 Node {
252 name: name.to_string(),
253 kind,
254 pos: Vec2::new(x, y),
255 stock,
256 front,
257 hunger: 0.0,
258 output: 1.0,
259 captured: false,
260 evac: None,
261 }
262}
263
264impl Default for Network {
265 /// The operation map. World coordinates, roughly ±600 x ±340.
266 /// Stock order: [ammo, food, troops, wounded].
267 fn default() -> Self {
268 let nodes = vec![
269 node(
270 "Varenholm",
271 NodeKind::Capital,
272 -500.0,
273 0.0,
274 [0.0, 0.0, 10.0, 0.0],
275 ), // 0
276 node("Brenhollow", NodeKind::City, -340.0, 160.0, [0.0; 4]), // 1
277 node("Kestrau", NodeKind::City, -340.0, -170.0, [0.0; 4]), // 2
278 node(
279 "Ostwerk",
280 NodeKind::Factory,
281 -470.0,
282 200.0,
283 [20.0, 0.0, 0.0, 0.0],
284 ), // 3
285 node("Vellin", NodeKind::Factory, -470.0, -200.0, [0.0; 4]), // 4
286 node(
287 "Lindach",
288 NodeKind::Farm,
289 -250.0,
290 110.0,
291 [0.0, 20.0, 0.0, 0.0],
292 ), // 5
293 node("Sorvik", NodeKind::Farm, -250.0, -110.0, [0.0; 4]), // 6
294 node("Feldau", NodeKind::Depot, 0.0, 60.0, [0.0; 4]), // 7
295 node("Rhunen", NodeKind::Depot, 0.0, -80.0, [0.0; 4]), // 8
296 node(
297 "North Sector",
298 NodeKind::Front,
299 500.0,
300 200.0,
301 [40.0, 40.0, 10.0, 0.0],
302 ), // 9
303 node(
304 "Centre Sector",
305 NodeKind::Front,
306 510.0,
307 0.0,
308 [40.0, 40.0, 10.0, 0.0],
309 ), // 10
310 node(
311 "South Sector",
312 NodeKind::Front,
313 500.0,
314 -200.0,
315 [40.0, 40.0, 10.0, 0.0],
316 ), // 11
317 node(
318 "Dornmark",
319 NodeKind::Factory,
320 280.0,
321 170.0,
322 [12.0, 0.0, 0.0, 0.0],
323 ), // 12, forward factory: first evacuation target
324 node("Halvik", NodeKind::Farm, 280.0, -160.0, [0.0, 15.0, 0.0, 0.0]), // 13, forward farm
325 ];
326 let mut net = Network {
327 nodes,
328 tracks: Vec::new(),
329 };
330 // Starting line: Capital-Brenhollow, Capital-Ostwerk, and the rail
331 // from the Capital through Feldau to Centre Sector.
332 for (a, b) in [(0usize, 1usize), (0, 3), (0, 7), (7, 10)] {
333 let length = net.nodes[a].pos.distance(net.nodes[b].pos);
334 net.tracks.push(TrackSeg {
335 a: NodeId(a),
336 b: NodeId(b),
337 length,
338 condition: 1.0,
339 });
340 }
341 net
342 }
343}
344
345/// Cargo units one freight car holds of its good.
346pub const CAR_CAPACITY: f32 = 10.0;
347/// Speed lost per car beyond the first, as a fraction of the locomotive's speed.
348const CAR_SLOWDOWN: f32 = 0.05;
349/// Slowest a train gets, however many cars it pulls.
350const MIN_CAR_SPEED: f32 = 0.7;
351
352/// The locomotive that pulls a train's cars.
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
354pub enum LocoKind {
355 Light,
356 Heavy,
357}
358
359impl LocoKind {
360 /// World units per second at 1x.
361 pub fn speed(self) -> f32 {
362 match self {
363 LocoKind::Light => 175.0,
364 LocoKind::Heavy => 100.0,
365 }
366 }
367
368 /// Most cars this locomotive can pull.
369 pub fn max_cars(self) -> usize {
370 match self {
371 LocoKind::Light => 3,
372 LocoKind::Heavy => 6,
373 }
374 }
375
376 pub fn cost(self) -> i64 {
377 match self {
378 LocoKind::Light => 600,
379 LocoKind::Heavy => 1400,
380 }
381 }
382
383 pub fn upkeep_per_week(self) -> i64 {
384 match self {
385 LocoKind::Light => 50,
386 LocoKind::Heavy => 120,
387 }
388 }
389
390 pub fn name(self) -> &'static str {
391 match self {
392 LocoKind::Light => "Light",
393 LocoKind::Heavy => "Heavy",
394 }
395 }
396}
397
398/// One car type. The first four carry one good each; `Flat` carries one evacuation crate.
399#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
400pub enum CarKind {
401 Ammo,
402 Food,
403 Troop,
404 Hospital,
405 Flat,
406}
407
408impl CarKind {
409 /// Every car type, in the order the HUD shows them.
410 pub const ALL: [CarKind; 5] = [
411 CarKind::Ammo,
412 CarKind::Food,
413 CarKind::Troop,
414 CarKind::Hospital,
415 CarKind::Flat,
416 ];
417
418 /// The good this car carries, if any.
419 pub fn good(self) -> Option<Good> {
420 match self {
421 CarKind::Ammo => Some(Good::Ammo),
422 CarKind::Food => Some(Good::Food),
423 CarKind::Troop => Some(Good::Troops),
424 CarKind::Hospital => Some(Good::Wounded),
425 CarKind::Flat => None,
426 }
427 }
428
429 pub fn cost(self) -> i64 {
430 100
431 }
432
433 pub fn upkeep_per_week(self) -> i64 {
434 10
435 }
436
437 /// Short label for HUD buttons and tooltips.
438 pub fn name(self) -> &'static str {
439 match self {
440 CarKind::Ammo => "Ammo",
441 CarKind::Food => "Food",
442 CarKind::Troop => "Troop",
443 CarKind::Hospital => "Hospital",
444 CarKind::Flat => "Flat",
445 }
446 }
447}
448
449/// Price of a locomotive pulling `cars`.
450pub fn consist_cost(loco: LocoKind, cars: &[CarKind]) -> i64 {
451 loco.cost() + cars.iter().map(|c| c.cost()).sum::<i64>()
452}
453
454/// One ordered stop on a route. `load[g.idx()]` means load that good here.
455#[derive(Debug, Clone, Copy, PartialEq, Eq)]
456pub struct Stop {
457 pub node: NodeId,
458 pub load: [bool; 4],
459}
460
461#[derive(Component, Debug, Clone, PartialEq)]
462pub struct Train {
463 pub loco: LocoKind,
464 /// Freight cars behind the locomotive, front to back.
465 pub cars: Vec<CarKind>,
466 pub route: Vec<Stop>,
467 pub stop_idx: usize,
468 /// Node the train is currently at (or last left).
469 pub at: NodeId,
470 /// Remaining nodes to the next stop, excluding `at`.
471 pub path: Vec<NodeId>,
472 /// 0..1 along the current segment.
473 pub progress: f32,
474 /// [ammo, food, troops, wounded].
475 pub cargo: [f32; 4],
476 /// Seconds left loading.
477 pub dwell: f32,
478 /// True when no path to the next stop exists.
479 pub stalled: bool,
480 /// Crates aboard, carried by the Flat cars.
481 pub crates: u32,
482}
483
484impl Train {
485 /// Cargo units the train can hold of `g`: one car's worth per car carrying it.
486 pub fn capacity(&self, g: Good) -> f32 {
487 CAR_CAPACITY * self.cars.iter().filter(|c| c.good() == Some(g)).count() as f32
488 }
489
490 pub fn can_carry(&self, g: Good) -> bool {
491 self.capacity(g) > 0.0
492 }
493
494 /// Crates the train can hold: one per Flat car.
495 pub fn crate_slots(&self) -> u32 {
496 self.cars.iter().filter(|c| **c == CarKind::Flat).count() as u32
497 }
498
499 /// World units per second at 1x: the locomotive's speed, less a little per car past the first.
500 pub fn speed(&self) -> f32 {
501 let extra = self.cars.len().saturating_sub(1) as f32;
502 self.loco.speed() * (1.0 - CAR_SLOWDOWN * extra).max(MIN_CAR_SPEED)
503 }
504
505 pub fn upkeep_per_week(&self) -> i64 {
506 self.loco.upkeep_per_week() + self.cars.iter().map(|c| c.upkeep_per_week()).sum::<i64>()
507 }
508}
509
510#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq)]
511pub struct Treasury(pub i64);
512
513impl Default for Treasury {
514 fn default() -> Self {
515 Treasury(6000)
516 }
517}
518
519/// Real seconds per game hour at 1x.
520pub const SECS_PER_HOUR: f32 = 0.5;
521
522#[derive(Resource, Debug, Clone, Copy, PartialEq)]
523pub struct SimClock {
524 /// Total elapsed game hours.
525 pub hour: u32,
526 /// 0 = paused, 1, 2 or 4.
527 pub speed: u32,
528 /// Real-time accumulator in seconds.
529 pub acc: f32,
530}
531
532impl Default for SimClock {
533 fn default() -> Self {
534 SimClock {
535 hour: 0,
536 speed: 1,
537 acc: 0.0,
538 }
539 }
540}
541
542impl SimClock {
543 /// Elapsed whole game days.
544 pub fn day(&self) -> u32 {
545 self.hour / 24
546 }
547
548 /// Elapsed whole game weeks.
549 pub fn week(&self) -> u32 {
550 self.hour / (24 * 7)
551 }
552}
553
554#[derive(Resource, Debug, Clone, Default, PartialEq)]
555pub enum Tool {
556 #[default]
557 Inspect,
558 BuildTrack {
559 from: Option<NodeId>,
560 },
561 NewRoute {
562 loco: LocoKind,
563 cars: Vec<CarKind>,
564 stops: Vec<Stop>,
565 },
566 Repair,
567}
568
569#[derive(Resource, Debug, Clone, Copy, Default, PartialEq, Eq)]
570pub struct Selected(pub Option<NodeId>);
571
572#[derive(Resource, Debug, Clone, Copy, Default, PartialEq, Eq)]
573pub enum Outcome {
574 #[default]
575 Ongoing,
576 Victory,
577 Defeat,
578}
579
580#[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
581pub struct NodeClicked(pub NodeId);
582
583#[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
584pub struct TrackClicked(pub usize);
585
586/// Sent once per game hour by the economy.
587#[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
588pub struct HourTick;
589
590/// News and log lines shown by the HUD.
591#[derive(Message, Debug, Clone, PartialEq, Eq)]
592pub struct Notify(pub String);
593
594pub const TRACK_COST_PER_UNIT: i64 = 2;
595pub const REPAIR_COST: i64 = 150;
596
597/// "Ammo 20, Food 0, Troops 5, Wounded 0", whole numbers, every good listed.
598pub fn stock_text(v: &[f32; 4]) -> String {
599 GOODS
600 .iter()
601 .map(|g| format!("{} {:.0}", g.name(), v[g.idx()]))
602 .collect::<Vec<_>>()
603 .join(", ")
604}
605
606#[cfg(test)]
607mod tests {
608 use super::*;
609
610 #[test]
611 fn shortest_path_factory_to_centre_via_capital_and_feldau() {
612 let net = Network::default();
613 // Ostwerk (3) -> Varenholm (0) -> Feldau (7) -> Centre Sector (10).
614 let path = net.shortest_path(NodeId(3), NodeId(10));
615 assert_eq!(
616 path,
617 Some(vec![NodeId(3), NodeId(0), NodeId(7), NodeId(10)])
618 );
619 }
620}