diff --git a/.ignore b/.ignore new file mode 100644 index 0000000..8e062ad --- /dev/null +++ b/.ignore @@ -0,0 +1 @@ +*.drawio diff --git a/more_fields/Cargo.toml b/more_fields/Cargo.toml index ba443ad..1c83567 100644 --- a/more_fields/Cargo.toml +++ b/more_fields/Cargo.toml @@ -5,6 +5,8 @@ version.workspace = true [dependencies] more_fields_macro = {path ="../more_fields_macro"} + +[dev-dependencies] pretty_assertions = "1.4.1" [features] diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 915b59d..ae487b4 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -8,7 +8,6 @@ more_fields = {path ="../more_fields"} comfy-table = "7.1.4" csv = "1.3.1" fastrand = "2.3.0" -pretty_assertions = "1.4.1" probability = "0.20.3" rusqlite = { version = "0.33.0" } # , features = ["bundled"] serde = { version = "1.0.217", features = ["derive"] } @@ -16,9 +15,13 @@ serde_rusqlite = "0.37.0" serde_json = { version = "1.0.138", features = ["alloc"] } strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" +regex = "1.11.1" [dev-dependencies] criterion = { version = "0.5" } +regex = "1.11.1" +pretty_assertions = "^1.4" +logos = "^0.15" [[bench]] name = "iter_creation" diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index f0862ff..7e68296 100644 Binary files a/weaponry/databases/weapons.db and b/weaponry/databases/weapons.db differ diff --git a/weaponry/examples/.rustfmt.toml b/weaponry/examples/.rustfmt.toml new file mode 100644 index 0000000..98b9e7f --- /dev/null +++ b/weaponry/examples/.rustfmt.toml @@ -0,0 +1 @@ +max_width = 278 diff --git a/weaponry/examples/first_import.rs b/weaponry/examples/first_import.rs new file mode 100644 index 0000000..73b7ca4 --- /dev/null +++ b/weaponry/examples/first_import.rs @@ -0,0 +1,215 @@ +// Workspace: weaponry +// File: examples/typical_wl_recipe.rs +//! Example of a first initialisation +//! All this work is cursed and rushed + +// use logos::Logos; +// use more_fields::FieldsAsSlice; +// use serde::Serialize; +// use serde_rusqlite::to_params_named; +use weaponry::interfaces::RecipeDatabase; +use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase; +// use weaponry::weaponry_structs::{DamageMod, DamageType, WeaponMetaCategory}; +// use weaponry::weaponry_structs::PhysicalDamageType; +use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; + +// #[derive(Logos, Debug, PartialEq)] +// enum ModeParser { +// #[regex(r"\[\[\w+\]\]", |lex| std::convert::TryInto::::try_into(&lex.slice()[2..lex.slice().len()-2]).unwrap())] +// Tertiary(PhysicalDamageType), +// #[regex(r"\[\w+\]", |lex| std::convert::TryInto::::try_into(&lex.slice()[1..lex.slice().len()-1]).unwrap())] +// Secondary(PhysicalDamageType), +// #[regex(r"\w+", |lex| std::convert::TryInto::::try_into(lex.slice()).unwrap())] +// Primary(PhysicalDamageType), +// } +// let b = DamageMod::Primary() + +fn main() { + let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); + // init_db(&db); + let initial_deserialisation = db.serialize_vec_from_table::("Equipements", None); + // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", initial_deserialisation); + // 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!("Succeded in parsing {}/{}", f.0, f.1); +} + +// #[derive(Default)] +// struct FoundFields { +// reload: Option, +// range: Option, +// parmor: Option, +// } +// fn init_db(db: &EquipementDatabase) { +// let mut global_index = 0; +// let b = load_base(&mut global_index); +// db.initialize_empty_table::("Equipements").unwrap(); + +// db.conn.execute("DELETE FROM Equipements", []).unwrap(); +// println!("Added {global_index} ids to the new database"); + +// b.iter().for_each(|v| insert_into_db(db, v)); +// } +// fn parse_special_field(fields: &str) -> FoundFields { +// // "Arbalète & Distance & 4 & 1 & 3 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", +// let re = regex::Regex::new(r"((?\d)reload)?(, )?(Gls\{parmure\} (?\d))?(, )?((?\d+)m)?").unwrap(); +// re.captures(fields).map_or(FoundFields::default(), |f| FoundFields { +// reload: f.name("reload").map(|n| n.as_str().parse().unwrap()), +// range: f.name("range").map(|v| v.as_str().parse().unwrap()), +// parmor: f.name("parmor").map(|v| v.as_str().parse().unwrap()), +// }) +// } + +// #[allow(dead_code)] +// fn insert_into_db(db: &EquipementDatabase, row: T) { +// let sql = &format!( +// "INSERT INTO Equipements ({}) VALUES ({})", +// DatabaseEquipementStats::attributes_slice() +// .iter() +// // .filter_map(|(k, _v)| (*k != "id").then_some(*k)) +// .map(|(k, _v)| *k) +// .collect::>() +// .join(", "), +// DatabaseEquipementStats::attributes_slice() +// .iter() +// // .filter_map(|(k, _v)| (*k != "id").then_some(":".to_string() + *k)) +// .map(|(k, _v)| ":".to_string() + *k) +// .collect::>() +// .join(", ") +// ); +// // println!("Database Request {}", sql); +// let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice()); +// match r { +// Ok(_r) => { +// // println!("Loaded {:?} entries into the database", _r); +// } +// Err(e) => println!("Error: {} while processing entry", e), +// }; +// } + +// // fn load_base(index: &mut u8) -> Vec { +// // BASE_FORME +// // .iter() +// // .map(|row| { +// // let fields = row.split("&").map(|field| field.trim()).collect::>(); +// // let FoundFields { reload, range, parmor } = parse_special_field(fields[15]); +// // *index += 1; +// // // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", +// // // 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 +// // DatabaseEquipementStats { +// // id: *index, +// // meta_category: "Forme".into(), +// // name: fields[0].to_string(), +// // category: serde_json::to_string(&parse_to_type(fields[1]).unwrap()).unwrap(), +// // rarity: 0, +// // cost: 0, +// // precision: 0, +// // difficulty: fields[16].parse().unwrap_or_default(), // NOT PARSED YET +// // // tier: , +// // damage: fields[2].parse().unwrap_or_default(), +// // p_damage: fields[3].parse().unwrap_or_default(), +// // rmax: fields[4].parse().unwrap_or_default(), +// // armor_break: fields[5].parse().unwrap_or_default(), +// // protection: fields[6].parse().unwrap_or_default(), +// // integrity: fields[7].parse().unwrap_or_default(), + +// // torque_two_handed: serde_json::to_string(&match fields[8] { +// // "-" => None, +// // v => Some(v.parse::().unwrap()), +// // }) +// // .unwrap(), +// // torque_one_handed: serde_json::to_string(&match fields[9] { +// // "-" => None, +// // v => Some(v.parse::().unwrap()), +// // }) +// // .unwrap(), // The or default is a problem +// // damage_type: serde_json::to_string(&parse_to_damagetype(fields[10])).unwrap(), + +// // dodge: fields[11].parse().unwrap_or_default(), +// // parry: fields[12].parse().unwrap_or_default(), +// // speed: fields[13].parse().unwrap_or_default(), +// // stealth: fields[14].parse().unwrap_or_default(), +// // reload_cost: serde_json::to_string(&reload).unwrap(), +// // range: range.unwrap_or_default(), +// // armor_pierce: parmor.unwrap_or_default(), +// // // meta_category: parse_to_type(fields[1]), + +// // // target: fields[5].parse().unwrap(), // Armors ? +// // ..Default::default() +// // } +// // }) +// // .collect::>() +// // } + +// fn parse_to_damagetype(fields: &str) -> DamageType { +// DamageType(fields.split(",").map(|v| ModeParser::lexer(v.trim()).next().unwrap().unwrap().into()).collect::>()) +// } + +// impl From for DamageMod { +// fn from(value: ModeParser) -> Self { +// match value { +// ModeParser::Primary(v) => DamageMod::Primary(v), +// ModeParser::Secondary(v) => DamageMod::Secondary(v), +// ModeParser::Tertiary(v) => DamageMod::Tertiary(v), +// } +// } +// } + +// fn parse_to_type(text: &str) -> Option { +// match text { +// "Hast" => Some(WeaponMetaCategory::Staves), +// "Tranchantes" => Some(WeaponMetaCategory::Slash), +// "Contondantes" => Some(WeaponMetaCategory::Blunt), +// "Distance" => Some(WeaponMetaCategory::Ranged), +// "Boucliers" => Some(WeaponMetaCategory::Shields), +// "Armures" => Some(WeaponMetaCategory::Armor), +// "Exotiques" => Some(WeaponMetaCategory::Exotic), +// _ => None, +// } +// } + +// const BASE_FORME: &[&str] = &[ +// // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", +// // "Name & Type & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & mode & 9 & 10 & 11 & 12 & 3reload, & ddlvl{13} ", +// "Griffes & Tranchantes & 2 & 1 & 4 & 1 & 1 & 2 & 3 & 6 & slash & 2 & 0 & 3 & 1 & - & ddlvl{1} ", +// "Hast & Hast & 4 & 1 & 2 & 1 & 4 & 3 & 10 & 18 & pierce, [slash] & -1 & -3 & 1 & 0 & - & ddlvl{1} ", +// "Épée & Tranchantes & 3 & 1 & 3 & 1 & 3 & 4 & 12 & 15 & slash, [pierce] & 0 & 1 & 0 & 0 & - & ddlvl{1} ", +// "Marteau & Contondantes & 5 & 1 & 1 & 1 & 4 & 3 & 11 & 18 & blunt & -1 & -1 & 0 & -2 & - & ddlvl{1} ", +// "Hache & Tranchantes & 4 & 2 & 1 & 3 & 4 & 3 & 9 & 14 & slash & 0 & -1 & 1 & 0 & - & ddlvl{1} ", +// "Arbalète & Distance & 4 & 1 & 3 & 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", +// "Arc & Distance & 3 & 1 & 4 & 0 & 2 & 1 & - & 7 & pierce & 0 & 0 & 0 & 0 & 1reload, Gls{parmure} 2, 120m & ddlvl{1} ", +// "Boucliers & Boucliers & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ", +// "Armures & Armures & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & ddlvl{1} ", +// // "% Explosive & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{5} ", +// // "% Flexible & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{2} ", +// // "% Exotique & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{3} ", +// ]; +// #[allow(dead_code)] +// const BASE_SHAPE: &[&str] = &[ +// // " Maniement & damagew & + & rmax & arbreakw & faShield* & faShieldVirus & $mathbb{T}2$ & $mathbb{T}$1 & Esq. & Par. & Vit. & Disc. & Spécial & Diff. " +// // " % Nom & Dg & + & RM & AB & Pr & In & T2 & T1 & Esq. & Par. & Vit. & Disc. & Sp & Diff", +// " Arme Légère & -1 & 0 & 2 & -1 & -1 & -1 & -5 & -6 & 2 & 2 & 0 & 0 & Ag+half, Esq.+half & ddlvl{1}", +// " Arme Moyenne & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & - & ddzero", +// " Arme Lourde & 2 & 1 & 1 & 0 & 1 & 0 & 8 & 11 & -2 & -2 & -1 & -1 & - & ddlvl{1}", +// " Arme Super-lourde & 3 & 2 & 1 & 1 & 2 & 1 & 23 & 23 & -3 & -3 & -3 & -3 & 2A, Ag-1, [[blunt]], Précision-1 & ddlvl{2}", +// // " Arme Combinée & - & - & - & - & - & -2 & - & - & - & - & - & - & - & ddlvl{3}", // We'll have to think about this one +// // " Arme Escamotable & - & - & - & - & - & - & - & - & - & - & - & - & - & ddlvl{3}", // We'll have to think about this one +// " Armure Légère & - & - & - & - & -1 & -1 & -1 & - & 1 & 0 & 0 & 1 & Ag+1 & ddlvl{1}", +// " Armure Moyenne & - & - & - & - & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & - & ddzero", +// " Armure Lourde & - & - & - & - & 1 & 1 & 13 & - & -3 & -3 & -2 & -3 & Ag-1, Précision -1 & ddlvl{1}", +// " Armure Super-lourde & - & - & - & - & 3 & 3 & 25 & - & -5 & -4 & -4 & -6 & Ag-1, Précision -1 & ddlvl{2}", +// ]; diff --git a/weaponry/examples/serde_loading.rs b/weaponry/examples/serde_loading.rs deleted file mode 100644 index d9dde9f..0000000 --- a/weaponry/examples/serde_loading.rs +++ /dev/null @@ -1,68 +0,0 @@ -// Workspace: weaponry -// File: examples/typical_wl_recipe.rs -//! Example of a typical workload -//! - -use more_fields::FieldsAsSlice; -use serde_rusqlite::to_params_named; -use weaponry::interfaces::RecipeDatabase; -use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase; -use weaponry::weaponry_structs::equipement_structs::{ - DatabaseEquipementStats, InnerEquipementStats, -}; - -fn main() { - let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); - let mut data_eg = DatabaseEquipementStats::random_new(); - // data_eg.id = fastrand::u8(1..u8::MAX); - // data_eg.damage_type = serde_json::to_string(&Some(DamageType(vec![DamageMod::Primary( - // PhysicalDamageType::Blunt, - // )]))) - // .unwrap(); - // data_eg.category = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); - // data_eg.target = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); - // data_eg.special = - // serde_json::to_string(&SpecialCategory(vec!["noo".to_string(), "boo".to_string()])) - // .unwrap(); - // data_eg.reload_cost = serde_json::to_string(&Some(12)).unwrap(); - data_eg.id = fastrand::u8(1..u8::MAX); - - db.initialize_empty_table::("Equipements") - .unwrap(); - - let sql = &format!( - "INSERT INTO Equipements ({}) VALUES ({})", - DatabaseEquipementStats::attributes_slice() - .iter() - // .filter_map(|(k, _v)| (*k != "id").then_some(*k)) - .map(|(k, _v)| *k) - .collect::>() - .join(", "), - DatabaseEquipementStats::attributes_slice() - .iter() - // .filter_map(|(k, _v)| (*k != "id").then_some(":".to_string() + *k)) - .map(|(k, _v)| ":".to_string() + *k) - .collect::>() - .join(", ") - ); - println!("{}", sql); - let r = db.conn.execute( - sql, - to_params_named(&data_eg).unwrap().to_slice().as_slice(), - ); - println!("{:?}", r); - - let v = db.serialize_vec_from_table::("Equipements", None); - // println!("{:#?}", v); - - println!( - "{:#?}", - v.unwrap() - .into_iter() - .map(InnerEquipementStats::try_from) - .collect::>() - ); - // let mut r = db.conn.prepare("SELECT * FROM InnerStats").unwrap(); - // let mut v = r.query([]).unwrap(); - // println!("{:?}:\n {:#?}", db, r); -} diff --git a/weaponry/examples/test_serialisation_wl.rs b/weaponry/examples/test_serialisation_wl.rs new file mode 100644 index 0000000..d5d9ad0 --- /dev/null +++ b/weaponry/examples/test_serialisation_wl.rs @@ -0,0 +1,32 @@ +// Workspace: weaponry +// File: examples/test_serialisation_wl.rs +//! Test of an initial serialisation and scenario wl +//! Doing this work on an example will help writing it as an integration test afterwards + +use weaponry::interfaces::RecipeDatabase; +use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase; +use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; + +fn main() { + let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); + let initial_deserialisation = db.serialize_vec_from_table::("Equipements", None); + // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", initial_deserialisation); + // 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::>()); + println!("Succeded in parsing {}/{}", f.0, f.1); +} diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index a372c66..b6fdc44 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -7,19 +7,25 @@ use rusqlite::{self}; use serde::de::DeserializeOwned; +use crate::error::FatalEquipementError; + /// Public function to get data from db. Returns the result as a vec with structs pub fn get_data( conn: &rusqlite::Connection, table_name: &str, filter: Option<&str>, -) -> Result, serde_rusqlite::Error> +) -> Result, FatalEquipementError> where T: DeserializeOwned + more_fields::FieldsAsSlice, { - let mut query_result = conn.prepare(&generate_select_query::(table_name, filter))?; - Ok(serde_rusqlite::from_rows::(query_result.query([])?) - .filter_map(|s| s.ok()) - .collect()) + let mut binding = conn.prepare(&generate_select_query::(table_name, filter))?; + let rows = binding.query([])?; + serde_rusqlite::from_rows::(rows) + .enumerate() + .map(|(row_id, result)| { + result.map_err(|error| FatalEquipementError::SerdeRusqlite { error, row_id }) + }) + .collect() } /// Generate a SELECT query with fields generated from a struct. Returns a SQL request as a String diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index a410c4d..808b9d8 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -11,11 +11,27 @@ pub enum FatalEquipementError { #[error("Rusqlite failed to connect to the given path {0}")] RusqliteConnection(#[from] rusqlite::Error), - #[error("Deserialization from object failed : {0}")] - SerdeRusqlite(#[from] serde_rusqlite::Error), + #[error("Deserialization from object failed : rowid {row_id} \n{error}")] + SerdeRusqlite { + error: serde_rusqlite::Error, + row_id: usize, + }, #[error("Deserialisation from json failed : {0}")] SerdeJSON(#[from] serde_json::Error), + + #[error( + "Deserialisation from json failed at line {line} on file {file} while trying to parse the value: {parsed_value}: {error}]" + )] + SerdeJSONAt { + line: String, + file: String, + error: serde_json::Error, + parsed_value: String, + }, + + #[error("Couldn't convert into type {origin_type} with data {data}")] + Conversion { origin_type: String, data: String }, } #[derive(Error, Debug)] diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index e1d9e1b..cd52da0 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -2,9 +2,9 @@ // File: weaponry/src/weaponry_structs/equipement_fields.rs //! The inner fields used by the super structs -use std::fmt::Display; - use serde::{Deserialize, Serialize}; +use std::fmt::Display; +use std::ops::Add; use strum::Display; #[derive(Clone, Default, Debug, Deserialize, Serialize)] @@ -26,14 +26,30 @@ pub enum NatureTarget { /// Enum of all different physical weapon damage types #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Deserialize, Serialize)] -#[cfg_attr(test, derive(PartialEq))] +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +// #[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { Blunt, Slash, Pierce, } +// impl TryFrom<&str> for PhysicalDamageType { +// type Error = FatalEquipementError; + +// fn try_from(value: &str) -> Result { +// match value.to_ascii_lowercase().as_str() { +// "blunt" => Ok(Self::Blunt), +// "slash" => Ok(Self::Slash), +// "pierce" => Ok(Self::Pierce), +// _ => Err(FatalEquipementError::Conversion { +// origin_type: std::any::type_name::().to_owned(), +// data: value.to_string(), +// }), +// } +// } +// } + /// Weapon damage, combining the base weapon damage type and it's level /// /// Signifying wether the damage is pure or [secondary] or [[tertiary]] @@ -66,9 +82,46 @@ impl Display for DamageType { } } +// impl TryFrom<&str> for DamageType { +// type Error = FatalEquipementError; + +// fn try_from(value: &str) -> Result { +// let re = regex::Regex::new(r"(?\[\[\w+\]\])|(?\[\w+\])|(?\w+)") +// .unwrap(); +// let v = value +// .split(",") +// .map( +// |v| { +// let groups = re.captures(v).unwrap(); +// *groups +// }, // match v.trim() { +// // _ => Ok(DamageMod::Primary(PhysicalDamageType::Blunt)), +// // } +// ) +// .collect::, FatalEquipementError>>(); +// Ok(Self(v?)) +// } +// } +// impl FromSql for DamageType { +// fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult { +// Ok(DamageType(vec![DamageMod::Secondary( +// PhysicalDamageType::Pierce, +// )])) +// } +// } + +impl Add for DamageType { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self(self.0.iter().chain(rhs.0.iter()).cloned().collect()) + } +} + +// TODO: Convert into this category at the end, depending on all important factors /// List all weapon categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize)] +#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize, strum::EnumString)] // #[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, @@ -86,6 +139,25 @@ pub enum WeaponCategory { Bow, Crossbow, Cannon, + // Armor, + // Shield, +} + +// 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)] +pub enum WeaponMacroCategory { + Staves, + Blunt, + Slash, + Ranged, + Armor, + Shields, + Exotic, + /// A custom none category, used to forbid a part to be cast upon of from + // TODO: Check the soundness of this implementation + None, } #[cfg(test)] diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 9b7cb66..509ea8e 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -42,7 +42,10 @@ 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.category) { + filter_function: FilterFunction::new(&|sel, lhs| match ( + &sel.target, + &lhs.macro_category, + ) { (Some(a), Some(b)) => a == b, (None, None) => true, _ => false, @@ -83,7 +86,7 @@ impl Display for InnerEquipementStats { self.cost, self.difficulty, self.tier, - self.category + self.macro_category .clone() .map_or_else(|| "ø".to_string(), |v| v.to_string()) )]); @@ -107,7 +110,7 @@ impl Display for InnerEquipementStats { vec![format!("Prot:{} Int:{}", self.protection, self.integrity)], ); table.add_row(vec![format!( - "T1/T2 {}/{} Dodge:{} Parry:{} Speed:{} Stealth:{} Agility: {}", + "T1/T2 {:?}/{:?} Dodge:{} Parry:{} Speed:{} Stealth:{} Agility: {}", self.torque_one_handed, self.torque_two_handed, self.dodge, diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 47afd3f..58611ac 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -27,7 +27,7 @@ impl RecipeDatabase for EquipementDatabase { table: &str, filter: Option<&str>, ) -> Result, crate::error::FatalEquipementError> { - Ok(get_data(&self.conn, table, filter)?) + get_data(&self.conn, table, filter) } /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. @@ -73,6 +73,18 @@ impl FixedRecipe for EquipementFixedRecipe { } } +/// Macro converting a value using serde and mapping an in house error +macro_rules! from_serde { + ($value: expr) => { + serde_json::from_str(&$value).map_err(|error| FatalEquipementError::SerdeJSONAt { + line: line!().to_string(), + file: file!().to_string(), + parsed_value: $value.to_string(), + error, + }) + }; +} + // #[allow(clippy::useless_conversion)] impl TryFrom for InnerEquipementStats { type Error = FatalEquipementError; @@ -84,7 +96,8 @@ impl TryFrom for InnerEquipementStats { rarity: value.rarity, // Generic case, into(), serde or cast are equivalent cost: value.cost, difficulty: value.difficulty, - tier: value.tier, + // tier: value.tier, + tier: 0, damage: value.damage, p_damage: value.p_damage, precision: value.precision, @@ -92,20 +105,20 @@ impl TryFrom for InnerEquipementStats { armor_break: value.armor_break, armor_pierce: value.armor_pierce, antimaterial: value.antimaterial, - damage_type: serde_json::from_str(&value.damage_type)?, // Serde and derive are godsent + damage_type: from_serde!(&value.damage_type)?, // Serde and derive are godsent protection: value.protection, integrity: value.integrity, - torque_two_handed: value.torque_two_handed, - torque_one_handed: value.torque_one_handed, + torque_two_handed: from_serde!(&value.torque_two_handed)?, + torque_one_handed: from_serde!(&value.torque_one_handed)?, dodge: value.dodge, parry: value.parry, speed: value.speed, stealth: value.stealth, - category: serde_json::from_str(&value.category)?, - target: serde_json::from_str(&value.target)?, - special: serde_json::from_str(&value.special)?, + macro_category: from_serde!(&value.category)?, + target: from_serde!(&value.target)?, + special: from_serde!(&value.special)?, action_cost: value.action_cost, - reload_cost: serde_json::from_str(&value.reload_cost)?, + reload_cost: from_serde!(&value.reload_cost)?, range: value.range, agility_bonus: value.agility_bonus, }) diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index 36cd772..ae5370c 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -53,7 +53,7 @@ mod test { interfaces::RecipeCollection, weaponry_structs::{ DamageMod, DamageType, Equipement, InitialEquipementList, SpecialCategory, - WeaponCategory, equipement_fields::PhysicalDamageType, + equipement_fields::{PhysicalDamageType, WeaponMacroCategory}, equipement_structs::InnerEquipementStats, }, }; @@ -93,8 +93,8 @@ mod test { rarity: 1, integrity: 2, range: 3, - agility_bonus: 4, - category: Some(WeaponCategory::Dagger), + agility_bonus: 4., + macro_category: Some(WeaponMacroCategory::Staves), special: SpecialCategory(vec!["zero".into()]), damage_type: Some(DamageType(vec![DamageMod::Secondary( PhysicalDamageType::Slash, @@ -103,7 +103,7 @@ mod test { }; let i2 = InnerEquipementStats { integrity: 3, - agility_bonus: 5, + agility_bonus: 5., damage: 10, damage_type: Some(DamageType(vec![DamageMod::Primary( PhysicalDamageType::Blunt, @@ -116,10 +116,10 @@ mod test { InnerEquipementStats { rarity: 1, integrity: 5, - agility_bonus: 9, + agility_bonus: 9., damage: 10, range: 3, - category: Some(WeaponCategory::Dagger), + macro_category: Some(WeaponMacroCategory::Staves), special: SpecialCategory(vec!["zero".into(), "one".into(), "two".into()]), damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), @@ -172,7 +172,7 @@ mod test { fn test_basic_logic() {} impl Equipement { - fn newish(name: &[&str], i: u8) -> Self { + fn newish(name: &[&str], i: i8) -> Self { Equipement { stats: InnerEquipementStats { name: name.iter().map(|s| s.to_string()).collect(), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index ac6c4a6..e6e376d 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -22,10 +22,7 @@ macro_rules! add_two_options { (None, None) => None, (None, Some(a)) => Some(a), (Some(a), None) => Some(a), - (Some(mut a), Some(mut b)) => { - a.0.append(&mut b.0); - Some(a) - } + (Some(a), Some(b)) => Some(a + b), } }}; } @@ -52,15 +49,15 @@ impl std::ops::Add for &InnerEquipementStats { damage_type: add_two_options!(self.damage_type, rhs.damage_type), protection: self.protection + rhs.protection, integrity: self.integrity + rhs.integrity, - torque_two_handed: self.torque_two_handed + rhs.torque_two_handed, - torque_one_handed: self.torque_one_handed + rhs.torque_one_handed, + torque_two_handed: add_two_options!(self.torque_two_handed, rhs.torque_two_handed), + torque_one_handed: add_two_options!(self.torque_one_handed, rhs.torque_one_handed), dodge: self.dodge + rhs.dodge, parry: self.parry + rhs.parry, speed: self.speed + rhs.speed, stealth: self.stealth + rhs.stealth, - category: self.category.clone().or(rhs.category.clone()), // Can be further optimized - target: self.target.clone().or(rhs.target.clone()), // Can be further optimized - special: self.special.clone() + rhs.special.clone(), // Can be further optimized + macro_category: self.macro_category.clone().or(rhs.macro_category.clone()), // Can be further optimized + target: self.target.clone().or(rhs.target.clone()), // Can be further optimized + special: self.special.clone() + rhs.special.clone(), // Can be further optimized action_cost: self.action_cost + rhs.action_cost, reload_cost: self.reload_cost.or(rhs.reload_cost), range: self.range + rhs.range, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 0fd7c2d..e0899ef 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -8,7 +8,7 @@ use crate::interfaces::{FilterFunction, FilterFunctionType}; use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; -use super::{DamageType, SpecialCategory, WeaponCategory}; +use super::{DamageType, SpecialCategory, WeaponCategory, equipement_fields::WeaponMacroCategory}; /// The final equipement list /// @@ -59,33 +59,34 @@ impl FilterFunction { pub struct InnerEquipementStats { pub id: Vec, pub name: Vec, - pub(super) rarity: u8, - pub(super) cost: u8, - pub(super) difficulty: u8, - pub(super) tier: u8, - pub(super) damage: u8, - pub(super) p_damage: u8, + pub(super) rarity: i8, + pub(super) cost: i8, + pub(super) difficulty: i8, + pub(super) tier: i8, + pub(super) damage: i8, + pub(super) p_damage: i8, pub(super) precision: i8, - pub(super) rmax: u8, - pub(super) armor_break: u8, - pub(super) armor_pierce: u8, - pub(super) antimaterial: u8, + pub(super) rmax: i8, + pub(super) armor_break: i8, + pub(super) armor_pierce: i8, + pub(super) antimaterial: i8, pub(super) damage_type: Option, - pub(super) protection: u8, - pub(super) integrity: u8, - pub(super) torque_two_handed: u8, - pub(super) torque_one_handed: u8, - pub(super) dodge: u8, - pub(super) parry: u8, - pub(super) speed: u8, - pub(super) stealth: u8, - pub(super) category: Option, - pub(super) target: Option, + pub(super) protection: i8, + pub(super) integrity: i8, + pub(super) torque_two_handed: Option, // Might be option (single claw) + pub(super) torque_one_handed: Option, // Should be option (bows) + pub(super) dodge: f32, // I could also use a custom HalfValue + pub(super) parry: i8, + pub(super) speed: i8, + pub(super) stealth: i8, + /// The initial macro category, in turn combined with other stats it will describe a final category + pub(super) macro_category: Option, // TODO : This initial macro category fill as a final stat feed the final category + pub(super) target: Option, // TODO: This might be incorrect, to check pub(super) special: SpecialCategory, - pub(super) action_cost: u8, - pub(super) reload_cost: Option, - pub(super) range: u8, - pub(super) agility_bonus: u8, + 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) agility_bonus: f32, // Also convert this one to HalfValue } // TODO: This implementation of default is painfull @@ -101,54 +102,52 @@ pub struct DatabaseEquipementStats { pub meta_category: String, pub name: String, #[INTEGER] - pub rarity: u8, + pub rarity: i8, #[INTEGER] - pub cost: u8, + pub cost: i8, #[INTEGER] - pub difficulty: u8, + pub difficulty: i8, #[INTEGER] - pub tier: u8, + pub tier: i8, #[INTEGER] - pub damage: u8, + pub damage: i8, #[INTEGER] - pub p_damage: u8, + pub p_damage: i8, #[INTEGER] pub precision: i8, #[INTEGER] - pub rmax: u8, + pub rmax: i8, #[INTEGER] - pub armor_break: u8, + pub armor_break: i8, #[INTEGER] - pub armor_pierce: u8, + pub armor_pierce: i8, #[INTEGER] - pub antimaterial: u8, + pub antimaterial: i8, pub damage_type: String, #[INTEGER] - pub protection: u8, + pub protection: i8, #[INTEGER] - pub integrity: u8, + pub integrity: i8, + pub torque_two_handed: String, + pub torque_one_handed: String, + #[REAL] + pub dodge: f32, #[INTEGER] - pub torque_two_handed: u8, + pub parry: i8, #[INTEGER] - pub torque_one_handed: u8, + pub speed: i8, #[INTEGER] - pub dodge: u8, - #[INTEGER] - pub parry: u8, - #[INTEGER] - pub speed: u8, - #[INTEGER] - pub stealth: u8, + pub stealth: i8, pub category: String, pub target: String, pub special: String, #[INTEGER] - pub action_cost: u8, + pub action_cost: i8, pub reload_cost: String, #[INTEGER] - pub range: u8, - #[INTEGER] - pub agility_bonus: u8, + pub range: i8, + #[REAL] + pub agility_bonus: f32, } impl Default for DatabaseEquipementStats { @@ -158,7 +157,7 @@ impl Default for DatabaseEquipementStats { meta_category: "EqShape".to_string(), name: String::new(), damage_type: serde_json::to_string(&None::).unwrap(), - category: serde_json::to_string(&None::).unwrap(), + category: serde_json::to_string(&None::).unwrap(), target: serde_json::to_string(&None::).unwrap(), special: serde_json::to_string(&SpecialCategory::default()).unwrap(), reload_cost: serde_json::to_string(&None::).unwrap(), @@ -175,14 +174,14 @@ impl Default for DatabaseEquipementStats { antimaterial: 0, protection: 0, integrity: 0, - torque_two_handed: 0, - torque_one_handed: 0, - dodge: 0, + torque_two_handed: serde_json::to_string(&0).unwrap(), + torque_one_handed: serde_json::to_string(&None::).unwrap(), + dodge: 0., parry: 0, speed: 0, stealth: 0, range: 0, - agility_bonus: 0, + agility_bonus: 0., action_cost: 0, } } @@ -193,7 +192,7 @@ impl Default for DatabaseEquipementStats { #[doc(hidden)] macro_rules! r { () => { - fastrand::u8(1..u8::MAX) + fastrand::i8(1..i8::MAX) }; } // TODO: Make this a test requirement or hide it behind a profile @@ -201,11 +200,11 @@ impl InnerEquipementStats { /// Testing function to fuzz data pub fn random_new() -> Self { Self { - id: vec![r!()], - range: r!(), - damage: r!(), - p_damage: r!(), - protection: r!(), + id: vec![r!() as u8], + range: r!() - 10, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, ..Default::default() } } @@ -215,11 +214,11 @@ impl DatabaseEquipementStats { /// Testing function to fuzz data pub fn random_new() -> Self { Self { - id: r!(), - range: r!(), - damage: r!(), - p_damage: r!(), - protection: r!(), + id: r!() as u8, + range: r!() - 19, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, ..Default::default() } } diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index d9203c8..e4ab206 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -34,4 +34,6 @@ pub use equipement_structs::{Equipement, InitialEquipementList}; // All generic fields // #[allow(unused_imports)] pub use equipement_fields::PhysicalDamageType; -pub use equipement_fields::{DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory}; +pub use equipement_fields::{ + DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMacroCategory, +};