//! Player settings, stored as `settings.toml` in the platform config directory. //! //! The settings drive the primary window, the FPS limit and the performance //! overlay. The settings menu changes them through `save`. use std::fs; use std::io::ErrorKind; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin}; use bevy::prelude::*; use bevy::ui::{Display, UiScale}; use bevy::window::{MonitorSelection, PresentMode, PrimaryWindow, VideoModeSelection, WindowMode}; use serde::{Deserialize, Serialize}; use crate::hud::TOP_H; use crate::model::UiPassThrough; const PERF_TEXT: Color = Color::srgb(0.55, 0.52, 0.45); /// Left of the [?] button at the right end of the top bar (14 px inset, ~34 px wide, 16 px gap). const PERF_RIGHT: f32 = 64.0; /// Smallest window side accepted from the file. Anything smaller is replaced by the default. const MIN_SIDE: u32 = 320; /// Window height at which the UI is drawn at scale 1.0. Layout and text are sized for it. const UI_REFERENCE_HEIGHT: f32 = 720.0; /// Limits on the UI scale, so tiny windows stay usable and huge ones stay sane. const MIN_UI_SCALE: f32 = 0.75; const MAX_UI_SCALE: f32 = 4.0; /// Limits on the text size setting. const MIN_TEXT_SIZE: f32 = 0.8; const MAX_TEXT_SIZE: f32 = 2.0; #[derive(Resource, Serialize, Deserialize, Clone, PartialEq, Debug, Default)] #[serde(default)] pub struct Settings { pub display: DisplaySettings, pub audio: AudioSettings, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] #[serde(default)] pub struct DisplaySettings { /// Window size in logical pixels. pub resolution: [u32; 2], pub window_mode: WindowModeSetting, pub vsync: bool, /// Frames per second. 0 means unlimited. pub fps_limit: u32, pub show_performance: bool, /// Multiplier on all text and UI size, on top of the window-height scale. pub text_size: f32, } impl Default for DisplaySettings { fn default() -> Self { DisplaySettings { resolution: [1280, 720], window_mode: WindowModeSetting::Windowed, vsync: true, fps_limit: 0, show_performance: false, text_size: 1.0, } } } #[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)] #[serde(rename_all = "lowercase")] pub enum WindowModeSetting { #[default] Windowed, Borderless, Fullscreen, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] #[serde(default)] pub struct AudioSettings { /// 0..1 volume multipliers. pub master: f32, pub effects: f32, pub ambient: f32, pub muted: bool, } impl Default for AudioSettings { fn default() -> Self { AudioSettings { master: 0.8, effects: 1.0, ambient: 0.6, muted: false, } } } impl Settings { /// Replaces values the game cannot use with defaults or clamps them into range. fn sanitized(mut self) -> Self { let [w, h] = self.display.resolution; if w < MIN_SIDE || h < MIN_SIDE { self.display.resolution = DisplaySettings::default().resolution; } let text_size = self.display.text_size; self.display.text_size = if text_size.is_finite() { text_size.clamp(MIN_TEXT_SIZE, MAX_TEXT_SIZE) } else { DisplaySettings::default().text_size }; let audio = &mut self.audio; audio.master = audio.master.clamp(0.0, 1.0); audio.effects = audio.effects.clamp(0.0, 1.0); audio.ambient = audio.ambient.clamp(0.0, 1.0); self } } /// Where the settings file lives, e.g. `~/.config/iron_lifeline/settings.toml` on Linux. pub fn settings_path() -> Option { directories::ProjectDirs::from("", "", "iron_lifeline") .map(|dirs| dirs.config_dir().join("settings.toml")) } /// Reads the settings file at startup. /// /// A missing or broken file gives the defaults and writes a fresh file. The /// returned warning, if any, is for the caller to log. This never panics. pub fn load() -> (Settings, Option) { let Some(path) = settings_path() else { return ( Settings::default(), Some("no config directory found; settings will not be saved".to_string()), ); }; match fs::read_to_string(&path) { Ok(text) => match toml::from_str::(&text) { Ok(settings) => (settings.sanitized(), None), Err(err) => { let defaults = Settings::default(); let mut warning = format!( "settings file {} is broken ({err}); using defaults", path.display() ); if let Err(write_err) = save_to(&path, &defaults) { warning = format!("{warning}; {write_err}"); } (defaults, Some(warning)) } }, Err(err) if err.kind() == ErrorKind::NotFound => { let defaults = Settings::default(); let warning = save_to(&path, &defaults).err(); (defaults, warning) } Err(err) => ( Settings::default(), Some(format!("cannot read {}: {err}", path.display())), ), } } fn save_to(path: &Path, settings: &Settings) -> Result<(), String> { let text = toml::to_string_pretty(settings) .map_err(|err| format!("cannot encode settings: {err}"))?; if let Some(dir) = path.parent() { fs::create_dir_all(dir) .map_err(|err| format!("cannot create {}: {err}", dir.display()))?; } fs::write(path, text).map_err(|err| format!("cannot write {}: {err}", path.display())) } /// Writes the settings file. A failure is logged and never fatal. pub fn save(settings: &Settings) { let Some(path) = settings_path() else { return; }; if let Err(err) = save_to(&path, settings) { warn!("{err}"); } } /// Applies display settings to a window: size, window mode and vsync. pub fn configure_window(display: &DisplaySettings, window: &mut Window) { let [w, h] = display.resolution; window.resolution.set(w as f32, h as f32); window.mode = match display.window_mode { WindowModeSetting::Windowed => WindowMode::Windowed, WindowModeSetting::Borderless => { WindowMode::BorderlessFullscreen(MonitorSelection::Current) } WindowModeSetting::Fullscreen => WindowMode::Fullscreen( MonitorSelection::Current, VideoModeSelection::Current, ), }; window.present_mode = if display.vsync { PresentMode::AutoVsync } else { PresentMode::AutoNoVsync }; } /// The primary window at startup, already sized and moded from the settings. pub fn initial_window(display: &DisplaySettings) -> Window { let mut window = Window { title: "Iron Lifeline".into(), ..default() }; configure_window(display, &mut window); // The window does not exist yet, so `Current` has no monitor to resolve; use the primary one. if let WindowMode::BorderlessFullscreen(_) | WindowMode::Fullscreen(..) = window.mode { window.mode = match display.window_mode { WindowModeSetting::Fullscreen => WindowMode::Fullscreen( MonitorSelection::Primary, VideoModeSelection::Current, ), _ => WindowMode::BorderlessFullscreen(MonitorSelection::Primary), }; } window } /// Settings-driven behaviour: window, FPS limit and the performance overlay. pub struct SettingsPlugin { /// A problem found by `load`, logged once at startup. pub load_warning: Option, } impl Plugin for SettingsPlugin { fn build(&self, app: &mut App) { if !app.is_plugin_added::() { app.add_plugins(FrameTimeDiagnosticsPlugin::default()); } app.insert_resource(LoadWarning(self.load_warning.clone())) .init_resource::() .add_systems(Startup, (report_load_warning, spawn_perf_overlay)) .add_systems(First, mark_frame_start) .add_systems(Last, limit_fps) .add_systems(Update, (apply_window, update_ui_scale, update_perf_overlay)); } } #[derive(Resource)] struct LoadWarning(Option); fn report_load_warning(warning: Res) { if let Some(text) = &warning.0 { warn!("{text}"); } } fn apply_window(settings: Res, mut windows: Query<&mut Window, With>) { if !settings.is_changed() { return; } for mut window in &mut windows { configure_window(&settings.display, &mut window); } } /// Scales all UI with the window height and the text size setting. /// /// At 720 px high the UI is drawn at 1.0, so the layout keeps its proportions /// at any resolution. Runs every frame; it is a cheap comparison. fn update_ui_scale( settings: Res, windows: Query<&Window, With>, mut ui_scale: ResMut, ) { let Ok(window) = windows.single() else { return; }; let target = (window.height() / UI_REFERENCE_HEIGHT * settings.display.text_size) .clamp(MIN_UI_SCALE, MAX_UI_SCALE); if ui_scale.0 != target { ui_scale.0 = target; } } /// Start time of the current frame, taken at the top of `First`. #[derive(Resource, Default)] struct FrameStart(Option); fn mark_frame_start(mut start: ResMut) { start.0 = Some(Instant::now()); } /// Sleeps off the rest of the frame budget so frames take 1/fps seconds. fn limit_fps(settings: Res, start: Res) { let fps = settings.display.fps_limit; if fps == 0 { return; } let Some(began) = start.0 else { return; }; let budget = Duration::from_secs_f64(1.0 / f64::from(fps)); let spent = began.elapsed(); if spent < budget { std::thread::sleep(budget - spent); } } #[derive(Component)] struct PerfRoot; #[derive(Component)] struct PerfText; /// Small dim text inside the top bar, left of the [?] button. Pass-through, so it never eats clicks. fn spawn_perf_overlay(mut commands: Commands) { commands.spawn(( PerfRoot, Node { position_type: PositionType::Absolute, top: Val::Px(0.0), height: Val::Px(TOP_H), right: Val::Px(PERF_RIGHT), align_items: AlignItems::Center, display: Display::None, ..default() }, GlobalZIndex(5), UiPassThrough, children![( Text::new(""), TextFont::from_font_size(12.0), TextColor(PERF_TEXT), PerfText, )], )); } fn update_perf_overlay( settings: Res, diagnostics: Res, mut roots: Query<&mut Node, With>, mut texts: Query<&mut Text, With>, ) { let show = settings.display.show_performance; let target = if show { Display::Flex } else { Display::None }; for mut node in &mut roots { if node.display != target { node.display = target; } } if !show { return; } let fps = diagnostics .get(&FrameTimeDiagnosticsPlugin::FPS) .and_then(|d| d.smoothed()) .unwrap_or(0.0); let frame_ms = diagnostics .get(&FrameTimeDiagnosticsPlugin::FRAME_TIME) .and_then(|d| d.smoothed()) .unwrap_or(0.0); let line = format!("{fps:.0} FPS {frame_ms:.1} ms"); for mut text in &mut texts { if text.0 != line { text.0 = line.clone(); } } } #[cfg(test)] mod tests { use super::*; #[test] fn partial_file_falls_back_to_defaults_and_round_trips() { let settings: Settings = toml::from_str("[display]\nvsync = false\n").expect("partial settings parse"); assert!(!settings.display.vsync); assert_eq!(settings.display.resolution, [1280, 720]); assert_eq!(settings.audio, AudioSettings::default()); let text = toml::to_string_pretty(&settings).expect("encode settings"); let back: Settings = toml::from_str(&text).expect("decode settings"); assert_eq!(back, settings); } }