| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use bevy::ecs::system::SystemParam; |
| 6 | use bevy::prelude::*; |
| 7 | use bevy::ui_widgets::Activate; |
| 8 | |
| 9 | use crate::audio::SoundEvent; |
| 10 | use crate::map::{WorldText, dashed}; |
| 11 | use crate::model::{ |
| 12 | CarKind, GOODS, Good, Network, NodeClicked, NodeId, NodeKind, Notify, Stop, Tool, Train, |
| 13 | Treasury, consist_cost, |
| 14 | }; |
| 15 | use crate::supply::{buy_line, money, produces}; |
| 16 | |
| 17 | pub struct RoutesPlugin; |
| 18 | |
| 19 | impl Plugin for RoutesPlugin { |
| 20 | fn build(&self, app: &mut App) { |
| 21 | app.add_systems( |
| 22 | Update, |
| 23 | (on_node_clicked, sync_route_labels, draw_route_preview), |
| 24 | ) |
| 25 | .add_observer(on_scrap) |
| 26 | .add_observer(on_add_train) |
| 27 | .add_observer(on_remove_car) |
| 28 | .add_observer(on_add_car); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | |
| 33 | const DASH_LEN: f32 = 10.0; |
| 34 | const GAP_LEN: f32 = 6.0; |
| 35 | |
| 36 | const STOP_LABEL_SIZE: f32 = 16.0; |
| 37 | |
| 38 | fn ink() -> Color { |
| 39 | Color::srgb(0.15, 0.12, 0.08) |
| 40 | } |
| 41 | fn amber() -> Color { |
| 42 | Color::srgb(1.0, 0.75, 0.2) |
| 43 | } |
| 44 | fn red() -> Color { |
| 45 | Color::srgb(0.9, 0.15, 0.1) |
| 46 | } |
| 47 | |
| 48 | |
| 49 | |
| 50 | #[derive(Component, Debug, Clone, Copy)] |
| 51 | pub(crate) struct Scrap(pub Entity); |
| 52 | |
| 53 | |
| 54 | |
| 55 | #[derive(Component, Debug, Clone, Copy)] |
| 56 | pub(crate) struct AddTrain { |
| 57 | pub from: NodeId, |
| 58 | pub to: NodeId, |
| 59 | } |
| 60 | |
| 61 | |
| 62 | |
| 63 | #[derive(Component, Debug, Clone, Copy)] |
| 64 | pub(crate) struct RemoveCar { |
| 65 | pub entity: Entity, |
| 66 | pub index: usize, |
| 67 | } |
| 68 | |
| 69 | |
| 70 | |
| 71 | #[derive(Component, Debug, Clone, Copy)] |
| 72 | pub(crate) struct AddCar { |
| 73 | pub entity: Entity, |
| 74 | pub car: CarKind, |
| 75 | } |
| 76 | |
| 77 | |
| 78 | #[derive(Component)] |
| 79 | struct RouteLabel; |
| 80 | |
| 81 | #[derive(SystemParam)] |
| 82 | struct ScrapParams<'w, 's> { |
| 83 | commands: Commands<'w, 's>, |
| 84 | treasury: ResMut<'w, Treasury>, |
| 85 | trains: Query<'w, 's, &'static Train>, |
| 86 | notify: MessageWriter<'w, Notify>, |
| 87 | } |
| 88 | |
| 89 | #[derive(SystemParam)] |
| 90 | struct CarParams<'w, 's> { |
| 91 | net: Res<'w, Network>, |
| 92 | treasury: ResMut<'w, Treasury>, |
| 93 | trains: Query<'w, 's, &'static mut Train>, |
| 94 | notify: MessageWriter<'w, Notify>, |
| 95 | } |
| 96 | |
| 97 | |
| 98 | fn default_load(cars: &[CarKind], node: NodeKind) -> [bool; 4] { |
| 99 | let wanted = match node { |
| 100 | NodeKind::Factory => [true, false, false, false], |
| 101 | NodeKind::Farm => [false, true, false, false], |
| 102 | NodeKind::Capital | NodeKind::City => [false, false, true, false], |
| 103 | NodeKind::Front => [false, false, false, true], |
| 104 | NodeKind::Depot => [true, true, true, false], |
| 105 | }; |
| 106 | let mut load = [false; 4]; |
| 107 | for g in GOODS { |
| 108 | load[g.idx()] = wanted[g.idx()] && cars.iter().any(|c| c.good() == Some(g)); |
| 109 | } |
| 110 | load |
| 111 | } |
| 112 | |
| 113 | |
| 114 | pub(crate) fn cargo_good(train: &Train) -> Option<Good> { |
| 115 | let first = train.route.first()?; |
| 116 | GOODS.into_iter().find(|g| first.load[g.idx()]) |
| 117 | } |
| 118 | |
| 119 | |
| 120 | fn on_node_clicked( |
| 121 | mut clicks: MessageReader<NodeClicked>, |
| 122 | mut tool: ResMut<Tool>, |
| 123 | network: Res<Network>, |
| 124 | ) { |
| 125 | if !matches!(*tool, Tool::NewRoute { .. }) { |
| 126 | return; |
| 127 | } |
| 128 | for NodeClicked(node) in clicks.read() { |
| 129 | let Some(info) = network.nodes.get(node.0) else { |
| 130 | continue; |
| 131 | }; |
| 132 | let Tool::NewRoute { cars, stops, .. } = &mut *tool else { |
| 133 | continue; |
| 134 | }; |
| 135 | if stops.last().is_some_and(|s| s.node == *node) { |
| 136 | continue; |
| 137 | } |
| 138 | stops.push(Stop { |
| 139 | node: *node, |
| 140 | load: default_load(cars, info.kind), |
| 141 | }); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | |
| 146 | fn on_scrap(ev: On<Activate>, scraps: Query<&Scrap>, mut p: ScrapParams<'_, '_>) { |
| 147 | let Ok(Scrap(entity)) = scraps.get(ev.entity) else { |
| 148 | return; |
| 149 | }; |
| 150 | let entity = *entity; |
| 151 | let Ok(train) = p.trains.get(entity) else { |
| 152 | return; |
| 153 | }; |
| 154 | let loco = train.loco; |
| 155 | let refund = consist_cost(loco, &train.cars) / 2; |
| 156 | p.treasury.0 += refund; |
| 157 | p.commands.entity(entity).despawn(); |
| 158 | p.notify.write(Notify(format!( |
| 159 | "{} train scrapped, ${refund} refunded", |
| 160 | loco.name() |
| 161 | ))); |
| 162 | } |
| 163 | |
| 164 | |
| 165 | fn on_remove_car(ev: On<Activate>, removes: Query<&RemoveCar>, mut p: CarParams) { |
| 166 | let Ok(&RemoveCar { entity, index }) = removes.get(ev.entity) else { |
| 167 | return; |
| 168 | }; |
| 169 | let Ok(mut train) = p.trains.get_mut(entity) else { |
| 170 | return; |
| 171 | }; |
| 172 | if index >= train.cars.len() { |
| 173 | return; |
| 174 | } |
| 175 | let car = train.cars.remove(index); |
| 176 | let refund = car.cost() / 2; |
| 177 | p.treasury.0 += refund; |
| 178 | p.notify.write(Notify(format!( |
| 179 | "{} car removed, ${refund} refunded", |
| 180 | car.name() |
| 181 | ))); |
| 182 | } |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | fn on_add_car(ev: On<Activate>, adds: Query<&AddCar>, mut p: CarParams) { |
| 188 | let Ok(&AddCar { entity, car }) = adds.get(ev.entity) else { |
| 189 | return; |
| 190 | }; |
| 191 | let Ok(mut train) = p.trains.get_mut(entity) else { |
| 192 | return; |
| 193 | }; |
| 194 | if train.cars.len() >= train.loco.max_cars() { |
| 195 | p.notify.write(Notify(format!("{} is full", train.loco.name()))); |
| 196 | return; |
| 197 | } |
| 198 | if car.cost() > p.treasury.0 { |
| 199 | p.notify.write(Notify(format!("Need {}", money(car.cost())))); |
| 200 | return; |
| 201 | } |
| 202 | p.treasury.0 -= car.cost(); |
| 203 | train.cars.push(car); |
| 204 | if let Some(good) = car.good() { |
| 205 | let net = &p.net; |
| 206 | let source = train.route.iter_mut().find(|s| { |
| 207 | let node = &net.nodes[s.node.0]; |
| 208 | produces(node.kind) == Some(good) || node.stock[good.idx()] > 0.0 |
| 209 | }); |
| 210 | if let Some(stop) = source { |
| 211 | stop.load[good.idx()] = true; |
| 212 | } |
| 213 | } |
| 214 | p.notify.write(Notify(format!("{} car added", car.name()))); |
| 215 | } |
| 216 | |
| 217 | |
| 218 | |
| 219 | fn on_add_train( |
| 220 | ev: On<Activate>, |
| 221 | adds: Query<&AddTrain>, |
| 222 | mut net: ResMut<Network>, |
| 223 | mut treasury: ResMut<Treasury>, |
| 224 | mut commands: Commands, |
| 225 | mut notify: MessageWriter<Notify>, |
| 226 | mut sounds: MessageWriter<SoundEvent>, |
| 227 | ) { |
| 228 | let Ok(&AddTrain { from, to }) = adds.get(ev.entity) else { |
| 229 | return; |
| 230 | }; |
| 231 | buy_line( |
| 232 | &mut net, |
| 233 | &mut treasury, |
| 234 | &mut commands, |
| 235 | &mut notify, |
| 236 | &mut sounds, |
| 237 | from, |
| 238 | to, |
| 239 | ); |
| 240 | } |
| 241 | |
| 242 | |
| 243 | fn sync_route_labels( |
| 244 | mut commands: Commands, |
| 245 | tool: Res<Tool>, |
| 246 | network: Res<Network>, |
| 247 | old: Query<Entity, With<RouteLabel>>, |
| 248 | ) { |
| 249 | if !tool.is_changed() { |
| 250 | return; |
| 251 | } |
| 252 | for e in &old { |
| 253 | commands.entity(e).despawn(); |
| 254 | } |
| 255 | let Tool::NewRoute { stops, .. } = tool.as_ref() else { |
| 256 | return; |
| 257 | }; |
| 258 | for (i, stop) in stops.iter().enumerate() { |
| 259 | let Some(node) = network.nodes.get(stop.node.0) else { |
| 260 | continue; |
| 261 | }; |
| 262 | commands.spawn(( |
| 263 | RouteLabel, |
| 264 | Text2d::new(format!("{}", i + 1)), |
| 265 | WorldText { |
| 266 | size: STOP_LABEL_SIZE, |
| 267 | }, |
| 268 | TextColor(ink()), |
| 269 | Transform::from_xyz(node.pos.x, node.pos.y, 10.0), |
| 270 | )); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | |
| 275 | fn draw_route_preview(mut gizmos: Gizmos, tool: Res<Tool>, network: Res<Network>) { |
| 276 | let Tool::NewRoute { stops, .. } = tool.as_ref() else { |
| 277 | return; |
| 278 | }; |
| 279 | for stop in stops { |
| 280 | if let Some(node) = network.nodes.get(stop.node.0) { |
| 281 | gizmos.circle_2d(node.pos, 16.0, amber()); |
| 282 | } |
| 283 | } |
| 284 | for pair in stops.windows(2) { |
| 285 | let (a, b) = (pair[0].node, pair[1].node); |
| 286 | let (Some(na), Some(nb)) = (network.nodes.get(a.0), network.nodes.get(b.0)) else { |
| 287 | continue; |
| 288 | }; |
| 289 | match network.shortest_path(a, b) { |
| 290 | Some(path) => { |
| 291 | for leg in path.windows(2) { |
| 292 | let p = network.nodes[leg[0].0].pos; |
| 293 | let q = network.nodes[leg[1].0].pos; |
| 294 | dashed(&mut gizmos, p, q, DASH_LEN, GAP_LEN, amber()); |
| 295 | } |
| 296 | } |
| 297 | None => dashed(&mut gizmos, na.pos, nb.pos, DASH_LEN, GAP_LEN, red()), |
| 298 | } |
| 299 | } |
| 300 | } |