forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

settings.rs383 lines, 12.2 KiBHistoryRawDownload
1//! Player settings, stored as `settings.toml` in the platform config directory.
2//!
3//! The settings drive the primary window, the FPS limit and the performance
4//! overlay. The settings menu changes them through `save`.
5
6use std::fs;
7use std::io::ErrorKind;
8use std::path::{Path, PathBuf};
9use std::time::{Duration, Instant};
10
11use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
12use bevy::prelude::*;
13use bevy::ui::{Display, UiScale};
14use bevy::window::{MonitorSelection, PresentMode, PrimaryWindow, VideoModeSelection, WindowMode};
15use serde::{Deserialize, Serialize};
16
17use crate::hud::TOP_H;
18use crate::model::UiPassThrough;
19
20const PERF_TEXT: Color = Color::srgb(0.55, 0.52, 0.45);
21/// Left of the [?] button at the right end of the top bar (14 px inset, ~34 px wide, 16 px gap).
22const PERF_RIGHT: f32 = 64.0;
23/// Smallest window side accepted from the file. Anything smaller is replaced by the default.
24const MIN_SIDE: u32 = 320;
25/// Window height at which the UI is drawn at scale 1.0. Layout and text are sized for it.
26const UI_REFERENCE_HEIGHT: f32 = 720.0;
27/// Limits on the UI scale, so tiny windows stay usable and huge ones stay sane.
28const MIN_UI_SCALE: f32 = 0.75;
29const MAX_UI_SCALE: f32 = 4.0;
30/// Limits on the text size setting.
31const MIN_TEXT_SIZE: f32 = 0.8;
32const MAX_TEXT_SIZE: f32 = 2.0;
33
34#[derive(Resource, Serialize, Deserialize, Clone, PartialEq, Debug, Default)]
35#[serde(default)]
36pub struct Settings {
37 pub display: DisplaySettings,
38 pub audio: AudioSettings,
39}
40
41#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
42#[serde(default)]
43pub struct DisplaySettings {
44 /// Window size in logical pixels.
45 pub resolution: [u32; 2],
46 pub window_mode: WindowModeSetting,
47 pub vsync: bool,
48 /// Frames per second. 0 means unlimited.
49 pub fps_limit: u32,
50 pub show_performance: bool,
51 /// Multiplier on all text and UI size, on top of the window-height scale.
52 pub text_size: f32,
53}
54
55impl Default for DisplaySettings {
56 fn default() -> Self {
57 DisplaySettings {
58 resolution: [1280, 720],
59 window_mode: WindowModeSetting::Windowed,
60 vsync: true,
61 fps_limit: 0,
62 show_performance: false,
63 text_size: 1.0,
64 }
65 }
66}
67
68#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
69#[serde(rename_all = "lowercase")]
70pub enum WindowModeSetting {
71 #[default]
72 Windowed,
73 Borderless,
74 Fullscreen,
75}
76
77#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
78#[serde(default)]
79pub struct AudioSettings {
80 /// 0..1 volume multipliers.
81 pub master: f32,
82 pub effects: f32,
83 pub ambient: f32,
84 pub muted: bool,
85}
86
87impl Default for AudioSettings {
88 fn default() -> Self {
89 AudioSettings {
90 master: 0.8,
91 effects: 1.0,
92 ambient: 0.6,
93 muted: false,
94 }
95 }
96}
97
98impl Settings {
99 /// Replaces values the game cannot use with defaults or clamps them into range.
100 fn sanitized(mut self) -> Self {
101 let [w, h] = self.display.resolution;
102 if w < MIN_SIDE || h < MIN_SIDE {
103 self.display.resolution = DisplaySettings::default().resolution;
104 }
105 let text_size = self.display.text_size;
106 self.display.text_size = if text_size.is_finite() {
107 text_size.clamp(MIN_TEXT_SIZE, MAX_TEXT_SIZE)
108 } else {
109 DisplaySettings::default().text_size
110 };
111 let audio = &mut self.audio;
112 audio.master = audio.master.clamp(0.0, 1.0);
113 audio.effects = audio.effects.clamp(0.0, 1.0);
114 audio.ambient = audio.ambient.clamp(0.0, 1.0);
115 self
116 }
117}
118
119/// Where the settings file lives, e.g. `~/.config/iron_lifeline/settings.toml` on Linux.
120pub fn settings_path() -> Option<PathBuf> {
121 directories::ProjectDirs::from("", "", "iron_lifeline")
122 .map(|dirs| dirs.config_dir().join("settings.toml"))
123}
124
125/// Reads the settings file at startup.
126///
127/// A missing or broken file gives the defaults and writes a fresh file. The
128/// returned warning, if any, is for the caller to log. This never panics.
129pub fn load() -> (Settings, Option<String>) {
130 let Some(path) = settings_path() else {
131 return (
132 Settings::default(),
133 Some("no config directory found; settings will not be saved".to_string()),
134 );
135 };
136 match fs::read_to_string(&path) {
137 Ok(text) => match toml::from_str::<Settings>(&text) {
138 Ok(settings) => (settings.sanitized(), None),
139 Err(err) => {
140 let defaults = Settings::default();
141 let mut warning = format!(
142 "settings file {} is broken ({err}); using defaults",
143 path.display()
144 );
145 if let Err(write_err) = save_to(&path, &defaults) {
146 warning = format!("{warning}; {write_err}");
147 }
148 (defaults, Some(warning))
149 }
150 },
151 Err(err) if err.kind() == ErrorKind::NotFound => {
152 let defaults = Settings::default();
153 let warning = save_to(&path, &defaults).err();
154 (defaults, warning)
155 }
156 Err(err) => (
157 Settings::default(),
158 Some(format!("cannot read {}: {err}", path.display())),
159 ),
160 }
161}
162
163fn save_to(path: &Path, settings: &Settings) -> Result<(), String> {
164 let text = toml::to_string_pretty(settings)
165 .map_err(|err| format!("cannot encode settings: {err}"))?;
166 if let Some(dir) = path.parent() {
167 fs::create_dir_all(dir)
168 .map_err(|err| format!("cannot create {}: {err}", dir.display()))?;
169 }
170 fs::write(path, text).map_err(|err| format!("cannot write {}: {err}", path.display()))
171}
172
173/// Writes the settings file. A failure is logged and never fatal.
174pub fn save(settings: &Settings) {
175 let Some(path) = settings_path() else {
176 return;
177 };
178 if let Err(err) = save_to(&path, settings) {
179 warn!("{err}");
180 }
181}
182
183/// Applies display settings to a window: size, window mode and vsync.
184pub fn configure_window(display: &DisplaySettings, window: &mut Window) {
185 let [w, h] = display.resolution;
186 window.resolution.set(w as f32, h as f32);
187 window.mode = match display.window_mode {
188 WindowModeSetting::Windowed => WindowMode::Windowed,
189 WindowModeSetting::Borderless => {
190 WindowMode::BorderlessFullscreen(MonitorSelection::Current)
191 }
192 WindowModeSetting::Fullscreen => WindowMode::Fullscreen(
193 MonitorSelection::Current,
194 VideoModeSelection::Current,
195 ),
196 };
197 window.present_mode = if display.vsync {
198 PresentMode::AutoVsync
199 } else {
200 PresentMode::AutoNoVsync
201 };
202}
203
204/// The primary window at startup, already sized and moded from the settings.
205pub fn initial_window(display: &DisplaySettings) -> Window {
206 let mut window = Window {
207 title: "Iron Lifeline".into(),
208 ..default()
209 };
210 configure_window(display, &mut window);
211 // The window does not exist yet, so `Current` has no monitor to resolve; use the primary one.
212 if let WindowMode::BorderlessFullscreen(_) | WindowMode::Fullscreen(..) = window.mode {
213 window.mode = match display.window_mode {
214 WindowModeSetting::Fullscreen => WindowMode::Fullscreen(
215 MonitorSelection::Primary,
216 VideoModeSelection::Current,
217 ),
218 _ => WindowMode::BorderlessFullscreen(MonitorSelection::Primary),
219 };
220 }
221 window
222}
223
224/// Settings-driven behaviour: window, FPS limit and the performance overlay.
225pub struct SettingsPlugin {
226 /// A problem found by `load`, logged once at startup.
227 pub load_warning: Option<String>,
228}
229
230impl Plugin for SettingsPlugin {
231 fn build(&self, app: &mut App) {
232 if !app.is_plugin_added::<FrameTimeDiagnosticsPlugin>() {
233 app.add_plugins(FrameTimeDiagnosticsPlugin::default());
234 }
235 app.insert_resource(LoadWarning(self.load_warning.clone()))
236 .init_resource::<FrameStart>()
237 .add_systems(Startup, (report_load_warning, spawn_perf_overlay))
238 .add_systems(First, mark_frame_start)
239 .add_systems(Last, limit_fps)
240 .add_systems(Update, (apply_window, update_ui_scale, update_perf_overlay));
241 }
242}
243
244#[derive(Resource)]
245struct LoadWarning(Option<String>);
246
247fn report_load_warning(warning: Res<LoadWarning>) {
248 if let Some(text) = &warning.0 {
249 warn!("{text}");
250 }
251}
252
253fn apply_window(settings: Res<Settings>, mut windows: Query<&mut Window, With<PrimaryWindow>>) {
254 if !settings.is_changed() {
255 return;
256 }
257 for mut window in &mut windows {
258 configure_window(&settings.display, &mut window);
259 }
260}
261
262/// Scales all UI with the window height and the text size setting.
263///
264/// At 720 px high the UI is drawn at 1.0, so the layout keeps its proportions
265/// at any resolution. Runs every frame; it is a cheap comparison.
266fn update_ui_scale(
267 settings: Res<Settings>,
268 windows: Query<&Window, With<PrimaryWindow>>,
269 mut ui_scale: ResMut<UiScale>,
270) {
271 let Ok(window) = windows.single() else {
272 return;
273 };
274 let target = (window.height() / UI_REFERENCE_HEIGHT * settings.display.text_size)
275 .clamp(MIN_UI_SCALE, MAX_UI_SCALE);
276 if ui_scale.0 != target {
277 ui_scale.0 = target;
278 }
279}
280
281/// Start time of the current frame, taken at the top of `First`.
282#[derive(Resource, Default)]
283struct FrameStart(Option<Instant>);
284
285fn mark_frame_start(mut start: ResMut<FrameStart>) {
286 start.0 = Some(Instant::now());
287}
288
289/// Sleeps off the rest of the frame budget so frames take 1/fps seconds.
290fn limit_fps(settings: Res<Settings>, start: Res<FrameStart>) {
291 let fps = settings.display.fps_limit;
292 if fps == 0 {
293 return;
294 }
295 let Some(began) = start.0 else {
296 return;
297 };
298 let budget = Duration::from_secs_f64(1.0 / f64::from(fps));
299 let spent = began.elapsed();
300 if spent < budget {
301 std::thread::sleep(budget - spent);
302 }
303}
304
305#[derive(Component)]
306struct PerfRoot;
307
308#[derive(Component)]
309struct PerfText;
310
311/// Small dim text inside the top bar, left of the [?] button. Pass-through, so it never eats clicks.
312fn spawn_perf_overlay(mut commands: Commands) {
313 commands.spawn((
314 PerfRoot,
315 Node {
316 position_type: PositionType::Absolute,
317 top: Val::Px(0.0),
318 height: Val::Px(TOP_H),
319 right: Val::Px(PERF_RIGHT),
320 align_items: AlignItems::Center,
321 display: Display::None,
322 ..default()
323 },
324 GlobalZIndex(5),
325 UiPassThrough,
326 children![(
327 Text::new(""),
328 TextFont::from_font_size(12.0),
329 TextColor(PERF_TEXT),
330 PerfText,
331 )],
332 ));
333}
334
335fn update_perf_overlay(
336 settings: Res<Settings>,
337 diagnostics: Res<DiagnosticsStore>,
338 mut roots: Query<&mut Node, With<PerfRoot>>,
339 mut texts: Query<&mut Text, With<PerfText>>,
340) {
341 let show = settings.display.show_performance;
342 let target = if show { Display::Flex } else { Display::None };
343 for mut node in &mut roots {
344 if node.display != target {
345 node.display = target;
346 }
347 }
348 if !show {
349 return;
350 }
351 let fps = diagnostics
352 .get(&FrameTimeDiagnosticsPlugin::FPS)
353 .and_then(|d| d.smoothed())
354 .unwrap_or(0.0);
355 let frame_ms = diagnostics
356 .get(&FrameTimeDiagnosticsPlugin::FRAME_TIME)
357 .and_then(|d| d.smoothed())
358 .unwrap_or(0.0);
359 let line = format!("{fps:.0} FPS {frame_ms:.1} ms");
360 for mut text in &mut texts {
361 if text.0 != line {
362 text.0 = line.clone();
363 }
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 #[test]
372 fn partial_file_falls_back_to_defaults_and_round_trips() {
373 let settings: Settings =
374 toml::from_str("[display]\nvsync = false\n").expect("partial settings parse");
375 assert!(!settings.display.vsync);
376 assert_eq!(settings.display.resolution, [1280, 720]);
377 assert_eq!(settings.audio, AudioSettings::default());
378
379 let text = toml::to_string_pretty(&settings).expect("encode settings");
380 let back: Settings = toml::from_str(&text).expect("decode settings");
381 assert_eq!(back, settings);
382 }
383}