//! Self-playing narrated demo, active only with `--demo`. //! //! A scripted bot plays the real game. It sets the same `Tool` and writes the //! same `NodeClicked` and `TrackClicked` messages a mouse would, and it confirms //! routes the way the route editor does. Captions explain each step. With //! `--record` the run ends four seconds after the last caption, and the screenshot //! recorder in `scenario.rs` writes the frames. use std::collections::VecDeque; use bevy::app::AppExit; use bevy::ecs::change_detection::Mut; use bevy::prelude::*; use bevy::time::{Real, Time}; use bevy::ui::Display; use crate::audio::SoundEvent; use crate::build::track_cost; use crate::front::{FrontRuntime, air_raid, reset_game}; use crate::hud::BOTTOM_H; use crate::menu::{Menu, MenuScreen}; use crate::model::{ Network, NodeClicked, NodeId, NodeKind, Notify, REPAIR_COST, Selected, SimClock, Tool, CarKind, LocoKind, TrackClicked, Train, Treasury, consist_cost, }; /// Captions stay at least this long (real seconds), longer for longer text. const CAPTION_MIN_SECS: f64 = 4.0; const CAPTION_SECS_PER_CHAR: f64 = 0.05; /// Gap between the subtitle box and the bottom strip. const SUBTITLE_GAP: f32 = 12.0; /// Side margin of the subtitle box, from the window edge. const SUBTITLE_MARGIN: f32 = 16.0; /// Real seconds to wait for a natural air raid before forcing one. At 4x a game day /// passes in about 3 real seconds, so a long wait lets the unsupplied South Sector collapse. const RAID_WAIT_SECS: f64 = 8.0; /// Real seconds allowed for a money wait or a budget wait before moving on. const WAIT_TIMEOUT_SECS: f64 = 150.0; /// One weekly budget, in game hours. const WEEK_HOURS: u32 = 24 * 7; /// Adds the narrated demo bot and its caption box. pub struct DemoPlugin { /// End the run when the script ends (used with `--record`). pub exit_when_done: bool, } impl Plugin for DemoPlugin { fn build(&self, app: &mut App) { app.insert_resource(Captions::default()) .insert_resource(Script { steps: build_steps(), wait: None, exit_when_done: self.exit_when_done, done: false, }) .add_systems(Startup, spawn_subtitle) .add_systems(Update, (advance_captions, update_subtitle).chain()) .add_systems(Update, run_script); } } /// Captions waiting to be shown, and the one on screen now. #[derive(Resource, Default)] struct Captions { queue: VecDeque, current: Option, /// Real seconds when `current` appeared, and how long it stays. shown_at: f64, hold: f64, } impl Captions { fn idle(&self) -> bool { self.queue.is_empty() && self.current.is_none() } } fn hold_secs(text: &str) -> f64 { (text.chars().count() as f64 * CAPTION_SECS_PER_CHAR).max(CAPTION_MIN_SECS) } fn advance_captions(time: Res>, mut captions: ResMut) { let now = time.elapsed_secs_f64(); if captions.current.is_some() { if now - captions.shown_at < captions.hold { return; } captions.current = None; } if let Some(next) = captions.queue.pop_front() { captions.hold = hold_secs(&next); captions.shown_at = now; captions.current = Some(next); } } #[derive(Component)] struct SubtitleRoot; #[derive(Component)] struct SubtitleText; /// The caption box sits above the bottom strip, centred, and above the menus. fn spawn_subtitle(mut commands: Commands) { commands.spawn(( SubtitleRoot, Node { position_type: PositionType::Absolute, left: Val::Px(SUBTITLE_MARGIN), right: Val::Px(SUBTITLE_MARGIN), bottom: Val::Px(BOTTOM_H + SUBTITLE_GAP), justify_content: JustifyContent::Center, display: Display::None, ..default() }, GlobalZIndex(300), children![( Node { max_width: Val::Vw(60.0), padding: UiRect::axes(Val::Px(14.0), Val::Px(9.0)), ..default() }, BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.72)), children![( SubtitleText, Text::new(""), TextFont { font_size: FontSize::Px(22.0), ..default() }, TextColor(Color::WHITE), TextLayout::justify(Justify::Center), )], )], )); } fn update_subtitle( captions: Res, mut roots: Query<&mut Node, With>, mut texts: Query<&mut Text, With>, ) { let shown = captions.current.as_deref(); let display = if shown.is_some() { Display::Flex } else { Display::None }; for mut node in &mut roots { if node.display != display { node.display = display; } } let want = shown.unwrap_or(""); for mut text in &mut texts { if text.0 != want { text.0 = want.to_string(); } } } type Act = Box; type Check = Box bool + Send + Sync>; /// One scripted step. The script runs them in order. enum Step { /// Queue a caption and wait until it has been read. Say(String), /// Wait this many real seconds. Pause(f64), /// Run game code once. Act(Act), /// Wait until the check passes, or until the timeout (real seconds) runs out. Until(Check, f64), } enum Wait { /// Real time (elapsed seconds) to wait until. Pause(f64), /// Check to pass, and the real time after which the wait ends anyway. Until(Check, f64), } #[derive(Resource)] struct Script { steps: VecDeque, wait: Option, exit_when_done: bool, done: bool, } fn act(f: impl Fn(&mut World) + Send + Sync + 'static) -> Step { Step::Act(Box::new(f)) } fn until(f: impl Fn(&World) -> bool + Send + Sync + 'static, timeout: f64) -> Step { Step::Until(Box::new(f), timeout) } fn say(text: impl Into) -> Step { Step::Say(text.into()) } fn pause(secs: f64) -> Step { Step::Pause(secs) } /// Runs the script. Exclusive, so steps can change any resource and write messages. fn run_script(world: &mut World) { let now = world.resource::>().elapsed_secs_f64(); loop { let taken = world.resource_mut::