use std::path::{Path, PathBuf};
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use crate::audio::SfxConfig;
use crate::player::PlayerConfig;
use crate::ui::SaveSettingsRequest;
use crate::world::{ChunkManager, WorldConfig};
pub const RENDER_DISTANCE_STEP: f32 = 16.0;
pub const RENDER_DISTANCE_UNLOAD_MARGIN: f32 = 32.0;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersistedSettings {
pub fov_degrees: f32,
pub sfx_volume: f32,
pub render_distance_chunks: u32,
pub sensitivity_pct: u32,
}
impl PersistedSettings {
pub fn save(&self, world_name: &str) {
self.save_to(&settings_path(world_name));
}
pub fn load(world_name: &str) -> Option<Self> {
Self::load_from(&settings_path(world_name))
}
pub fn save_to(&self, path: &Path) {
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Ok(json) = serde_json::to_string_pretty(self) {
let _ = std::fs::write(path, json);
}
}
pub fn load_from(path: &Path) -> Option<Self> {
let data = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&data).ok()
}
pub fn load_distance(&self) -> f32 {
self.render_distance_chunks.clamp(4, 32) as f32 * RENDER_DISTANCE_STEP
}
pub fn capture(
player: Option<&PlayerConfig>,
world: Option<&WorldConfig>,
sfx: Option<&SfxConfig>,
) -> Self {
let default_player = PlayerConfig::default();
let player = player.unwrap_or(&default_player);
let load_distance = world.map_or(WorldConfig::default().load_distance, |w| w.load_distance);
let volume = sfx.map_or(SfxConfig::default().volume, |s| s.volume);
Self {
fov_degrees: player.fov_degrees,
sfx_volume: volume,
render_distance_chunks: ((load_distance / RENDER_DISTANCE_STEP).round() as i64)
.clamp(4, 32) as u32,
sensitivity_pct: ((player.sensitivity * 100.0).round() as i64).clamp(10, 100) as u32,
}
}
pub fn apply(
&self,
player: Option<&mut PlayerConfig>,
world: Option<&mut WorldConfig>,
manager: Option<&mut ChunkManager>,
sfx: Option<&mut SfxConfig>,
) {
if let Some(player) = player {
if self.fov_degrees.is_finite() {
player.fov_degrees = self.fov_degrees.clamp(50.0, 120.0);
}
player.sensitivity = self.sensitivity_pct.clamp(10, 100) as f32 / 100.0;
}
if let Some(sfx) = sfx
&& self.sfx_volume.is_finite()
{
sfx.volume = self.sfx_volume.clamp(0.0, 1.0);
}
let load = self.load_distance();
let unload = load + RENDER_DISTANCE_UNLOAD_MARGIN;
let configured = match (&world, &manager) {
(Some(world), _) => Some(world.load_distance),
(None, Some(manager)) => Some(manager.load_distance),
(None, None) => None,
};
if configured == Some(load) {
return;
}
if let Some(world) = world {
world.load_distance = load;
world.unload_distance = unload;
}
if let Some(manager) = manager {
manager.load_distance = load;
manager.unload_distance = unload;
}
}
}
fn settings_path(world_name: &str) -> PathBuf {
PathBuf::from(format!("worlds/{world_name}/settings.json"))
}
#[derive(Resource, Debug, Clone, PartialEq, Eq)]
pub struct SettingsFile {
pub path: PathBuf,
}
impl SettingsFile {
pub fn for_world(world_name: &str) -> Self {
Self {
path: settings_path(world_name),
}
}
}
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SettingsSystems {
Load,
Save,
}
pub struct SettingsPlugin {
world_name: String,
}
impl SettingsPlugin {
pub fn with_world(world_name: impl Into<String>) -> Self {
Self {
world_name: world_name.into(),
}
}
}
impl Plugin for SettingsPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(SettingsFile::for_world(&self.world_name));
app.add_message::<SaveSettingsRequest>();
app.add_systems(
Startup,
load_settings_system
.in_set(SettingsSystems::Load)
.after(crate::world::config::load_world_config)
.before(crate::player::spawn_player),
);
app.add_systems(Update, save_settings_system.in_set(SettingsSystems::Save));
}
}
pub fn load_settings_system(
file: Res<SettingsFile>,
mut player: Option<ResMut<PlayerConfig>>,
mut world: Option<ResMut<WorldConfig>>,
mut manager: Option<ResMut<ChunkManager>>,
mut sfx: Option<ResMut<SfxConfig>>,
) {
let Some(saved) = PersistedSettings::load_from(&file.path) else {
return;
};
saved.apply(
player.as_deref_mut(),
world.as_deref_mut(),
manager.as_deref_mut(),
sfx.as_deref_mut(),
);
}
pub fn save_settings_system(
mut requests: MessageReader<SaveSettingsRequest>,
file: Res<SettingsFile>,
player: Option<Res<PlayerConfig>>,
world: Option<Res<WorldConfig>>,
sfx: Option<Res<SfxConfig>>,
) {
if requests.read().count() == 0 {
return;
}
PersistedSettings::capture(player.as_deref(), world.as_deref(), sfx.as_deref())
.save_to(&file.path);
}
#[cfg(test)]
mod tests {
use super::*;
fn saved() -> PersistedSettings {
PersistedSettings {
fov_degrees: 75.0,
sfx_volume: 0.4,
render_distance_chunks: 12,
sensitivity_pct: 60,
}
}
fn settings_app(dir: &Path) -> App {
let mut app = App::new();
app.add_plugins(MinimalPlugins)
.init_resource::<PlayerConfig>()
.init_resource::<WorldConfig>()
.init_resource::<ChunkManager>()
.init_resource::<SfxConfig>()
.add_plugins(SettingsPlugin::with_world("unused"))
.insert_resource(SettingsFile {
path: dir.join("settings.json"),
});
app
}
#[test]
fn the_file_of_a_world_is_inside_its_world_directory() {
assert_eq!(
SettingsFile::for_world("alpha").path,
PathBuf::from("worlds/alpha/settings.json")
);
}
#[test]
fn a_saved_file_is_applied_at_startup() {
let dir = tempfile::tempdir().unwrap();
saved().save_to(&dir.path().join("settings.json"));
let mut app = settings_app(dir.path());
app.update();
let player = app.world().resource::<PlayerConfig>();
assert_eq!(player.fov_degrees, 75.0);
assert!((player.sensitivity - 0.6).abs() < 1e-6);
assert_eq!(app.world().resource::<SfxConfig>().volume, 0.4);
let world = app.world().resource::<WorldConfig>();
assert_eq!(world.load_distance, 192.0);
assert_eq!(world.unload_distance, 224.0);
let manager = app.world().resource::<ChunkManager>();
assert_eq!(manager.load_distance, 192.0);
assert_eq!(manager.unload_distance, 224.0);
}
#[test]
fn a_missing_file_leaves_the_configuration_untouched() {
let dir = tempfile::tempdir().unwrap();
let mut app = settings_app(dir.path());
app.world_mut().resource_mut::<PlayerConfig>().fov_degrees = 101.0;
app.update();
assert_eq!(app.world().resource::<PlayerConfig>().fov_degrees, 101.0);
let defaults = WorldConfig::default();
let world = app.world().resource::<WorldConfig>();
assert_eq!(world.load_distance, defaults.load_distance);
assert_eq!(world.unload_distance, defaults.unload_distance);
}
#[test]
fn an_unreadable_file_leaves_the_configuration_untouched() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("settings.json"), b"{ not json").unwrap();
let mut app = settings_app(dir.path());
app.update();
assert_eq!(
app.world().resource::<PlayerConfig>().fov_degrees,
PlayerConfig::default().fov_degrees
);
}
#[test]
fn values_outside_the_menu_ranges_are_limited() {
let mut player = PlayerConfig::default();
let mut sfx = SfxConfig::default();
let mut world = WorldConfig::default();
PersistedSettings {
fov_degrees: 500.0,
sfx_volume: -3.0,
render_distance_chunks: 1000,
sensitivity_pct: 0,
}
.apply(Some(&mut player), Some(&mut world), None, Some(&mut sfx));
assert_eq!(player.fov_degrees, 120.0);
assert!((player.sensitivity - 0.1).abs() < 1e-6);
assert_eq!(sfx.volume, 0.0);
assert_eq!(world.load_distance, 32.0 * RENDER_DISTANCE_STEP);
}
#[test]
fn values_that_are_not_numbers_are_skipped() {
let mut player = PlayerConfig::default();
let mut sfx = SfxConfig::default();
PersistedSettings {
fov_degrees: f32::NAN,
sfx_volume: f32::INFINITY,
..saved()
}
.apply(Some(&mut player), None, None, Some(&mut sfx));
assert_eq!(player.fov_degrees, PlayerConfig::default().fov_degrees);
assert_eq!(sfx.volume, SfxConfig::default().volume);
}
#[test]
fn a_render_distance_equal_to_the_configured_one_keeps_the_unload_distance() {
let mut world = WorldConfig {
load_distance: 192.0,
unload_distance: 400.0,
..default()
};
let mut manager = ChunkManager::new(192.0, 400.0);
saved().apply(None, Some(&mut world), Some(&mut manager), None);
assert_eq!(world.unload_distance, 400.0);
assert_eq!(manager.unload_distance, 400.0);
}
#[test]
fn a_save_request_writes_the_current_values() {
let dir = tempfile::tempdir().unwrap();
let mut app = settings_app(dir.path());
app.update();
assert!(!dir.path().join("settings.json").exists());
{
let world = app.world_mut();
world.resource_mut::<PlayerConfig>().fov_degrees = 85.0;
world.resource_mut::<PlayerConfig>().sensitivity = 0.35;
world.resource_mut::<SfxConfig>().volume = 0.7;
world.resource_mut::<WorldConfig>().load_distance = 20.0 * RENDER_DISTANCE_STEP;
world.write_message(SaveSettingsRequest);
}
app.update();
let written = PersistedSettings::load_from(&dir.path().join("settings.json")).unwrap();
assert_eq!(written.fov_degrees, 85.0);
assert_eq!(written.sfx_volume, 0.7);
assert_eq!(written.render_distance_chunks, 20);
assert_eq!(written.sensitivity_pct, 35);
}
#[test]
fn what_is_saved_is_what_the_next_start_loads() {
let dir = tempfile::tempdir().unwrap();
let mut first = settings_app(dir.path());
first.update();
first.world_mut().resource_mut::<PlayerConfig>().fov_degrees = 65.0;
first.world_mut().write_message(SaveSettingsRequest);
first.update();
let mut second = settings_app(dir.path());
second.update();
assert_eq!(second.world().resource::<PlayerConfig>().fov_degrees, 65.0);
}
#[test]
fn the_plugin_runs_without_the_pause_menu_and_without_the_resources() {
let dir = tempfile::tempdir().unwrap();
saved().save_to(&dir.path().join("settings.json"));
let mut app = App::new();
app.add_plugins(MinimalPlugins)
.add_plugins(SettingsPlugin::with_world("unused"))
.insert_resource(SettingsFile {
path: dir.path().join("settings.json"),
});
app.update();
app.world_mut().write_message(SaveSettingsRequest);
app.update();
}
#[test]
fn the_saved_field_of_view_reaches_the_spawned_camera() {
use crate::player::{Player, PlayerHealth, spawn_player};
let dir = tempfile::tempdir().unwrap();
saved().save_to(&dir.path().join("settings.json"));
let mut app = settings_app(dir.path());
app.init_resource::<PlayerHealth>()
.add_systems(Startup, spawn_player);
app.update();
let mut cameras = app
.world_mut()
.query_filtered::<&Projection, With<Player>>();
let Projection::Perspective(perspective) = cameras.single(app.world()).unwrap() else {
panic!("the player camera is perspective");
};
assert!((perspective.fov.to_degrees() - 75.0).abs() < 1e-3);
}
}