diff --git a/badges/coverage.svg b/badges/coverage.svg index ea72a13..6fdcf57 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 19%test-coverage19% +test-coverage: 16%test-coverage16% diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 7e68296..1ad235a 100644 Binary files a/weaponry/databases/weapons.db and b/weaponry/databases/weapons.db differ diff --git a/weaponry/examples/test_serialisation_wl.rs b/weaponry/examples/bench_serialisation_wl.rs similarity index 81% rename from weaponry/examples/test_serialisation_wl.rs rename to weaponry/examples/bench_serialisation_wl.rs index d5d9ad0..4d86296 100644 --- a/weaponry/examples/test_serialisation_wl.rs +++ b/weaponry/examples/bench_serialisation_wl.rs @@ -14,17 +14,6 @@ fn main() { // println!("First entry: {:?}", initial_deserialisation.as_ref().unwrap()[0]); let intermediate_deserialisation = initial_deserialisation.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); - // let v = intermediate_deserialisation - // .iter() - // .scan(0, |status, eq| { - // if eq.is_ok() { - // *status = 1; - // } else { - // *status = 0; - // } - // Some(*status) - // }) - // .sum::(); let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize)); // println!("Final data {:#?}", intermediate_deserialisation); println!("Failed to parse: {:#?}", intermediate_deserialisation.into_iter().filter_map(|v| v.err()).collect::>()); diff --git a/weaponry/examples/first_import.rs b/weaponry/examples/usage_import_tex.rs similarity index 99% rename from weaponry/examples/first_import.rs rename to weaponry/examples/usage_import_tex.rs index 73b7ca4..a8a4721 100644 --- a/weaponry/examples/first_import.rs +++ b/weaponry/examples/usage_import_tex.rs @@ -1,5 +1,5 @@ // Workspace: weaponry -// File: examples/typical_wl_recipe.rs +// File: examples/usage_import_tex.rs //! Example of a first initialisation //! All this work is cursed and rushed diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs new file mode 100644 index 0000000..95b1f2f --- /dev/null +++ b/weaponry/examples/usage_scenario.rs @@ -0,0 +1,30 @@ +// Workspace: weaponry +// File: examples/usage_scenario.rs +//! Test use case of a scenario +//! +//! + +// TODO : All of these should likely be in the prelude if used like this +use weaponry::interfaces::{Reportable, Scenario}; +use weaponry::weaponry_structs::CrossRecipeScenario; +use weaponry::weaponry_structs::equipement_scenario::ConfigMock; +// use weaponry::interfaces:: +fn main() { + let s = CrossRecipeScenario::new_with_config(ConfigMock {}).unwrap(); + let re = s.generate_refined_recipes().unwrap(); + println!("{}", re.get_report(Some("Refined List"))); +} + +// // Load DB +// let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); +// // Do a first deserialisation +// let initial_deserialisation = db.serialize_vec_from_table::("Equipements", None).unwrap(); +// // Follow up by parsing this deserialisation by a transformation into the right intermediate representation +// let intermediate_deserialisation = initial_deserialisation.into_iter().map(InnerEquipementStats::try_from).collect::>(); + +// // // Inspect the sucesses/filures +// // let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize)); +// // println!("Succeded in parsing {}/{}", f.0, f.1); + +// // println!("Final data {:#?}", intermediate_deserialisation); +// // println!("Failed to parse: {:#?}", intermediate_deserialisation.into_iter().filter_map(|v| v.err()).collect::>()); diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index b6fdc44..c9766d4 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -18,8 +18,8 @@ pub fn get_data( where T: DeserializeOwned + more_fields::FieldsAsSlice, { - let mut binding = conn.prepare(&generate_select_query::(table_name, filter))?; - let rows = binding.query([])?; + let mut connection = conn.prepare(&generate_select_query::(table_name, filter))?; + let rows = connection.query([])?; serde_rusqlite::from_rows::(rows) .enumerate() .map(|(row_id, result)| { diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 92126cf..05a8d0e 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -196,7 +196,7 @@ pub trait Reportable { /// Get a detailled inner status report with as many useful informations as possible /// /// This report should give detailled information about the inner data, without showing the actual inner data - fn get_report(&self) -> String; + fn get_report(&self, title: Option<&str>) -> String; } /// A recipe full stack scenario, from loading database through view table generation diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index cd52da0..d6aa96c 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -146,7 +146,7 @@ pub enum WeaponCategory { // TODO: This is the real initial category /// The list of initial weapon meta categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize, strum::EnumString)] +#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] pub enum WeaponMacroCategory { Staves, Blunt, @@ -155,11 +155,35 @@ pub enum WeaponMacroCategory { Armor, Shields, Exotic, + /// A custom weapon category, only used by the target + // TODO: Get rid of this category and make a custom category for target + Weapons, /// A custom none category, used to forbid a part to be cast upon of from // TODO: Check the soundness of this implementation None, } +// TODO: This is only needed as long as we dont have a special category for the target +impl PartialEq for WeaponMacroCategory { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (&Self::None, _) => false, + (_, Self::None) => false, + (&Self::Armor, &Self::Armor) => true, + (&Self::Armor, _) => false, + (_, &Self::Armor) => false, + (&Self::Weapons, _) => true, + (_, &Self::Weapons) => true, + (&Self::Staves, &Self::Staves) => true, + (&Self::Blunt, &Self::Blunt) => true, + (&Self::Slash, &Self::Slash) => true, + (&Self::Ranged, &Self::Ranged) => true, + (&Self::Exotic, &Self::Exotic) => true, + _ => false, + } + } +} + #[cfg(test)] mod test { // use super::*; diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 509ea8e..4e199f4 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -35,6 +35,8 @@ impl From for Equipement { } } } + +// TODO: Change this into tryfrom impl From for Equipement { fn from(val: EqNature) -> Self { Self { @@ -42,18 +44,42 @@ impl From for Equipement { // TODO : Checks that this is exactly desired behavious // :Also check for Cross Weapon/Armor contamination // Checks that the nature is compatible with the previous iteration - filter_function: FilterFunction::new(&|sel, lhs| match ( - &sel.target, - &lhs.macro_category, - ) { - (Some(a), Some(b)) => a == b, - (None, None) => true, - _ => false, + filter_function: FilterFunction::new(&|sel, lhs| { + // println!( + // "Trying to match {:?} with {:?}. {:?} {:?}", + // sel.name, lhs.name, sel.target, lhs.macro_category + // ); + + match (&sel.target, &lhs.macro_category) { + // There is a specific target and the part about to be added has a category + (Some(a), Some(b)) => { + // println!("{} {}", a, b); + a == b + } + // There is no target and the part about to be added is generic + // TODO: Unsound to have a generic nature, this should be caught at serialisation + (None, _) => panic!("The EqNature about to be added cannot be generic"), + // There is a specific target but the part about to be added is generic + // TODO: Impossible + (Some(_), None) => panic!("The part about to be added unto cannot be generic"), + // // There is restriction on the target and the recipient + // (None, Some(_)) => true, + } }), } } } +// (Some(a), Some(b)) => { +// println!("{} {}", a, b); +// a == b +// } +// // There is no target and the part about to be added is generic +// (None, None) => true, +// // There is a specific target but the part about to be added is generic +// (Some(_), None) => true, +// // There is restriction on the target and the recipient +// (None, Some(_)) => true, impl From for Equipement { fn from(val: EqFinishing) -> Self { Self { @@ -143,21 +169,36 @@ impl Display for InnerEquipementStats { } } +// impl Display for InitialEquipementList { +// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +// for v in self.ref_inner() { +// write!(f, "{v}")?; +// } +// Ok(()) +// } +// } + impl Reportable for InitialEquipementList { - fn get_report(&self) -> String { + fn get_report(&self, title: Option<&str>) -> String { let mut table = Table::new(); table.apply_modifier(UTF8_ROUND_CORNERS); - table.add_row(vec![format!("Refined Equipement List")]); + match title { + Some(t) => table.add_row(vec![format!("[IEL] {t}")]), + None => table.add_row(vec![format!("Initial Equipement List")]), + }; table.add_row(vec![format!("Rows: {}", self.inner.len())]); table.to_string() } } impl Reportable for RefinedEquipementList { - fn get_report(&self) -> String { + fn get_report(&self, title: Option<&str>) -> String { let mut table = Table::new(); table.apply_modifier(UTF8_ROUND_CORNERS); - table.add_row(vec![format!("Refined Equipement List")]); + match title { + Some(t) => table.add_row(vec![format!("[REL] {t}")]), + None => table.add_row(vec![format!("Refined Equipement List")]), + }; table.add_row(vec![format!("Rows: {}", self.inner.len())]); table.to_string() } @@ -187,7 +228,7 @@ mod test { let eqlist = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); let feqlist: RefinedEquipementList = eqlist.clone().into(); - println!("{}", feqlist.get_report()); - println!("{}", eqlist.get_report()); + println!("{}", feqlist.get_report(None)); + println!("{}", eqlist.get_report(None)); } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 58611ac..ebc47db 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -119,7 +119,7 @@ impl TryFrom for InnerEquipementStats { special: from_serde!(&value.special)?, action_cost: value.action_cost, reload_cost: from_serde!(&value.reload_cost)?, - range: value.range, + range: value.range as i16, agility_bonus: value.agility_bonus, }) } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 5670c0f..480c3ea 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -9,51 +9,22 @@ #![allow(dead_code)] -use crate::weaponry_structs::Equipement; +use crate::interfaces::Reportable; use crate::weaponry_structs::InitialEquipementList; use crate::weaponry_structs::equipement_structs::DatabaseEquipementStats; +use crate::weaponry_structs::equipement_structs::EqFinishing; +use crate::weaponry_structs::equipement_structs::EqMaterial; +use crate::weaponry_structs::equipement_structs::EqNature; +use crate::weaponry_structs::equipement_structs::EqShape; +use crate::weaponry_structs::equipement_structs::InnerEquipementStats; use crate::{ - error::{EquipementError, FatalEquipementError}, + error::EquipementError, interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable}, - weaponry_structs::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}, }; use super::equipement_advanced_repr::RefinedEquipementList; +use super::equipement_impl_database::EquipementDatabase; -/// Mock of the existing database -pub struct DatabaseMock {} -impl RecipeDatabase for DatabaseMock { - fn serialize_vec_from_table( - &self, - table: &str, - filter: Option<&str>, - ) -> std::result::Result, crate::error::FatalEquipementError> { - let _ = table; - let _ = filter; - unimplemented!() - } - - fn new(origin: &str) -> Result - where - Self: std::marker::Sized, - { - let _ = origin; - unimplemented!() - } - - fn initialize_empty_table(&self, table: &str) -> Result<(), FatalEquipementError> { - let _ = table; - unimplemented!() - } - - fn insert_row( - &self, - row: T, - ) -> Result<(), FatalEquipementError> { - let _ = row; - todo!() - } -} /// Mock config pub struct ConfigMock {} /// Mock Viewtable @@ -74,34 +45,37 @@ impl ViewTable for ViewtableMock { /// A simple cross recipe scenario #[allow(clippy::missing_docs_in_private_items)] pub struct CrossRecipeScenario { - database: DatabaseMock, + database: EquipementDatabase, config: ConfigMock, } /// Automatically deserialize into an equipement // TODO: This macro only exists because no blanket implementation or function does this *relatively* easy step // TODO: This place the place where all new impl and simplifications will be done +// TODO: Streamline this so no macro is needed macro_rules! deserde_into_equipement { ( $db:expr, $name:expr, $type:ident) => { InitialEquipementList::from_vectored( $db.serialize_vec_from_table::( - "Equipement", - Some(&format!("CATEGORY == {}", $name)), + "Equipements", + Some(&format!("META_CATEGORY LIKE '{}'", $name)), + // None, )? .into_iter() - .map(|eq| { + // TODO: This is the lamest way to init this data + .map(|v| { $type { - stats: eq.try_into().unwrap(), + stats: InnerEquipementStats::try_from(v).unwrap(), } .into() }) - .collect::>(), + .collect::>(), ) }; } impl Scenario for CrossRecipeScenario { - type DatabaseType = DatabaseMock; + type DatabaseType = EquipementDatabase; type ViewTableType = ViewtableMock; type FinalListType = RefinedEquipementList; type Config = ConfigMock; @@ -120,18 +94,32 @@ impl Scenario for CrossRecipeScenario { fn generate_refined_recipes(&self) -> Result { // TODO: Depending on config, a different filter might be given here let eq_shape = deserde_into_equipement!(self.database, "Shape", EqShape); - let eq_material = deserde_into_equipement!(self.database, "Material", EqMaterial); + let eq_material = deserde_into_equipement!(self.database, "Materials", EqMaterial); let eq_nature = deserde_into_equipement!(self.database, "Nature", EqNature); let eq_finishing = deserde_into_equipement!(self.database, "Finishing", EqFinishing); + // println!( + // "{}\n{}\n{}\n{}", + // eq_shape.get_report(Some("EqShape ")), + // eq_material.get_report(Some("EqMaterials")), + // eq_nature.get_report(Some("EqNature ")), + // eq_finishing.get_report(Some("EqFinishing")) + // ); + // No op, just clarity // TODO: Depending on config this step might differ let mut f_list = eq_shape; + // println!("{}", f_list.get_report(Some("Initial Weapons "))); f_list.combine_all(&eq_material); + // println!("{}", f_list.get_report(Some("Combined with Materials"))); f_list.combine_all(&eq_nature); - f_list.combine_all(&eq_finishing); + // println!("{}", f_list.get_report(Some("Combined with Natures "))); + // f_list.combine_all(&eq_finishing); + // println!("{}", f_list.get_report(Some("Combined with Finishing"))); + // TODO: The finishes are interesting if they are configured or at least tamed a little + // TODO: As a high cost finish cannot hope to compete with a low one + // TODO: and therefore need a special metric and fixed entry data to be mesured - // This oneline is neat Ok(f_list.into()) } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index e0899ef..57533f6 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -85,7 +85,7 @@ pub struct InnerEquipementStats { pub(super) special: SpecialCategory, pub(super) action_cost: i8, pub(super) reload_cost: Option, // Shouldn't it be Option ? - pub(super) range: i8, // Shoudln't it be Option ? + pub(super) range: i16, // Shoudln't it be Option ? pub(super) agility_bonus: f32, // Also convert this one to HalfValue } @@ -201,7 +201,7 @@ impl InnerEquipementStats { pub fn random_new() -> Self { Self { id: vec![r!() as u8], - range: r!() - 10, + range: (r!() - 10) as i16, damage: r!() - 10, p_damage: r!() - 10, protection: r!() - 10, diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index e4ab206..f347a40 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -23,7 +23,7 @@ pub mod equipement_impl_database; mod equipement_impl_io; mod equipement_impl_logic; mod equipement_impl_math; -mod equipement_scenario; +pub mod equipement_scenario; pub mod equipement_structs; mod equipement_views; @@ -37,3 +37,6 @@ pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{ DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMacroCategory, }; + +// Likely ? Final Re-Exports +pub use equipement_scenario::CrossRecipeScenario;