//! Opening tutorial that teaches by pointing. Arrows and pulsing rings are drawn on the map //! with a short caption each, and the player's own drags move the tutorial along. //! //! The steps are: send Ammo, Food and Troops into the Centre Sector by dragging from a source //! node to it, then supply the North and South Sectors for a few seconds. The tutorial is //! skipped in the scenario and demo runs. use std::f32::consts::TAU; use bevy::ecs::system::SystemParam; use bevy::prelude::*; use bevy::time::{Real, Time}; use crate::map::WorldText; use crate::menu::Menu; use crate::model::{Network, NodeId, Train}; const INK: Color = Color::srgb(0.22, 0.15, 0.09); const RUST: Color = Color::srgb(0.66, 0.26, 0.12); /// Glyph size of the captions, in world units. const CAPTION_SIZE: f32 = 30.0; /// Average advance of the caption font in ems, to estimate its width before layout. const CAPTION_CHAR_EM: f32 = 0.6; /// Gap between the target node centre and the caption's right edge, clear of the node icon /// and the arrow head. const CAPTION_NODE_GAP: f32 = 40.0; /// How far below the target a step's caption sits. Keeps it off the node name label above /// the node and off the arrow shaft coming in from the left. const CAPTION_DROP: f32 = 20.0; /// Caption centres are kept this far inside the map frame, in world units. The frame is /// 1280 by 720, so the x limit leaves a margin at each side. const CAPTION_X_LIMIT: f32 = 560.0; const CAPTION_Y_LIMIT: f32 = 340.0; /// Radius of the pulsing ring around a node, at rest. const RING_RADIUS: f32 = 26.0; /// Seconds per pulse of the rings. const PULSE_PERIOD: f32 = 1.2; /// Distance from the source centre where the arrow starts, clear of its ring. const ARROW_START_GAP: f32 = 32.0; /// Distance from the target centre where the arrow tip sits, clear of the node icon. const ARROW_TIP_GAP: f32 = 26.0; /// Length of the arrowhead. const ARROW_HEAD_LEN: f32 = 18.0; /// Half the width of the arrowhead base. const ARROW_HEAD_HALF_W: f32 = 9.0; /// Spacing between the parallel lines that make the shaft thick. const SHAFT_LINE_STEP: f32 = 1.2; /// Number of parallel lines on each side of the shaft centre line. const SHAFT_LINES: i32 = 2; /// World units per real second the dashes and chevrons travel. const FLOW_SPEED: f32 = 42.0; /// Length of a dash and the gap after it. const DASH_ON: f32 = 14.0; const DASH_PERIOD: f32 = 22.0; /// Distance between chevrons along the shaft. const CHEVRON_PERIOD: f32 = 66.0; /// Size of a chevron's arms. const CHEVRON_ARM: f32 = 6.0; /// Real seconds the supply step lasts. const SUPPLY_SECONDS: f32 = 8.0; /// One arrow step: drag from `from` to `to` to send what `from` makes. struct Lesson { from: &'static str, to: &'static str, caption: &'static str, } const LESSONS: [Lesson; 3] = [ Lesson { from: "Ostwerk", to: "Centre Sector", caption: "Drag: send Ammo", }, Lesson { from: "Lindach", to: "Centre Sector", caption: "Drag: send Food", }, Lesson { from: "Varenholm", to: "Centre Sector", caption: "Drag: send Troops", }, ]; const SUPPLY_NODES: [&str; 2] = ["North Sector", "South Sector"]; const SUPPLY_CAPTION: &str = "Now supply these"; pub struct TutorialPlugin { /// False in the scenario and demo runs, which have their own script. pub enabled: bool, } impl Plugin for TutorialPlugin { fn build(&self, app: &mut App) { if !self.enabled { return; } app.init_resource::() .add_systems(Update, run_tutorial); } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Stage { /// Index into `LESSONS`. Send(usize), Supply, Done, } #[derive(Resource)] struct Tutorial { stage: Stage, /// Stage whose caption is currently on screen. shown: Option, caption: Option, /// Real seconds left in the supply step. supply_left: f32, } impl Default for Tutorial { fn default() -> Self { Self { stage: Stage::Send(0), shown: None, caption: None, supply_left: SUPPLY_SECONDS, } } } /// Marker for the caption text of the current step. #[derive(Component)] struct TutorialCaption; enum Body { Arrow(Vec2, Vec2), Rings(Vec), } struct Shape { caption: &'static str, /// Centre of the caption in world units. anchor: Vec2, body: Body, } /// Centre for a caption placed to the left of `target`, `drop` below its height. The result /// is clamped so the whole caption stays inside the map frame. fn caption_anchor(target: Vec2, caption: &str, drop: f32) -> Vec2 { let half_w = caption.chars().count() as f32 * CAPTION_CHAR_EM * CAPTION_SIZE * 0.5; let x = (target.x - CAPTION_NODE_GAP - half_w) .clamp(-CAPTION_X_LIMIT + half_w, CAPTION_X_LIMIT - half_w); let y = (target.y - drop).clamp(-CAPTION_Y_LIMIT, CAPTION_Y_LIMIT); Vec2::new(x, y) } fn node_named(net: &Network, name: &str) -> Option<(NodeId, Vec2)> { net.nodes .iter() .enumerate() .find(|(_, n)| n.name == name) .map(|(i, n)| (NodeId(i), n.pos)) } /// True when some train's route visits both nodes. fn sent(trains: &Query<&Train>, a: NodeId, b: NodeId) -> bool { trains.iter().any(|t| { t.route.iter().any(|s| s.node == a) && t.route.iter().any(|s| s.node == b) }) } /// What to draw for a stage, or `None` when its nodes are not on the map. fn shape_for(stage: Stage, net: &Network) -> Option { match stage { Stage::Send(i) => { let lesson = &LESSONS[i]; let (_, a) = node_named(net, lesson.from)?; let (_, b) = node_named(net, lesson.to)?; Some(Shape { caption: lesson.caption, anchor: caption_anchor(b, lesson.caption, CAPTION_DROP), body: Body::Arrow(a, b), }) } Stage::Supply => { let points = SUPPLY_NODES .iter() .map(|name| node_named(net, name).map(|(_, p)| p)) .collect::>>()?; // Beside the northernmost sector, so the caption sits on no node. let top = points.iter().copied().max_by(|a, b| a.y.total_cmp(&b.y))?; Some(Shape { caption: SUPPLY_CAPTION, anchor: caption_anchor(top, SUPPLY_CAPTION, 0.0), body: Body::Rings(points), }) } Stage::Done => None, } } fn clear_caption(commands: &mut Commands, tut: &mut Tutorial) { if let Some(entity) = tut.caption.take() { commands.entity(entity).despawn(); } tut.shown = None; } /// What the tutorial reads and draws, grouped to keep the system signature short. #[derive(SystemParam)] struct TutorialParams<'w, 's> { net: Res<'w, Network>, trains: Query<'w, 's, &'static Train>, time: Res<'w, Time>, menu: Res<'w, Menu>, gizmos: Gizmos<'w, 's>, captions: Query<'w, 's, &'static mut Visibility, With>, } fn run_tutorial(mut commands: Commands, mut tut: ResMut, p: TutorialParams) { let TutorialParams { net, trains, time, menu, mut gizmos, mut captions, } = p; // The tutorial waits behind any open menu, so captions hide and the clock stops. let open = menu.is_open(); for mut visibility in &mut captions { *visibility = if open { Visibility::Hidden } else { Visibility::Visible }; } if open { return; } // Advance once the goal of the current step is met. let next = match tut.stage { Stage::Send(i) => match ( node_named(&net, LESSONS[i].from), node_named(&net, LESSONS[i].to), ) { (Some((a, _)), Some((b, _))) if sent(&trains, a, b) => Some(if i + 1 < LESSONS.len() { Stage::Send(i + 1) } else { Stage::Supply }), _ => None, }, Stage::Supply | Stage::Done => None, }; if let Some(stage) = next { tut.stage = stage; if stage == Stage::Supply { tut.supply_left = SUPPLY_SECONDS; } } if tut.stage == Stage::Supply { tut.supply_left -= time.delta_secs(); if tut.supply_left <= 0.0 { tut.stage = Stage::Done; } } let Some(shape) = shape_for(tut.stage, &net) else { clear_caption(&mut commands, &mut tut); return; }; if tut.shown != Some(tut.stage) { clear_caption(&mut commands, &mut tut); let entity = commands .spawn(( TutorialCaption, Text2d(shape.caption.to_string()), WorldText { size: CAPTION_SIZE, }, TextColor(INK), TextLayout::justify(Justify::Center), Transform::from_xyz(shape.anchor.x, shape.anchor.y, 2.0), Visibility::Visible, )) .id(); tut.caption = Some(entity); tut.shown = Some(tut.stage); } let t = time.elapsed_secs(); match shape.body { Body::Arrow(from, to) => { draw_arrow(&mut gizmos, from, to, t); draw_ring(&mut gizmos, from, t); } Body::Rings(points) => { for p in points { draw_ring(&mut gizmos, p, t); } } } } /// Pulsing ring that marks where to grab or where to supply. fn draw_ring(gizmos: &mut Gizmos, center: Vec2, t: f32) { let pulse = (t * TAU / PULSE_PERIOD).sin() * 0.5 + 0.5; let r = RING_RADIUS + pulse * 4.0; let iso = Isometry2d::from_translation(center); gizmos.circle_2d(iso, r, RUST); gizmos.circle_2d(iso, r + 1.5, RUST); } /// Thick dashed shaft with chevrons flowing from `from` to `to`, and a filled head at `to`. fn draw_arrow(gizmos: &mut Gizmos, from: Vec2, to: Vec2, t: f32) { let delta = to - from; let length = delta.length(); if length <= ARROW_START_GAP + ARROW_TIP_GAP + ARROW_HEAD_LEN { return; } let dir = delta / length; let perp = dir.perp(); let start = from + dir * ARROW_START_GAP; let tip = to - dir * ARROW_TIP_GAP; let shaft_end = tip - dir * ARROW_HEAD_LEN; let shaft_len = (shaft_end - start).length(); // Dashes, drawn as several parallel lines so the shaft reads as thick. let dash_phase = (t * FLOW_SPEED).rem_euclid(DASH_PERIOD); for k in -SHAFT_LINES..=SHAFT_LINES { let off = perp * (k as f32 * SHAFT_LINE_STEP); let mut s = dash_phase - DASH_PERIOD; while s < shaft_len { let a = s.max(0.0); let b = (s + DASH_ON).min(shaft_len); if b > a { gizmos.line_2d(start + dir * a + off, start + dir * b + off, RUST); } s += DASH_PERIOD; } } // Chevrons moving along the shaft in the direction of travel. let chevron_phase = (t * FLOW_SPEED).rem_euclid(CHEVRON_PERIOD); let mut p = chevron_phase; while p < shaft_len { let c = start + dir * p; gizmos.line_2d(c - dir * CHEVRON_ARM + perp * CHEVRON_ARM, c, RUST); gizmos.line_2d(c - dir * CHEVRON_ARM - perp * CHEVRON_ARM, c, RUST); p += CHEVRON_PERIOD; } // Filled head: fan of lines from the tip across the base. let base = shaft_end; for i in -6..=6 { let off = perp * (i as f32 * ARROW_HEAD_HALF_W / 6.0); gizmos.line_2d(tip, base + off, RUST); } }