From 19c2bf11815b1e9d31be49367c00f6a0bdd2deec Mon Sep 17 00:00:00 2001 From: Kevin Glasson Date: Tue, 16 Jun 2020 21:55:37 +0800 Subject: [PATCH] Add hotbar state persistence. Persist the hotbar state to disk by writing it out to a `profile.ron` situated next to the existing `settings.ron`. There are individual profiles for every character on every server. On creation of a new character the default hotbar state will be `[None; 10]` i.e. the hotbar will be empty. Resolves: https://gitlab.com/veloren/veloren/-/issues/577 --- CHANGELOG.md | 1 + client/src/lib.rs | 4 +- voxygen/src/hud/hotbar.rs | 20 +++- voxygen/src/hud/mod.rs | 18 +++- voxygen/src/lib.rs | 7 +- voxygen/src/main.rs | 8 +- voxygen/src/profile.rs | 194 ++++++++++++++++++++++++++++++++++++++ voxygen/src/session.rs | 16 ++++ 8 files changed, 259 insertions(+), 9 deletions(-) create mode 100644 voxygen/src/profile.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 25f94fb983..0d2634c4bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added basic auto walk - Added weapon/attack sound effects - M2 attack for bow +- Hotbar persistence. ### Changed diff --git a/client/src/lib.rs b/client/src/lib.rs index a49e29eba0..5e0a84fc0d 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -71,6 +71,7 @@ pub struct Client { pub world_map: (Arc, Vec2), pub player_list: HashMap, pub character_list: CharacterList, + pub active_character_id: Option, postbox: PostBox, @@ -176,6 +177,7 @@ impl Client { world_map, player_list: HashMap::new(), character_list: CharacterList::default(), + active_character_id: None, postbox, @@ -243,7 +245,7 @@ impl Client { pub fn request_character(&mut self, character_id: i32, body: comp::Body) { self.postbox .send_message(ClientMsg::Character { character_id, body }); - + self.active_character_id = Some(character_id); self.client_state = ClientState::Pending; } diff --git a/voxygen/src/hud/hotbar.rs b/voxygen/src/hud/hotbar.rs index fe5a2f3696..b6c00f6079 100644 --- a/voxygen/src/hud/hotbar.rs +++ b/voxygen/src/hud/hotbar.rs @@ -1,3 +1,5 @@ +use serde_derive::{Deserialize, Serialize}; + #[derive(Clone, Copy, PartialEq)] pub enum Slot { One = 0, @@ -12,24 +14,34 @@ pub enum Slot { Ten = 9, } -#[derive(Clone, Copy, PartialEq)] +#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)] pub enum SlotContents { Inventory(usize), Ability3, } +#[derive(Clone, Debug)] pub struct State { - slots: [Option; 10], + pub slots: [Option; 10], inputs: [bool; 10], } -impl State { - pub fn new() -> Self { +impl Default for State { + fn default() -> Self { Self { slots: [None; 10], inputs: [false; 10], } } +} + +impl State { + pub fn new(slots: [Option; 10]) -> Self { + Self { + slots, + inputs: [false; 10], + } + } /// Returns true if the button was just pressed pub fn process_input(&mut self, slot: Slot, state: bool) -> bool { diff --git a/voxygen/src/hud/mod.rs b/voxygen/src/hud/mod.rs index 3177c9c140..1cbf758d82 100644 --- a/voxygen/src/hud/mod.rs +++ b/voxygen/src/hud/mod.rs @@ -16,6 +16,8 @@ mod social; mod spell; use crate::{ecs::comp::HpFloaterList, hud::img_ids::ImgsRot, ui::img_ids::Rotations}; +pub use hotbar::{SlotContents as HotbarSlotContents, State as HotbarState}; + pub use settings_window::ScaleChange; use std::time::Duration; @@ -253,6 +255,7 @@ pub enum Event { UseSlot(comp::slot::Slot), SwapSlots(comp::slot::Slot, comp::slot::Slot), DropSlot(comp::slot::Slot), + ChangeHotbarState(HotbarState), Ability3(bool), Logout, Quit, @@ -490,13 +493,21 @@ impl Hud { let rot_imgs = ImgsRot::load(&mut ui).expect("Failed to load rot images!"); // Load item images. let item_imgs = ItemImgs::new(&mut ui, imgs.not_found); - // Load language + // Load language. let voxygen_i18n = load_expect::(&i18n_asset_key( &global_state.settings.language.selected_language, )); // Load fonts. let fonts = ConrodVoxygenFonts::load(&voxygen_i18n.fonts, &mut ui) .expect("Impossible to load fonts!"); + // Get the server name. + let server = &client.server_info.name; + // Get the id, unwrap is safe because this CANNOT be None at this + // point. + let character_id = client.active_character_id.unwrap(); + // Create a new HotbarState from the persisted slots. + let hotbar_state = + HotbarState::new(global_state.profile.get_hotbar_slots(server, character_id)); let slot_manager = slots::SlotManager::new(ui.id_generator(), Vec2::broadcast(40.0)); @@ -541,7 +552,7 @@ impl Hud { velocity: 0.0, voxygen_i18n, slot_manager, - hotbar: hotbar::State::new(), + hotbar: hotbar_state, events: Vec::new(), crosshair_opacity: 0.0, } @@ -1846,8 +1857,10 @@ impl Hud { events.push(Event::SwapSlots(a, b)); } else if let (Inventory(i), Hotbar(h)) = (a, b) { self.hotbar.add_inventory_link(h, i.0); + events.push(Event::ChangeHotbarState(self.hotbar.to_owned())); } else if let (Hotbar(a), Hotbar(b)) = (a, b) { self.hotbar.swap(a, b); + events.push(Event::ChangeHotbarState(self.hotbar.to_owned())); } }, slot::Event::Dropped(from) => { @@ -1856,6 +1869,7 @@ impl Hud { events.push(Event::DropSlot(from)); } else if let Hotbar(h) = from { self.hotbar.clear_slot(h); + events.push(Event::ChangeHotbarState(self.hotbar.to_owned())); } }, slot::Event::Used(from) => { diff --git a/voxygen/src/lib.rs b/voxygen/src/lib.rs index f0a9f34124..de25dc82ed 100644 --- a/voxygen/src/lib.rs +++ b/voxygen/src/lib.rs @@ -16,6 +16,7 @@ pub mod key_state; pub mod logging; pub mod menu; pub mod mesh; +pub mod profile; pub mod render; pub mod scene; pub mod session; @@ -27,11 +28,15 @@ pub mod window; // Reexports pub use crate::error::Error; -use crate::{audio::AudioFrontend, settings::Settings, singleplayer::Singleplayer, window::Window}; +use crate::{ + audio::AudioFrontend, profile::Profile, settings::Settings, singleplayer::Singleplayer, + window::Window, +}; /// A type used to store state that is shared between all play states. pub struct GlobalState { pub settings: Settings, + pub profile: Profile, pub window: Window, pub audio: AudioFrontend, pub info_message: Option, diff --git a/voxygen/src/main.rs b/voxygen/src/main.rs index dcfc6d4407..54fdd777dd 100644 --- a/voxygen/src/main.rs +++ b/voxygen/src/main.rs @@ -8,6 +8,7 @@ use veloren_voxygen::{ i18n::{self, i18n_asset_key, VoxygenLocalization}, logging, menu::main::MainMenuState, + profile::Profile, settings::{AudioOutput, Settings}, window::Window, Direction, GlobalState, PlayState, PlayStateResult, @@ -37,6 +38,8 @@ fn main() { // whether we create a log file or not. let settings = Settings::load(); + let profile = Profile::load(); + logging::init(&settings, term_log_level, file_log_level); // Save settings to add new fields or create the file if it is not already there @@ -57,6 +60,7 @@ fn main() { let mut global_state = GlobalState { audio, + profile, window: Window::new(&settings).expect("Failed to create window!"), settings, info_message: None, @@ -217,6 +221,8 @@ fn main() { } } - // Save any unsaved changes to settings + // Save any unsaved changes to profile. + global_state.profile.save_to_file_warn(); + // Save any unsaved changes to settings. global_state.settings.save_to_file_warn(); } diff --git a/voxygen/src/profile.rs b/voxygen/src/profile.rs new file mode 100644 index 0000000000..b4193041dc --- /dev/null +++ b/voxygen/src/profile.rs @@ -0,0 +1,194 @@ +use crate::hud; +use directories::ProjectDirs; +use hashbrown::HashMap; +use log::warn; +use serde_derive::{Deserialize, Serialize}; +use std::{fs, io::prelude::*, path::PathBuf}; + +/// Represents a character in the profile. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct CharacterProfile { + /// Array representing a character's hotbar. + pub hotbar_slots: [Option; 10], +} + +impl Default for CharacterProfile { + fn default() -> Self { + CharacterProfile { + hotbar_slots: [None; 10], + } + } +} + +/// Represents a server in the profile. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct ServerProfile { + /// A map of character's by id to their CharacterProfile. + pub characters: HashMap, +} + +impl Default for ServerProfile { + fn default() -> Self { + ServerProfile { + characters: HashMap::new(), + } + } +} + +/// `Profile` contains everything that can be configured in the profile.ron +/// +/// Initially it is just for persisting things that don't belong in +/// setttings.ron - like the state of hotbar and any other character level +/// configuration. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct Profile { + pub servers: HashMap, +} + +impl Default for Profile { + fn default() -> Self { + Profile { + servers: HashMap::new(), + } + } +} + +impl Profile { + /// Load the profile.ron file from the standard path or create it. + pub fn load() -> Self { + let path = Profile::get_path(); + + if let Ok(file) = fs::File::open(&path) { + match ron::de::from_reader(file) { + Ok(profile) => return profile, + Err(e) => { + log::warn!( + "Failed to parse profile file! Falling back to default. {}", + e + ); + // Rename the corrupted profile file. + let new_path = path.with_extension("invalid.ron"); + if let Err(err) = std::fs::rename(path, new_path) { + log::warn!("Failed to rename profile file. {}", err); + } + }, + } + } + // This is reached if either: + // - The file can't be opened (presumably it doesn't exist) + // - Or there was an error parsing the file + let default_profile = Self::default(); + default_profile.save_to_file_warn(); + default_profile + } + + /// Save the current profile to disk, warn on failure. + pub fn save_to_file_warn(&self) { + if let Err(err) = self.save_to_file() { + warn!("Failed to save profile: {:?}", err); + } + } + + /// Get the hotbar_slots for the requested character_id. + /// + /// if the server or character does not exist then the appropriate fields + /// will be initialised and default hotbar_slots (empty) returned. + /// + /// # Arguments + /// + /// * server - current server the character is on. + /// * character_id - id of the character. + pub fn get_hotbar_slots( + &mut self, + server: &str, + character_id: i32, + ) -> [Option; 10] { + self.servers + .entry(server.to_string()) + .or_insert(ServerProfile::default()) + // Get or update the CharacterProfile. + .characters + .entry(character_id) + .or_insert(CharacterProfile::default()) + .hotbar_slots + } + + /// Set the hotbar_slots for the requested character_id. + /// + /// If the server or character does not exist then the appropriate fields + /// will be initialised and the slots added. + /// + /// # Arguments + /// + /// * server - current server the character is on. + /// * character_id - id of the character. + /// * slots - array of hotbar_slots to save. + pub fn set_hotbar_slots( + &mut self, + server: &str, + character_id: i32, + slots: [Option; 10], + ) { + self.servers + .entry(server.to_string()) + .or_insert(ServerProfile::default()) + // Get or update the CharacterProfile. + .characters + .entry(character_id) + .or_insert(CharacterProfile::default()) + .hotbar_slots = slots; + } + + /// Save the current profile to disk. + fn save_to_file(&self) -> std::io::Result<()> { + let path = Profile::get_path(); + if let Some(dir) = path.parent() { + fs::create_dir_all(dir)?; + } + let mut config_file = fs::File::create(path)?; + + let s: &str = &ron::ser::to_string_pretty(self, ron::ser::PrettyConfig::default()).unwrap(); + config_file.write_all(s.as_bytes()).unwrap(); + Ok(()) + } + + fn get_path() -> PathBuf { + if let Some(val) = std::env::var_os("VOXYGEN_CONFIG") { + let profile = PathBuf::from(val).join("profile.ron"); + if profile.exists() || profile.parent().map(|x| x.exists()).unwrap_or(false) { + return profile; + } + log::warn!("VOXYGEN_CONFIG points to invalid path."); + } + + let proj_dirs = ProjectDirs::from("net", "veloren", "voxygen") + .expect("System's $HOME directory path not found!"); + + proj_dirs + .config_dir() + .join("profile.ron") + .with_extension("ron") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_get_slots_with_empty_profile() { + let mut profile = Profile::default(); + let slots = profile.get_hotbar_slots("TestServer", 12345); + assert_eq!(slots, [None; 10]) + } + + #[test] + fn test_set_slots_with_empty_profile() { + let mut profile = Profile::default(); + let slots = [None; 10]; + profile.set_hotbar_slots("TestServer", 12345, slots); + } +} diff --git a/voxygen/src/session.rs b/voxygen/src/session.rs index fd7729db33..8afd79201b 100644 --- a/voxygen/src/session.rs +++ b/voxygen/src/session.rs @@ -747,6 +747,22 @@ impl PlayState for SessionState { } } }, + HudEvent::ChangeHotbarState(state) => { + let client = self.client.borrow(); + + let server = &client.server_info.name; + // If we are changing the hotbar state this CANNOT be None. + let character_id = client.active_character_id.unwrap(); + + // Get or update the ServerProfile. + global_state + .profile + .set_hotbar_slots(server, character_id, state.slots); + + global_state.profile.save_to_file_warn(); + + log::info!("Event! -> ChangedHotbarState") + }, HudEvent::Ability3(state) => self.inputs.ability3.set_state(state), HudEvent::ChangeFOV(new_fov) => { global_state.settings.graphics.fov = new_fov;