feat: asset glob loading, random weapons in chests

This commit is contained in:
timokoesters 2019-10-24 19:43:55 +02:00
parent f1b728b89b
commit a6faffca4e
No known key found for this signature in database
GPG Key ID: CD80BE9AAEE78097
2 changed files with 62 additions and 13 deletions

View File

@ -72,6 +72,43 @@ pub fn load_map<A: Asset + 'static, F: FnOnce(A) -> A>(
}
}
pub fn load_glob<A: Asset + 'static>(specifier: &str) -> Result<Arc<Vec<Arc<A>>>, Error> {
if let Some(assets) = ASSETS.read().unwrap().get(specifier) {
return Ok(Arc::clone(assets).downcast()?);
}
// Get glob matches
let glob_matches = read_dir(specifier.trim_end_matches(".*")).map(|dir| {
dir.filter_map(|direntry| {
direntry.ok().and_then(|file| {
file.file_name()
.to_string_lossy()
.rsplitn(2, '.')
.last()
.map(|s| s.to_owned())
})
})
.collect::<Vec<_>>()
});
match glob_matches {
Ok(glob_matches) => {
let assets = Arc::new(
glob_matches
.into_iter()
.filter_map(|name| load(&specifier.replace("*", &name)).ok())
.collect::<Vec<_>>(),
);
let clone = Arc::clone(&assets);
let mut assets_write = ASSETS.write().unwrap();
assets_write.insert(specifier.to_owned(), clone);
Ok(assets)
}
Err(error) => Err(error),
}
}
/// Function used to load assets from the filesystem or the cache.
/// Example usage:
/// ```no_run
@ -141,8 +178,6 @@ pub fn load_watched<A: Asset + 'static>(
Ok(asset)
}
/// The Asset trait, which is implemented by all structures that have their data stored in the
/// filesystem.
fn reload<A: Asset + 'static>(specifier: &str) -> Result<(), Error> {
let asset = Arc::new(A::parse(load_file(specifier, A::ENDINGS)?)?);
let clone = Arc::clone(&asset);
@ -157,7 +192,8 @@ fn reload<A: Asset + 'static>(specifier: &str) -> Result<(), Error> {
Ok(())
}
/// Asset Trait
/// The Asset trait, which is implemented by all structures that have their data stored in the
/// filesystem.
pub trait Asset: Send + Sync + Sized {
const ENDINGS: &'static [&'static str];
/// Parse the input file and return the correct Asset.
@ -268,6 +304,22 @@ pub fn load_file(specifier: &str, endings: &[&str]) -> Result<BufReader<File>, E
Err(Error::NotFound(path.to_string_lossy().into_owned()))
}
/// Loads a file based on the specifier and possible extensions
pub fn load_file_glob(specifier: &str, endings: &[&str]) -> Result<BufReader<File>, Error> {
let path = unpack_specifier(specifier);
for ending in endings {
let mut path = path.clone();
path.set_extension(ending);
debug!("Trying to access \"{:?}\"", path);
if let Ok(file) = File::open(path) {
return Ok(BufReader::new(file));
}
}
Err(Error::NotFound(path.to_string_lossy().into_owned()))
}
/// Read directory from `veloren/assets/*`
pub fn read_dir(specifier: &str) -> Result<ReadDir, Error> {
let dir_name = unpack_specifier(specifier);

View File

@ -3,10 +3,12 @@ use crate::{
effect::Effect,
terrain::{Block, BlockKind},
};
use rand::prelude::*;
use specs::{Component, FlaggedStorage};
use specs_idvs::IDVStorage;
use std::fs::File;
use std::io::BufReader;
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Tool {
@ -112,16 +114,11 @@ impl Item {
BlockKind::Chest => Some(match rand::random::<usize>() % 4 {
0 => assets::load_expect_cloned("common.items.apple"),
1 => assets::load_expect_cloned("common.items.velorite"),
// TODO: Implement random asset loading
//2 => Item::Tool {
// kind: *(&ALL_TOOLS).choose(&mut rand::thread_rng()),
// power: 8 + rand::random::<u32>() % (rand::random::<u32>() % 29 + 1),
// stamina: 0,
// strength: 0,
// dexterity: 0,
// intelligence: 0,
//},
2 => assets::load_expect_cloned("common.items.apple"),
2 => (**assets::load_glob::<Item>("common.items.weapons.*")
.expect("Error getting glob")
.choose(&mut rand::thread_rng())
.expect("Empty glob"))
.clone(),
3 => assets::load_expect_cloned("common.items.veloritefrag"),
_ => unreachable!(),
}),