| 1 | use bevy::prelude::*; |
| 2 | use bevy::window::PrimaryWindow; |
| 3 | |
| 4 | use crate::audio::SoundEvent; |
| 5 | use crate::map::{MapHover, WorldText}; |
| 6 | use crate::model::{ |
| 7 | MIN_USABLE_CONDITION, Network, NodeClicked, NodeId, Notify, REPAIR_COST, TRACK_COST_PER_UNIT, |
| 8 | Tool, TrackClicked, TrackSeg, Treasury, |
| 9 | }; |
| 10 | |
| 11 | pub struct BuildPlugin; |
| 12 | |
| 13 | impl Plugin for BuildPlugin { |
| 14 | fn build(&self, app: &mut App) { |
| 15 | app.add_systems(Startup, spawn_cost_label).add_systems( |
| 16 | Update, |
| 17 | (handle_node_clicks, handle_track_clicks, build_preview).chain(), |
| 18 | ); |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | |
| 23 | const SNAP_RADIUS: f32 = 24.0; |
| 24 | |
| 25 | const COST_LABEL_SIZE: f32 = 27.0; |
| 26 | |
| 27 | const DASH_LEN: f32 = 12.0; |
| 28 | const GAP_LEN: f32 = 8.0; |
| 29 | |
| 30 | #[derive(Component)] |
| 31 | struct BuildCostLabel; |
| 32 | |
| 33 | fn spawn_cost_label(mut commands: Commands) { |
| 34 | commands.spawn(( |
| 35 | BuildCostLabel, |
| 36 | Text2d::new(""), |
| 37 | WorldText { |
| 38 | size: COST_LABEL_SIZE, |
| 39 | }, |
| 40 | TextColor(Color::WHITE), |
| 41 | Visibility::Hidden, |
| 42 | Transform::from_xyz(0.0, 0.0, 20.0), |
| 43 | )); |
| 44 | } |
| 45 | |
| 46 | |
| 47 | pub(crate) fn track_cost(length: f32) -> i64 { |
| 48 | (length * TRACK_COST_PER_UNIT as f32) as i64 |
| 49 | } |
| 50 | |
| 51 | |
| 52 | pub(crate) fn segments_cost(segs: &[TrackSeg]) -> i64 { |
| 53 | segs.iter().map(|s| track_cost(s.length)).sum() |
| 54 | } |
| 55 | |
| 56 | |
| 57 | const ON_TRACK_RADIUS: f32 = 30.0; |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | pub(crate) fn new_segments(net: &Network, from: NodeId, to: NodeId) -> Vec<TrackSeg> { |
| 66 | if from == to || net.track_between(from, to).is_some() { |
| 67 | return Vec::new(); |
| 68 | } |
| 69 | let a = net.nodes[from.0].pos; |
| 70 | let d = net.nodes[to.0].pos - a; |
| 71 | let len2 = d.length_squared(); |
| 72 | let mut mids: Vec<(f32, NodeId)> = Vec::new(); |
| 73 | if len2 > 0.0 { |
| 74 | for (i, node) in net.nodes.iter().enumerate() { |
| 75 | let id = NodeId(i); |
| 76 | if id == from || id == to { |
| 77 | continue; |
| 78 | } |
| 79 | let t = (node.pos - a).dot(d) / len2; |
| 80 | if t > 0.0 && t < 1.0 && node.pos.distance(a + d * t) <= ON_TRACK_RADIUS { |
| 81 | mids.push((t, id)); |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | mids.sort_by(|x, y| x.0.total_cmp(&y.0)); |
| 86 | |
| 87 | let mut chain = vec![from]; |
| 88 | chain.extend(mids.into_iter().map(|(_, id)| id)); |
| 89 | chain.push(to); |
| 90 | let mut segs = Vec::new(); |
| 91 | for link in chain.windows(2) { |
| 92 | let (x, y) = (link[0], link[1]); |
| 93 | match net.track_between(x, y) { |
| 94 | |
| 95 | Some(i) if net.tracks[i].condition < MIN_USABLE_CONDITION => return Vec::new(), |
| 96 | Some(_) => {} |
| 97 | None => segs.push(TrackSeg { |
| 98 | a: x, |
| 99 | b: y, |
| 100 | length: net.nodes[x.0].pos.distance(net.nodes[y.0].pos), |
| 101 | condition: 1.0, |
| 102 | }), |
| 103 | } |
| 104 | } |
| 105 | segs |
| 106 | } |
| 107 | |
| 108 | |
| 109 | fn track_name(net: &Network, seg: &TrackSeg) -> String { |
| 110 | format!("{}-{}", net.nodes[seg.a.0].name, net.nodes[seg.b.0].name) |
| 111 | } |
| 112 | |
| 113 | fn handle_node_clicks( |
| 114 | mut clicks: MessageReader<NodeClicked>, |
| 115 | mut tool: ResMut<Tool>, |
| 116 | mut net: ResMut<Network>, |
| 117 | mut treasury: ResMut<Treasury>, |
| 118 | mut notify: MessageWriter<Notify>, |
| 119 | mut sounds: MessageWriter<SoundEvent>, |
| 120 | ) { |
| 121 | for &NodeClicked(n) in clicks.read() { |
| 122 | let Tool::BuildTrack { from } = tool.as_mut() else { |
| 123 | continue; |
| 124 | }; |
| 125 | match *from { |
| 126 | None => *from = Some(n), |
| 127 | Some(f) if f == n => *from = None, |
| 128 | Some(f) => { |
| 129 | let segs = new_segments(&net, f, n); |
| 130 | let cost = segments_cost(&segs); |
| 131 | if segs.is_empty() { |
| 132 | let msg = if net.track_between(f, n).is_some() { |
| 133 | "Track already exists" |
| 134 | } else { |
| 135 | "No new track to lay" |
| 136 | }; |
| 137 | notify.write(Notify(msg.into())); |
| 138 | } else if treasury.0 >= cost { |
| 139 | let name = format!("{}-{}", net.nodes[f.0].name, net.nodes[n.0].name); |
| 140 | net.tracks.extend(segs); |
| 141 | treasury.0 -= cost; |
| 142 | notify.write(Notify(format!("Laid track {name} for ${cost}"))); |
| 143 | sounds.write(SoundEvent::TrackLaid); |
| 144 | } else { |
| 145 | notify.write(Notify(format!("Not enough funds (${cost} needed)"))); |
| 146 | } |
| 147 | |
| 148 | *from = Some(n); |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | fn handle_track_clicks( |
| 155 | mut clicks: MessageReader<TrackClicked>, |
| 156 | tool: Res<Tool>, |
| 157 | mut net: ResMut<Network>, |
| 158 | mut treasury: ResMut<Treasury>, |
| 159 | mut notify: MessageWriter<Notify>, |
| 160 | mut sounds: MessageWriter<SoundEvent>, |
| 161 | ) { |
| 162 | for &TrackClicked(i) in clicks.read() { |
| 163 | let Some(seg) = net.tracks.get(i).copied() else { |
| 164 | continue; |
| 165 | }; |
| 166 | match tool.as_ref() { |
| 167 | Tool::Repair => repair_track(i, &mut net, &mut treasury, &mut notify, &mut sounds), |
| 168 | |
| 169 | Tool::Inspect if seg.condition < 1.0 => { |
| 170 | repair_track(i, &mut net, &mut treasury, &mut notify, &mut sounds) |
| 171 | } |
| 172 | _ => {} |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | |
| 178 | fn repair_track( |
| 179 | i: usize, |
| 180 | net: &mut Network, |
| 181 | treasury: &mut Treasury, |
| 182 | notify: &mut MessageWriter<Notify>, |
| 183 | sounds: &mut MessageWriter<SoundEvent>, |
| 184 | ) { |
| 185 | let seg = net.tracks[i]; |
| 186 | let name = track_name(net, &seg); |
| 187 | if seg.condition >= 1.0 { |
| 188 | notify.write(Notify("Track is intact".into())); |
| 189 | } else if treasury.0 >= REPAIR_COST { |
| 190 | net.tracks[i].condition = 1.0; |
| 191 | treasury.0 -= REPAIR_COST; |
| 192 | notify.write(Notify(format!("Repaired {name} (-${REPAIR_COST})"))); |
| 193 | sounds.write(SoundEvent::TrackLaid); |
| 194 | } else { |
| 195 | notify.write(Notify("Not enough funds".into())); |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | |
| 200 | #[allow( |
| 201 | clippy::too_many_arguments, |
| 202 | reason = "Bevy system: one parameter per resource and query" |
| 203 | )] |
| 204 | fn build_preview( |
| 205 | tool: Res<Tool>, |
| 206 | net: Res<Network>, |
| 207 | treasury: Res<Treasury>, |
| 208 | hover: Res<MapHover>, |
| 209 | windows: Query<&Window, With<PrimaryWindow>>, |
| 210 | cameras: Query<(&Camera, &GlobalTransform), With<Camera2d>>, |
| 211 | mut gizmos: Gizmos, |
| 212 | mut labels: Query< |
| 213 | (&mut Text2d, &mut TextColor, &mut Transform, &mut Visibility), |
| 214 | With<BuildCostLabel>, |
| 215 | >, |
| 216 | ) { |
| 217 | let Ok((mut text, mut color, mut transform, mut visibility)) = labels.single_mut() else { |
| 218 | return; |
| 219 | }; |
| 220 | |
| 221 | let Tool::BuildTrack { from: Some(f) } = tool.as_ref() else { |
| 222 | *visibility = Visibility::Hidden; |
| 223 | return; |
| 224 | }; |
| 225 | let f = *f; |
| 226 | |
| 227 | let cursor_world = windows |
| 228 | .single() |
| 229 | .ok() |
| 230 | .and_then(|w| w.cursor_position()) |
| 231 | .and_then(|cursor| { |
| 232 | let (camera, gt) = cameras.single().ok()?; |
| 233 | camera.viewport_to_world_2d(gt, cursor).ok() |
| 234 | }); |
| 235 | let (Some(cursor_world), Some(from_node)) = (cursor_world, net.nodes.get(f.0)) else { |
| 236 | *visibility = Visibility::Hidden; |
| 237 | return; |
| 238 | }; |
| 239 | let from_pos = from_node.pos; |
| 240 | |
| 241 | let snapped = net.node_at(cursor_world, SNAP_RADIUS * hover.world_per_px); |
| 242 | let target = match snapped { |
| 243 | Some(n) => net.nodes[n.0].pos, |
| 244 | None => cursor_world, |
| 245 | }; |
| 246 | |
| 247 | let on_origin = snapped == Some(f); |
| 248 | |
| 249 | let segs = match snapped { |
| 250 | Some(n) if !on_origin => Some(new_segments(&net, f, n)), |
| 251 | _ => None, |
| 252 | }; |
| 253 | |
| 254 | let (label, label_color) = if on_origin { |
| 255 | |
| 256 | ( |
| 257 | "Click again to cancel".to_string(), |
| 258 | Color::srgb(0.35, 0.35, 0.35), |
| 259 | ) |
| 260 | } else if matches!(&segs, Some(s) if s.is_empty()) { |
| 261 | ( |
| 262 | "Track already exists".to_string(), |
| 263 | Color::srgb(0.8, 0.1, 0.1), |
| 264 | ) |
| 265 | } else { |
| 266 | let cost = match &segs { |
| 267 | Some(segs) => segments_cost(segs), |
| 268 | None => track_cost(from_pos.distance(target)), |
| 269 | }; |
| 270 | let color = if treasury.0 >= cost { |
| 271 | Color::srgb(0.1, 0.5, 0.1) |
| 272 | } else { |
| 273 | Color::srgb(0.8, 0.1, 0.1) |
| 274 | }; |
| 275 | |
| 276 | let prefix = if snapped.is_some() { "" } else { "~" }; |
| 277 | (format!("{prefix}${cost}"), color) |
| 278 | }; |
| 279 | |
| 280 | |
| 281 | match &segs { |
| 282 | Some(segs) if !segs.is_empty() => { |
| 283 | for s in segs { |
| 284 | draw_dashed( |
| 285 | &mut gizmos, |
| 286 | net.nodes[s.a.0].pos, |
| 287 | net.nodes[s.b.0].pos, |
| 288 | Color::srgba(0.2, 0.15, 0.1, 0.8), |
| 289 | ); |
| 290 | } |
| 291 | } |
| 292 | _ if !on_origin => draw_dashed( |
| 293 | &mut gizmos, |
| 294 | from_pos, |
| 295 | target, |
| 296 | Color::srgba(0.2, 0.15, 0.1, 0.8), |
| 297 | ), |
| 298 | _ => {} |
| 299 | } |
| 300 | |
| 301 | if text.0 != label { |
| 302 | text.0 = label; |
| 303 | } |
| 304 | *color = TextColor(label_color); |
| 305 | transform.translation = Vec3::new(target.x + 14.0, target.y + 14.0, 20.0); |
| 306 | *visibility = Visibility::Visible; |
| 307 | } |
| 308 | |
| 309 | fn draw_dashed(gizmos: &mut Gizmos<'_, '_>, from: Vec2, to: Vec2, color: Color) { |
| 310 | let delta = to - from; |
| 311 | let len = delta.length(); |
| 312 | if len <= 0.0 { |
| 313 | return; |
| 314 | } |
| 315 | let dir = delta / len; |
| 316 | let mut s = 0.0; |
| 317 | while s < len { |
| 318 | let e = (s + DASH_LEN).min(len); |
| 319 | gizmos.line_2d(from + dir * s, from + dir * e, color); |
| 320 | s += DASH_LEN + GAP_LEN; |
| 321 | } |
| 322 | } |