Skip to main content

voxel_framework/
settings.rs

1//! Persistent user settings saved to `worlds/{world_name}/settings.json`.
2//!
3//! [`PersistedSettings`] holds the four in-game slider values (FOV, SFX
4//! volume, render distance, mouse sensitivity).
5//!
6//! [`SettingsPlugin`] does the whole job for one world: it applies the saved
7//! file to the configuration resources at startup and writes the file when the
8//! player leaves the Settings menu.
9//!
10//! # By hand
11//!
12//! A game with its own rules can read and write the file itself:
13//!
14//! ```rust,no_run
15//! use voxel_framework::settings::PersistedSettings;
16//!
17//! // Save
18//! let settings = PersistedSettings {
19//!     fov_degrees: 90.0,
20//!     sfx_volume: 0.8,
21//!     render_distance_chunks: 10,
22//!     sensitivity_pct: 100,
23//! };
24//! settings.save("my_world");
25//!
26//! // Load
27//! if let Some(saved) = PersistedSettings::load("my_world") {
28//!     println!("Loaded FOV: {}", saved.fov_degrees);
29//! }
30//! ```
31
32use std::path::{Path, PathBuf};
33
34use bevy::prelude::*;
35use serde::{Deserialize, Serialize};
36
37use crate::audio::SfxConfig;
38use crate::player::PlayerConfig;
39use crate::ui::SaveSettingsRequest;
40use crate::world::{ChunkManager, WorldConfig};
41
42/// World units of load distance per render-distance step of the settings
43/// menu. One step is one chunk.
44pub const RENDER_DISTANCE_STEP: f32 = 16.0;
45
46/// How far beyond the load distance chunks are kept when the render distance
47/// comes from the settings menu or from a settings file.
48pub const RENDER_DISTANCE_UNLOAD_MARGIN: f32 = 32.0;
49
50/// User-adjustable settings persisted to `worlds/{world_name}/settings.json`.
51///
52/// All four fields map directly to the in-game sliders exposed by
53/// [`crate::ui::PauseMenuPlugin`]:
54///
55/// | Field | Slider | Range |
56/// |-------|--------|-------|
57/// | `fov_degrees` | Field of View | 50–120 |
58/// | `sfx_volume` | SFX Volume | 0.0–1.0 |
59/// | `render_distance_chunks` | Render Distance | 4–32 (even) |
60/// | `sensitivity_pct` | Mouse Sensitivity | 10–100 |
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct PersistedSettings {
63    /// Vertical field-of-view in degrees. Valid range: `50.0`–`120.0`.
64    pub fov_degrees: f32,
65    /// SFX volume in the range `[0.0, 1.0]`.
66    pub sfx_volume: f32,
67    /// Render distance in chunks (even values only). Valid range: `4`–`32`.
68    pub render_distance_chunks: u32,
69    /// Mouse sensitivity as a percentage of the default.
70    /// `100` = default ("Minecraft-like" feel), `10` = slowest.
71    /// The underlying [`crate::player::Player::sensitivity`] multiplier is
72    /// `sensitivity_pct / 100`, combined internally with the hidden
73    /// `MOUSE_SCALE` constant (rad/px) to produce camera rotation per mouse
74    /// pixel.
75    pub sensitivity_pct: u32,
76}
77
78impl PersistedSettings {
79    /// Saves these settings to `worlds/{world_name}/settings.json`.
80    ///
81    /// Creates the directory if it does not exist. Silently ignores I/O errors
82    /// so that a read-only filesystem does not crash the game.
83    pub fn save(&self, world_name: &str) {
84        self.save_to(&settings_path(world_name));
85    }
86
87    /// Loads settings from `worlds/{world_name}/settings.json`.
88    ///
89    /// Returns `None` if the file does not exist or cannot be parsed (e.g. on
90    /// the first run before any settings have been saved).
91    pub fn load(world_name: &str) -> Option<Self> {
92        Self::load_from(&settings_path(world_name))
93    }
94
95    /// Saves these settings to the file at `path`.
96    ///
97    /// Creates the parent directory if it does not exist. Silently ignores
98    /// I/O errors, like [`save`](Self::save).
99    pub fn save_to(&self, path: &Path) {
100        if let Some(dir) = path.parent() {
101            let _ = std::fs::create_dir_all(dir);
102        }
103        if let Ok(json) = serde_json::to_string_pretty(self) {
104            let _ = std::fs::write(path, json);
105        }
106    }
107
108    /// Loads settings from the file at `path`.
109    ///
110    /// Returns `None` if the file does not exist or cannot be parsed.
111    pub fn load_from(path: &Path) -> Option<Self> {
112        let data = std::fs::read_to_string(path).ok()?;
113        serde_json::from_str(&data).ok()
114    }
115
116    /// Load distance in world units for the saved render distance, with the
117    /// chunk count limited to the menu range `4`–`32`.
118    pub fn load_distance(&self) -> f32 {
119        self.render_distance_chunks.clamp(4, 32) as f32 * RENDER_DISTANCE_STEP
120    }
121
122    /// Reads the four settings from the resources the settings menu edits.
123    ///
124    /// A missing resource contributes the default of its type. The render
125    /// distance is the load distance in whole chunks, limited to `4`–`32`.
126    pub fn capture(
127        player: Option<&PlayerConfig>,
128        world: Option<&WorldConfig>,
129        sfx: Option<&SfxConfig>,
130    ) -> Self {
131        let default_player = PlayerConfig::default();
132        let player = player.unwrap_or(&default_player);
133        let load_distance = world.map_or(WorldConfig::default().load_distance, |w| w.load_distance);
134        let volume = sfx.map_or(SfxConfig::default().volume, |s| s.volume);
135        Self {
136            fov_degrees: player.fov_degrees,
137            sfx_volume: volume,
138            render_distance_chunks: ((load_distance / RENDER_DISTANCE_STEP).round() as i64)
139                .clamp(4, 32) as u32,
140            sensitivity_pct: ((player.sensitivity * 100.0).round() as i64).clamp(10, 100) as u32,
141        }
142    }
143
144    /// Writes these settings to the resources the settings menu edits.
145    ///
146    /// Every value is limited to the range documented on its field first; a
147    /// field of view or volume that is not a finite number is skipped.
148    ///
149    /// The render distance is written to [`WorldConfig`] and [`ChunkManager`]
150    /// only when it differs from the load distance already configured. The
151    /// unload distance then becomes the load distance plus
152    /// [`RENDER_DISTANCE_UNLOAD_MARGIN`]. A saved value equal to the
153    /// configured one leaves a custom unload distance as it is.
154    pub fn apply(
155        &self,
156        player: Option<&mut PlayerConfig>,
157        world: Option<&mut WorldConfig>,
158        manager: Option<&mut ChunkManager>,
159        sfx: Option<&mut SfxConfig>,
160    ) {
161        if let Some(player) = player {
162            if self.fov_degrees.is_finite() {
163                player.fov_degrees = self.fov_degrees.clamp(50.0, 120.0);
164            }
165            player.sensitivity = self.sensitivity_pct.clamp(10, 100) as f32 / 100.0;
166        }
167        if let Some(sfx) = sfx
168            && self.sfx_volume.is_finite()
169        {
170            sfx.volume = self.sfx_volume.clamp(0.0, 1.0);
171        }
172
173        let load = self.load_distance();
174        let unload = load + RENDER_DISTANCE_UNLOAD_MARGIN;
175        let configured = match (&world, &manager) {
176            (Some(world), _) => Some(world.load_distance),
177            (None, Some(manager)) => Some(manager.load_distance),
178            (None, None) => None,
179        };
180        if configured == Some(load) {
181            return;
182        }
183        if let Some(world) = world {
184            world.load_distance = load;
185            world.unload_distance = unload;
186        }
187        if let Some(manager) = manager {
188            manager.load_distance = load;
189            manager.unload_distance = unload;
190        }
191    }
192}
193
194fn settings_path(world_name: &str) -> PathBuf {
195    PathBuf::from(format!("worlds/{world_name}/settings.json"))
196}
197
198// ─── SettingsPlugin ───────────────────────────────────────────────────────────
199
200/// The file [`SettingsPlugin`] reads at startup and writes on
201/// [`SaveSettingsRequest`].
202///
203/// [`SettingsPlugin::with_world`] inserts it as
204/// `worlds/{world_name}/settings.json`. Replace the resource to keep the file
205/// somewhere else.
206#[derive(Resource, Debug, Clone, PartialEq, Eq)]
207pub struct SettingsFile {
208    /// Path of the settings file.
209    pub path: PathBuf,
210}
211
212impl SettingsFile {
213    /// The settings file of a world: `worlds/{world_name}/settings.json`.
214    pub fn for_world(world_name: &str) -> Self {
215        Self {
216            path: settings_path(world_name),
217        }
218    }
219}
220
221/// System sets of [`SettingsPlugin`].
222#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
223pub enum SettingsSystems {
224    /// `Startup`: the saved file is applied to the configuration resources.
225    /// Runs after the `world.toml` load of `WorldConfigPlugin` and before
226    /// [`spawn_player`](crate::player::spawn_player). Order your own startup
227    /// systems after this set when they read the configured values.
228    Load,
229    /// `Update`: the file is written when a [`SaveSettingsRequest`] arrives.
230    Save,
231}
232
233/// Loads and saves the settings of the pause menu for one world.
234///
235/// The settings menu of [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin) edits
236/// four values and writes [`SaveSettingsRequest`] when the player leaves it.
237/// This plugin is the other half: it applies the saved file at startup and
238/// writes the file on that request. The game only names the world.
239///
240/// ```rust,no_run
241/// use bevy::prelude::*;
242/// use voxel_framework::prelude::*;
243///
244/// App::new()
245///     .add_plugins(PauseMenuPlugin)
246///     .add_plugins(SettingsPlugin::with_world("my_world"));
247/// ```
248///
249/// # At startup
250///
251/// [`load_settings_system`] reads the file and writes its values to
252/// [`PlayerConfig`], [`WorldConfig`], [`ChunkManager`] and [`SfxConfig`], each
253/// only when the resource exists. See [`PersistedSettings::apply`] for the
254/// limits and for how the unload distance is treated. A missing or unreadable
255/// file leaves every configured value untouched.
256///
257/// # On `SaveSettingsRequest`
258///
259/// [`save_settings_system`] writes [`PersistedSettings::capture`] of the
260/// current resources to the file. Any system may write the request; it does
261/// not have to come from the pause menu.
262///
263/// The plugin is opt-in and no bundle adds it. It does not add the pause
264/// menu, and it works without it.
265pub struct SettingsPlugin {
266    world_name: String,
267}
268
269impl SettingsPlugin {
270    /// Settings stored in `worlds/{world_name}/settings.json`.
271    pub fn with_world(world_name: impl Into<String>) -> Self {
272        Self {
273            world_name: world_name.into(),
274        }
275    }
276}
277
278impl Plugin for SettingsPlugin {
279    fn build(&self, app: &mut App) {
280        app.insert_resource(SettingsFile::for_world(&self.world_name));
281        // The pause menu registers it too; this plugin must run without it.
282        app.add_message::<SaveSettingsRequest>();
283        app.add_systems(
284            Startup,
285            load_settings_system
286                .in_set(SettingsSystems::Load)
287                .after(crate::world::config::load_world_config)
288                .before(crate::player::spawn_player),
289        );
290        app.add_systems(Update, save_settings_system.in_set(SettingsSystems::Save));
291    }
292}
293
294/// Applies the saved settings file to the configuration resources.
295///
296/// Added by [`SettingsPlugin`] in `Startup`, in [`SettingsSystems::Load`].
297pub fn load_settings_system(
298    file: Res<SettingsFile>,
299    mut player: Option<ResMut<PlayerConfig>>,
300    mut world: Option<ResMut<WorldConfig>>,
301    mut manager: Option<ResMut<ChunkManager>>,
302    mut sfx: Option<ResMut<SfxConfig>>,
303) {
304    let Some(saved) = PersistedSettings::load_from(&file.path) else {
305        return;
306    };
307    saved.apply(
308        player.as_deref_mut(),
309        world.as_deref_mut(),
310        manager.as_deref_mut(),
311        sfx.as_deref_mut(),
312    );
313}
314
315/// Writes the settings file when a [`SaveSettingsRequest`] arrives.
316///
317/// Added by [`SettingsPlugin`] in `Update`, in [`SettingsSystems::Save`].
318/// Several requests in one frame write the file once.
319pub fn save_settings_system(
320    mut requests: MessageReader<SaveSettingsRequest>,
321    file: Res<SettingsFile>,
322    player: Option<Res<PlayerConfig>>,
323    world: Option<Res<WorldConfig>>,
324    sfx: Option<Res<SfxConfig>>,
325) {
326    if requests.read().count() == 0 {
327        return;
328    }
329    PersistedSettings::capture(player.as_deref(), world.as_deref(), sfx.as_deref())
330        .save_to(&file.path);
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    fn saved() -> PersistedSettings {
338        PersistedSettings {
339            fov_degrees: 75.0,
340            sfx_volume: 0.4,
341            render_distance_chunks: 12,
342            sensitivity_pct: 60,
343        }
344    }
345
346    /// App with the four resources at their defaults and the plugin pointed
347    /// at a file inside `dir`.
348    fn settings_app(dir: &Path) -> App {
349        let mut app = App::new();
350        app.add_plugins(MinimalPlugins)
351            .init_resource::<PlayerConfig>()
352            .init_resource::<WorldConfig>()
353            .init_resource::<ChunkManager>()
354            .init_resource::<SfxConfig>()
355            .add_plugins(SettingsPlugin::with_world("unused"))
356            .insert_resource(SettingsFile {
357                path: dir.join("settings.json"),
358            });
359        app
360    }
361
362    #[test]
363    fn the_file_of_a_world_is_inside_its_world_directory() {
364        assert_eq!(
365            SettingsFile::for_world("alpha").path,
366            PathBuf::from("worlds/alpha/settings.json")
367        );
368    }
369
370    #[test]
371    fn a_saved_file_is_applied_at_startup() {
372        let dir = tempfile::tempdir().unwrap();
373        saved().save_to(&dir.path().join("settings.json"));
374        let mut app = settings_app(dir.path());
375
376        app.update();
377
378        let player = app.world().resource::<PlayerConfig>();
379        assert_eq!(player.fov_degrees, 75.0);
380        assert!((player.sensitivity - 0.6).abs() < 1e-6);
381        assert_eq!(app.world().resource::<SfxConfig>().volume, 0.4);
382        let world = app.world().resource::<WorldConfig>();
383        assert_eq!(world.load_distance, 192.0);
384        assert_eq!(world.unload_distance, 224.0);
385        let manager = app.world().resource::<ChunkManager>();
386        assert_eq!(manager.load_distance, 192.0);
387        assert_eq!(manager.unload_distance, 224.0);
388    }
389
390    #[test]
391    fn a_missing_file_leaves_the_configuration_untouched() {
392        let dir = tempfile::tempdir().unwrap();
393        let mut app = settings_app(dir.path());
394        app.world_mut().resource_mut::<PlayerConfig>().fov_degrees = 101.0;
395
396        app.update();
397
398        assert_eq!(app.world().resource::<PlayerConfig>().fov_degrees, 101.0);
399        let defaults = WorldConfig::default();
400        let world = app.world().resource::<WorldConfig>();
401        assert_eq!(world.load_distance, defaults.load_distance);
402        assert_eq!(world.unload_distance, defaults.unload_distance);
403    }
404
405    #[test]
406    fn an_unreadable_file_leaves_the_configuration_untouched() {
407        let dir = tempfile::tempdir().unwrap();
408        std::fs::write(dir.path().join("settings.json"), b"{ not json").unwrap();
409        let mut app = settings_app(dir.path());
410
411        app.update();
412
413        assert_eq!(
414            app.world().resource::<PlayerConfig>().fov_degrees,
415            PlayerConfig::default().fov_degrees
416        );
417    }
418
419    #[test]
420    fn values_outside_the_menu_ranges_are_limited() {
421        let mut player = PlayerConfig::default();
422        let mut sfx = SfxConfig::default();
423        let mut world = WorldConfig::default();
424        PersistedSettings {
425            fov_degrees: 500.0,
426            sfx_volume: -3.0,
427            render_distance_chunks: 1000,
428            sensitivity_pct: 0,
429        }
430        .apply(Some(&mut player), Some(&mut world), None, Some(&mut sfx));
431
432        assert_eq!(player.fov_degrees, 120.0);
433        assert!((player.sensitivity - 0.1).abs() < 1e-6);
434        assert_eq!(sfx.volume, 0.0);
435        assert_eq!(world.load_distance, 32.0 * RENDER_DISTANCE_STEP);
436    }
437
438    #[test]
439    fn values_that_are_not_numbers_are_skipped() {
440        let mut player = PlayerConfig::default();
441        let mut sfx = SfxConfig::default();
442        PersistedSettings {
443            fov_degrees: f32::NAN,
444            sfx_volume: f32::INFINITY,
445            ..saved()
446        }
447        .apply(Some(&mut player), None, None, Some(&mut sfx));
448
449        assert_eq!(player.fov_degrees, PlayerConfig::default().fov_degrees);
450        assert_eq!(sfx.volume, SfxConfig::default().volume);
451    }
452
453    #[test]
454    fn a_render_distance_equal_to_the_configured_one_keeps_the_unload_distance() {
455        let mut world = WorldConfig {
456            load_distance: 192.0,
457            unload_distance: 400.0,
458            ..default()
459        };
460        let mut manager = ChunkManager::new(192.0, 400.0);
461
462        saved().apply(None, Some(&mut world), Some(&mut manager), None);
463
464        assert_eq!(world.unload_distance, 400.0);
465        assert_eq!(manager.unload_distance, 400.0);
466    }
467
468    #[test]
469    fn a_save_request_writes_the_current_values() {
470        let dir = tempfile::tempdir().unwrap();
471        let mut app = settings_app(dir.path());
472        app.update();
473        assert!(!dir.path().join("settings.json").exists());
474
475        {
476            let world = app.world_mut();
477            world.resource_mut::<PlayerConfig>().fov_degrees = 85.0;
478            world.resource_mut::<PlayerConfig>().sensitivity = 0.35;
479            world.resource_mut::<SfxConfig>().volume = 0.7;
480            world.resource_mut::<WorldConfig>().load_distance = 20.0 * RENDER_DISTANCE_STEP;
481            world.write_message(SaveSettingsRequest);
482        }
483        app.update();
484
485        let written = PersistedSettings::load_from(&dir.path().join("settings.json")).unwrap();
486        assert_eq!(written.fov_degrees, 85.0);
487        assert_eq!(written.sfx_volume, 0.7);
488        assert_eq!(written.render_distance_chunks, 20);
489        assert_eq!(written.sensitivity_pct, 35);
490    }
491
492    #[test]
493    fn what_is_saved_is_what_the_next_start_loads() {
494        let dir = tempfile::tempdir().unwrap();
495        let mut first = settings_app(dir.path());
496        first.update();
497        first.world_mut().resource_mut::<PlayerConfig>().fov_degrees = 65.0;
498        first.world_mut().write_message(SaveSettingsRequest);
499        first.update();
500
501        let mut second = settings_app(dir.path());
502        second.update();
503
504        assert_eq!(second.world().resource::<PlayerConfig>().fov_degrees, 65.0);
505    }
506
507    #[test]
508    fn the_plugin_runs_without_the_pause_menu_and_without_the_resources() {
509        let dir = tempfile::tempdir().unwrap();
510        saved().save_to(&dir.path().join("settings.json"));
511        let mut app = App::new();
512        app.add_plugins(MinimalPlugins)
513            .add_plugins(SettingsPlugin::with_world("unused"))
514            .insert_resource(SettingsFile {
515                path: dir.path().join("settings.json"),
516            });
517
518        app.update();
519        app.world_mut().write_message(SaveSettingsRequest);
520        app.update();
521    }
522
523    #[test]
524    fn the_saved_field_of_view_reaches_the_spawned_camera() {
525        use crate::player::{Player, PlayerHealth, spawn_player};
526        let dir = tempfile::tempdir().unwrap();
527        saved().save_to(&dir.path().join("settings.json"));
528        let mut app = settings_app(dir.path());
529        app.init_resource::<PlayerHealth>()
530            .add_systems(Startup, spawn_player);
531
532        app.update();
533
534        let mut cameras = app
535            .world_mut()
536            .query_filtered::<&Projection, With<Player>>();
537        let Projection::Perspective(perspective) = cameras.single(app.world()).unwrap() else {
538            panic!("the player camera is perspective");
539        };
540        assert!((perspective.fov.to_degrees() - 75.0).abs() < 1e-3);
541    }
542}