| 1 | |
| 2 | |
| 3 | use bevy::prelude::*; |
| 4 | |
| 5 | use crate::audio::SoundEvent; |
| 6 | use crate::map::good_color; |
| 7 | use crate::model::{ |
| 8 | CAR_CAPACITY, CarKind, GOODS, LocoKind, MIN_USABLE_CONDITION, Network, NodeId, Notify, |
| 9 | SimClock, Stop, Train, speed_factor, |
| 10 | }; |
| 11 | use crate::seasons::SeasonState; |
| 12 | |
| 13 | |
| 14 | |
| 15 | pub fn starting_train() -> Train { |
| 16 | new_train( |
| 17 | LocoKind::Heavy, |
| 18 | vec![CarKind::Ammo; 4], |
| 19 | vec![ |
| 20 | Stop { |
| 21 | node: NodeId(3), |
| 22 | load: [true, false, false, false], |
| 23 | }, |
| 24 | Stop { |
| 25 | node: NodeId(10), |
| 26 | load: [false; 4], |
| 27 | }, |
| 28 | ], |
| 29 | ) |
| 30 | } |
| 31 | |
| 32 | |
| 33 | pub fn new_train(loco: LocoKind, cars: Vec<CarKind>, route: Vec<Stop>) -> Train { |
| 34 | Train { |
| 35 | loco, |
| 36 | cars, |
| 37 | at: route[0].node, |
| 38 | route, |
| 39 | stop_idx: 0, |
| 40 | path: Vec::new(), |
| 41 | progress: 0.0, |
| 42 | cargo: [0.0; 4], |
| 43 | dwell: 0.0, |
| 44 | stalled: false, |
| 45 | crates: 0, |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | fn spawn_starting_train(mut commands: Commands) { |
| 50 | commands.spawn(starting_train()); |
| 51 | } |
| 52 | |
| 53 | |
| 54 | pub fn train_center(net: &Network, train: &Train) -> Vec2 { |
| 55 | let origin = net.nodes[train.at.0].pos; |
| 56 | match train.path.first() { |
| 57 | Some(next) => origin.lerp(net.nodes[next.0].pos, train.progress.clamp(0.0, 1.0)), |
| 58 | None => origin, |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | |
| 63 | #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)] |
| 64 | pub struct TrainNo(pub u32); |
| 65 | |
| 66 | |
| 67 | #[derive(Resource, Debug, Default)] |
| 68 | pub struct TrainCounter(pub u32); |
| 69 | |
| 70 | |
| 71 | #[derive(Component, Debug, Default)] |
| 72 | struct TrainAux { |
| 73 | |
| 74 | retry: f32, |
| 75 | |
| 76 | notified: bool, |
| 77 | } |
| 78 | |
| 79 | const DWELL_SECS: f32 = 1.0; |
| 80 | const STALL_RETRY_SECS: f32 = 1.0; |
| 81 | |
| 82 | const LOCO_LEN: f32 = 18.0; |
| 83 | const CAR_LEN: f32 = 12.0; |
| 84 | const CAR_GAP: f32 = 2.0; |
| 85 | const TRAIN_HALF_WIDTH: f32 = 4.0; |
| 86 | const LOAD_EPS: f32 = 1e-4; |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | pub fn split_load(free: f32, stock: [f32; 4], room: [f32; 4]) -> [f32; 4] { |
| 97 | let limit = |i: usize| stock[i].min(room[i]); |
| 98 | let mut take = [0.0_f32; 4]; |
| 99 | let mut left = free.max(0.0); |
| 100 | let mut open: Vec<usize> = (0..4).filter(|&i| limit(i) > LOAD_EPS).collect(); |
| 101 | while left > LOAD_EPS && !open.is_empty() { |
| 102 | let share = left / open.len() as f32; |
| 103 | let mut spent = 0.0; |
| 104 | for &i in &open { |
| 105 | let t = share.min(limit(i) - take[i]); |
| 106 | take[i] += t; |
| 107 | spent += t; |
| 108 | } |
| 109 | left -= spent; |
| 110 | open.retain(|&i| limit(i) - take[i] > LOAD_EPS); |
| 111 | } |
| 112 | take |
| 113 | } |
| 114 | |
| 115 | |
| 116 | fn number_new_trains( |
| 117 | mut commands: Commands, |
| 118 | mut counter: ResMut<TrainCounter>, |
| 119 | new_trains: Query<Entity, Added<Train>>, |
| 120 | ) { |
| 121 | for entity in &new_trains { |
| 122 | counter.0 += 1; |
| 123 | commands |
| 124 | .entity(entity) |
| 125 | .insert((TrainNo(counter.0), TrainAux::default())); |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | fn plan_next(train: &mut Train, net: &Network) -> bool { |
| 133 | let target = train.route[train.stop_idx].node; |
| 134 | match net.shortest_path(train.at, target) { |
| 135 | Some(mut p) => { |
| 136 | p.remove(0); |
| 137 | train.path = p; |
| 138 | train.stalled = false; |
| 139 | true |
| 140 | } |
| 141 | None => { |
| 142 | train.path.clear(); |
| 143 | train.stalled = true; |
| 144 | false |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | |
| 150 | |
| 151 | fn plan_or_stall( |
| 152 | train: &mut Train, |
| 153 | aux: &mut TrainAux, |
| 154 | net: &Network, |
| 155 | no: TrainNo, |
| 156 | notify: &mut MessageWriter<Notify>, |
| 157 | ) { |
| 158 | if plan_next(train, net) { |
| 159 | aux.notified = false; |
| 160 | return; |
| 161 | } |
| 162 | aux.retry = STALL_RETRY_SECS; |
| 163 | if !aux.notified { |
| 164 | aux.notified = true; |
| 165 | let target = train.route[train.stop_idx].node; |
| 166 | notify.write(Notify(format!( |
| 167 | "Train #{} stalled: no track to {}", |
| 168 | no.0, net.nodes[target.0].name |
| 169 | ))); |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | fn run_stop(train: &mut Train, net: &mut Network) { |
| 177 | let stop = train.route[train.stop_idx]; |
| 178 | |
| 179 | |
| 180 | |
| 181 | let origin = train.route[0].node; |
| 182 | if train.crates > 0 && origin != train.at { |
| 183 | if let Some(evac) = net.nodes[origin.0].evac.as_mut() { |
| 184 | evac.delivered += train.crates; |
| 185 | } |
| 186 | train.crates = 0; |
| 187 | } |
| 188 | if let Some(evac) = net.nodes[train.at.0].evac.as_mut() |
| 189 | && evac.dest.is_some() |
| 190 | { |
| 191 | let take = train.crate_slots().saturating_sub(train.crates).min(evac.crates_left); |
| 192 | evac.crates_left -= take; |
| 193 | train.crates += take; |
| 194 | } |
| 195 | |
| 196 | let node = &mut net.nodes[train.at.0]; |
| 197 | |
| 198 | |
| 199 | for g in GOODS { |
| 200 | let i = g.idx(); |
| 201 | if train.cargo[i] > 0.0 && node.kind.accepts(g) { |
| 202 | node.stock[i] += train.cargo[i]; |
| 203 | train.cargo[i] = 0.0; |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | |
| 208 | let mut room = [0.0_f32; 4]; |
| 209 | for g in GOODS { |
| 210 | let i = g.idx(); |
| 211 | if stop.load[i] { |
| 212 | room[i] = (train.capacity(g) - train.cargo[i]).max(0.0); |
| 213 | } |
| 214 | } |
| 215 | let take = split_load(room.iter().sum(), node.stock, room); |
| 216 | for (i, &amount) in take.iter().enumerate() { |
| 217 | train.cargo[i] += amount; |
| 218 | node.stock[i] = (node.stock[i] - amount).max(0.0); |
| 219 | } |
| 220 | |
| 221 | |
| 222 | train.dwell = DWELL_SECS; |
| 223 | train.stop_idx = (train.stop_idx + 1) % train.route.len(); |
| 224 | } |
| 225 | |
| 226 | fn simulate_trains( |
| 227 | time: Res<Time>, |
| 228 | clock: Res<SimClock>, |
| 229 | season: Res<SeasonState>, |
| 230 | mut network: ResMut<Network>, |
| 231 | mut notify: MessageWriter<Notify>, |
| 232 | mut sounds: MessageWriter<SoundEvent>, |
| 233 | mut trains: Query<(&mut Train, &mut TrainAux, &TrainNo)>, |
| 234 | ) { |
| 235 | let dt = time.delta_secs() * clock.speed as f32; |
| 236 | if dt <= 0.0 { |
| 237 | return; |
| 238 | } |
| 239 | let net: &mut Network = &mut network; |
| 240 | |
| 241 | for (mut train, mut aux, no) in &mut trains { |
| 242 | let len = train.route.len(); |
| 243 | if len == 0 { |
| 244 | continue; |
| 245 | } |
| 246 | if train.stop_idx >= len { |
| 247 | train.stop_idx = 0; |
| 248 | } |
| 249 | if train.dwell > 0.0 { |
| 250 | train.dwell -= dt; |
| 251 | } |
| 252 | |
| 253 | |
| 254 | if train.stalled { |
| 255 | aux.retry -= dt; |
| 256 | if aux.retry <= 0.0 { |
| 257 | plan_or_stall(&mut train, &mut aux, net, *no, &mut notify); |
| 258 | } |
| 259 | continue; |
| 260 | } |
| 261 | |
| 262 | |
| 263 | if train.path.is_empty() { |
| 264 | if train.dwell > 0.0 { |
| 265 | continue; |
| 266 | } |
| 267 | if train.at == train.route[train.stop_idx].node { |
| 268 | run_stop(&mut train, net); |
| 269 | sounds.write(SoundEvent::TrainDeparts); |
| 270 | } |
| 271 | plan_or_stall(&mut train, &mut aux, net, *no, &mut notify); |
| 272 | continue; |
| 273 | } |
| 274 | |
| 275 | |
| 276 | let next = train.path[0]; |
| 277 | if train.progress <= 0.0 { |
| 278 | let usable = net |
| 279 | .track_between(train.at, next) |
| 280 | .is_some_and(|i| net.tracks[i].condition >= MIN_USABLE_CONDITION); |
| 281 | if !usable { |
| 282 | plan_or_stall(&mut train, &mut aux, net, *no, &mut notify); |
| 283 | continue; |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | |
| 288 | let segment = net.track_between(train.at, next).map(|i| net.tracks[i]); |
| 289 | let length = segment.map_or(0.0, |t| t.length); |
| 290 | let condition = segment.map_or(1.0, |t| t.condition); |
| 291 | if length <= 0.0 { |
| 292 | train.progress = 1.0; |
| 293 | } else { |
| 294 | train.progress += |
| 295 | train.speed() * speed_factor(condition) * season.season.speed_mult() * dt / length; |
| 296 | } |
| 297 | if train.progress >= 1.0 { |
| 298 | train.at = train.path.remove(0); |
| 299 | train.progress = 0.0; |
| 300 | } |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | |
| 305 | |
| 306 | fn draw_band(gizmos: &mut Gizmos, frame: &Frame, x0: f32, x1: f32, half_h: f32, color: Color) { |
| 307 | let steps = (2.0 * half_h).round() as i32; |
| 308 | for k in 0..=steps { |
| 309 | let y = -half_h + k as f32; |
| 310 | gizmos.line_2d(frame.at(x0, y), frame.at(x1, y), color); |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | |
| 315 | struct Frame { |
| 316 | center: Vec2, |
| 317 | dir: Vec2, |
| 318 | nrm: Vec2, |
| 319 | } |
| 320 | |
| 321 | impl Frame { |
| 322 | fn at(&self, x: f32, y: f32) -> Vec2 { |
| 323 | self.center + self.dir * x + self.nrm * y |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | fn draw_trains(mut gizmos: Gizmos, time: Res<Time>, network: Res<Network>, trains: Query<&Train>) { |
| 328 | let ink = Color::srgb(0.12, 0.10, 0.08); |
| 329 | let steel_blue = Color::srgb(0.27, 0.51, 0.71); |
| 330 | let near_black = Color::srgb(0.08, 0.08, 0.09); |
| 331 | let cross_red = Color::srgb(0.80, 0.10, 0.10); |
| 332 | let stall_red = Color::srgb(0.90, 0.12, 0.12); |
| 333 | let flat_grey = Color::srgb(0.55, 0.53, 0.50); |
| 334 | let crate_fill = Color::srgb(0.55, 0.36, 0.16); |
| 335 | let blink_on = ((time.elapsed_secs() * 2.0) as u32).is_multiple_of(2); |
| 336 | |
| 337 | for train in &trains { |
| 338 | let Some(origin) = network.nodes.get(train.at.0).map(|n| n.pos) else { |
| 339 | continue; |
| 340 | }; |
| 341 | let (center, dir) = match train.path.first() { |
| 342 | Some(next) => { |
| 343 | let target = network.nodes[next.0].pos; |
| 344 | let d = (target - origin).normalize_or_zero(); |
| 345 | let d = if d == Vec2::ZERO { Vec2::X } else { d }; |
| 346 | let p = origin.lerp(target, train.progress.clamp(0.0, 1.0)); |
| 347 | (p, d) |
| 348 | } |
| 349 | None => (origin, Vec2::X), |
| 350 | }; |
| 351 | let frame = Frame { |
| 352 | center, |
| 353 | dir, |
| 354 | nrm: Vec2::new(-dir.y, dir.x), |
| 355 | }; |
| 356 | let angle = dir.y.atan2(dir.x); |
| 357 | |
| 358 | |
| 359 | let half_loco = LOCO_LEN / 2.0; |
| 360 | gizmos.rect_2d( |
| 361 | Isometry2d::new(center, Rot2::radians(angle)), |
| 362 | Vec2::new(LOCO_LEN, TRAIN_HALF_WIDTH * 2.0), |
| 363 | ink, |
| 364 | ); |
| 365 | let base = match train.loco { |
| 366 | LocoKind::Light => steel_blue, |
| 367 | LocoKind::Heavy => near_black, |
| 368 | }; |
| 369 | let body = if train.stalled && blink_on { |
| 370 | stall_red |
| 371 | } else { |
| 372 | base |
| 373 | }; |
| 374 | draw_band( |
| 375 | &mut gizmos, |
| 376 | &frame, |
| 377 | -half_loco, |
| 378 | half_loco, |
| 379 | TRAIN_HALF_WIDTH, |
| 380 | body, |
| 381 | ); |
| 382 | |
| 383 | |
| 384 | for (i, car) in train.cars.iter().enumerate() { |
| 385 | let right = -half_loco - CAR_GAP - i as f32 * (CAR_LEN + CAR_GAP); |
| 386 | let left = right - CAR_LEN; |
| 387 | let mid = (left + right) / 2.0; |
| 388 | let Some(good) = car.good() else { |
| 389 | |
| 390 | gizmos.rect_2d( |
| 391 | Isometry2d::new(frame.at(mid, 0.0), Rot2::radians(angle)), |
| 392 | Vec2::new(CAR_LEN, TRAIN_HALF_WIDTH * 2.0), |
| 393 | flat_grey, |
| 394 | ); |
| 395 | let flats_before = train.cars[..i].iter().filter(|c| **c == CarKind::Flat).count(); |
| 396 | if (flats_before as u32) < train.crates { |
| 397 | draw_band(&mut gizmos, &frame, mid - 4.0, mid + 4.0, 3.0, crate_fill); |
| 398 | } |
| 399 | continue; |
| 400 | }; |
| 401 | gizmos.rect_2d( |
| 402 | Isometry2d::new(frame.at(mid, 0.0), Rot2::radians(angle)), |
| 403 | Vec2::new(CAR_LEN, TRAIN_HALF_WIDTH * 2.0), |
| 404 | ink, |
| 405 | ); |
| 406 | |
| 407 | |
| 408 | let color = good_color(good); |
| 409 | draw_band( |
| 410 | &mut gizmos, |
| 411 | &frame, |
| 412 | left, |
| 413 | right, |
| 414 | TRAIN_HALF_WIDTH, |
| 415 | color.with_alpha(0.25), |
| 416 | ); |
| 417 | let before = train.cars[..i].iter().filter(|c| c.good() == Some(good)).count(); |
| 418 | let held = (train.cargo[good.idx()] - before as f32 * CAR_CAPACITY) |
| 419 | .clamp(0.0, CAR_CAPACITY); |
| 420 | let fill = held / CAR_CAPACITY; |
| 421 | if fill > 0.0 { |
| 422 | draw_band( |
| 423 | &mut gizmos, |
| 424 | &frame, |
| 425 | left, |
| 426 | left + CAR_LEN * fill, |
| 427 | TRAIN_HALF_WIDTH, |
| 428 | color, |
| 429 | ); |
| 430 | } |
| 431 | |
| 432 | |
| 433 | if *car == CarKind::Hospital { |
| 434 | gizmos.line_2d(frame.at(mid - 3.0, 0.0), frame.at(mid + 3.0, 0.0), cross_red); |
| 435 | gizmos.line_2d(frame.at(mid, -3.0), frame.at(mid, 3.0), cross_red); |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | pub struct TrainsPlugin; |
| 442 | |
| 443 | impl Plugin for TrainsPlugin { |
| 444 | fn build(&self, app: &mut App) { |
| 445 | app.init_resource::<TrainCounter>() |
| 446 | .add_systems(Startup, spawn_starting_train) |
| 447 | .add_systems( |
| 448 | Update, |
| 449 | (number_new_trains, simulate_trains, draw_trains).chain(), |
| 450 | ); |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | #[cfg(test)] |
| 455 | mod tests { |
| 456 | use super::*; |
| 457 | |
| 458 | fn total(v: [f32; 4]) -> f32 { |
| 459 | v.iter().sum() |
| 460 | } |
| 461 | |
| 462 | #[test] |
| 463 | fn split_gives_leftover_to_others() { |
| 464 | |
| 465 | let take = split_load(10.0, [2.0, 100.0, 0.0, 0.0], [10.0, 10.0, 0.0, 0.0]); |
| 466 | assert!((take[0] - 2.0).abs() < 1e-4); |
| 467 | assert!((take[1] - 8.0).abs() < 1e-4); |
| 468 | } |
| 469 | |
| 470 | #[test] |
| 471 | fn split_never_exceeds_free_or_stock() { |
| 472 | let stock = [3.0, 7.0, 1.0, 50.0]; |
| 473 | let room = [12.0, 12.0, 12.0, 0.0]; |
| 474 | let take = split_load(12.0, stock, room); |
| 475 | assert!(total(take) <= 12.0 + 1e-3); |
| 476 | for i in 0..4 { |
| 477 | assert!(take[i] <= stock[i] + 1e-4); |
| 478 | } |
| 479 | assert!((total(take) - 11.0).abs() < 1e-3); |
| 480 | } |
| 481 | |
| 482 | #[test] |
| 483 | fn stop_loads_only_up_to_each_goods_cars() { |
| 484 | |
| 485 | let mut net = Network::default(); |
| 486 | let stop = Stop { |
| 487 | node: NodeId(3), |
| 488 | load: [true, true, true, false], |
| 489 | }; |
| 490 | let mut train = new_train( |
| 491 | LocoKind::Light, |
| 492 | vec![CarKind::Ammo, CarKind::Food, CarKind::Food], |
| 493 | vec![stop, stop], |
| 494 | ); |
| 495 | net.nodes[3].stock = [100.0, 100.0, 100.0, 0.0]; |
| 496 | run_stop(&mut train, &mut net); |
| 497 | assert_eq!(train.cargo, [10.0, 20.0, 0.0, 0.0]); |
| 498 | } |
| 499 | } |