forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

build.rs322 lines, 10.3 KiBHistoryRawDownload
1use bevy::prelude::*;
2use bevy::window::PrimaryWindow;
3
4use crate::audio::SoundEvent;
5use crate::map::{MapHover, WorldText};
6use crate::model::{
7 MIN_USABLE_CONDITION, Network, NodeClicked, NodeId, Notify, REPAIR_COST, TRACK_COST_PER_UNIT,
8 Tool, TrackClicked, TrackSeg, Treasury,
9};
10
11pub struct BuildPlugin;
12
13impl 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/// Logical pixels within which the cursor snaps to a node.
23const SNAP_RADIUS: f32 = 24.0;
24/// Cost label glyph size in world units (see `map::WorldText`).
25const COST_LABEL_SIZE: f32 = 27.0;
26/// Dash and gap lengths of the preview line, in world units.
27const DASH_LEN: f32 = 12.0;
28const GAP_LEN: f32 = 8.0;
29
30#[derive(Component)]
31struct BuildCostLabel;
32
33fn 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/// Cost of a track of the given length, in dollars.
47pub(crate) fn track_cost(length: f32) -> i64 {
48 (length * TRACK_COST_PER_UNIT as f32) as i64
49}
50
51/// Cost of laying the given track segments, in dollars.
52pub(crate) fn segments_cost(segs: &[TrackSeg]) -> i64 {
53 segs.iter().map(|s| track_cost(s.length)).sum()
54}
55
56/// A node within this many world units of a straight track counts as lying on it.
57const ON_TRACK_RADIUS: f32 = 30.0;
58
59/// The new segments that make a straight track from `from` to `to`.
60///
61/// The line is split at every node it passes within `ON_TRACK_RADIUS`, so the track
62/// connects there instead of running past it. Segments that already exist are left
63/// out. Empty when nothing new would be laid: the pair is already linked directly,
64/// or a link on the way is cut and must be repaired first.
65pub(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 // A cut link on the way blocks the whole line.
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/// "A-B" using the node names of a track.
109fn track_name(net: &Network, seg: &TrackSeg) -> String {
110 format!("{}-{}", net.nodes[seg.a.0].name, net.nodes[seg.b.0].name)
111}
112
113fn 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 // Keep chaining from the node just clicked.
148 *from = Some(n);
149 }
150 }
151 }
152}
153
154fn 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 // Inspect is the default mode: a click on a damaged track repairs it, an intact one does nothing.
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/// Repairs track `i` to full condition if the treasury can pay for it, otherwise says why not.
178fn 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/// Draws the dashed track preview and the cost label while laying track.
200#[allow(
201 clippy::too_many_arguments,
202 reason = "Bevy system: one parameter per resource and query"
203)]
204fn 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 // Snapped to another node: the exact new segments, split at any node the line passes.
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 // Hovering the origin node: clicking it again cancels.
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 // Off-node cursor: the cost is only an estimate from the cursor distance.
276 let prefix = if snapped.is_some() { "" } else { "~" };
277 (format!("{prefix}${cost}"), color)
278 };
279
280 // Draw each new segment; otherwise the straight dashed preview, unless on the origin.
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
309fn 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}