forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

tutorial.rs366 lines, 11.5 KiBHistoryRawDownload
1//! Opening tutorial that teaches by pointing. Arrows and pulsing rings are drawn on the map
2//! with a short caption each, and the player's own drags move the tutorial along.
3//!
4//! The steps are: send Ammo, Food and Troops into the Centre Sector by dragging from a source
5//! node to it, then supply the North and South Sectors for a few seconds. The tutorial is
6//! skipped in the scenario and demo runs.
7
8use std::f32::consts::TAU;
9
10use bevy::ecs::system::SystemParam;
11use bevy::prelude::*;
12use bevy::time::{Real, Time};
13
14use crate::map::WorldText;
15use crate::menu::Menu;
16use crate::model::{Network, NodeId, Train};
17
18const INK: Color = Color::srgb(0.22, 0.15, 0.09);
19const RUST: Color = Color::srgb(0.66, 0.26, 0.12);
20
21/// Glyph size of the captions, in world units.
22const CAPTION_SIZE: f32 = 30.0;
23/// Average advance of the caption font in ems, to estimate its width before layout.
24const CAPTION_CHAR_EM: f32 = 0.6;
25/// Gap between the target node centre and the caption's right edge, clear of the node icon
26/// and the arrow head.
27const CAPTION_NODE_GAP: f32 = 40.0;
28/// How far below the target a step's caption sits. Keeps it off the node name label above
29/// the node and off the arrow shaft coming in from the left.
30const CAPTION_DROP: f32 = 20.0;
31/// Caption centres are kept this far inside the map frame, in world units. The frame is
32/// 1280 by 720, so the x limit leaves a margin at each side.
33const CAPTION_X_LIMIT: f32 = 560.0;
34const CAPTION_Y_LIMIT: f32 = 340.0;
35/// Radius of the pulsing ring around a node, at rest.
36const RING_RADIUS: f32 = 26.0;
37/// Seconds per pulse of the rings.
38const PULSE_PERIOD: f32 = 1.2;
39/// Distance from the source centre where the arrow starts, clear of its ring.
40const ARROW_START_GAP: f32 = 32.0;
41/// Distance from the target centre where the arrow tip sits, clear of the node icon.
42const ARROW_TIP_GAP: f32 = 26.0;
43/// Length of the arrowhead.
44const ARROW_HEAD_LEN: f32 = 18.0;
45/// Half the width of the arrowhead base.
46const ARROW_HEAD_HALF_W: f32 = 9.0;
47/// Spacing between the parallel lines that make the shaft thick.
48const SHAFT_LINE_STEP: f32 = 1.2;
49/// Number of parallel lines on each side of the shaft centre line.
50const SHAFT_LINES: i32 = 2;
51/// World units per real second the dashes and chevrons travel.
52const FLOW_SPEED: f32 = 42.0;
53/// Length of a dash and the gap after it.
54const DASH_ON: f32 = 14.0;
55const DASH_PERIOD: f32 = 22.0;
56/// Distance between chevrons along the shaft.
57const CHEVRON_PERIOD: f32 = 66.0;
58/// Size of a chevron's arms.
59const CHEVRON_ARM: f32 = 6.0;
60/// Real seconds the supply step lasts.
61const SUPPLY_SECONDS: f32 = 8.0;
62
63/// One arrow step: drag from `from` to `to` to send what `from` makes.
64struct Lesson {
65 from: &'static str,
66 to: &'static str,
67 caption: &'static str,
68}
69
70const LESSONS: [Lesson; 3] = [
71 Lesson {
72 from: "Ostwerk",
73 to: "Centre Sector",
74 caption: "Drag: send Ammo",
75 },
76 Lesson {
77 from: "Lindach",
78 to: "Centre Sector",
79 caption: "Drag: send Food",
80 },
81 Lesson {
82 from: "Varenholm",
83 to: "Centre Sector",
84 caption: "Drag: send Troops",
85 },
86];
87
88const SUPPLY_NODES: [&str; 2] = ["North Sector", "South Sector"];
89const SUPPLY_CAPTION: &str = "Now supply these";
90
91pub struct TutorialPlugin {
92 /// False in the scenario and demo runs, which have their own script.
93 pub enabled: bool,
94}
95
96impl Plugin for TutorialPlugin {
97 fn build(&self, app: &mut App) {
98 if !self.enabled {
99 return;
100 }
101 app.init_resource::<Tutorial>()
102 .add_systems(Update, run_tutorial);
103 }
104}
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107enum Stage {
108 /// Index into `LESSONS`.
109 Send(usize),
110 Supply,
111 Done,
112}
113
114#[derive(Resource)]
115struct Tutorial {
116 stage: Stage,
117 /// Stage whose caption is currently on screen.
118 shown: Option<Stage>,
119 caption: Option<Entity>,
120 /// Real seconds left in the supply step.
121 supply_left: f32,
122}
123
124impl Default for Tutorial {
125 fn default() -> Self {
126 Self {
127 stage: Stage::Send(0),
128 shown: None,
129 caption: None,
130 supply_left: SUPPLY_SECONDS,
131 }
132 }
133}
134
135/// Marker for the caption text of the current step.
136#[derive(Component)]
137struct TutorialCaption;
138
139enum Body {
140 Arrow(Vec2, Vec2),
141 Rings(Vec<Vec2>),
142}
143
144struct Shape {
145 caption: &'static str,
146 /// Centre of the caption in world units.
147 anchor: Vec2,
148 body: Body,
149}
150
151/// Centre for a caption placed to the left of `target`, `drop` below its height. The result
152/// is clamped so the whole caption stays inside the map frame.
153fn caption_anchor(target: Vec2, caption: &str, drop: f32) -> Vec2 {
154 let half_w = caption.chars().count() as f32 * CAPTION_CHAR_EM * CAPTION_SIZE * 0.5;
155 let x = (target.x - CAPTION_NODE_GAP - half_w)
156 .clamp(-CAPTION_X_LIMIT + half_w, CAPTION_X_LIMIT - half_w);
157 let y = (target.y - drop).clamp(-CAPTION_Y_LIMIT, CAPTION_Y_LIMIT);
158 Vec2::new(x, y)
159}
160
161fn node_named(net: &Network, name: &str) -> Option<(NodeId, Vec2)> {
162 net.nodes
163 .iter()
164 .enumerate()
165 .find(|(_, n)| n.name == name)
166 .map(|(i, n)| (NodeId(i), n.pos))
167}
168
169/// True when some train's route visits both nodes.
170fn sent(trains: &Query<&Train>, a: NodeId, b: NodeId) -> bool {
171 trains.iter().any(|t| {
172 t.route.iter().any(|s| s.node == a) && t.route.iter().any(|s| s.node == b)
173 })
174}
175
176/// What to draw for a stage, or `None` when its nodes are not on the map.
177fn shape_for(stage: Stage, net: &Network) -> Option<Shape> {
178 match stage {
179 Stage::Send(i) => {
180 let lesson = &LESSONS[i];
181 let (_, a) = node_named(net, lesson.from)?;
182 let (_, b) = node_named(net, lesson.to)?;
183 Some(Shape {
184 caption: lesson.caption,
185 anchor: caption_anchor(b, lesson.caption, CAPTION_DROP),
186 body: Body::Arrow(a, b),
187 })
188 }
189 Stage::Supply => {
190 let points = SUPPLY_NODES
191 .iter()
192 .map(|name| node_named(net, name).map(|(_, p)| p))
193 .collect::<Option<Vec<Vec2>>>()?;
194 // Beside the northernmost sector, so the caption sits on no node.
195 let top = points.iter().copied().max_by(|a, b| a.y.total_cmp(&b.y))?;
196 Some(Shape {
197 caption: SUPPLY_CAPTION,
198 anchor: caption_anchor(top, SUPPLY_CAPTION, 0.0),
199 body: Body::Rings(points),
200 })
201 }
202 Stage::Done => None,
203 }
204}
205
206fn clear_caption(commands: &mut Commands, tut: &mut Tutorial) {
207 if let Some(entity) = tut.caption.take() {
208 commands.entity(entity).despawn();
209 }
210 tut.shown = None;
211}
212
213/// What the tutorial reads and draws, grouped to keep the system signature short.
214#[derive(SystemParam)]
215struct TutorialParams<'w, 's> {
216 net: Res<'w, Network>,
217 trains: Query<'w, 's, &'static Train>,
218 time: Res<'w, Time<Real>>,
219 menu: Res<'w, Menu>,
220 gizmos: Gizmos<'w, 's>,
221 captions: Query<'w, 's, &'static mut Visibility, With<TutorialCaption>>,
222}
223
224fn run_tutorial(mut commands: Commands, mut tut: ResMut<Tutorial>, p: TutorialParams) {
225 let TutorialParams {
226 net,
227 trains,
228 time,
229 menu,
230 mut gizmos,
231 mut captions,
232 } = p;
233 // The tutorial waits behind any open menu, so captions hide and the clock stops.
234 let open = menu.is_open();
235 for mut visibility in &mut captions {
236 *visibility = if open {
237 Visibility::Hidden
238 } else {
239 Visibility::Visible
240 };
241 }
242 if open {
243 return;
244 }
245
246 // Advance once the goal of the current step is met.
247 let next = match tut.stage {
248 Stage::Send(i) => match (
249 node_named(&net, LESSONS[i].from),
250 node_named(&net, LESSONS[i].to),
251 ) {
252 (Some((a, _)), Some((b, _))) if sent(&trains, a, b) => Some(if i + 1 < LESSONS.len() {
253 Stage::Send(i + 1)
254 } else {
255 Stage::Supply
256 }),
257 _ => None,
258 },
259 Stage::Supply | Stage::Done => None,
260 };
261 if let Some(stage) = next {
262 tut.stage = stage;
263 if stage == Stage::Supply {
264 tut.supply_left = SUPPLY_SECONDS;
265 }
266 }
267 if tut.stage == Stage::Supply {
268 tut.supply_left -= time.delta_secs();
269 if tut.supply_left <= 0.0 {
270 tut.stage = Stage::Done;
271 }
272 }
273
274 let Some(shape) = shape_for(tut.stage, &net) else {
275 clear_caption(&mut commands, &mut tut);
276 return;
277 };
278
279 if tut.shown != Some(tut.stage) {
280 clear_caption(&mut commands, &mut tut);
281 let entity = commands
282 .spawn((
283 TutorialCaption,
284 Text2d(shape.caption.to_string()),
285 WorldText {
286 size: CAPTION_SIZE,
287 },
288 TextColor(INK),
289 TextLayout::justify(Justify::Center),
290 Transform::from_xyz(shape.anchor.x, shape.anchor.y, 2.0),
291 Visibility::Visible,
292 ))
293 .id();
294 tut.caption = Some(entity);
295 tut.shown = Some(tut.stage);
296 }
297
298 let t = time.elapsed_secs();
299 match shape.body {
300 Body::Arrow(from, to) => {
301 draw_arrow(&mut gizmos, from, to, t);
302 draw_ring(&mut gizmos, from, t);
303 }
304 Body::Rings(points) => {
305 for p in points {
306 draw_ring(&mut gizmos, p, t);
307 }
308 }
309 }
310}
311
312/// Pulsing ring that marks where to grab or where to supply.
313fn draw_ring(gizmos: &mut Gizmos, center: Vec2, t: f32) {
314 let pulse = (t * TAU / PULSE_PERIOD).sin() * 0.5 + 0.5;
315 let r = RING_RADIUS + pulse * 4.0;
316 let iso = Isometry2d::from_translation(center);
317 gizmos.circle_2d(iso, r, RUST);
318 gizmos.circle_2d(iso, r + 1.5, RUST);
319}
320
321/// Thick dashed shaft with chevrons flowing from `from` to `to`, and a filled head at `to`.
322fn draw_arrow(gizmos: &mut Gizmos, from: Vec2, to: Vec2, t: f32) {
323 let delta = to - from;
324 let length = delta.length();
325 if length <= ARROW_START_GAP + ARROW_TIP_GAP + ARROW_HEAD_LEN {
326 return;
327 }
328 let dir = delta / length;
329 let perp = dir.perp();
330 let start = from + dir * ARROW_START_GAP;
331 let tip = to - dir * ARROW_TIP_GAP;
332 let shaft_end = tip - dir * ARROW_HEAD_LEN;
333 let shaft_len = (shaft_end - start).length();
334
335 // Dashes, drawn as several parallel lines so the shaft reads as thick.
336 let dash_phase = (t * FLOW_SPEED).rem_euclid(DASH_PERIOD);
337 for k in -SHAFT_LINES..=SHAFT_LINES {
338 let off = perp * (k as f32 * SHAFT_LINE_STEP);
339 let mut s = dash_phase - DASH_PERIOD;
340 while s < shaft_len {
341 let a = s.max(0.0);
342 let b = (s + DASH_ON).min(shaft_len);
343 if b > a {
344 gizmos.line_2d(start + dir * a + off, start + dir * b + off, RUST);
345 }
346 s += DASH_PERIOD;
347 }
348 }
349
350 // Chevrons moving along the shaft in the direction of travel.
351 let chevron_phase = (t * FLOW_SPEED).rem_euclid(CHEVRON_PERIOD);
352 let mut p = chevron_phase;
353 while p < shaft_len {
354 let c = start + dir * p;
355 gizmos.line_2d(c - dir * CHEVRON_ARM + perp * CHEVRON_ARM, c, RUST);
356 gizmos.line_2d(c - dir * CHEVRON_ARM - perp * CHEVRON_ARM, c, RUST);
357 p += CHEVRON_PERIOD;
358 }
359
360 // Filled head: fan of lines from the tip across the base.
361 let base = shaft_end;
362 for i in -6..=6 {
363 let off = perp * (i as f32 * ARROW_HEAD_HALF_W / 6.0);
364 gizmos.line_2d(tip, base + off, RUST);
365 }
366}