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
This commit is contained in:
Kevin Glasson 2020-06-16 21:55:37 +08:00
parent 2835303de5
commit 19c2bf1181
8 changed files with 259 additions and 9 deletions

View File

@ -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

View File

@ -71,6 +71,7 @@ pub struct Client {
pub world_map: (Arc<DynamicImage>, Vec2<u32>),
pub player_list: HashMap<u64, PlayerInfo>,
pub character_list: CharacterList,
pub active_character_id: Option<i32>,
postbox: PostBox<ClientMsg, ServerMsg>,
@ -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;
}

View File

@ -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<SlotContents>; 10],
pub slots: [Option<SlotContents>; 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<SlotContents>; 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 {

View File

@ -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::<VoxygenLocalization>(&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) => {

View File

@ -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<String>,

View File

@ -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();
}

194
voxygen/src/profile.rs Normal file
View File

@ -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<hud::HotbarSlotContents>; 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<i32, CharacterProfile>,
}
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<String, ServerProfile>,
}
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<hud::HotbarSlotContents>; 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<hud::HotbarSlotContents>; 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);
}
}

View File

@ -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;