From d27cc588b1530cfdceebf880e0cb9285e59b9302 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 11 Feb 2025 00:45:34 +0100 Subject: [PATCH 01/97] First implementation of the Polymorphism --- weaponry/src/interfaces.rs | 37 ++++++++++ weaponry/src/strategy.rs | 65 +++++++---------- weaponry/src/weaponry_structs.rs | 115 ++++++++++++++++++++++++++++++- 3 files changed, 175 insertions(+), 42 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 32b050c..3252bd9 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -10,3 +10,40 @@ pub trait ToTex {} /// Specify this element can be made from parts (Unsure, maybe a way to ensure Add is presend ?) pub trait FromParts {} + +/// Trait implemented for the final collection of a recipe, allowing it to be combined with something +/// +/// A recipe list will be combined with a part list to be updated and generate all combinaisons, so on and so forth +pub trait RecipeCombinaison { + /// The type of the inner recipes, this type must be combinable + type Recipes: Combineable; + + /// Combine all current recipies with all the parts given + fn combine_all(&mut self, other: G) -> Self + where + G: RecipeCombinaison; + + /// Access the inner list + // TODO: Use iterators ? + fn inner(&self) -> Vec; + // Optional filter ? +} + +/// Trait that ensure that two elements of a recipe are combinable, +/// +/// Being combinable means it can be coerced into elements that implement add +pub trait Combineable { + /// The inner type of the combined elements, this type must implement Add + type Inner: std::ops::Add; + + /// Give access to an owned underlying type that can be combined + // TODO: the ownership part might not be needed + fn clone_combinable_part(&self) -> Self::Inner; + + /// Add an element to self and return a new value + /// + /// This method will clone it's own combinable part + fn add_to_self(&self, rhs: T) -> Self + where + T: Combineable; +} diff --git a/weaponry/src/strategy.rs b/weaponry/src/strategy.rs index 15c8c97..03b8c4f 100644 --- a/weaponry/src/strategy.rs +++ b/weaponry/src/strategy.rs @@ -8,8 +8,6 @@ //! #![allow(dead_code)] -use rayon::iter::ParallelIterator; - /// Generation strategy, how to generate all the data, instead of a full permutation pub enum EquipementStrategy { /// Full permutation, generate all possible outcomes @@ -44,50 +42,39 @@ pub enum EquipementFilter { Named, } -// /// D -// struct Gen -// where -// T: Send, -// { -// /// E -// elem: Vec, -// } - -// impl ParallelIterator for Gen { -// type Item = T; - -// fn drive_unindexed(self, consumer: C) -> C::Result -// where -// C: rayon::iter::plumbing::UnindexedConsumer, -// { -// let _ = consumer; -// todo!() -// } -// } // /// Default full generation strategy // pub fn default_generation() -> impl ParallelIterator { // Gen:: { elem: Vec::new() } // } -/// Default full generation strategy -pub fn default_generation(a: Vec, b: Vec) -> Vec<(T, T)> { - a.iter() - .flat_map(|e| { - b.iter() - .map(|f| ((e.clone()), (f.clone()))) - .collect::>() - }) - // .collect::>>() - // .flatten() - .collect() -} + +// /// Default full generation strategy +// pub fn naive_generation(left: Vec, right: Vec) -> Vec +// where +// T: Clone, +// for<'a> &'a T: std::ops::Add<&'a T>, +// { +// left.iter() +// .flat_map(move |e| right.iter().map(move |f| (e + f)).collect::>()) +// .collect() +// } + +// /// Default full generation strategy +// /// +// /// Take a list of various parts that are combinable and combines them +// pub fn naive_generation( +// list_recipes: Vec>>, +// ) -> Vec { +// list_recipes.iter().reduce(|acc, e| acc.combine_all(e)); +// todo!() +// } #[cfg(test)] mod test { - use super::*; + // use super::*; + #[test] - fn test_creator() { - let t = default_generation(vec![1, 2, 3], vec![5, 6, 7]); - println!("{:?}", t); - panic!() + fn test_naive_generator() { + // let t = naive_generation(vec![1, 2, 3], vec![5, 6, 7]); + // assert_eq!(t.len(), 3 * 3); } } diff --git a/weaponry/src/weaponry_structs.rs b/weaponry/src/weaponry_structs.rs index 73c6389..f5f60d0 100644 --- a/weaponry/src/weaponry_structs.rs +++ b/weaponry/src/weaponry_structs.rs @@ -4,9 +4,12 @@ #![allow(dead_code)] +use crate::interfaces::{Combineable, RecipeCombinaison}; + /// The inner statistics of the equipement, used across all parts and final weapon // #[derive(Default)] #[allow(clippy::missing_docs_in_private_items)] +#[derive(Clone, Default)] pub struct InnerStats { id: usize, name: String, @@ -21,7 +24,7 @@ pub struct InnerStats { armor_break: u8, armor_pierce: u8, antimaterial: u8, - damage_type: DamageMod, + damage_type: Option, protection: u8, integrity: u8, torque_two_handed: Option, @@ -30,20 +33,87 @@ pub struct InnerStats { parry: u8, speed: u8, stealth: u8, - category: WeaponCategory, - special: Vec, + category: Option, + special: SpecialCategory, action_cost: u8, reload_cost: Option, range: u8, agility_bonus: u8, } +impl std::ops::Add for InnerStats { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + rarity: self.rarity + rhs.rarity, + cost: self.cost + rhs.cost, + difficulty: self.difficulty + rhs.difficulty, + tier: self.tier + rhs.tier, + damage: self.damage + rhs.damage, + p_damage: self.p_damage + rhs.p_damage, + precision: self.precision + rhs.precision, + rmax: self.rmax + rhs.rmax, + armor_break: self.armor_break + rhs.armor_break, + armor_pierce: self.armor_pierce + rhs.armor_pierce, + antimaterial: self.antimaterial + rhs.antimaterial, + damage_type: self.damage_type.or(rhs.damage_type), + protection: self.protection + rhs.protection, + integrity: self.integrity + rhs.integrity, + two_handed: self.two_handed + rhs.two_handed, + one_handed: self.one_handed + rhs.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.or(rhs.category), + special: self.special + rhs.special, + action_cost: self.action_cost + rhs.action_cost, + reload_cost: self.reload_cost + rhs.reload_cost, + range: self.range + rhs.range, + agility_bonus: self.agility_bonus + rhs.agility_bonus, + } + } +} + +#[derive(Clone, Default)] +/// The special category, a vec of string, for display purposes only +struct SpecialCategory(Vec); + +impl std::ops::Add for SpecialCategory { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + let mut c = self.clone(); + // TODO: Overcopy, kinda meaningless optimisation tho + c.0.append(&mut rhs.clone().0); + c + } +} + /// The final equipement, obtained by combining all parts +#[derive(Clone)] pub struct Equipement { /// The inner stats used by the equipement stats: InnerStats, } +impl Combineable for Equipement { + type Inner = InnerStats; + fn clone_combinable_part(&self) -> InnerStats { + self.stats.clone() + } + + fn add_to_self(&self, rhs: T) -> Self + where + T: Combineable, + { + let mut new = self.clone(); + new.stats = self.clone_combinable_part() + rhs.clone_combinable_part(); + new + } +} + /// Shape of the equipement, first mandatory part of an equipement pub struct EqShape { /// The inner stats of the part @@ -84,6 +154,7 @@ pub enum NatureTarget { /// Enum of all different physical weapon damage types #[allow(clippy::missing_docs_in_private_items)] +#[derive(Clone)] pub enum PhysicalDamageType { Blunt, Slash, @@ -102,6 +173,7 @@ impl From<&str> for PhysicalDamageType { /// /// Signifying wether the damage is pure or [secondary] or [[tertiary]] #[allow(clippy::missing_docs_in_private_items)] +#[derive(Clone)] pub enum DamageMod { Primary(PhysicalDamageType), Secondary(PhysicalDamageType), @@ -131,6 +203,7 @@ impl From<&str> for DamageType { /// List all weapon categories #[allow(clippy::missing_docs_in_private_items)] +#[derive(Clone)] pub enum WeaponCategory { Exotic, Dagger, @@ -156,6 +229,42 @@ impl From<&str> for WeaponCategory { } } +/// The final equipement list +/// +/// This list is initialized with the base part and updated by succesive combinaisons +#[derive(Clone)] +struct FinalEquipementList { + /// Inner List of final equipements + inner: Vec, +} + +impl RecipeCombinaison for FinalEquipementList { + type Recipes = Equipement; + + fn combine_all(&mut self, other: G) -> Self + where + G: RecipeCombinaison, + { + self.inner = self + .inner() + .iter() + .flat_map(|e| { + other + .inner() + .iter() + .map(|f: &Self::Recipes| e.add_to_self(f.clone())) + .collect::>() + // .collect::>>() + }) + .collect(); + todo!() + } + + fn inner(&self) -> Vec { + self.inner.clone() + } +} + #[cfg(test)] mod test { // use super::*; -- 2.45.1 From 69fcf1dffbea45175bcaf091a5f25db1cf6c50f2 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 11 Feb 2025 03:46:02 +0100 Subject: [PATCH 02/97] Quick and dirty combination --- weaponry/Cargo.toml | 9 + weaponry/benches/iter_creation.rs | 119 ++++++++ weaponry/src/interfaces.rs | 12 +- weaponry/src/lib.rs | 4 +- weaponry/src/weaponry_structs.rs | 277 ----------------- .../src/weaponry_structs/equipement_fields.rs | 121 ++++++++ .../equipement_impl_database.rs | 3 + .../weaponry_structs/equipement_impl_io.rs | 20 ++ .../weaponry_structs/equipement_impl_logic.rs | 287 ++++++++++++++++++ .../weaponry_structs/equipement_structs.rs | 130 ++++++++ weaponry/src/weaponry_structs/mod.rs | 19 ++ 11 files changed, 718 insertions(+), 283 deletions(-) create mode 100644 weaponry/benches/iter_creation.rs delete mode 100644 weaponry/src/weaponry_structs.rs create mode 100644 weaponry/src/weaponry_structs/equipement_fields.rs create mode 100644 weaponry/src/weaponry_structs/equipement_impl_database.rs create mode 100644 weaponry/src/weaponry_structs/equipement_impl_io.rs create mode 100644 weaponry/src/weaponry_structs/equipement_impl_logic.rs create mode 100644 weaponry/src/weaponry_structs/equipement_structs.rs create mode 100644 weaponry/src/weaponry_structs/mod.rs diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 84ccf64..4299523 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -4,4 +4,13 @@ version = "0.1.0" edition = "2024" [dependencies] +pretty_assertions = "1.4.1" rayon = "1.10.0" + +[dev-dependencies] +criterion = { version = "0.5"} + +[[bench]] +name = "iter_creation" +harness = false + diff --git a/weaponry/benches/iter_creation.rs b/weaponry/benches/iter_creation.rs new file mode 100644 index 0000000..0d5511f --- /dev/null +++ b/weaponry/benches/iter_creation.rs @@ -0,0 +1,119 @@ +use criterion::{Criterion, criterion_group, criterion_main}; +use std::{hint::black_box, time::Duration}; +use weaponry::{ + interfaces::RecipeCollection, + weaponry_structs::{ + Equipement, FinalEquipementList, equipement_structs::FinalEquipementListPar, + }, +}; + +fn criterion_benchmark(c: &mut Criterion) { + let steps = [ + FinalEquipementList::from_vectored(vec![Equipement::default(); 100]), + FinalEquipementList::from_vectored(vec![Equipement::default(); 100]), + FinalEquipementList::from_vectored(vec![Equipement::default(); 100]), + ]; + let par_steps = [ + FinalEquipementListPar::from_vectored(vec![Equipement::default(); 100]), + FinalEquipementListPar::from_vectored(vec![Equipement::default(); 100]), + FinalEquipementListPar::from_vectored(vec![Equipement::default(); 100]), + ]; + c.bench_function("creating 100 Elements", |b| { + b.iter(|| FinalEquipementList::from_vectored(black_box(vec![Equipement::default(); 100]))) + }); + c.bench_function("IterGen: 100x100x100", |b| { + b.iter(|| { + let mut s = steps[0].clone(); + s.combine_all(steps[1].clone()); + s.combine_all(steps[2].clone()); + }) + }); + c.bench_function("IterGen: 100x100x100", |b| { + b.iter(|| { + let mut s = par_steps[0].clone(); + s.combine_all(par_steps[1].clone()); + s.combine_all(par_steps[2].clone()); + }) + }); + // c.bench_function("IterGen: 100x100x100x100", |b| { + // b.iter(|| { + // let mut s = steps[0].clone(); + // s.combine_all(steps[1].clone()); + // s.combine_all(steps[2].clone()); + // s.combine_all(steps[2].clone()); + // }) + // }); + c.bench_function("IterGenPar: 100x100x100x100", |b| { + b.iter(|| { + let mut s = par_steps[0].clone(); + s.combine_all(par_steps[1].clone()); + s.combine_all(par_steps[2].clone()); + s.combine_all(par_steps[2].clone()); + }) + }); +} + +criterion_group! { + name = benches; + config = Criterion::default().measurement_time(Duration::from_secs(10)); + targets= criterion_benchmark +} +criterion_main!(benches); + +// TODO: Add to a How to add new Lists + +// #[derive(Clone)] +// struct Equipo { +// stats: InnerStats, +// } + +// impl Equipo { +// fn newish(i: u8) -> Self { +// let mut stats = InnerStats::default(); +// stats.id = i; +// Equipo { stats } +// } +// } + +// struct ListStatic { +// inner: Vec, +// } +// struct ListParIter { +// inner: Vec, +// } + +// impl RecipeCollection for ListStatic { +// type Recipes = Equipo; + +// fn combine_all(&mut self, other: G) +// where +// G: RecipeCollection, +// { +// todo!() +// } + +// fn inner(&self) -> Vec { +// self.inner.clone() +// } + +// fn from_vectored(list: Vec) -> Self { +// Self { inner: list } +// } +// } + +// impl Combineable for Equipo { +// type Inner = InnerStats; + +// fn clone_combinable_part(&self) -> Self::Inner { +// self.stats.clone() +// } + +// fn add_to_self(&self, rhs: T) -> Self +// where +// T: Combineable, +// { +// Equipo { +// stats: self.clone_combinable_part() + rhs.clone_combinable_part(), +// } +// } +// } diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 3252bd9..bb75100 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -11,22 +11,25 @@ pub trait ToTex {} /// Specify this element can be made from parts (Unsure, maybe a way to ensure Add is presend ?) pub trait FromParts {} -/// Trait implemented for the final collection of a recipe, allowing it to be combined with something +/// Trait implemented for the final collection of a recipe, allowing it to be combined with parts /// /// A recipe list will be combined with a part list to be updated and generate all combinaisons, so on and so forth -pub trait RecipeCombinaison { +pub trait RecipeCollection { /// The type of the inner recipes, this type must be combinable type Recipes: Combineable; /// Combine all current recipies with all the parts given - fn combine_all(&mut self, other: G) -> Self + fn combine_all(&mut self, other: G) where - G: RecipeCombinaison; + G: RecipeCollection + std::marker::Sync; /// Access the inner list // TODO: Use iterators ? fn inner(&self) -> Vec; // Optional filter ? + + /// Create a collection from a vector + fn from_vectored(list: Vec) -> Self; } /// Trait that ensure that two elements of a recipe are combinable, @@ -34,6 +37,7 @@ pub trait RecipeCombinaison { /// Being combinable means it can be coerced into elements that implement add pub trait Combineable { /// The inner type of the combined elements, this type must implement Add + // TODO : Make this help much more readable type Inner: std::ops::Add; /// Give access to an owned underlying type that can be combined diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index dc0d79d..bf88e5e 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -6,6 +6,6 @@ mod database; mod export; -mod interfaces; +pub mod interfaces; mod strategy; -mod weaponry_structs; +pub mod weaponry_structs; diff --git a/weaponry/src/weaponry_structs.rs b/weaponry/src/weaponry_structs.rs deleted file mode 100644 index f5f60d0..0000000 --- a/weaponry/src/weaponry_structs.rs +++ /dev/null @@ -1,277 +0,0 @@ -// Workspace: weaponry -// File: weaponry/src/weaponry_structs.rs -//! All weaponry intermod structures - -#![allow(dead_code)] - -use crate::interfaces::{Combineable, RecipeCombinaison}; - -/// The inner statistics of the equipement, used across all parts and final weapon -// #[derive(Default)] -#[allow(clippy::missing_docs_in_private_items)] -#[derive(Clone, Default)] -pub struct InnerStats { - id: usize, - name: String, - rarity: u8, - cost: u8, - difficulty: u8, - tier: u8, - damage: u8, - p_damage: u8, - precision: u8, - rmax: u8, - armor_break: u8, - armor_pierce: u8, - antimaterial: u8, - damage_type: Option, - protection: u8, - integrity: u8, - torque_two_handed: Option, - torque_one_handed: Option, - dodge: u8, - parry: u8, - speed: u8, - stealth: u8, - category: Option, - special: SpecialCategory, - action_cost: u8, - reload_cost: Option, - range: u8, - agility_bonus: u8, -} - -impl std::ops::Add for InnerStats { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - Self { - rarity: self.rarity + rhs.rarity, - cost: self.cost + rhs.cost, - difficulty: self.difficulty + rhs.difficulty, - tier: self.tier + rhs.tier, - damage: self.damage + rhs.damage, - p_damage: self.p_damage + rhs.p_damage, - precision: self.precision + rhs.precision, - rmax: self.rmax + rhs.rmax, - armor_break: self.armor_break + rhs.armor_break, - armor_pierce: self.armor_pierce + rhs.armor_pierce, - antimaterial: self.antimaterial + rhs.antimaterial, - damage_type: self.damage_type.or(rhs.damage_type), - protection: self.protection + rhs.protection, - integrity: self.integrity + rhs.integrity, - two_handed: self.two_handed + rhs.two_handed, - one_handed: self.one_handed + rhs.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.or(rhs.category), - special: self.special + rhs.special, - action_cost: self.action_cost + rhs.action_cost, - reload_cost: self.reload_cost + rhs.reload_cost, - range: self.range + rhs.range, - agility_bonus: self.agility_bonus + rhs.agility_bonus, - } - } -} - -#[derive(Clone, Default)] -/// The special category, a vec of string, for display purposes only -struct SpecialCategory(Vec); - -impl std::ops::Add for SpecialCategory { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - let mut c = self.clone(); - // TODO: Overcopy, kinda meaningless optimisation tho - c.0.append(&mut rhs.clone().0); - c - } -} - -/// The final equipement, obtained by combining all parts -#[derive(Clone)] -pub struct Equipement { - /// The inner stats used by the equipement - stats: InnerStats, -} - -impl Combineable for Equipement { - type Inner = InnerStats; - fn clone_combinable_part(&self) -> InnerStats { - self.stats.clone() - } - - fn add_to_self(&self, rhs: T) -> Self - where - T: Combineable, - { - let mut new = self.clone(); - new.stats = self.clone_combinable_part() + rhs.clone_combinable_part(); - new - } -} - -/// Shape of the equipement, first mandatory part of an equipement -pub struct EqShape { - /// The inner stats of the part - stats: InnerStats, -} - -/// Material used for the equipement, all equipements are crafted with 1-2 materials -pub struct EqMaterial { - /// The inner stats of the part - stats: InnerStats, -} - -/// Nature of the equipement, some natures are reserved and some can be chained -/// -/// Deciding on the combinaison can be tricky an will need an extra field -pub struct EqNature { - /// The inner stats of the part - stats: InnerStats, - /// Which kind of target this nature applies to - target: NatureTarget, -} - -/// Finishing touches, since all of them have a cost, they are treated in a special fashion -pub struct EqFinishing { - /// The inner stats of the part - stats: InnerStats, -} - -/// The kind of target this nature can apply to -pub enum NatureTarget { - /// Can apply to a weapon and is unique - WeaponUnique, - /// Can apply to a weapon and must be combined with another - WeaponCombined, - /// Can apply to an armor (all armor nature are unique) - Armor, -} - -/// Enum of all different physical weapon damage types -#[allow(clippy::missing_docs_in_private_items)] -#[derive(Clone)] -pub enum PhysicalDamageType { - Blunt, - Slash, - Pierce, -} - -impl From<&str> for PhysicalDamageType { - fn from(value: &str) -> Self { - let _ = value; - // Matchcase for all damage types - todo!() - } -} - -/// Weapon damage, combining the base weapon damage type and it's level -/// -/// Signifying wether the damage is pure or [secondary] or [[tertiary]] -#[allow(clippy::missing_docs_in_private_items)] -#[derive(Clone)] -pub enum DamageMod { - Primary(PhysicalDamageType), - Secondary(PhysicalDamageType), - Tertiary(PhysicalDamageType), -} - -impl From<&str> for DamageMod { - fn from(value: &str) -> Self { - let _ = value; - // Detect [] and recurse from - todo!() - } -} - -/// Combined damage type, as a vector of all damage types -/// -/// Meant to be serialised to tex and deserialized directly from the table -pub struct DamageType(Vec); - -impl From<&str> for DamageType { - fn from(value: &str) -> Self { - let _ = value; - // Split by , then recurse from and collect - todo!() - } -} - -/// List all weapon categories -#[allow(clippy::missing_docs_in_private_items)] -#[derive(Clone)] -pub enum WeaponCategory { - Exotic, - Dagger, - Claws, - Blade, - Haroth, - Axe, - Kahml, - Hammer, - Rhodarak, - Staff, - Lance, - Landscapper, - Bow, - Crossbow, - Cannon, -} - -impl From<&str> for WeaponCategory { - fn from(value: &str) -> Self { - let _ = value; - todo!() - } -} - -/// The final equipement list -/// -/// This list is initialized with the base part and updated by succesive combinaisons -#[derive(Clone)] -struct FinalEquipementList { - /// Inner List of final equipements - inner: Vec, -} - -impl RecipeCombinaison for FinalEquipementList { - type Recipes = Equipement; - - fn combine_all(&mut self, other: G) -> Self - where - G: RecipeCombinaison, - { - self.inner = self - .inner() - .iter() - .flat_map(|e| { - other - .inner() - .iter() - .map(|f: &Self::Recipes| e.add_to_self(f.clone())) - .collect::>() - // .collect::>>() - }) - .collect(); - todo!() - } - - fn inner(&self) -> Vec { - self.inner.clone() - } -} - -#[cfg(test)] -mod test { - // use super::*; - - #[test] - fn test_data_serialisation() {} - - #[test] - fn test_data_deserialisation() {} -} diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs new file mode 100644 index 0000000..2bbcb5d --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -0,0 +1,121 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_fields.rs +//! The inner fields used by the super structs + +#[derive(Clone, Default)] +#[cfg_attr(test, derive(Debug, PartialEq))] +/// The special category, a vec of string, for display purposes only +pub struct SpecialCategory(pub(super) Vec); + +/// The kind of target this nature can apply to +pub enum NatureTarget { + /// Can apply to a weapon and is unique + WeaponUnique, + /// Can apply to a weapon and must be combined with another + WeaponCombined, + /// Can apply to an armor (all armor nature are unique) + Armor, +} + +/// Enum of all different physical weapon damage types +#[allow(clippy::missing_docs_in_private_items)] +#[derive(Clone)] +#[cfg_attr(test, derive(Debug, PartialEq))] +pub enum PhysicalDamageType { + Blunt, + Slash, + Pierce, +} +impl From<&str> for PhysicalDamageType { + fn from(value: &str) -> Self { + let _ = value; + // Matchcase for all damage types + todo!() + } +} + +/// Weapon damage, combining the base weapon damage type and it's level +/// +/// Signifying wether the damage is pure or [secondary] or [[tertiary]] +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone)] +#[cfg_attr(test, derive(Debug, PartialEq))] +pub enum DamageMod { + Primary(PhysicalDamageType), + Secondary(PhysicalDamageType), + Tertiary(PhysicalDamageType), +} + +impl From<&str> for DamageMod { + fn from(value: &str) -> Self { + let _ = value; + // Detect [] and recurse from + todo!() + } +} + +/// Combined damage type, as a vector of all damage types +/// +/// Meant to be serialised to tex and deserialized directly from the table +#[derive(Clone)] +#[cfg_attr(test, derive(Debug, PartialEq))] +pub struct DamageType(pub(super) Vec); + +impl From<&str> for DamageType { + fn from(value: &str) -> Self { + let _ = value; + // Split by , then recurse from and collect + todo!() + } +} + +/// List all weapon categories +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone)] +#[cfg_attr(test, derive(Debug, PartialEq))] +pub enum WeaponCategory { + Exotic, + Dagger, + Claws, + Blade, + Haroth, + Axe, + Kahml, + Hammer, + Rhodarak, + Staff, + Lance, + Landscapper, + Bow, + Crossbow, + Cannon, +} + +impl From<&str> for WeaponCategory { + fn from(value: &str) -> Self { + let _ = value; + todo!() + } +} + +// TODO: Consider this for test +// impl Equipement{ +// fn random_equipement(){} +// } + +#[cfg(test)] +mod test { + // use super::*; + + #[ignore] + #[test] + fn test_fields_serialisation() { + unimplemented!() + } + + #[ignore] + #[test] + fn test_fields_deserialisation() { + unimplemented!() + } +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs new file mode 100644 index 0000000..d300254 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -0,0 +1,3 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_impl_database.rs +//! All database specific implementations diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs new file mode 100644 index 0000000..14c7ccd --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -0,0 +1,20 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_impl_io.rs +//! All implementation IO specific (mainly export and serde) + +#[cfg(test)] +mod test { + // use super::*; + + #[ignore] + #[test] + fn test_structs_serialisation() { + unimplemented!() + } + + #[ignore] + #[test] + fn test_structs_deserialisation() { + unimplemented!() + } +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs new file mode 100644 index 0000000..f7198e9 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -0,0 +1,287 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_impl_logic.rs +//! Implementation of the logic traits, used for equipement generation + +use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; + +use crate::interfaces::{Combineable, RecipeCollection}; + +use super::{ + Equipement, FinalEquipementList, SpecialCategory, + equipement_structs::{FinalEquipementListPar, InnerStats}, +}; + +impl std::ops::Add for InnerStats { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless + id: self.id, + name: [self.name, rhs.name].join("+"), + rarity: self.rarity + rhs.rarity, + cost: self.cost + rhs.cost, + difficulty: self.difficulty + rhs.difficulty, + tier: self.tier + rhs.tier, + damage: self.damage + rhs.damage, + p_damage: self.p_damage + rhs.p_damage, + precision: self.precision + rhs.precision, + rmax: self.rmax + rhs.rmax, + armor_break: self.armor_break + rhs.armor_break, + armor_pierce: self.armor_pierce + rhs.armor_pierce, + antimaterial: self.antimaterial + rhs.antimaterial, + damage_type: { + match (self.damage_type, rhs.damage_type) { + (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) + } + } + }, + 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, + dodge: self.dodge + rhs.dodge, + parry: self.parry + rhs.parry, + speed: self.speed + rhs.speed, + stealth: self.stealth + rhs.stealth, + category: self.category.or(rhs.category), + special: self.special + rhs.special, + action_cost: self.action_cost + rhs.action_cost, + reload_cost: self.reload_cost.or(rhs.reload_cost), + range: self.range + rhs.range, + agility_bonus: self.agility_bonus + rhs.agility_bonus, + } + } +} + +impl std::ops::Add for SpecialCategory { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + let mut c = self.clone(); + // TODO: Overcopy, kinda meaningless optimisation tho + c.0.append(&mut rhs.clone().0); + c + } +} + +impl Combineable for Equipement { + type Inner = InnerStats; + fn clone_combinable_part(&self) -> InnerStats { + self.stats.clone() + } + + fn add_to_self(&self, rhs: T) -> Self + where + T: Combineable, + { + Self { + stats: self.clone_combinable_part() + rhs.clone_combinable_part(), + } + } +} + +impl RecipeCollection for FinalEquipementList { + type Recipes = Equipement; + + fn combine_all(&mut self, other: G) + where + G: RecipeCollection, + { + self.inner = self + .inner() + .iter() + .flat_map(|e| { + other + .inner() + .iter() + .map(|f: &Self::Recipes| e.add_to_self(f.clone())) + .collect::>() + }) + .collect(); + } + + fn inner(&self) -> Vec { + self.inner.clone() + } + + fn from_vectored(list: Vec) -> Self { + Self { inner: list } + } +} + +impl RecipeCollection for FinalEquipementListPar { + type Recipes = Equipement; + + fn combine_all(&mut self, other: G) + where + G: RecipeCollection + std::marker::Sync, + { + self.inner = self + .inner() + .par_iter() + .flat_map(|e| { + other + .inner() + .par_iter() + .map(|f: &Self::Recipes| e.add_to_self(f.clone())) + .collect::>() + }) + .collect(); + } + + fn inner(&self) -> Vec { + self.inner.clone() + } + + fn from_vectored(list: Vec) -> Self { + Self { inner: list } + } +} + +#[cfg(test)] +mod test { + use crate::{ + interfaces::RecipeCollection, + weaponry_structs::{ + DamageMod, DamageType, Equipement, FinalEquipementList, SpecialCategory, + WeaponCategory, equipement_fields::PhysicalDamageType, equipement_structs::InnerStats, + }, + }; + use pretty_assertions::assert_eq; + + #[test] + fn test_struct_generation() { + let mut f = FinalEquipementList::from_vectored(vec![ + Equipement::newish("", 1), + Equipement::newish("", 2), + ]); + let g = FinalEquipementList::from_vectored(vec![ + Equipement::newish("", 4), + Equipement::newish("", 8), + ]); + + assert_eq!( + f.inner(), + vec![Equipement::newish("", 1), Equipement::newish("", 2)] + ); + + f.combine_all(g); + assert_eq!( + f, + FinalEquipementList::from_vectored(vec![ + Equipement::newish("+", 5), + Equipement::newish("+", 9), + Equipement::newish("+", 6), + Equipement::newish("+", 10) + ]) + ); + } + + #[test] + fn test_base_operation() { + // let inner = InnerStats::default(); + // let inner2 = inner.clone() + inner.clone(); + // assert_eq!(inner, inner2); // True because of the 0 initialisation + let i1 = InnerStats { + rarity: 1, + integrity: 2, + range: 3, + agility_bonus: 4, + category: Some(WeaponCategory::Dagger), + special: SpecialCategory(vec!["zero".into()]), + damage_type: Some(DamageType(vec![DamageMod::Secondary( + PhysicalDamageType::Slash, + )])), + ..Default::default() + }; + let i2 = InnerStats { + integrity: 3, + agility_bonus: 5, + damage: 10, + damage_type: Some(DamageType(vec![DamageMod::Primary( + PhysicalDamageType::Blunt, + )])), + special: SpecialCategory(vec!["one".into(), "two".into()]), + ..Default::default() + }; + assert_eq!( + i1 + i2, + InnerStats { + name: "+".into(), + rarity: 1, + integrity: 5, + agility_bonus: 9, + damage: 10, + range: 3, + category: Some(WeaponCategory::Dagger), + special: SpecialCategory(vec!["zero".into(), "one".into(), "two".into()]), + damage_type: Some(DamageType(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + } + ); + assert_eq!( + InnerStats { + damage_type: Some(DamageType(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + } + InnerStats::default(), + InnerStats { + name: "+".into(), + damage_type: Some(DamageType(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + }, + ); + assert_eq!( + InnerStats::default() + + InnerStats { + damage_type: Some(DamageType(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + }, + InnerStats { + name: "+".into(), + damage_type: Some(DamageType(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + }, + ); + } + + #[ignore] + #[test] + fn test_generator_function() {} + + #[ignore] + #[test] + fn test_basic_logic() {} + + impl Equipement { + fn newish(name: &str, i: u8) -> Self { + Equipement { + stats: InnerStats { + name: name.to_owned(), + rarity: i, + ..Default::default() + }, + } + } + } +} diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs new file mode 100644 index 0000000..7ba3706 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -0,0 +1,130 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_structs.rs +//! Base equipement structures + +use super::{DamageType, NatureTarget, SpecialCategory, WeaponCategory}; + +/// The final equipement list +/// +/// This list is initialized with the base part and updated by succesive combinaisons +#[derive(Clone)] +#[cfg_attr(test, derive(PartialEq, Debug))] +pub struct FinalEquipementList { + /// Inner List of final equipements + pub(super) inner: Vec, +} + +/// A parallel Implementation of the final equipement list +/// +/// This list only serve for benchmark purposes +#[derive(Clone)] +#[cfg_attr(test, derive(PartialEq, Debug))] +pub struct FinalEquipementListPar { + /// Inner List of final equipements + pub(super) inner: Vec, +} + +/// The final equipement, obtained by combining all parts +#[derive(Clone, Default)] +#[cfg_attr(test, derive(PartialEq, Debug))] +pub struct Equipement { + /// The inner stats used by the equipement + pub(super) stats: InnerStats, +} + +/// The inner statistics of the equipement, used across all parts and final weapon +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Default)] +#[cfg_attr(test, derive(Debug, PartialEq))] +pub struct InnerStats { + pub id: u8, + pub name: String, + 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) precision: u8, + pub(super) rmax: u8, + pub(super) armor_break: u8, + pub(super) armor_pierce: u8, + pub(super) antimaterial: u8, + 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) special: SpecialCategory, + pub(super) action_cost: u8, + pub(super) reload_cost: Option, + pub(super) range: u8, + pub(super) agility_bonus: u8, +} + +/// Shape of the equipement, first mandatory part of an equipement +pub struct EqShape { + /// The inner stats of the part + pub(super) stats: InnerStats, +} + +/// Material used for the equipement, all equipements are crafted with 1-2 materials +pub struct EqMaterial { + /// The inner stats of the part + pub(super) stats: InnerStats, +} + +/// Nature of the equipement, some natures are reserved and some can be chained +/// +/// Deciding on the combinaison can be tricky an will need an extra field +pub struct EqNature { + /// The inner stats of the part + pub(super) stats: InnerStats, + /// Which kind of target this nature applies to + pub(super) target: NatureTarget, +} + +/// Finishing touches, since all of them have a cost, they are treated in a special fashion +pub struct EqFinishing { + /// The inner stats of the part + pub(super) stats: InnerStats, +} + +#[cfg(test)] +mod test { + // use super::*; + + use super::{Equipement, InnerStats}; + + fn list_equip() -> Vec { + (0..10) + .map(|_| Equipement { + ..Default::default() + }) + .collect::>() + } + + #[test] + fn test_struct_creation() { + let stats = InnerStats::default(); + let eq1 = Equipement { + ..Default::default() + }; + + let list_eq = list_equip(); + + assert_eq!(stats, eq1.stats); + assert_eq!(list_eq[0], eq1); + } + + #[ignore] + #[test] + fn test_default_behaviour() { + unimplemented!() + } +} diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs new file mode 100644 index 0000000..5f7d7d9 --- /dev/null +++ b/weaponry/src/weaponry_structs/mod.rs @@ -0,0 +1,19 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/mod.rs +//! All weaponry intermod structures + +#![allow(dead_code)] + +mod equipement_fields; +mod equipement_impl_database; +mod equipement_impl_io; +mod equipement_impl_logic; +pub mod equipement_structs; + +// Republishes the most used symbols +// All generic structs +pub use equipement_structs::{Equipement, FinalEquipementList}; + +// All generic fields +#[allow(unused_imports)] +pub use equipement_fields::{DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory}; -- 2.45.1 From 53de64946f0305b23bd8dfd1a7466107366e31e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Tue, 11 Feb 2025 22:18:28 +0100 Subject: [PATCH 03/97] Cargo.toml cleanup --- weaponry/Cargo.toml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 4299523..39fa15f 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -8,9 +8,8 @@ pretty_assertions = "1.4.1" rayon = "1.10.0" [dev-dependencies] -criterion = { version = "0.5"} +criterion = { version = "0.5" } [[bench]] name = "iter_creation" harness = false - -- 2.45.1 From 9786323e535bb0fcdfdab43b9e9670c75f6577d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Tue, 11 Feb 2025 22:24:27 +0100 Subject: [PATCH 04/97] Preparatory work for database input and output --- weaponry/Cargo.toml | 2 ++ weaponry/src/weaponry_structs/equipement_structs.rs | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 39fa15f..1e5ee4e 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -6,6 +6,8 @@ edition = "2024" [dependencies] pretty_assertions = "1.4.1" rayon = "1.10.0" +rusqlite = "0.33.0" +struct-field-names-as-array = "0.3.0" [dev-dependencies] criterion = { version = "0.5" } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 7ba3706..c73bc63 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -2,6 +2,8 @@ // File: weaponry/src/weaponry_structs/equipement_structs.rs //! Base equipement structures +use struct_field_names_as_array::FieldNamesAsArray; + use super::{DamageType, NatureTarget, SpecialCategory, WeaponCategory}; /// The final equipement list @@ -34,7 +36,7 @@ pub struct Equipement { /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default)] +#[derive(Clone, Default, FieldNamesAsArray)] #[cfg_attr(test, derive(Debug, PartialEq))] pub struct InnerStats { pub id: u8, -- 2.45.1 From 2c44cdd817e590e1a11cbc67dd61602c2fa4f4ca Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 11 Feb 2025 23:34:51 +0100 Subject: [PATCH 05/97] Switched to a blanket implementation --- .gitignore | 1 + Cargo.toml | 2 + weaponry/benches/iter_creation.rs | 45 ++-- weaponry/src/interfaces.rs | 88 ++++++-- .../weaponry_structs/equipement_impl_logic.rs | 202 +++++++++++------- .../weaponry_structs/equipement_structs.rs | 11 +- weaponry/src/weaponry_structs/mod.rs | 13 +- 7 files changed, 240 insertions(+), 122 deletions(-) diff --git a/.gitignore b/.gitignore index 6126be9..a47be09 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,4 @@ Cargo.lock /target .cargo/ +*.tar.gz diff --git a/Cargo.toml b/Cargo.toml index 46bf157..f6e0776 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,3 +28,5 @@ lto = false codegen-units = 256 incremental = true panic = "abort" + + diff --git a/weaponry/benches/iter_creation.rs b/weaponry/benches/iter_creation.rs index 0d5511f..75c07b9 100644 --- a/weaponry/benches/iter_creation.rs +++ b/weaponry/benches/iter_creation.rs @@ -2,37 +2,28 @@ use criterion::{Criterion, criterion_group, criterion_main}; use std::{hint::black_box, time::Duration}; use weaponry::{ interfaces::RecipeCollection, - weaponry_structs::{ - Equipement, FinalEquipementList, equipement_structs::FinalEquipementListPar, - }, + weaponry_structs::{Equipement, FinalEquipementList}, }; fn criterion_benchmark(c: &mut Criterion) { - let steps = [ + let blk_steps = [ FinalEquipementList::from_vectored(vec![Equipement::default(); 100]), FinalEquipementList::from_vectored(vec![Equipement::default(); 100]), FinalEquipementList::from_vectored(vec![Equipement::default(); 100]), ]; - let par_steps = [ - FinalEquipementListPar::from_vectored(vec![Equipement::default(); 100]), - FinalEquipementListPar::from_vectored(vec![Equipement::default(); 100]), - FinalEquipementListPar::from_vectored(vec![Equipement::default(); 100]), - ]; c.bench_function("creating 100 Elements", |b| { - b.iter(|| FinalEquipementList::from_vectored(black_box(vec![Equipement::default(); 100]))) - }); - c.bench_function("IterGen: 100x100x100", |b| { b.iter(|| { - let mut s = steps[0].clone(); - s.combine_all(steps[1].clone()); - s.combine_all(steps[2].clone()); + FinalEquipementList::from_vectored(black_box(vec![ + black_box(Equipement::default()); + 100 + ])) }) }); - c.bench_function("IterGen: 100x100x100", |b| { + c.bench_function("IterGenBlanket: 100x100x100", |b| { b.iter(|| { - let mut s = par_steps[0].clone(); - s.combine_all(par_steps[1].clone()); - s.combine_all(par_steps[2].clone()); + let mut s = blk_steps[0].clone(); + s.combine_all_by_blanket(black_box(&blk_steps[1])); + s.combine_all_by_blanket(black_box(&blk_steps[2])); }) }); // c.bench_function("IterGen: 100x100x100x100", |b| { @@ -43,14 +34,14 @@ fn criterion_benchmark(c: &mut Criterion) { // s.combine_all(steps[2].clone()); // }) // }); - c.bench_function("IterGenPar: 100x100x100x100", |b| { - b.iter(|| { - let mut s = par_steps[0].clone(); - s.combine_all(par_steps[1].clone()); - s.combine_all(par_steps[2].clone()); - s.combine_all(par_steps[2].clone()); - }) - }); + // c.bench_function("IterGenPar: 100x100x100x100", |b| { + // b.iter(|| { + // let mut s = par_steps[0].clone(); + // s.combine_all(par_steps[1].clone()); + // s.combine_all(par_steps[2].clone()); + // s.combine_all(par_steps[2].clone()); + // }) + // }); } criterion_group! { diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index bb75100..eb18263 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -18,14 +18,62 @@ pub trait RecipeCollection { /// The type of the inner recipes, this type must be combinable type Recipes: Combineable; - /// Combine all current recipies with all the parts given - fn combine_all(&mut self, other: G) - where - G: RecipeCollection + std::marker::Sync; + // /// Combine all current recipies with all the parts given + // #[deprecated] + // fn combine_all(&mut self, other: G) + // where + // G: RecipeCollection + std::marker::Sync; + + /// Do the parrallel combination all inside + fn combine_all_by_blanket(&mut self, other: &G) + where + G: RecipeCollection, + { + self.assign_inner( + self.ref_inner() + .iter() + .flat_map(|inner_recipes| { + other + .ref_inner() + .iter() + .map(|external_recipes: &Self::Recipes| { + inner_recipes.add_ref_to_self(external_recipes) + }) + .collect::>() + }) + .collect::>(), + ); + } + + // fn combine_all_by_ref(&mut self, other: G) + // where + // G: RecipeCollection + std::marker::Sync, + // { + // let mut future_receipes = vec![self.ref_inner().clone(); other.ref_inner().len()]; + // future_receipes + // .par_iter_mut() + // .zip(other.ref_inner()) + // .for_each(move |(a, b)| { + // a.par_iter_mut().for_each(move |e| { + // e.add_to_self(b); + // }); + // }); + + // self.inner = future_receipes.into_par_iter().flatten().collect(); + // } + + /// Assign the inner value from an owned value, used for blanket implementations + fn assign_inner(&mut self, inner: Vec); + + /// Gives access to a reference of the inner list + /// + /// This allows to only clone when needed + fn ref_inner(&self) -> &Vec; + + // /// Gives access to a mutable reference of the inner list + // #[deprecated] + // fn refmut_inner(&mut self) -> &mut Vec; - /// Access the inner list - // TODO: Use iterators ? - fn inner(&self) -> Vec; // Optional filter ? /// Create a collection from a vector @@ -38,16 +86,32 @@ pub trait RecipeCollection { pub trait Combineable { /// The inner type of the combined elements, this type must implement Add // TODO : Make this help much more readable - type Inner: std::ops::Add; + type Inner: std::ops::Add + std::ops::AddAssign; - /// Give access to an owned underlying type that can be combined - // TODO: the ownership part might not be needed - fn clone_combinable_part(&self) -> Self::Inner; + /// Give access to a reference of the underlying data to be combined + /// + /// The designed combinaison method is std::ops::Add + fn combinable_part(&self) -> &Self::Inner; /// Add an element to self and return a new value /// /// This method will clone it's own combinable part - fn add_to_self(&self, rhs: T) -> Self + #[deprecated] + fn add_to_other(&self, rhs: T) -> Self + where + T: Combineable; + + /// Add an element to a mutable self + // #[deprecated(note = "Mutate in place")] + fn add_to_self(&mut self, rhs: &T) + where + T: Combineable; + + /// Add an element to self and generate a new Self + /// + /// As the signature implies, it will not mutate self not rhs and will generate a new value from the operation + /// This pushes the actual requirement to &Inner : Add<&Inner> + fn add_ref_to_self(&self, rhs: &T) -> Self where T: Combineable; } diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index f7198e9..f34fccc 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -2,14 +2,9 @@ // File: weaponry/src/weaponry_structs/equipement_impl_logic.rs //! Implementation of the logic traits, used for equipement generation -use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; - use crate::interfaces::{Combineable, RecipeCollection}; -use super::{ - Equipement, FinalEquipementList, SpecialCategory, - equipement_structs::{FinalEquipementListPar, InnerStats}, -}; +use super::{Equipement, FinalEquipementList, SpecialCategory, equipement_structs::InnerStats}; impl std::ops::Add for InnerStats { type Output = Self; @@ -58,6 +53,97 @@ impl std::ops::Add for InnerStats { } } } +impl std::ops::Add for &InnerStats { + type Output = InnerStats; + + fn add(self, rhs: Self) -> Self::Output { + InnerStats { + // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless + id: self.id, + name: [self.name.clone(), rhs.name.clone()].join("+"), + rarity: self.rarity + rhs.rarity, + cost: self.cost + rhs.cost, + difficulty: self.difficulty + rhs.difficulty, + tier: self.tier + rhs.tier, + damage: self.damage + rhs.damage, + p_damage: self.p_damage + rhs.p_damage, + precision: self.precision + rhs.precision, + rmax: self.rmax + rhs.rmax, + armor_break: self.armor_break + rhs.armor_break, + armor_pierce: self.armor_pierce + rhs.armor_pierce, + antimaterial: self.antimaterial + rhs.antimaterial, + damage_type: { + match (self.damage_type.clone(), rhs.damage_type.clone()) { + (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) + } + } + }, + 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, + 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 + 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, + agility_bonus: self.agility_bonus + rhs.agility_bonus, + } + } +} + +impl std::ops::AddAssign for InnerStats { + fn add_assign(&mut self, rhs: InnerStats) { + // self.id; + self.name.push('+'); + self.name.push_str(&rhs.name); + self.rarity += rhs.rarity; + self.cost += rhs.cost; + self.difficulty += rhs.difficulty; + self.tier += rhs.tier; + self.damage += rhs.damage; + self.p_damage += rhs.p_damage; + self.precision += rhs.precision; + self.rmax += rhs.rmax; + self.armor_break += rhs.armor_break; + self.armor_pierce += rhs.armor_pierce; + self.antimaterial += rhs.antimaterial; + self.damage_type = { + match (self.damage_type.clone(), rhs.damage_type.clone()) { + (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) + } + } + }; + self.protection += rhs.protection; + self.integrity += rhs.integrity; + self.torque_two_handed += rhs.torque_two_handed; + self.torque_one_handed += rhs.torque_one_handed; + self.dodge += rhs.dodge; + self.parry += rhs.parry; + self.speed += rhs.speed; + self.stealth += rhs.stealth; + self.category.clone().or(rhs.category.clone()); // Can be further optimized + // self.special += rhs.special.clone(); // Can be further optimized + self.action_cost += rhs.action_cost; + self.reload_cost.or(rhs.reload_cost); + self.range += rhs.range; + self.agility_bonus += rhs.agility_bonus; + } +} impl std::ops::Add for SpecialCategory { type Output = Self; @@ -72,16 +158,33 @@ impl std::ops::Add for SpecialCategory { impl Combineable for Equipement { type Inner = InnerStats; - fn clone_combinable_part(&self) -> InnerStats { - self.stats.clone() - } - fn add_to_self(&self, rhs: T) -> Self + fn add_to_other(&self, rhs: T) -> Self where T: Combineable, { Self { - stats: self.clone_combinable_part() + rhs.clone_combinable_part(), + stats: self.combinable_part() + rhs.combinable_part(), + } + } + + fn combinable_part(&self) -> &Self::Inner { + &self.stats + } + + fn add_to_self(&mut self, rhs: &T) + where + T: Combineable, + { + self.stats += rhs.combinable_part().clone() + } + + fn add_ref_to_self(&self, rhs: &T) -> Self + where + T: Combineable, + { + Self { + stats: self.combinable_part() + rhs.combinable_part(), } } } @@ -89,58 +192,16 @@ impl Combineable for Equipement { impl RecipeCollection for FinalEquipementList { type Recipes = Equipement; - fn combine_all(&mut self, other: G) - where - G: RecipeCollection, - { - self.inner = self - .inner() - .iter() - .flat_map(|e| { - other - .inner() - .iter() - .map(|f: &Self::Recipes| e.add_to_self(f.clone())) - .collect::>() - }) - .collect(); - } - - fn inner(&self) -> Vec { - self.inner.clone() - } - fn from_vectored(list: Vec) -> Self { Self { inner: list } } -} -impl RecipeCollection for FinalEquipementListPar { - type Recipes = Equipement; - - fn combine_all(&mut self, other: G) - where - G: RecipeCollection + std::marker::Sync, - { - self.inner = self - .inner() - .par_iter() - .flat_map(|e| { - other - .inner() - .par_iter() - .map(|f: &Self::Recipes| e.add_to_self(f.clone())) - .collect::>() - }) - .collect(); + fn ref_inner(&self) -> &Vec { + &self.inner } - fn inner(&self) -> Vec { - self.inner.clone() - } - - fn from_vectored(list: Vec) -> Self { - Self { inner: list } + fn assign_inner(&mut self, inner: Vec) { + self.inner = inner; } } @@ -156,38 +217,35 @@ mod test { use pretty_assertions::assert_eq; #[test] - fn test_struct_generation() { + fn test_blanket_struct_generation() { let mut f = FinalEquipementList::from_vectored(vec![ - Equipement::newish("", 1), - Equipement::newish("", 2), + Equipement::newish("a", 1), + Equipement::newish("b", 2), ]); let g = FinalEquipementList::from_vectored(vec![ - Equipement::newish("", 4), - Equipement::newish("", 8), + Equipement::newish("c", 4), + Equipement::newish("d", 8), ]); assert_eq!( - f.inner(), - vec![Equipement::newish("", 1), Equipement::newish("", 2)] + f.ref_inner(), + &vec![Equipement::newish("a", 1), Equipement::newish("b", 2)] ); - f.combine_all(g); + f.combine_all_by_blanket(&g); assert_eq!( f, FinalEquipementList::from_vectored(vec![ - Equipement::newish("+", 5), - Equipement::newish("+", 9), - Equipement::newish("+", 6), - Equipement::newish("+", 10) + Equipement::newish("a+c", 5), + Equipement::newish("a+d", 9), + Equipement::newish("b+c", 6), + Equipement::newish("b+d", 10) ]) ); } #[test] fn test_base_operation() { - // let inner = InnerStats::default(); - // let inner2 = inner.clone() + inner.clone(); - // assert_eq!(inner, inner2); // True because of the 0 initialisation let i1 = InnerStats { rarity: 1, integrity: 2, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index c73bc63..eddb28d 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -5,6 +5,7 @@ use struct_field_names_as_array::FieldNamesAsArray; use super::{DamageType, NatureTarget, SpecialCategory, WeaponCategory}; +// use derive_more::Add; /// The final equipement list /// @@ -16,16 +17,6 @@ pub struct FinalEquipementList { pub(super) inner: Vec, } -/// A parallel Implementation of the final equipement list -/// -/// This list only serve for benchmark purposes -#[derive(Clone)] -#[cfg_attr(test, derive(PartialEq, Debug))] -pub struct FinalEquipementListPar { - /// Inner List of final equipements - pub(super) inner: Vec, -} - /// The final equipement, obtained by combining all parts #[derive(Clone, Default)] #[cfg_attr(test, derive(PartialEq, Debug))] diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 5f7d7d9..2f7ba60 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -2,7 +2,18 @@ // File: weaponry/src/weaponry_structs/mod.rs //! All weaponry intermod structures -#![allow(dead_code)] +// #![allow(dead_code)] +// use mimalloc::MiMalloc; + +// #[global_allocator] +// static GLOBAL: MiMalloc = MiMalloc; + +// #[cfg(not(target_env = "msvc"))] +// use tikv_jemallocator::Jemalloc; + +// #[cfg(not(target_env = "msvc"))] +// #[global_allocator] +// static GLOBAL: Jemalloc = Jemalloc; mod equipement_fields; mod equipement_impl_database; -- 2.45.1 From 9e1521e37357ee778563ebf0bd90df55288f0909 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 11 Feb 2025 23:30:27 +0100 Subject: [PATCH 06/97] Refactor of impls --- weaponry/src/interfaces.rs | 15 +- .../weaponry_structs/equipement_impl_logic.rs | 190 ++-------------- .../weaponry_structs/equipement_impl_math.rs | 208 ++++++++++++++++++ .../weaponry_structs/equipement_structs.rs | 21 +- weaponry/src/weaponry_structs/mod.rs | 1 + 5 files changed, 250 insertions(+), 185 deletions(-) create mode 100644 weaponry/src/weaponry_structs/equipement_impl_math.rs diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index eb18263..cfa97cc 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -29,6 +29,7 @@ pub trait RecipeCollection { where G: RecipeCollection, { + // TODO: Test Add to Self instead self.assign_inner( self.ref_inner() .iter() @@ -93,13 +94,13 @@ pub trait Combineable { /// The designed combinaison method is std::ops::Add fn combinable_part(&self) -> &Self::Inner; - /// Add an element to self and return a new value - /// - /// This method will clone it's own combinable part - #[deprecated] - fn add_to_other(&self, rhs: T) -> Self - where - T: Combineable; + // /// Add an element to self and return a new value + // /// + // /// This method will clone it's own combinable part + // #[deprecated] + // fn add_to_other(&self, rhs: T) -> Self + // where + // T: Combineable; /// Add an element to a mutable self // #[deprecated(note = "Mutate in place")] diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index f34fccc..ac25025 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -4,170 +4,11 @@ use crate::interfaces::{Combineable, RecipeCollection}; -use super::{Equipement, FinalEquipementList, SpecialCategory, equipement_structs::InnerStats}; - -impl std::ops::Add for InnerStats { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - Self { - // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless - id: self.id, - name: [self.name, rhs.name].join("+"), - rarity: self.rarity + rhs.rarity, - cost: self.cost + rhs.cost, - difficulty: self.difficulty + rhs.difficulty, - tier: self.tier + rhs.tier, - damage: self.damage + rhs.damage, - p_damage: self.p_damage + rhs.p_damage, - precision: self.precision + rhs.precision, - rmax: self.rmax + rhs.rmax, - armor_break: self.armor_break + rhs.armor_break, - armor_pierce: self.armor_pierce + rhs.armor_pierce, - antimaterial: self.antimaterial + rhs.antimaterial, - damage_type: { - match (self.damage_type, rhs.damage_type) { - (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) - } - } - }, - 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, - dodge: self.dodge + rhs.dodge, - parry: self.parry + rhs.parry, - speed: self.speed + rhs.speed, - stealth: self.stealth + rhs.stealth, - category: self.category.or(rhs.category), - special: self.special + rhs.special, - action_cost: self.action_cost + rhs.action_cost, - reload_cost: self.reload_cost.or(rhs.reload_cost), - range: self.range + rhs.range, - agility_bonus: self.agility_bonus + rhs.agility_bonus, - } - } -} -impl std::ops::Add for &InnerStats { - type Output = InnerStats; - - fn add(self, rhs: Self) -> Self::Output { - InnerStats { - // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless - id: self.id, - name: [self.name.clone(), rhs.name.clone()].join("+"), - rarity: self.rarity + rhs.rarity, - cost: self.cost + rhs.cost, - difficulty: self.difficulty + rhs.difficulty, - tier: self.tier + rhs.tier, - damage: self.damage + rhs.damage, - p_damage: self.p_damage + rhs.p_damage, - precision: self.precision + rhs.precision, - rmax: self.rmax + rhs.rmax, - armor_break: self.armor_break + rhs.armor_break, - armor_pierce: self.armor_pierce + rhs.armor_pierce, - antimaterial: self.antimaterial + rhs.antimaterial, - damage_type: { - match (self.damage_type.clone(), rhs.damage_type.clone()) { - (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) - } - } - }, - 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, - 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 - 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, - agility_bonus: self.agility_bonus + rhs.agility_bonus, - } - } -} - -impl std::ops::AddAssign for InnerStats { - fn add_assign(&mut self, rhs: InnerStats) { - // self.id; - self.name.push('+'); - self.name.push_str(&rhs.name); - self.rarity += rhs.rarity; - self.cost += rhs.cost; - self.difficulty += rhs.difficulty; - self.tier += rhs.tier; - self.damage += rhs.damage; - self.p_damage += rhs.p_damage; - self.precision += rhs.precision; - self.rmax += rhs.rmax; - self.armor_break += rhs.armor_break; - self.armor_pierce += rhs.armor_pierce; - self.antimaterial += rhs.antimaterial; - self.damage_type = { - match (self.damage_type.clone(), rhs.damage_type.clone()) { - (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) - } - } - }; - self.protection += rhs.protection; - self.integrity += rhs.integrity; - self.torque_two_handed += rhs.torque_two_handed; - self.torque_one_handed += rhs.torque_one_handed; - self.dodge += rhs.dodge; - self.parry += rhs.parry; - self.speed += rhs.speed; - self.stealth += rhs.stealth; - self.category.clone().or(rhs.category.clone()); // Can be further optimized - // self.special += rhs.special.clone(); // Can be further optimized - self.action_cost += rhs.action_cost; - self.reload_cost.or(rhs.reload_cost); - self.range += rhs.range; - self.agility_bonus += rhs.agility_bonus; - } -} - -impl std::ops::Add for SpecialCategory { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - let mut c = self.clone(); - // TODO: Overcopy, kinda meaningless optimisation tho - c.0.append(&mut rhs.clone().0); - c - } -} +use super::{Equipement, FinalEquipementList, equipement_structs::InnerStats}; impl Combineable for Equipement { type Inner = InnerStats; - fn add_to_other(&self, rhs: T) -> Self - where - T: Combineable, - { - Self { - stats: self.combinable_part() + rhs.combinable_part(), - } - } - fn combinable_part(&self) -> &Self::Inner { &self.stats } @@ -219,27 +60,27 @@ mod test { #[test] fn test_blanket_struct_generation() { let mut f = FinalEquipementList::from_vectored(vec![ - Equipement::newish("a", 1), - Equipement::newish("b", 2), + Equipement::newish(&["a"], 1), + Equipement::newish(&["b"], 2), ]); let g = FinalEquipementList::from_vectored(vec![ - Equipement::newish("c", 4), - Equipement::newish("d", 8), + Equipement::newish(&["c"], 4), + Equipement::newish(&["d"], 8), ]); assert_eq!( f.ref_inner(), - &vec![Equipement::newish("a", 1), Equipement::newish("b", 2)] + &vec![Equipement::newish(&["a"], 1), Equipement::newish(&["b"], 2)] ); f.combine_all_by_blanket(&g); assert_eq!( f, FinalEquipementList::from_vectored(vec![ - Equipement::newish("a+c", 5), - Equipement::newish("a+d", 9), - Equipement::newish("b+c", 6), - Equipement::newish("b+d", 10) + Equipement::newish(&["a", "c"], 5), + Equipement::newish(&["a", "d"], 9), + Equipement::newish(&["b", "c"], 6), + Equipement::newish(&["b", "d"], 10) ]) ); } @@ -271,7 +112,6 @@ mod test { assert_eq!( i1 + i2, InnerStats { - name: "+".into(), rarity: 1, integrity: 5, agility_bonus: 9, @@ -287,15 +127,14 @@ mod test { } ); assert_eq!( - InnerStats { + &InnerStats { damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), ..Default::default() - } + InnerStats::default(), + } + &InnerStats::default(), InnerStats { - name: "+".into(), damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), @@ -313,7 +152,6 @@ mod test { ..Default::default() }, InnerStats { - name: "+".into(), damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), @@ -332,10 +170,10 @@ mod test { fn test_basic_logic() {} impl Equipement { - fn newish(name: &str, i: u8) -> Self { + fn newish(name: &[&str], i: u8) -> Self { Equipement { stats: InnerStats { - name: name.to_owned(), + name: name.iter().map(|s| s.to_string()).collect(), rarity: i, ..Default::default() }, diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs new file mode 100644 index 0000000..721d6dd --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -0,0 +1,208 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_math.rs +//! Implements base math for each field +//! + +use super::equipement_structs::InnerStats; +use crate::weaponry_structs::SpecialCategory; + +impl std::ops::Add for InnerStats { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless + id: self.id, + name: { + let mut b = self.name.clone(); + b.append(&mut rhs.name.clone()); + b + }, + rarity: self.rarity + rhs.rarity, + cost: self.cost + rhs.cost, + difficulty: self.difficulty + rhs.difficulty, + tier: self.tier + rhs.tier, + damage: self.damage + rhs.damage, + p_damage: self.p_damage + rhs.p_damage, + precision: self.precision + rhs.precision, + rmax: self.rmax + rhs.rmax, + armor_break: self.armor_break + rhs.armor_break, + armor_pierce: self.armor_pierce + rhs.armor_pierce, + antimaterial: self.antimaterial + rhs.antimaterial, + damage_type: { + match (self.damage_type, rhs.damage_type) { + (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) + } + } + }, + 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, + dodge: self.dodge + rhs.dodge, + parry: self.parry + rhs.parry, + speed: self.speed + rhs.speed, + stealth: self.stealth + rhs.stealth, + category: self.category.or(rhs.category), + special: self.special + rhs.special, + action_cost: self.action_cost + rhs.action_cost, + reload_cost: self.reload_cost.or(rhs.reload_cost), + range: self.range + rhs.range, + agility_bonus: self.agility_bonus + rhs.agility_bonus, + } + } +} +impl std::ops::Add for &InnerStats { + type Output = InnerStats; + + fn add(self, rhs: Self) -> Self::Output { + InnerStats { + // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless + id: self.id, + name: { + let mut b = self.name.clone(); + b.append(&mut rhs.name.clone()); + b + }, + rarity: self.rarity + rhs.rarity, + cost: self.cost + rhs.cost, + difficulty: self.difficulty + rhs.difficulty, + tier: self.tier + rhs.tier, + damage: self.damage + rhs.damage, + p_damage: self.p_damage + rhs.p_damage, + precision: self.precision + rhs.precision, + rmax: self.rmax + rhs.rmax, + armor_break: self.armor_break + rhs.armor_break, + armor_pierce: self.armor_pierce + rhs.armor_pierce, + antimaterial: self.antimaterial + rhs.antimaterial, + damage_type: { + match (self.damage_type.clone(), rhs.damage_type.clone()) { + (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) + } + } + }, + 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, + 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 + 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, + agility_bonus: self.agility_bonus + rhs.agility_bonus, + } + } +} + +impl std::ops::AddAssign for InnerStats { + fn add_assign(&mut self, rhs: InnerStats) { + // self.id; + // self.name.push('+'); + // self.name.push_str(&rhs.name); + self.rarity += rhs.rarity; + self.cost += rhs.cost; + self.difficulty += rhs.difficulty; + self.tier += rhs.tier; + self.damage += rhs.damage; + self.p_damage += rhs.p_damage; + self.precision += rhs.precision; + self.rmax += rhs.rmax; + self.armor_break += rhs.armor_break; + self.armor_pierce += rhs.armor_pierce; + self.antimaterial += rhs.antimaterial; + self.damage_type = { + match (self.damage_type.clone(), rhs.damage_type.clone()) { + (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) + } + } + }; + self.protection += rhs.protection; + self.integrity += rhs.integrity; + self.torque_two_handed += rhs.torque_two_handed; + self.torque_one_handed += rhs.torque_one_handed; + self.dodge += rhs.dodge; + self.parry += rhs.parry; + self.speed += rhs.speed; + self.stealth += rhs.stealth; + self.category.clone().or(rhs.category.clone()); // Can be further optimized + // self.special += rhs.special.clone(); // Can be further optimized + self.action_cost += rhs.action_cost; + self.reload_cost.or(rhs.reload_cost); + self.range += rhs.range; + self.agility_bonus += rhs.agility_bonus; + } +} + +impl std::ops::Add for SpecialCategory { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + let mut c = self.clone(); + // TODO: Overcopy, kinda meaningless optimisation tho + c.0.append(&mut rhs.clone().0); + c + } +} + +// impl std::ops::AddAssign for SpecialCategory { +// fn add_assign(&mut self, rhs: Self) { +// todo!() +// } +// } + +// impl std::ops::Add for OptionnalReloadType { +// type Output = OptionnalReloadType; + +// fn add(self, rhs: Self) -> Self::Output { +// todo!() +// } +// } +// impl std::ops::AddAssign for OptionnalReloadType { +// fn add_assign(&mut self, rhs: Self) { +// todo!() +// } +// } +// impl std::ops::Add for OptionnalWeaponCategory { +// type Output = OptionnalWeaponCategory; + +// fn add(self, rhs: Self) -> Self::Output { +// todo!() +// } +// } +// impl std::ops::AddAssign for OptionnalWeaponCategory { +// fn add_assign(&mut self, rhs: Self) { +// todo!() +// } +// } +// impl std::ops::Add for OptionnalDamageType { +// type Output = OptionnalDamageType; + +// fn add(self, rhs: Self) -> Self::Output { +// todo!() +// } +// } +// impl std::ops::AddAssign for OptionnalDamageType { +// fn add_assign(&mut self, rhs: Self) { +// todo!() +// } +// } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index eddb28d..33624e3 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -5,7 +5,6 @@ use struct_field_names_as_array::FieldNamesAsArray; use super::{DamageType, NatureTarget, SpecialCategory, WeaponCategory}; -// use derive_more::Add; /// The final equipement list /// @@ -31,7 +30,7 @@ pub struct Equipement { #[cfg_attr(test, derive(Debug, PartialEq))] pub struct InnerStats { pub id: u8, - pub name: String, + pub name: Vec, pub(super) rarity: u8, pub(super) cost: u8, pub(super) difficulty: u8, @@ -60,6 +59,21 @@ pub struct InnerStats { pub(super) agility_bonus: u8, } +// /// A type representing a weapon reload potential +// #[derive(Clone, Default)] +// #[cfg_attr(test, derive(Debug, PartialEq))] +// pub struct OptionnalReloadType(Option); + +// /// Optionnal Weapon +// #[derive(Clone, Default)] +// #[cfg_attr(test, derive(Debug, PartialEq))] +// pub struct OptionnalWeaponCategory(Option); + +// /// Optionnal damage type +// #[derive(Clone, Default)] +// #[cfg_attr(test, derive(Debug, PartialEq))] +// pub struct OptionnalDamageType(Option); + /// Shape of the equipement, first mandatory part of an equipement pub struct EqShape { /// The inner stats of the part @@ -115,6 +129,9 @@ mod test { assert_eq!(list_eq[0], eq1); } + #[test] + fn test_creating_all_equipements() {} + #[ignore] #[test] fn test_default_behaviour() { diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 2f7ba60..228a565 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -19,6 +19,7 @@ mod equipement_fields; mod equipement_impl_database; mod equipement_impl_io; mod equipement_impl_logic; +mod equipement_impl_math; pub mod equipement_structs; // Republishes the most used symbols -- 2.45.1 From 4b4d39257a9e0676ca518672c3a689d2b025bd85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Wed, 12 Feb 2025 00:11:23 +0100 Subject: [PATCH 07/97] generate_query push --- weaponry/src/database.rs | 75 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 1ac040d..ba0e30d 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -2,3 +2,78 @@ // File: weaponry/src/database.rs //! Database handiling module //! Implements the basics deserialisation from a database to the weaponry components +//! Should dump whole database in a vec of structs from weaponry_structs +#![allow(dead_code)] +#![allow(unused_imports)] +use std::ops::Deref; + +use crate::weaponry_structs::equipement_structs::InnerStats; +use rusqlite::{self, Connection, Result, params}; +use struct_field_names_as_array::FieldNamesAsArray; + +fn generate_query(fields: &[&str], table_name: &str) -> String { + let mut query = String::new(); + query.push_str("SELECT"); + for item in fields.iter() { + query.push_str(" "); + query.push_str(*item); + query.push_str(","); + } + query.pop(); + query.push_str(format!(" FROM {};", table_name).as_str()); + query +} + +/// Checks if database exists, and returns a rusqlite::Connection. If not, panics while insulting you. You deserved it. +fn initialize_database_conn(filename: Option) -> Result { + if let Some(text) = filename { + let conn = Connection::open(text)?; + Ok(conn) + } else { + panic!("No filename, you big oaf."); + //let conn = Connection::open_in_memory()?; + //Ok(conn) + } +} + +pub fn get_data() -> Vec { + //let query = generate_query(&InnerStats::FIELD_NAMES_AS_ARRAY, "InnerStats"); + todo!() +} + +#[cfg(test)] +mod test { + use std::any::type_name; + + use pretty_assertions::assert_eq; + + use super::*; + #[derive(FieldNamesAsArray)] + struct TestStruct { + id: usize, + name: String, + } + + #[test] + fn test_generate_query() { + assert_eq!( + generate_query(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct"), + "SELECT id, name FROM TestStruct;" + ) + } + + #[test] + fn test_initialize_database() { + todo!() + } + + #[test] + fn test_generate_table_from_struct() { + todo!() + } + + #[test] + fn test_get_data() { + todo!() + } +} -- 2.45.1 From 603a1cd8b680a023b8d904e675d2d1dae6b7d23b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 11 Feb 2025 23:54:06 +0100 Subject: [PATCH 08/97] Cleanup requirements for impls --- weaponry/src/interfaces.rs | 54 ++--------- .../weaponry_structs/equipement_impl_logic.rs | 13 +-- .../weaponry_structs/equipement_impl_math.rs | 95 ------------------- 3 files changed, 12 insertions(+), 150 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index cfa97cc..f7b169e 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -14,22 +14,18 @@ pub trait FromParts {} /// Trait implemented for the final collection of a recipe, allowing it to be combined with parts /// /// A recipe list will be combined with a part list to be updated and generate all combinaisons, so on and so forth -pub trait RecipeCollection { +pub trait RecipeCollection +where + for<'a> &'a <::Recipes as Combineable>::Inner: std::ops::Add, +{ /// The type of the inner recipes, this type must be combinable type Recipes: Combineable; - // /// Combine all current recipies with all the parts given - // #[deprecated] - // fn combine_all(&mut self, other: G) - // where - // G: RecipeCollection + std::marker::Sync; - /// Do the parrallel combination all inside fn combine_all_by_blanket(&mut self, other: &G) where G: RecipeCollection, { - // TODO: Test Add to Self instead self.assign_inner( self.ref_inner() .iter() @@ -46,23 +42,6 @@ pub trait RecipeCollection { ); } - // fn combine_all_by_ref(&mut self, other: G) - // where - // G: RecipeCollection + std::marker::Sync, - // { - // let mut future_receipes = vec![self.ref_inner().clone(); other.ref_inner().len()]; - // future_receipes - // .par_iter_mut() - // .zip(other.ref_inner()) - // .for_each(move |(a, b)| { - // a.par_iter_mut().for_each(move |e| { - // e.add_to_self(b); - // }); - // }); - - // self.inner = future_receipes.into_par_iter().flatten().collect(); - // } - /// Assign the inner value from an owned value, used for blanket implementations fn assign_inner(&mut self, inner: Vec); @@ -71,10 +50,6 @@ pub trait RecipeCollection { /// This allows to only clone when needed fn ref_inner(&self) -> &Vec; - // /// Gives access to a mutable reference of the inner list - // #[deprecated] - // fn refmut_inner(&mut self) -> &mut Vec; - // Optional filter ? /// Create a collection from a vector @@ -84,30 +59,19 @@ pub trait RecipeCollection { /// Trait that ensure that two elements of a recipe are combinable, /// /// Being combinable means it can be coerced into elements that implement add -pub trait Combineable { +pub trait Combineable +where + for<'a> &'a ::Inner: std::ops::Add, +{ /// The inner type of the combined elements, this type must implement Add // TODO : Make this help much more readable - type Inner: std::ops::Add + std::ops::AddAssign; + type Inner; /// Give access to a reference of the underlying data to be combined /// /// The designed combinaison method is std::ops::Add fn combinable_part(&self) -> &Self::Inner; - // /// Add an element to self and return a new value - // /// - // /// This method will clone it's own combinable part - // #[deprecated] - // fn add_to_other(&self, rhs: T) -> Self - // where - // T: Combineable; - - /// Add an element to a mutable self - // #[deprecated(note = "Mutate in place")] - fn add_to_self(&mut self, rhs: &T) - where - T: Combineable; - /// Add an element to self and generate a new Self /// /// As the signature implies, it will not mutate self not rhs and will generate a new value from the operation diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index ac25025..e2fed62 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -13,13 +13,6 @@ impl Combineable for Equipement { &self.stats } - fn add_to_self(&mut self, rhs: &T) - where - T: Combineable, - { - self.stats += rhs.combinable_part().clone() - } - fn add_ref_to_self(&self, rhs: &T) -> Self where T: Combineable, @@ -110,7 +103,7 @@ mod test { ..Default::default() }; assert_eq!( - i1 + i2, + &i1 + &i2, InnerStats { rarity: 1, integrity: 5, @@ -143,8 +136,8 @@ mod test { }, ); assert_eq!( - InnerStats::default() - + InnerStats { + &InnerStats::default() + + &InnerStats { damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 721d6dd..19d8235 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -6,57 +6,6 @@ use super::equipement_structs::InnerStats; use crate::weaponry_structs::SpecialCategory; -impl std::ops::Add for InnerStats { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - Self { - // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless - id: self.id, - name: { - let mut b = self.name.clone(); - b.append(&mut rhs.name.clone()); - b - }, - rarity: self.rarity + rhs.rarity, - cost: self.cost + rhs.cost, - difficulty: self.difficulty + rhs.difficulty, - tier: self.tier + rhs.tier, - damage: self.damage + rhs.damage, - p_damage: self.p_damage + rhs.p_damage, - precision: self.precision + rhs.precision, - rmax: self.rmax + rhs.rmax, - armor_break: self.armor_break + rhs.armor_break, - armor_pierce: self.armor_pierce + rhs.armor_pierce, - antimaterial: self.antimaterial + rhs.antimaterial, - damage_type: { - match (self.damage_type, rhs.damage_type) { - (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) - } - } - }, - 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, - dodge: self.dodge + rhs.dodge, - parry: self.parry + rhs.parry, - speed: self.speed + rhs.speed, - stealth: self.stealth + rhs.stealth, - category: self.category.or(rhs.category), - special: self.special + rhs.special, - action_cost: self.action_cost + rhs.action_cost, - reload_cost: self.reload_cost.or(rhs.reload_cost), - range: self.range + rhs.range, - agility_bonus: self.agility_bonus + rhs.agility_bonus, - } - } -} impl std::ops::Add for &InnerStats { type Output = InnerStats; @@ -109,50 +58,6 @@ impl std::ops::Add for &InnerStats { } } -impl std::ops::AddAssign for InnerStats { - fn add_assign(&mut self, rhs: InnerStats) { - // self.id; - // self.name.push('+'); - // self.name.push_str(&rhs.name); - self.rarity += rhs.rarity; - self.cost += rhs.cost; - self.difficulty += rhs.difficulty; - self.tier += rhs.tier; - self.damage += rhs.damage; - self.p_damage += rhs.p_damage; - self.precision += rhs.precision; - self.rmax += rhs.rmax; - self.armor_break += rhs.armor_break; - self.armor_pierce += rhs.armor_pierce; - self.antimaterial += rhs.antimaterial; - self.damage_type = { - match (self.damage_type.clone(), rhs.damage_type.clone()) { - (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) - } - } - }; - self.protection += rhs.protection; - self.integrity += rhs.integrity; - self.torque_two_handed += rhs.torque_two_handed; - self.torque_one_handed += rhs.torque_one_handed; - self.dodge += rhs.dodge; - self.parry += rhs.parry; - self.speed += rhs.speed; - self.stealth += rhs.stealth; - self.category.clone().or(rhs.category.clone()); // Can be further optimized - // self.special += rhs.special.clone(); // Can be further optimized - self.action_cost += rhs.action_cost; - self.reload_cost.or(rhs.reload_cost); - self.range += rhs.range; - self.agility_bonus += rhs.agility_bonus; - } -} - impl std::ops::Add for SpecialCategory { type Output = Self; -- 2.45.1 From 9facac6b9f96e48e583def3c49e74dc5a1542b0a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 12 Feb 2025 00:36:49 +0100 Subject: [PATCH 09/97] Work on the Generic impls --- weaponry/src/interfaces.rs | 4 +- .../weaponry_structs/equipement_into_impls.rs | 30 ++++++++++ .../weaponry_structs/equipement_structs.rs | 56 +++++++++++++------ weaponry/src/weaponry_structs/mod.rs | 1 + 4 files changed, 73 insertions(+), 18 deletions(-) create mode 100644 weaponry/src/weaponry_structs/equipement_into_impls.rs diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index f7b169e..d72a4cc 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -21,7 +21,9 @@ where /// The type of the inner recipes, this type must be combinable type Recipes: Combineable; - /// Do the parrallel combination all inside + /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection + /// + /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch fn combine_all_by_blanket(&mut self, other: &G) where G: RecipeCollection, diff --git a/weaponry/src/weaponry_structs/equipement_into_impls.rs b/weaponry/src/weaponry_structs/equipement_into_impls.rs new file mode 100644 index 0000000..3aae092 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_into_impls.rs @@ -0,0 +1,30 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_into_impls.rs +//! Implementations to transform all Specialized equipement into a generic Equipement +//! A specific implementation could be preferable, but this simplicity might allow for easier developpement + +use super::{ + Equipement, + equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}, +}; + +impl From for Equipement { + fn from(val: EqShape) -> Self { + Self { stats: val.stats } + } +} +impl From for Equipement { + fn from(val: EqMaterial) -> Self { + Self { stats: val.stats } + } +} +impl From for Equipement { + fn from(val: EqNature) -> Self { + Self { stats: val.stats } + } +} +impl From for Equipement { + fn from(val: EqFinishing) -> Self { + Self { stats: val.stats } + } +} diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 33624e3..856ff94 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -59,21 +59,6 @@ pub struct InnerStats { pub(super) agility_bonus: u8, } -// /// A type representing a weapon reload potential -// #[derive(Clone, Default)] -// #[cfg_attr(test, derive(Debug, PartialEq))] -// pub struct OptionnalReloadType(Option); - -// /// Optionnal Weapon -// #[derive(Clone, Default)] -// #[cfg_attr(test, derive(Debug, PartialEq))] -// pub struct OptionnalWeaponCategory(Option); - -// /// Optionnal damage type -// #[derive(Clone, Default)] -// #[cfg_attr(test, derive(Debug, PartialEq))] -// pub struct OptionnalDamageType(Option); - /// Shape of the equipement, first mandatory part of an equipement pub struct EqShape { /// The inner stats of the part @@ -92,6 +77,8 @@ pub struct EqMaterial { pub struct EqNature { /// The inner stats of the part pub(super) stats: InnerStats, + // TODO: Be sure to take this into account + #[allow(dead_code)] /// Which kind of target this nature applies to pub(super) target: NatureTarget, } @@ -106,7 +93,11 @@ pub struct EqFinishing { mod test { // use super::*; - use super::{Equipement, InnerStats}; + use crate::{interfaces::RecipeCollection, weaponry_structs::NatureTarget}; + + use super::{ + EqFinishing, EqMaterial, EqNature, EqShape, Equipement, FinalEquipementList, InnerStats, + }; fn list_equip() -> Vec { (0..10) @@ -130,7 +121,38 @@ mod test { } #[test] - fn test_creating_all_equipements() {} + fn test_creating_all_equipements() { + let shape = vec![ + EqShape { + stats: InnerStats::default(), + } + .into(), + ]; + let nature = vec![ + EqNature { + stats: InnerStats::default(), + target: NatureTarget::Armor, + } + .into(), + ]; + let material = vec![ + EqMaterial { + stats: InnerStats::default(), + } + .into(), + ]; + let finishing = vec![ + EqFinishing { + stats: InnerStats::default(), + } + .into(), + ]; + + let mut leq = FinalEquipementList::from_vectored(shape); + leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(nature)); + leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(material)); + leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(finishing)); + } #[ignore] #[test] diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 228a565..6f34bd1 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -20,6 +20,7 @@ mod equipement_impl_database; mod equipement_impl_io; mod equipement_impl_logic; mod equipement_impl_math; +mod equipement_into_impls; pub mod equipement_structs; // Republishes the most used symbols -- 2.45.1 From 5d514d3d331b718f1ece73fa4beb9c1ce965ba04 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 12 Feb 2025 00:59:13 +0100 Subject: [PATCH 10/97] Adds todo notes --- weaponry/src/weaponry_structs/equipement_into_impls.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/weaponry/src/weaponry_structs/equipement_into_impls.rs b/weaponry/src/weaponry_structs/equipement_into_impls.rs index 3aae092..5beefef 100644 --- a/weaponry/src/weaponry_structs/equipement_into_impls.rs +++ b/weaponry/src/weaponry_structs/equipement_into_impls.rs @@ -1,5 +1,10 @@ // Workspace: weaponry // File: weaponry/src/weaponry_structs/equipement_into_impls.rs +// TODO: At some point a trait might want to be used to use these into instead of calling it directly +// : Doing so would ensure all prerequists are met +// : Another way of doing so might be to instead use Into instead +// : Another way would be to add a filter field that would allow or not the combinaison and abstract all +// logic that would be into doing multi traits things //! Implementations to transform all Specialized equipement into a generic Equipement //! A specific implementation could be preferable, but this simplicity might allow for easier developpement -- 2.45.1 From 6f1b2d98fa3e2ef8cb6da66817846ba8e7f2e835 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Wed, 12 Feb 2025 16:58:40 +0100 Subject: [PATCH 11/97] Correcting clippy warns --- weaponry/src/database.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index ba0e30d..6250efa 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -11,13 +11,14 @@ use crate::weaponry_structs::equipement_structs::InnerStats; use rusqlite::{self, Connection, Result, params}; use struct_field_names_as_array::FieldNamesAsArray; +/// Generate a SELECT query with fields generated from a struct. Returns a String fn generate_query(fields: &[&str], table_name: &str) -> String { let mut query = String::new(); query.push_str("SELECT"); for item in fields.iter() { - query.push_str(" "); - query.push_str(*item); - query.push_str(","); + query.push(' '); + query.push_str(item); + query.push(','); } query.pop(); query.push_str(format!(" FROM {};", table_name).as_str()); @@ -36,8 +37,11 @@ fn initialize_database_conn(filename: Option) -> Result { } } +/// Public function to get data from db pub fn get_data() -> Vec { - //let query = generate_query(&InnerStats::FIELD_NAMES_AS_ARRAY, "InnerStats"); + /* let gen_query = generate_query(&InnerStats::FIELD_NAMES_AS_ARRAY, "InnerStats"); + let db_conn = initialize_database_conn(Some("/tmp/data.sqlite3".to_owned())).unwrap(); + let mut query_result = db_conn.prepare(&gen_query);*/ todo!() } @@ -63,7 +67,7 @@ mod test { } #[test] - fn test_initialize_database() { + fn test_initialize_database_conn() { todo!() } -- 2.45.1 From a7f4ceb0072ed18f78242fedc67cfa4c06703c02 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 12 Feb 2025 01:23:12 +0100 Subject: [PATCH 12/97] Clarifies the dependencies and cleanup the text --- README.md | 7 ++++++- weaponry/Cargo.toml | 2 +- weaponry/src/database.rs | 3 +++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5baf08d..0229a44 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,8 @@ # ravenous-tools -Set of tools to handle ravenous rulebook creation \ No newline at end of file +Set of tools to handle ravenous rulebook creation + +# Installation +Now depends on libsqlite3-dev and sqlite3 +A bundled implementation should be added + diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 1e5ee4e..981c9b1 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -6,7 +6,7 @@ edition = "2024" [dependencies] pretty_assertions = "1.4.1" rayon = "1.10.0" -rusqlite = "0.33.0" +rusqlite = { version = "0.33.0", features = ["bundled"] } struct-field-names-as-array = "0.3.0" [dev-dependencies] diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 6250efa..6aebc1e 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -66,16 +66,19 @@ mod test { ) } + #[ignore] #[test] fn test_initialize_database_conn() { todo!() } + #[ignore] #[test] fn test_generate_table_from_struct() { todo!() } + #[ignore] #[test] fn test_get_data() { todo!() -- 2.45.1 From 495607efb4b7e2002f49bc31b81d9d803bc982d1 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 12 Feb 2025 20:03:11 +0100 Subject: [PATCH 13/97] Adds a semi realistic example and more filtering --- .gitignore | 4 +- weaponry/Cargo.toml | 1 + weaponry/benches/iter_creation.rs | 4 +- weaponry/examples/typical_wl_recipe.rs | 40 +++++++++++ weaponry/src/database.rs | 4 ++ weaponry/src/interfaces.rs | 69 ++++++++++++++++--- .../src/weaponry_structs/equipement_fields.rs | 20 +++--- ...nto_impls.rs => equipement_impl_basics.rs} | 51 ++++++++++++-- .../weaponry_structs/equipement_impl_logic.rs | 21 ++++-- .../weaponry_structs/equipement_impl_math.rs | 17 +++-- .../weaponry_structs/equipement_structs.rs | 58 +++++++++++----- weaponry/src/weaponry_structs/mod.rs | 2 +- 12 files changed, 238 insertions(+), 53 deletions(-) create mode 100644 weaponry/examples/typical_wl_recipe.rs rename weaponry/src/weaponry_structs/{equipement_into_impls.rs => equipement_impl_basics.rs} (50%) diff --git a/.gitignore b/.gitignore index a47be09..7d12725 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,6 @@ Cargo.lock /target .cargo/ -*.tar.gz +*.json.gz +callgrind* +cache.out diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 981c9b1..658d720 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] +fastrand = "2.3.0" pretty_assertions = "1.4.1" rayon = "1.10.0" rusqlite = { version = "0.33.0", features = ["bundled"] } diff --git a/weaponry/benches/iter_creation.rs b/weaponry/benches/iter_creation.rs index 75c07b9..8fa7981 100644 --- a/weaponry/benches/iter_creation.rs +++ b/weaponry/benches/iter_creation.rs @@ -22,8 +22,8 @@ fn criterion_benchmark(c: &mut Criterion) { c.bench_function("IterGenBlanket: 100x100x100", |b| { b.iter(|| { let mut s = blk_steps[0].clone(); - s.combine_all_by_blanket(black_box(&blk_steps[1])); - s.combine_all_by_blanket(black_box(&blk_steps[2])); + s.combine_all(black_box(&blk_steps[1])); + s.combine_all(black_box(&blk_steps[2])); }) }); // c.bench_function("IterGen: 100x100x100x100", |b| { diff --git a/weaponry/examples/typical_wl_recipe.rs b/weaponry/examples/typical_wl_recipe.rs new file mode 100644 index 0000000..ac1d0bb --- /dev/null +++ b/weaponry/examples/typical_wl_recipe.rs @@ -0,0 +1,40 @@ +// Workspace: weaponry +// File: examples/typical_wl_recipe.rs +//! Example of a typical workload + +use std::time::Instant; + +use weaponry::{ + interfaces::RecipeCollection, + weaponry_structs::{Equipement, FinalEquipementList}, +}; + +fn main() { + let blk_steps = [ + FinalEquipementList::from_vectored( + [1; 100].iter().map(|_| Equipement::default()).collect(), + ), + FinalEquipementList::from_vectored( + [1; 100].iter().map(|_| Equipement::default()).collect(), + ), + FinalEquipementList::from_vectored( + [1; 100].iter().map(|_| Equipement::default()).collect(), + ), + ]; + + // #[cfg(test)] + // println!("{:#?}", blk_steps); + let now = Instant::now(); + let mut s = blk_steps[0].clone(); + println!("First size {}", s.ref_inner().len()); + s.combine_all(&blk_steps[0]); + println!("Second size {}", s.ref_inner().len()); + s.combine_all(&blk_steps[0]); + println!("Third size {}", s.ref_inner().len()); + s.combine_all(&blk_steps[0]); + + // println!("{:#?}", blk_steps); + // println!("{:#?}", s); + println!("Final size {}", s.ref_inner().len()); + println!("Ellapsed: {:?}", Instant::now().duration_since(now)); +} diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 6aebc1e..ecea348 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -5,6 +5,10 @@ //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] #![allow(unused_imports)] +#![allow(missing_docs)] +#![allow(clippy::missing_docs_in_private_items)] +#![allow(clippy::single_char_add_str)] +#![allow(clippy::explicit_auto_deref)] use std::ops::Deref; use crate::weaponry_structs::equipement_structs::InnerStats; diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index d72a4cc..c78d5e3 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -5,6 +5,9 @@ //! handling of the whole crafting process when the times comes #![allow(dead_code)] +// use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; +use std::rc::Rc; + /// This element can be converted to tex pub trait ToTex {} @@ -16,15 +19,15 @@ pub trait FromParts {} /// A recipe list will be combined with a part list to be updated and generate all combinaisons, so on and so forth pub trait RecipeCollection where - for<'a> &'a <::Recipes as Combineable>::Inner: std::ops::Add, + for<'a> &'a <::Recipes as Combinable>::Inner: std::ops::Add, { /// The type of the inner recipes, this type must be combinable - type Recipes: Combineable; + type Recipes: Combinable; /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection /// /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch - fn combine_all_by_blanket(&mut self, other: &G) + fn combine_all(&mut self, other: &G) where G: RecipeCollection, { @@ -35,6 +38,7 @@ where other .ref_inner() .iter() + .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes)) .map(|external_recipes: &Self::Recipes| { inner_recipes.add_ref_to_self(external_recipes) }) @@ -51,8 +55,11 @@ where /// /// This allows to only clone when needed fn ref_inner(&self) -> &Vec; - - // Optional filter ? + /// + /// Gives access to a reference of the inner list + /// + /// This allows to only clone when needed + fn owned_inner(&self) -> Vec; /// Create a collection from a vector fn from_vectored(list: Vec) -> Self; @@ -61,11 +68,11 @@ where /// Trait that ensure that two elements of a recipe are combinable, /// /// Being combinable means it can be coerced into elements that implement add -pub trait Combineable +pub trait Combinable where - for<'a> &'a ::Inner: std::ops::Add, + for<'a> &'a ::Inner: std::ops::Add, { - /// The inner type of the combined elements, this type must implement Add + /// The inner type of the combined elements, this type must implement Add<&Inner> // TODO : Make this help much more readable type Inner; @@ -80,5 +87,49 @@ where /// This pushes the actual requirement to &Inner : Add<&Inner> fn add_ref_to_self(&self, rhs: &T) -> Self where - T: Combineable; + T: Combinable; + + /// Filter to decide if the addition should be done + /// + /// + /// Please note that this comparison is done from the new element perspective, + /// asking it if it will allow itself to be added as There is as of now no forward filtering + /// Most filters will defer an internal FilterFunction into the Inner to do all inner working, + /// but the implementation specifics are left open + fn backward_filter(&self, lhs: &T) -> bool + where + T: Combinable; } + +/// Type alias represinting the inner function parameter +pub(super) type FilterFunctionType = dyn Fn(&T, &T) -> bool; +/// Type alias representing a filter +pub(super) type FilterType = Box>>; + +#[derive(Clone)] +/// A generic Filtering function +pub(crate) struct FilterFunction(pub(super) FilterType); + +// /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection +// /// +// /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch +// fn combine_all_par(&mut self, other: &G) +// where +// G: RecipeCollection + std::marker::Sync, +// { +// self.assign_inner( +// self.owned_inner() +// .par_iter() +// .flat_map(|inner_recipes| { +// other +// .ref_inner() +// .iter() +// .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes)) +// .map(|external_recipes: &Self::Recipes| { +// inner_recipes.add_ref_to_self(external_recipes) +// }) +// .collect::>() +// }) +// .collect::>(), +// ); +// } diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 2bbcb5d..847c1e0 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -2,8 +2,8 @@ // File: weaponry/src/weaponry_structs/equipement_fields.rs //! The inner fields used by the super structs -#[derive(Clone, Default)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Default, Debug)] +#[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only pub struct SpecialCategory(pub(super) Vec); @@ -19,8 +19,8 @@ pub enum NatureTarget { /// Enum of all different physical weapon damage types #[allow(clippy::missing_docs_in_private_items)] -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { Blunt, Slash, @@ -38,8 +38,8 @@ impl From<&str> for PhysicalDamageType { /// /// Signifying wether the damage is pure or [secondary] or [[tertiary]] #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub enum DamageMod { Primary(PhysicalDamageType), Secondary(PhysicalDamageType), @@ -57,8 +57,8 @@ impl From<&str> for DamageMod { /// Combined damage type, as a vector of all damage types /// /// Meant to be serialised to tex and deserialized directly from the table -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub struct DamageType(pub(super) Vec); impl From<&str> for DamageType { @@ -71,8 +71,8 @@ impl From<&str> for DamageType { /// List all weapon categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, Dagger, diff --git a/weaponry/src/weaponry_structs/equipement_into_impls.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs similarity index 50% rename from weaponry/src/weaponry_structs/equipement_into_impls.rs rename to weaponry/src/weaponry_structs/equipement_impl_basics.rs index 5beefef..218b5f9 100644 --- a/weaponry/src/weaponry_structs/equipement_into_impls.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -8,6 +8,10 @@ //! Implementations to transform all Specialized equipement into a generic Equipement //! A specific implementation could be preferable, but this simplicity might allow for easier developpement +use crate::interfaces::FilterFunction; +use std::fmt::Debug; +use std::rc::Rc; + use super::{ Equipement, equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}, @@ -15,21 +19,60 @@ use super::{ impl From for Equipement { fn from(val: EqShape) -> Self { - Self { stats: val.stats } + Self { + stats: val.stats, + ..Default::default() + } } } impl From for Equipement { fn from(val: EqMaterial) -> Self { - Self { stats: val.stats } + Self { + stats: val.stats, + ..Default::default() + } } } impl From for Equipement { fn from(val: EqNature) -> Self { - Self { stats: val.stats } + Self { + stats: val.stats, + ..Default::default() + } } } impl From for Equipement { fn from(val: EqFinishing) -> Self { - Self { stats: val.stats } + Self { + stats: val.stats, + ..Default::default() + } } } + +impl Debug for FilterFunction { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Filter:{}", + // std::any::type_name::(), + std::any::type_name::() + ) + } +} +impl Default for FilterFunction { + fn default() -> Self { + FilterFunction(Box::new(Rc::new(|_, _| true))) + } +} +impl PartialEq for FilterFunction { + fn eq(&self, _other: &Self) -> bool { + true + } +} +// impl FilterFunction { +// /// Generate a new filter +// pub fn new(filter: FilterFunctionType) -> Self { +// Self(Box::new(Rc::new(filter))) +// } +// } diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index e2fed62..21acb2e 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -2,11 +2,11 @@ // File: weaponry/src/weaponry_structs/equipement_impl_logic.rs //! Implementation of the logic traits, used for equipement generation -use crate::interfaces::{Combineable, RecipeCollection}; +use crate::interfaces::{Combinable, RecipeCollection}; use super::{Equipement, FinalEquipementList, equipement_structs::InnerStats}; -impl Combineable for Equipement { +impl Combinable for Equipement { type Inner = InnerStats; fn combinable_part(&self) -> &Self::Inner { @@ -15,12 +15,20 @@ impl Combineable for Equipement { fn add_ref_to_self(&self, rhs: &T) -> Self where - T: Combineable, + T: Combinable, { Self { stats: self.combinable_part() + rhs.combinable_part(), + ..Default::default() } } + + fn backward_filter(&self, lhs: &T) -> bool + where + T: Combinable, + { + self.filter_function.0(self.combinable_part(), lhs.combinable_part()) + } } impl RecipeCollection for FinalEquipementList { @@ -37,6 +45,10 @@ impl RecipeCollection for FinalEquipementList { fn assign_inner(&mut self, inner: Vec) { self.inner = inner; } + + fn owned_inner(&self) -> Vec { + self.inner.clone() + } } #[cfg(test)] @@ -66,7 +78,7 @@ mod test { &vec![Equipement::newish(&["a"], 1), Equipement::newish(&["b"], 2)] ); - f.combine_all_by_blanket(&g); + f.combine_all(&g); assert_eq!( f, FinalEquipementList::from_vectored(vec![ @@ -170,6 +182,7 @@ mod test { rarity: i, ..Default::default() }, + ..Default::default() } } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 19d8235..0f49394 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -6,18 +6,23 @@ use super::equipement_structs::InnerStats; use crate::weaponry_structs::SpecialCategory; +/// Add a new vector to a clone of a inner field +macro_rules! add_to_vec { + ($self: expr, $rhs: expr) => {{ + let mut new = $self.clone(); + new.append(&mut $rhs.clone()); + new + }}; +} + impl std::ops::Add for &InnerStats { type Output = InnerStats; fn add(self, rhs: Self) -> Self::Output { InnerStats { // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless - id: self.id, - name: { - let mut b = self.name.clone(); - b.append(&mut rhs.name.clone()); - b - }, + id: add_to_vec!(self.id, rhs.id), + name: add_to_vec!(self.name, rhs.name), rarity: self.rarity + rhs.rarity, cost: self.cost + rhs.cost, difficulty: self.difficulty + rhs.difficulty, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 856ff94..c4ccdf8 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -2,34 +2,51 @@ // File: weaponry/src/weaponry_structs/equipement_structs.rs //! Base equipement structures +use std::rc::Rc; + use struct_field_names_as_array::FieldNamesAsArray; +use crate::interfaces::FilterFunction; + use super::{DamageType, NatureTarget, SpecialCategory, WeaponCategory}; /// The final equipement list /// /// This list is initialized with the base part and updated by succesive combinaisons -#[derive(Clone)] -#[cfg_attr(test, derive(PartialEq, Debug))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub struct FinalEquipementList { /// Inner List of final equipements pub(super) inner: Vec, } /// The final equipement, obtained by combining all parts -#[derive(Clone, Default)] -#[cfg_attr(test, derive(PartialEq, Debug))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub struct Equipement { /// The inner stats used by the equipement pub(super) stats: InnerStats, + /// The filter, used to determine if adding is warranted + pub(super) filter_function: FilterFunction, +} + +impl Default for Equipement { + fn default() -> Self { + Self { + filter_function: FilterFunction(Box::new(Rc::new(|self_, lhs| { + !self_.id.iter().any(|a| *a == lhs.id[0]) + }))), + stats: InnerStats::random_new(), + } + } } /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldNamesAsArray)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Default, FieldNamesAsArray, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub struct InnerStats { - pub id: u8, + pub id: Vec, pub name: Vec, pub(super) rarity: u8, pub(super) cost: u8, @@ -59,6 +76,16 @@ pub struct InnerStats { pub(super) agility_bonus: u8, } +impl InnerStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: vec![fastrand::u8(..10)], + ..Default::default() + } + } +} + /// Shape of the equipement, first mandatory part of an equipement pub struct EqShape { /// The inner stats of the part @@ -99,6 +126,8 @@ mod test { EqFinishing, EqMaterial, EqNature, EqShape, Equipement, FinalEquipementList, InnerStats, }; + // use pretty_assertions::assert_eq; + fn list_equip() -> Vec { (0..10) .map(|_| Equipement { @@ -109,15 +138,12 @@ mod test { #[test] fn test_struct_creation() { - let stats = InnerStats::default(); - let eq1 = Equipement { + let _stats = InnerStats::default(); + let _eq1 = Equipement { ..Default::default() }; - let list_eq = list_equip(); - - assert_eq!(stats, eq1.stats); - assert_eq!(list_eq[0], eq1); + let _list_eq = list_equip(); } #[test] @@ -149,9 +175,9 @@ mod test { ]; let mut leq = FinalEquipementList::from_vectored(shape); - leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(nature)); - leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(material)); - leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(finishing)); + leq.combine_all(&FinalEquipementList::from_vectored(nature)); + leq.combine_all(&FinalEquipementList::from_vectored(material)); + leq.combine_all(&FinalEquipementList::from_vectored(finishing)); } #[ignore] diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 6f34bd1..482bd6b 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -16,11 +16,11 @@ // static GLOBAL: Jemalloc = Jemalloc; mod equipement_fields; +mod equipement_impl_basics; mod equipement_impl_database; mod equipement_impl_io; mod equipement_impl_logic; mod equipement_impl_math; -mod equipement_into_impls; pub mod equipement_structs; // Republishes the most used symbols -- 2.45.1 From 91c5c4bb37016f6832decde5bd1b57a778c5752a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 12 Feb 2025 21:29:15 +0100 Subject: [PATCH 14/97] Cleans up further database --- weaponry/src/database.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index ecea348..0f56fad 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -4,16 +4,9 @@ //! Implements the basics deserialisation from a database to the weaponry components //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] -#![allow(unused_imports)] -#![allow(missing_docs)] -#![allow(clippy::missing_docs_in_private_items)] -#![allow(clippy::single_char_add_str)] -#![allow(clippy::explicit_auto_deref)] -use std::ops::Deref; use crate::weaponry_structs::equipement_structs::InnerStats; -use rusqlite::{self, Connection, Result, params}; -use struct_field_names_as_array::FieldNamesAsArray; +use rusqlite::{self, Connection, Result}; /// Generate a SELECT query with fields generated from a struct. Returns a String fn generate_query(fields: &[&str], table_name: &str) -> String { @@ -51,9 +44,8 @@ pub fn get_data() -> Vec { #[cfg(test)] mod test { - use std::any::type_name; - use pretty_assertions::assert_eq; + use struct_field_names_as_array::FieldNamesAsArray; use super::*; #[derive(FieldNamesAsArray)] -- 2.45.1 From c945ebccf052a2f2518b90491b5e9c73f2634810 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Wed, 12 Feb 2025 23:24:13 +0100 Subject: [PATCH 15/97] Adding new sqlite database with triggers baked inside --- weaponry/weapons.db | Bin 0 -> 28672 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 weaponry/weapons.db diff --git a/weaponry/weapons.db b/weaponry/weapons.db new file mode 100644 index 0000000000000000000000000000000000000000..f361221defc013df358aa2cb237d2de131edd91b GIT binary patch literal 28672 zcmeI(Z*S8^90zclLbI55LE6@++Jjy5C{Y<2;vqs?phvMtosu}~Djrx@`x;Ipc6zy} zbdx4^(=_p7_6oMQGQ?9Jf_MZx;Ow{wc2jjiW$J^kB`5Ly^Y1?QyGmA*_Jf8{oa{!j z&lI^~Tro`3_<<0^FqZULNKaG0U)SeFeI6Zg*=fg;aqZ{5#f9&TLh&!-^0Uhi7yeo7 zF8paV^(77nKmY;|fB*y_0D;p44!>C{eEsdpXNSKiDY{)Q1K#6`dqX8hzVbw1has13 z#nkXli`HFA+?Kt*PFp13kXS??^}DXFTcZuCn>HOX?QY$s>$a0LN~`a-nj6Gcyl)3& z>mF@U60$xgw@9d>tu#M(`(*x6i*VWv|hZR!#c5IvP@TT|Rgu1=V4!@jR4&iBW| zeF%}MNh}VH#X@;`**tux*iMg+?Z&Scj+Uo>yFp21Tv#Dht5^|1rKo2@<5hE-E^#`I z2I)BVgATo_tK*4PiZ1=h)mNJ>d!ydkCim%fHSS329k*#adhiYExHYS`IX7QkT{X9p z0ET-#5ibSb8}ZQRxyy^0kaCrY=T+Uaw(!E(IxS5(kHktDn!8zh6GFQ0HVz zKxJBSEHAQoFe^(WlR_O#5-INBM?;k<2*mEL@JGE|J0-Zxwqt$P)j5|YWjxlv3uY8b z?u(&_!c0^BSotJVz+^v?-j4pW@OVb~K;PZZ-i(Dx=x0+d1?y#cjAQWB!C<;0DgzlQ z?yGzlB2>J4%tS>}?*&ioN8Tf*GjF=};#sD(QOIZ222qe#VNzzzhXbA)bEr7$sYjW4 z_x%B@C$l{&V9AWUV{0gRFJi%rau()-V_l(l|ADs?g`?r*_Ev2%PVg&+ zQF>c?c}BU8VITkj2tWV=5P$##AOHafKmY;|IA;P@98diG|EBc%oP~yPAOHafKmY;| zfB*y_009U<00Iy=BZ2t;|E7NQFTF1PdqzWI7zjWB0uX=z1Rwwb2tWV=5P$##&Vhh+ zVQ$$R|1733`Tqa&(%)7#>4H w00Izz00bZa0SG_<0uX=z1Rwwb2tWV=5P$##AOHafKmY;|fB*y_@IMH=2R0|bsQ>@~ literal 0 HcmV?d00001 -- 2.45.1 From 36e1b84ae8b767d1f78cdc55d7b5b68a6bb9f8b1 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 12 Feb 2025 22:14:59 +0100 Subject: [PATCH 16/97] Adds better filters --- weaponry/src/interfaces.rs | 13 +++--- .../src/weaponry_structs/equipement_fields.rs | 5 ++- .../equipement_impl_advanced.rs | 24 ++++++++++ .../equipement_impl_basics.rs | 45 ++++++------------- .../weaponry_structs/equipement_impl_logic.rs | 4 -- .../weaponry_structs/equipement_impl_math.rs | 1 + .../weaponry_structs/equipement_structs.rs | 30 ++++++++----- weaponry/src/weaponry_structs/mod.rs | 1 + 8 files changed, 69 insertions(+), 54 deletions(-) create mode 100644 weaponry/src/weaponry_structs/equipement_impl_advanced.rs diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index c78d5e3..c54f718 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -55,11 +55,6 @@ where /// /// This allows to only clone when needed fn ref_inner(&self) -> &Vec; - /// - /// Gives access to a reference of the inner list - /// - /// This allows to only clone when needed - fn owned_inner(&self) -> Vec; /// Create a collection from a vector fn from_vectored(list: Vec) -> Self; @@ -73,7 +68,6 @@ where for<'a> &'a ::Inner: std::ops::Add, { /// The inner type of the combined elements, this type must implement Add<&Inner> - // TODO : Make this help much more readable type Inner; /// Give access to a reference of the underlying data to be combined @@ -102,6 +96,7 @@ where } /// Type alias represinting the inner function parameter +// #![feature(trait_alias)] pub(super) type FilterFunctionType = dyn Fn(&T, &T) -> bool; /// Type alias representing a filter pub(super) type FilterType = Box>>; @@ -110,6 +105,12 @@ pub(super) type FilterType = Box>>; /// A generic Filtering function pub(crate) struct FilterFunction(pub(super) FilterType); +// impl FilterFunction { +// fn new_from_closure(m: &FilterFunctionType) -> Self { +// FilterFunction(Box::new(Rc::new(m))) +// } +// } + // /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection // /// // /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 847c1e0..0940494 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -8,6 +8,7 @@ pub struct SpecialCategory(pub(super) Vec); /// The kind of target this nature can apply to +#[derive(Clone)] pub enum NatureTarget { /// Can apply to a weapon and is unique WeaponUnique, @@ -71,8 +72,8 @@ impl From<&str> for DamageType { /// List all weapon categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug)] -#[cfg_attr(test, derive(PartialEq))] +#[derive(Clone, Debug, PartialEq)] +// #[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, Dagger, diff --git a/weaponry/src/weaponry_structs/equipement_impl_advanced.rs b/weaponry/src/weaponry_structs/equipement_impl_advanced.rs new file mode 100644 index 0000000..c97cf7f --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_impl_advanced.rs @@ -0,0 +1,24 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_impl_advanced.rs +//! Advanced implementation, reserved for traits and impls that are implemented only once on the main equipement and it's helper +//! +//! These impls are here to either prettify output, or allow for smoother implementation of other traits and inner workings + +use crate::interfaces::FilterFunction; +use std::{fmt::Debug, rc::Rc}; + +impl Debug for FilterFunction { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Filter:{}", std::any::type_name::()) + } +} +impl Default for FilterFunction { + fn default() -> Self { + FilterFunction(Box::new(Rc::new(|_, _| true))) + } +} +impl PartialEq for FilterFunction { + fn eq(&self, _other: &Self) -> bool { + true + } +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 218b5f9..fc7f57d 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -1,5 +1,5 @@ // Workspace: weaponry -// File: weaponry/src/weaponry_structs/equipement_into_impls.rs +// File: weaponry/src/weaponry_structs/equipement_impl_basics.rs // TODO: At some point a trait might want to be used to use these into instead of calling it directly // : Doing so would ensure all prerequists are met // : Another way of doing so might be to instead use Into instead @@ -9,8 +9,6 @@ //! A specific implementation could be preferable, but this simplicity might allow for easier developpement use crate::interfaces::FilterFunction; -use std::fmt::Debug; -use std::rc::Rc; use super::{ Equipement, @@ -37,10 +35,22 @@ impl From for Equipement { fn from(val: EqNature) -> Self { Self { stats: val.stats, - ..Default::default() + // filter_function: FilterFunction(default_filter_for_equipement()), + filter_function: FilterFunction::new(&|sel, lhs| { + match (&sel.target, &lhs.category) { + (Some(a), Some(b)) => a == b, + (None, None) => true, + _ => false, + } + // if let Some(targ) = &sel.target { + // &lhs.category + // } + // & default_filter()(sel, lhs) + }), } } } + impl From for Equipement { fn from(val: EqFinishing) -> Self { Self { @@ -49,30 +59,3 @@ impl From for Equipement { } } } - -impl Debug for FilterFunction { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Filter:{}", - // std::any::type_name::(), - std::any::type_name::() - ) - } -} -impl Default for FilterFunction { - fn default() -> Self { - FilterFunction(Box::new(Rc::new(|_, _| true))) - } -} -impl PartialEq for FilterFunction { - fn eq(&self, _other: &Self) -> bool { - true - } -} -// impl FilterFunction { -// /// Generate a new filter -// pub fn new(filter: FilterFunctionType) -> Self { -// Self(Box::new(Rc::new(filter))) -// } -// } diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index 21acb2e..bb7bdc6 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -45,10 +45,6 @@ impl RecipeCollection for FinalEquipementList { fn assign_inner(&mut self, inner: Vec) { self.inner = inner; } - - fn owned_inner(&self) -> Vec { - self.inner.clone() - } } #[cfg(test)] diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 0f49394..7951a98 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -54,6 +54,7 @@ impl std::ops::Add for &InnerStats { 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 action_cost: self.action_cost + rhs.action_cost, reload_cost: self.reload_cost.or(rhs.reload_cost), diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index c4ccdf8..94900f2 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -6,9 +6,9 @@ use std::rc::Rc; use struct_field_names_as_array::FieldNamesAsArray; -use crate::interfaces::FilterFunction; +use crate::interfaces::{FilterFunction, FilterFunctionType}; -use super::{DamageType, NatureTarget, SpecialCategory, WeaponCategory}; +use super::{DamageType, SpecialCategory, WeaponCategory}; /// The final equipement list /// @@ -33,14 +33,25 @@ pub struct Equipement { impl Default for Equipement { fn default() -> Self { Self { - filter_function: FilterFunction(Box::new(Rc::new(|self_, lhs| { - !self_.id.iter().any(|a| *a == lhs.id[0]) - }))), + filter_function: FilterFunction::new(default_filter()), stats: InnerStats::random_new(), } } } +/// The default filter to use, usefull to implement a new filter function that also uses the default filter +pub(crate) fn default_filter() -> &'static impl Fn(&InnerStats, &InnerStats) -> bool { + &|self_, lhs| !self_.id.iter().any(|a| *a == lhs.id[0]) +} + +impl FilterFunction { + /// Generate a new filter + // TODO: This static lifetime is basically telling us that an owned value is needed + pub fn new(filter: &'static FilterFunctionType) -> Self { + Self(Box::new(Rc::new(filter))) + } +} + /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Default, FieldNamesAsArray, Debug)] @@ -69,6 +80,7 @@ pub struct InnerStats { pub(super) speed: u8, pub(super) stealth: u8, pub(super) category: Option, + pub(super) target: Option, pub(super) special: SpecialCategory, pub(super) action_cost: u8, pub(super) reload_cost: Option, @@ -76,6 +88,7 @@ pub struct InnerStats { pub(super) agility_bonus: u8, } +// TODO: Make this a test requirement or hide it behind a profile impl InnerStats { /// Testing function to fuzz data pub fn random_new() -> Self { @@ -104,10 +117,6 @@ pub struct EqMaterial { pub struct EqNature { /// The inner stats of the part pub(super) stats: InnerStats, - // TODO: Be sure to take this into account - #[allow(dead_code)] - /// Which kind of target this nature applies to - pub(super) target: NatureTarget, } /// Finishing touches, since all of them have a cost, they are treated in a special fashion @@ -120,7 +129,7 @@ pub struct EqFinishing { mod test { // use super::*; - use crate::{interfaces::RecipeCollection, weaponry_structs::NatureTarget}; + use crate::interfaces::RecipeCollection; use super::{ EqFinishing, EqMaterial, EqNature, EqShape, Equipement, FinalEquipementList, InnerStats, @@ -157,7 +166,6 @@ mod test { let nature = vec![ EqNature { stats: InnerStats::default(), - target: NatureTarget::Armor, } .into(), ]; diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 482bd6b..9bcb277 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -16,6 +16,7 @@ // static GLOBAL: Jemalloc = Jemalloc; mod equipement_fields; +mod equipement_impl_advanced; mod equipement_impl_basics; mod equipement_impl_database; mod equipement_impl_io; -- 2.45.1 From 06c74639ffb20d757c27720c60250bf03e2c5800 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 13 Feb 2025 00:13:46 +0100 Subject: [PATCH 17/97] Base impl for export --- weaponry/src/interfaces.rs | 12 ++++++--- .../weaponry_structs/equipement_impl_math.rs | 27 +++++++++++-------- .../src/weaponry_structs/equipement_tools.rs | 15 +++++++++++ weaponry/src/weaponry_structs/mod.rs | 1 + 4 files changed, 41 insertions(+), 14 deletions(-) create mode 100644 weaponry/src/weaponry_structs/equipement_tools.rs diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index c54f718..2252354 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -9,10 +9,16 @@ use std::rc::Rc; /// This element can be converted to tex -pub trait ToTex {} +pub trait ToTex { + /// Export the object to a Tex string + fn to_tex() -> String; +} -/// Specify this element can be made from parts (Unsure, maybe a way to ensure Add is presend ?) -pub trait FromParts {} +/// This element can be converted to a csv for further analysis +pub trait ToAnalysis { + /// Convert this object into a csv + fn to_csv() -> String; +} /// Trait implemented for the final collection of a recipe, allowing it to be combined with parts /// diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 7951a98..1f7c501 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -15,6 +15,21 @@ macro_rules! add_to_vec { }}; } +/// Adds either of the vectors or merge them +macro_rules! add_two_options { + ($self: expr, $rhs: expr) => {{ + match ($self.clone(), $rhs.clone()) { + (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) + } + } + }}; +} + impl std::ops::Add for &InnerStats { type Output = InnerStats; @@ -34,17 +49,7 @@ impl std::ops::Add for &InnerStats { armor_break: self.armor_break + rhs.armor_break, armor_pierce: self.armor_pierce + rhs.armor_pierce, antimaterial: self.antimaterial + rhs.antimaterial, - damage_type: { - match (self.damage_type.clone(), rhs.damage_type.clone()) { - (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) - } - } - }, + 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, diff --git a/weaponry/src/weaponry_structs/equipement_tools.rs b/weaponry/src/weaponry_structs/equipement_tools.rs new file mode 100644 index 0000000..1099749 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_tools.rs @@ -0,0 +1,15 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_tools.rs +//! Tools user facing, implement all that a end user would need +//! + +#![allow(dead_code)] + +/// Tooling utility +fn load_database() {} + +/// Export the data generated to tex +fn export_to_tex() {} + +/// Export the data generated to csv +fn export_to_csv() {} diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 9bcb277..6e3dd86 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -23,6 +23,7 @@ mod equipement_impl_io; mod equipement_impl_logic; mod equipement_impl_math; pub mod equipement_structs; +pub mod equipement_tools; // Republishes the most used symbols // All generic structs -- 2.45.1 From ddb70c1cb3f9936161b139c6bcfd580300ca6308 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 13 Feb 2025 03:22:58 +0100 Subject: [PATCH 18/97] Adds placeholders for refining and views --- weaponry/{ => databases}/weapons.db | Bin weaponry/src/interfaces.rs | 61 ++++++++--- .../equipement_advanced_repr.rs | 99 ++++++++++++++++++ .../equipement_impl_basics.rs | 18 ++-- .../equipement_impl_database.rs | 27 +++++ .../src/weaponry_structs/equipement_tools.rs | 1 + .../src/weaponry_structs/equipement_views.rs | 28 +++++ weaponry/src/weaponry_structs/mod.rs | 2 + 8 files changed, 210 insertions(+), 26 deletions(-) rename weaponry/{ => databases}/weapons.db (100%) create mode 100644 weaponry/src/weaponry_structs/equipement_advanced_repr.rs create mode 100644 weaponry/src/weaponry_structs/equipement_views.rs diff --git a/weaponry/weapons.db b/weaponry/databases/weapons.db similarity index 100% rename from weaponry/weapons.db rename to weaponry/databases/weapons.db diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 2252354..1f65804 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -5,20 +5,39 @@ //! handling of the whole crafting process when the times comes #![allow(dead_code)] -// use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use std::rc::Rc; -/// This element can be converted to tex -pub trait ToTex { - /// Export the object to a Tex string - fn to_tex() -> String; +/// Trait representing a view table +/// +/// These table exist to allow to link several point of interest to a RecipeCollection +/// Please note that while FinalRepresentations and ViewTable are two separate traits, +/// they are always tied together as a view table will alway take specific assumptions +/// on the data present inside therefore not allowing many variations on the underlying +/// implementation of the representation +pub trait ViewTable { + /// The inner type of element that one would be peeking into + /// + /// Usually the final representation of an Item + type InterestElement: RefinedList; + + /// Give a list of interesting element indicises to further analyse + fn index_of_interest_points(&self) -> Vec; + + /// Interrogate the FinalRepresentation to find interesting elements + fn find_points_of_interest(&self, representation: &Self::InterestElement); + // An alternative, non Self::Typed way of doing since there is only one usage for now + // fn find_points_of_interest(&self, representation: &impl FinalRepresentation); } -/// This element can be converted to a csv for further analysis -pub trait ToAnalysis { - /// Convert this object into a csv - fn to_csv() -> String; -} +/// Trait implemented by any struct holding the final representation of a RecipeCollection +/// +/// This trait is rather placeholder, reminding the user to give only objects that are indeed +/// final representations and contains all important fields calculated +/// +/// While it is possible to enforce from_recipe_collection, doing so would require the viewtable +/// lock itseld to a particular recipe. +/// While it is the case as of now, matters are not yet set in stone +pub trait RefinedList {} /// Trait implemented for the final collection of a recipe, allowing it to be combined with parts /// @@ -111,11 +130,23 @@ pub(super) type FilterType = Box>>; /// A generic Filtering function pub(crate) struct FilterFunction(pub(super) FilterType); -// impl FilterFunction { -// fn new_from_closure(m: &FilterFunctionType) -> Self { -// FilterFunction(Box::new(Rc::new(m))) -// } -// } +/// This element can be converted to tex +pub trait ToTex { + /// Export the object to a Tex string + fn to_tex(&self) -> String; +} + +/// This element can be converted to a csv for further analysis +pub trait ToAnalysis { + /// Convert this object into a csv + fn to_csv(&self) -> String; +} + +/// Garanties that a struct can be generated from a database +pub trait DbSerializable { + /// Serialize the object from a database + fn from_database() -> Self; +} // /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection // /// diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs new file mode 100644 index 0000000..3c71da0 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -0,0 +1,99 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_advanced_repr.rs +//! Give an advanced representation of the equipement, infering more fields (such a dpt, max_dps etc...) +//! +//! The generation of this fields is primordial to allow post filtering and visualisation +//! +//! Note that while ALL fields and representation will likely be backed into a megablob, +//! nothing prevents us to implement the trait for other objects and avoid massive computation +//! of all the fields even when the user will not be interested in them +#![allow(dead_code)] + +use crate::interfaces::RefinedList; + +use super::equipement_structs::InnerStats; + +/// The final representation of the equipement inplementing all the fields needed for processing +pub struct RefinedEquipement { + /// The original inner stats + /// + /// This structs takes ownership of the inner data + inner: InnerStats, + + /// Advanced stats + advanced: AdvancedStats, +} + +pub struct RefinedEquipementList(Vec); + +// Just a checkmark +impl RefinedList for RefinedEquipementList {} + +/// The list of advanced stats infered from an Equipement +#[allow(missing_docs, clippy::missing_docs_in_private_items)] +pub struct AdvancedStats { + damage_per_turn: f64, + damage_per_action: f64, + armor_break_per_turn: f64, + armor_break_per_action: f64, + damage_matrix: DamageMatrix, + /// Armor break factoring in the damage output: While a weapon might have high AB, not having any damage will seriously hinder that AB + expected_armor_break_per_turn: f64, + // All other criterias are already in the inner as raw criterias +} + +/// A damage matrix, crossing damage conditions (high dice to low dice) with precision (high precision to low precision) +/// +/// This simulation does only calculate a very limited preset of damage values +struct DamageMatrix { + /// The inner damage matrix + damage_matrix: Vec, +} +impl DamageMatrix { + /// Get the damage value from given condition + pub fn get_damage(&self, precision: Precision, dices: DiceNumber) -> f64 { + self.damage_matrix[precision.index() + 3 * dices.index()] + } + /// Calculate the damage simulation from a given InnerStats + pub fn calculate_damage(inner: &InnerStats) -> Self { + let _ = inner; + todo!() + } +} + +/// The precision infered for a damage calculation event +pub enum Precision { + High = 9, + Medium = 6, + Low = 3, +} + +/// The number of dices rolled for a damage simulation +pub enum DiceNumber { + High = 7, + Medium = 5, + Low = 3, +} + +impl Precision { + #[inline] + /// Associate an index to the different values + fn index(&self) -> usize { + match self { + Precision::High => 0, + Precision::Medium => 1, + Precision::Low => 2, + } + } +} +impl DiceNumber { + #[inline] + /// Associate an index to the different values + fn index(&self) -> usize { + match self { + DiceNumber::High => 0, + DiceNumber::Medium => 1, + DiceNumber::Low => 2, + } + } +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index fc7f57d..252833a 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -35,17 +35,13 @@ impl From for Equipement { fn from(val: EqNature) -> Self { Self { stats: val.stats, - // filter_function: FilterFunction(default_filter_for_equipement()), - filter_function: FilterFunction::new(&|sel, lhs| { - match (&sel.target, &lhs.category) { - (Some(a), Some(b)) => a == b, - (None, None) => true, - _ => false, - } - // if let Some(targ) = &sel.target { - // &lhs.category - // } - // & default_filter()(sel, lhs) + // 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) { + (Some(a), Some(b)) => a == b, + (None, None) => true, + _ => false, }), } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index d300254..8ab55b2 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -1,3 +1,30 @@ // Workspace: weaponry // File: weaponry/src/weaponry_structs/equipement_impl_database.rs //! All database specific implementations + +use crate::interfaces::DbSerializable; + +use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; + +//TODO: Fred, make these and I'm happy + +impl DbSerializable for EqShape { + fn from_database() -> Self { + todo!() + } +} +impl DbSerializable for EqMaterial { + fn from_database() -> Self { + todo!() + } +} +impl DbSerializable for EqNature { + fn from_database() -> Self { + todo!() + } +} +impl DbSerializable for EqFinishing { + fn from_database() -> Self { + todo!() + } +} diff --git a/weaponry/src/weaponry_structs/equipement_tools.rs b/weaponry/src/weaponry_structs/equipement_tools.rs index 1099749..739aad5 100644 --- a/weaponry/src/weaponry_structs/equipement_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_tools.rs @@ -2,6 +2,7 @@ // File: weaponry/src/weaponry_structs/equipement_tools.rs //! Tools user facing, implement all that a end user would need //! +//! This file implements all the functions the main runner will eventually launch #![allow(dead_code)] diff --git a/weaponry/src/weaponry_structs/equipement_views.rs b/weaponry/src/weaponry_structs/equipement_views.rs new file mode 100644 index 0000000..3339038 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_views.rs @@ -0,0 +1,28 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_views.rs +//! Implement the view trait to allow for a list of "Points of Interest" to be created +//! This list is imperative to allow several criterias to be looked up one after the other to gather as many points of data as possible +//! +//! It is mandatory that these points of interest link back to the original data by index and not by reference, to allow this operation to be thread safe + +#![allow(dead_code)] + +use crate::interfaces::ViewTable; + +use super::equipement_advanced_repr::RefinedEquipementList; + +/// A rather full view of an equipement, this multi field allow for a great amount of different operations but incurrs a rather hefty calculation price +struct EquipementFullView {} + +impl ViewTable for EquipementFullView { + type InterestElement = RefinedEquipementList; + + fn index_of_interest_points(&self) -> Vec { + todo!() + } + + fn find_points_of_interest(&self, representation: &Self::InterestElement) { + let _ = representation; + todo!() + } +} diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 6e3dd86..12fb55a 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -15,6 +15,7 @@ // #[global_allocator] // static GLOBAL: Jemalloc = Jemalloc; +mod equipement_advanced_repr; mod equipement_fields; mod equipement_impl_advanced; mod equipement_impl_basics; @@ -24,6 +25,7 @@ mod equipement_impl_logic; mod equipement_impl_math; pub mod equipement_structs; pub mod equipement_tools; +mod equipement_views; // Republishes the most used symbols // All generic structs -- 2.45.1 From b69206212c30d18ce383e88ea0177a777c365ef9 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 13 Feb 2025 20:05:00 +0100 Subject: [PATCH 19/97] Adds a lot ot the advanced representation --- weaponry/Cargo.toml | 3 + weaponry/benches/iter_creation.rs | 10 +- weaponry/examples/typical_wl_recipe.rs | 8 +- weaponry/src/database.rs | 4 +- weaponry/src/interfaces.rs | 18 ++- .../equipement_advanced_repr.rs | 145 +++++++++++++++--- .../weaponry_structs/equipement_impl_logic.rs | 36 ++--- .../weaponry_structs/equipement_impl_math.rs | 8 +- .../weaponry_structs/equipement_structs.rs | 44 +++--- weaponry/src/weaponry_structs/mod.rs | 2 +- 10 files changed, 197 insertions(+), 81 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 658d720..c15964e 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -5,10 +5,13 @@ edition = "2024" [dependencies] fastrand = "2.3.0" +iter-enum = "1.2.0" pretty_assertions = "1.4.1" +probability = "0.20.3" rayon = "1.10.0" rusqlite = { version = "0.33.0", features = ["bundled"] } struct-field-names-as-array = "0.3.0" +strum = { version = "0.27.0", features = ["derive"] } [dev-dependencies] criterion = { version = "0.5" } diff --git a/weaponry/benches/iter_creation.rs b/weaponry/benches/iter_creation.rs index 8fa7981..7ca9b5b 100644 --- a/weaponry/benches/iter_creation.rs +++ b/weaponry/benches/iter_creation.rs @@ -2,18 +2,18 @@ use criterion::{Criterion, criterion_group, criterion_main}; use std::{hint::black_box, time::Duration}; use weaponry::{ interfaces::RecipeCollection, - weaponry_structs::{Equipement, FinalEquipementList}, + weaponry_structs::{Equipement, InitialEquipementList}, }; fn criterion_benchmark(c: &mut Criterion) { let blk_steps = [ - FinalEquipementList::from_vectored(vec![Equipement::default(); 100]), - FinalEquipementList::from_vectored(vec![Equipement::default(); 100]), - FinalEquipementList::from_vectored(vec![Equipement::default(); 100]), + InitialEquipementList::from_vectored(vec![Equipement::default(); 100]), + InitialEquipementList::from_vectored(vec![Equipement::default(); 100]), + InitialEquipementList::from_vectored(vec![Equipement::default(); 100]), ]; c.bench_function("creating 100 Elements", |b| { b.iter(|| { - FinalEquipementList::from_vectored(black_box(vec![ + InitialEquipementList::from_vectored(black_box(vec![ black_box(Equipement::default()); 100 ])) diff --git a/weaponry/examples/typical_wl_recipe.rs b/weaponry/examples/typical_wl_recipe.rs index ac1d0bb..1efcc8a 100644 --- a/weaponry/examples/typical_wl_recipe.rs +++ b/weaponry/examples/typical_wl_recipe.rs @@ -6,18 +6,18 @@ use std::time::Instant; use weaponry::{ interfaces::RecipeCollection, - weaponry_structs::{Equipement, FinalEquipementList}, + weaponry_structs::{Equipement, InitialEquipementList}, }; fn main() { let blk_steps = [ - FinalEquipementList::from_vectored( + InitialEquipementList::from_vectored( [1; 100].iter().map(|_| Equipement::default()).collect(), ), - FinalEquipementList::from_vectored( + InitialEquipementList::from_vectored( [1; 100].iter().map(|_| Equipement::default()).collect(), ), - FinalEquipementList::from_vectored( + InitialEquipementList::from_vectored( [1; 100].iter().map(|_| Equipement::default()).collect(), ), ]; diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 0f56fad..ad2b81c 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -5,7 +5,7 @@ //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] -use crate::weaponry_structs::equipement_structs::InnerStats; +use crate::weaponry_structs::equipement_structs::InnerEquipementStats; use rusqlite::{self, Connection, Result}; /// Generate a SELECT query with fields generated from a struct. Returns a String @@ -35,7 +35,7 @@ fn initialize_database_conn(filename: Option) -> Result { } /// Public function to get data from db -pub fn get_data() -> Vec { +pub fn get_data() -> Vec { /* let gen_query = generate_query(&InnerStats::FIELD_NAMES_AS_ARRAY, "InnerStats"); let db_conn = initialize_database_conn(Some("/tmp/data.sqlite3".to_owned())).unwrap(); let mut query_result = db_conn.prepare(&gen_query);*/ diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 1f65804..ee0b004 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -37,7 +37,10 @@ pub trait ViewTable { /// While it is possible to enforce from_recipe_collection, doing so would require the viewtable /// lock itseld to a particular recipe. /// While it is the case as of now, matters are not yet set in stone -pub trait RefinedList {} +pub trait RefinedList { + // Must implement From, is it worth adding as a prerequite type ? + // type OriginCollection: Into; +} /// Trait implemented for the final collection of a recipe, allowing it to be combined with parts /// @@ -148,6 +151,19 @@ pub trait DbSerializable { fn from_database() -> Self; } +/// Trait implemented by any struct aiming to be a public recipe +pub trait FixedRecipe: DbSerializable { + /// Struct representing the database type, most likely a string + type Database; + /// Struct representing the keylist type, most likely a usize + type KeyList; + + /// Get the list of elements corresponding to the recipe + /// + /// These elements will either be iteratively fetched from the database or scoured through in the data depending on the scenario + fn get_elements() -> Vec<(Self::Database, Self::KeyList)>; +} + // /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection // /// // /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 3c71da0..bdac53f 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -9,31 +9,62 @@ //! of all the fields even when the user will not be interested in them #![allow(dead_code)] -use crate::interfaces::RefinedList; +use core::f64; -use super::equipement_structs::InnerStats; +use crate::interfaces::RefinedList; +use probability::prelude::{Binomial, Discrete}; +use strum::{EnumIter, IntoEnumIterator}; + +use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats}; /// The final representation of the equipement inplementing all the fields needed for processing pub struct RefinedEquipement { /// The original inner stats /// /// This structs takes ownership of the inner data - inner: InnerStats, + inner: InnerEquipementStats, /// Advanced stats advanced: AdvancedStats, } -pub struct RefinedEquipementList(Vec); +impl From for RefinedEquipement { + fn from(value: Equipement) -> Self { + Self { + advanced: AdvancedStats::from(&value.stats), + inner: value.stats, + } + } +} + +/// The complete equipement list, refined with all advanced stats +pub struct RefinedEquipementList { + /// Inner list of Refined Equipements + inner: Vec, +} // Just a checkmark impl RefinedList for RefinedEquipementList {} +impl From for RefinedEquipementList { + fn from(value: InitialEquipementList) -> Self { + Self { + inner: value + .inner + .into_iter() + .map(RefinedEquipement::from) + .collect(), + } + } +} + /// The list of advanced stats infered from an Equipement #[allow(missing_docs, clippy::missing_docs_in_private_items)] pub struct AdvancedStats { + damage_per_attack: f64, damage_per_turn: f64, damage_per_action: f64, + armor_break_per_attack: f64, armor_break_per_turn: f64, armor_break_per_action: f64, damage_matrix: DamageMatrix, @@ -41,6 +72,26 @@ pub struct AdvancedStats { expected_armor_break_per_turn: f64, // All other criterias are already in the inner as raw criterias } +impl From<&InnerEquipementStats> for AdvancedStats { + fn from(value: &InnerEquipementStats) -> Self { + let damage_per_attack = (value.damage + value.p_damage * (value.rmax - 1)) as f64; + let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack); + Self { + damage_per_attack, + damage_per_turn: damage_per_attack * 2., + damage_per_action: damage_per_attack / (value.action_cost as f64), + armor_break_per_attack, + armor_break_per_turn: armor_break_per_attack * 2., + armor_break_per_action: armor_break_per_attack / value.action_cost as f64, + + // Adds the base strength, substracts the expected protection + expected_armor_break_per_turn: (damage_per_attack + 6. - 8.) + .min(armor_break_per_attack), + damage_matrix: value.into(), + // armor_break_matrix: , + } + } +} /// A damage matrix, crossing damage conditions (high dice to low dice) with precision (high precision to low precision) /// @@ -52,48 +103,92 @@ struct DamageMatrix { impl DamageMatrix { /// Get the damage value from given condition pub fn get_damage(&self, precision: Precision, dices: DiceNumber) -> f64 { - self.damage_matrix[precision.index() + 3 * dices.index()] + self.damage_matrix[precision as usize + 3 * dices as usize] } - /// Calculate the damage simulation from a given InnerStats - pub fn calculate_damage(inner: &InnerStats) -> Self { - let _ = inner; - todo!() +} + +impl From<&InnerEquipementStats> for DamageMatrix { + fn from(value: &InnerEquipementStats) -> Self { + // let binomial_distribution = Binomial::new(dices, value.precision); + // binomial_distribution.mass(i) // -> The chance to have this number of success + DamageMatrix { + damage_matrix: (Precision::iter() + .flat_map(|precision| { + DiceNumber::iter() + .map(move |dices| { + binomial_dice_distribution(value, precision.value(), dices.value()) + }) + .collect::>() + }) + .collect::>()), + } } } +/// Calculate the binomial distribution and average the damage from there +fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, dices: usize) -> f64 { + let binomial = Binomial::new(dices, (precision as u8 + value.precision) as f64); + + (0..dices + 1) + .map(|target_dices| { + // TODO: This non rounding can be veird + let number_success = binomial.mass(target_dices); // Let's have weird half dices as usize; + if number_success >= 1. { + (value.damage + value.p_damage) as f64 * (number_success - 1.) + } else { + 0. + } + }) + .fold(0., |a, b| a + b) + / dices as f64 +} + /// The precision infered for a damage calculation event +#[derive(EnumIter, Clone, Copy)] +#[allow(clippy::missing_docs_in_private_items)] pub enum Precision { - High = 9, - Medium = 6, - Low = 3, + High, + Medium, + Low, } /// The number of dices rolled for a damage simulation +#[derive(EnumIter, Clone, Copy)] +#[allow(clippy::missing_docs_in_private_items)] pub enum DiceNumber { - High = 7, - Medium = 5, - Low = 3, + High, + Medium, + Low, } impl Precision { #[inline] - /// Associate an index to the different values - fn index(&self) -> usize { + /// Associate a value to the different values + fn value(&self) -> usize { match self { - Precision::High => 0, - Precision::Medium => 1, - Precision::Low => 2, + Precision::High => 9, + Precision::Medium => 6, + Precision::Low => 3, } } } impl DiceNumber { #[inline] - /// Associate an index to the different values - fn index(&self) -> usize { + /// Associate a value to the different values + fn value(&self) -> usize { match self { - DiceNumber::High => 0, - DiceNumber::Medium => 1, - DiceNumber::Low => 2, + DiceNumber::High => 7, + DiceNumber::Medium => 5, + DiceNumber::Low => 3, } } } + +#[cfg(test)] +mod test { + #[test] + fn test_binomial() {} + + #[test] + fn test_creation() {} +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index bb7bdc6..5e7b020 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -4,10 +4,10 @@ use crate::interfaces::{Combinable, RecipeCollection}; -use super::{Equipement, FinalEquipementList, equipement_structs::InnerStats}; +use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats}; impl Combinable for Equipement { - type Inner = InnerStats; + type Inner = InnerEquipementStats; fn combinable_part(&self) -> &Self::Inner { &self.stats @@ -31,7 +31,7 @@ impl Combinable for Equipement { } } -impl RecipeCollection for FinalEquipementList { +impl RecipeCollection for InitialEquipementList { type Recipes = Equipement; fn from_vectored(list: Vec) -> Self { @@ -52,19 +52,19 @@ mod test { use crate::{ interfaces::RecipeCollection, weaponry_structs::{ - DamageMod, DamageType, Equipement, FinalEquipementList, SpecialCategory, - WeaponCategory, equipement_fields::PhysicalDamageType, equipement_structs::InnerStats, + DamageMod, DamageType, Equipement, InitialEquipementList, SpecialCategory, + WeaponCategory, equipement_fields::PhysicalDamageType, equipement_structs::InnerEquipementStats, }, }; use pretty_assertions::assert_eq; #[test] fn test_blanket_struct_generation() { - let mut f = FinalEquipementList::from_vectored(vec![ + let mut f = InitialEquipementList::from_vectored(vec![ Equipement::newish(&["a"], 1), Equipement::newish(&["b"], 2), ]); - let g = FinalEquipementList::from_vectored(vec![ + let g = InitialEquipementList::from_vectored(vec![ Equipement::newish(&["c"], 4), Equipement::newish(&["d"], 8), ]); @@ -77,7 +77,7 @@ mod test { f.combine_all(&g); assert_eq!( f, - FinalEquipementList::from_vectored(vec![ + InitialEquipementList::from_vectored(vec![ Equipement::newish(&["a", "c"], 5), Equipement::newish(&["a", "d"], 9), Equipement::newish(&["b", "c"], 6), @@ -88,7 +88,7 @@ mod test { #[test] fn test_base_operation() { - let i1 = InnerStats { + let i1 = InnerEquipementStats { rarity: 1, integrity: 2, range: 3, @@ -100,7 +100,7 @@ mod test { )])), ..Default::default() }; - let i2 = InnerStats { + let i2 = InnerEquipementStats { integrity: 3, agility_bonus: 5, damage: 10, @@ -112,7 +112,7 @@ mod test { }; assert_eq!( &i1 + &i2, - InnerStats { + InnerEquipementStats { rarity: 1, integrity: 5, agility_bonus: 9, @@ -128,14 +128,14 @@ mod test { } ); assert_eq!( - &InnerStats { + &InnerEquipementStats { damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), ..Default::default() - } + &InnerStats::default(), - InnerStats { + } + &InnerEquipementStats::default(), + InnerEquipementStats { damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), @@ -144,15 +144,15 @@ mod test { }, ); assert_eq!( - &InnerStats::default() - + &InnerStats { + &InnerEquipementStats::default() + + &InnerEquipementStats { damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), ..Default::default() }, - InnerStats { + InnerEquipementStats { damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), @@ -173,7 +173,7 @@ mod test { impl Equipement { fn newish(name: &[&str], i: u8) -> Self { Equipement { - stats: InnerStats { + stats: InnerEquipementStats { name: name.iter().map(|s| s.to_string()).collect(), rarity: i, ..Default::default() diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 1f7c501..ac6c4a6 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -3,7 +3,7 @@ //! Implements base math for each field //! -use super::equipement_structs::InnerStats; +use super::equipement_structs::InnerEquipementStats; use crate::weaponry_structs::SpecialCategory; /// Add a new vector to a clone of a inner field @@ -30,11 +30,11 @@ macro_rules! add_two_options { }}; } -impl std::ops::Add for &InnerStats { - type Output = InnerStats; +impl std::ops::Add for &InnerEquipementStats { + type Output = InnerEquipementStats; fn add(self, rhs: Self) -> Self::Output { - InnerStats { + InnerEquipementStats { // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless id: add_to_vec!(self.id, rhs.id), name: add_to_vec!(self.name, rhs.name), diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 94900f2..eab2fce 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -15,7 +15,7 @@ use super::{DamageType, SpecialCategory, WeaponCategory}; /// This list is initialized with the base part and updated by succesive combinaisons #[derive(Clone, Debug)] #[cfg_attr(test, derive(PartialEq))] -pub struct FinalEquipementList { +pub struct InitialEquipementList { /// Inner List of final equipements pub(super) inner: Vec, } @@ -25,22 +25,23 @@ pub struct FinalEquipementList { #[cfg_attr(test, derive(PartialEq))] pub struct Equipement { /// The inner stats used by the equipement - pub(super) stats: InnerStats, + pub(super) stats: InnerEquipementStats, /// The filter, used to determine if adding is warranted - pub(super) filter_function: FilterFunction, + pub(super) filter_function: FilterFunction, } impl Default for Equipement { fn default() -> Self { Self { filter_function: FilterFunction::new(default_filter()), - stats: InnerStats::random_new(), + stats: InnerEquipementStats::random_new(), } } } /// The default filter to use, usefull to implement a new filter function that also uses the default filter -pub(crate) fn default_filter() -> &'static impl Fn(&InnerStats, &InnerStats) -> bool { +pub(crate) fn default_filter() +-> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { &|self_, lhs| !self_.id.iter().any(|a| *a == lhs.id[0]) } @@ -56,7 +57,7 @@ impl FilterFunction { #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Default, FieldNamesAsArray, Debug)] #[cfg_attr(test, derive(PartialEq))] -pub struct InnerStats { +pub struct InnerEquipementStats { pub id: Vec, pub name: Vec, pub(super) rarity: u8, @@ -89,7 +90,7 @@ pub struct InnerStats { } // TODO: Make this a test requirement or hide it behind a profile -impl InnerStats { +impl InnerEquipementStats { /// Testing function to fuzz data pub fn random_new() -> Self { Self { @@ -102,13 +103,13 @@ impl InnerStats { /// Shape of the equipement, first mandatory part of an equipement pub struct EqShape { /// The inner stats of the part - pub(super) stats: InnerStats, + pub(super) stats: InnerEquipementStats, } /// Material used for the equipement, all equipements are crafted with 1-2 materials pub struct EqMaterial { /// The inner stats of the part - pub(super) stats: InnerStats, + pub(super) stats: InnerEquipementStats, } /// Nature of the equipement, some natures are reserved and some can be chained @@ -116,13 +117,13 @@ pub struct EqMaterial { /// Deciding on the combinaison can be tricky an will need an extra field pub struct EqNature { /// The inner stats of the part - pub(super) stats: InnerStats, + pub(super) stats: InnerEquipementStats, } /// Finishing touches, since all of them have a cost, they are treated in a special fashion pub struct EqFinishing { /// The inner stats of the part - pub(super) stats: InnerStats, + pub(super) stats: InnerEquipementStats, } #[cfg(test)] @@ -132,7 +133,8 @@ mod test { use crate::interfaces::RecipeCollection; use super::{ - EqFinishing, EqMaterial, EqNature, EqShape, Equipement, FinalEquipementList, InnerStats, + EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, + InnerEquipementStats, }; // use pretty_assertions::assert_eq; @@ -147,7 +149,7 @@ mod test { #[test] fn test_struct_creation() { - let _stats = InnerStats::default(); + let _stats = InnerEquipementStats::default(); let _eq1 = Equipement { ..Default::default() }; @@ -159,33 +161,33 @@ mod test { fn test_creating_all_equipements() { let shape = vec![ EqShape { - stats: InnerStats::default(), + stats: InnerEquipementStats::default(), } .into(), ]; let nature = vec![ EqNature { - stats: InnerStats::default(), + stats: InnerEquipementStats::default(), } .into(), ]; let material = vec![ EqMaterial { - stats: InnerStats::default(), + stats: InnerEquipementStats::default(), } .into(), ]; let finishing = vec![ EqFinishing { - stats: InnerStats::default(), + stats: InnerEquipementStats::default(), } .into(), ]; - let mut leq = FinalEquipementList::from_vectored(shape); - leq.combine_all(&FinalEquipementList::from_vectored(nature)); - leq.combine_all(&FinalEquipementList::from_vectored(material)); - leq.combine_all(&FinalEquipementList::from_vectored(finishing)); + let mut leq = InitialEquipementList::from_vectored(shape); + leq.combine_all(&InitialEquipementList::from_vectored(nature)); + leq.combine_all(&InitialEquipementList::from_vectored(material)); + leq.combine_all(&InitialEquipementList::from_vectored(finishing)); } #[ignore] diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 12fb55a..7040c4f 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -29,7 +29,7 @@ mod equipement_views; // Republishes the most used symbols // All generic structs -pub use equipement_structs::{Equipement, FinalEquipementList}; +pub use equipement_structs::{Equipement, InitialEquipementList}; // All generic fields #[allow(unused_imports)] -- 2.45.1 From a512e0518db5411f203f15e627ae24eb4006064c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 13 Feb 2025 23:44:33 +0100 Subject: [PATCH 20/97] Corrects a flawed implementation of the binomial dist --- .gitignore | 1 + .../equipement_advanced_repr.rs | 43 ++++++++++++++++--- .../weaponry_structs/equipement_structs.rs | 37 +++++----------- 3 files changed, 48 insertions(+), 33 deletions(-) diff --git a/.gitignore b/.gitignore index 7d12725..f690d27 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ Cargo.lock *.json.gz callgrind* cache.out +tarpaulin-report.html diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index bdac53f..cb4ffe1 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -10,6 +10,7 @@ #![allow(dead_code)] use core::f64; +use std::fmt::Display; use crate::interfaces::RefinedList; use probability::prelude::{Binomial, Discrete}; @@ -96,6 +97,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { /// A damage matrix, crossing damage conditions (high dice to low dice) with precision (high precision to low precision) /// /// This simulation does only calculate a very limited preset of damage values +#[cfg_attr(test, derive(Debug))] struct DamageMatrix { /// The inner damage matrix damage_matrix: Vec, @@ -107,6 +109,13 @@ impl DamageMatrix { } } +impl Display for DamageMatrix { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let _ = f; + todo!() + } +} + impl From<&InnerEquipementStats> for DamageMatrix { fn from(value: &InnerEquipementStats) -> Self { // let binomial_distribution = Binomial::new(dices, value.precision); @@ -127,20 +136,25 @@ impl From<&InnerEquipementStats> for DamageMatrix { /// Calculate the binomial distribution and average the damage from there fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, dices: usize) -> f64 { - let binomial = Binomial::new(dices, (precision as u8 + value.precision) as f64); + let p = ((precision as i8 + value.precision) as f64 / 10.).clamp(0., 1. - 1E-10); + // println!("precision: {},{}", p, 9.99999); + let binomial = Binomial::new(dices, p); (0..dices + 1) .map(|target_dices| { // TODO: This non rounding can be veird - let number_success = binomial.mass(target_dices); // Let's have weird half dices as usize; - if number_success >= 1. { - (value.damage + value.p_damage) as f64 * (number_success - 1.) + let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize; + println!("probability : {:?}", probability_success); + if target_dices >= 1 { + (value.damage as f64 + + value.p_damage as f64 + * (target_dices.clamp(0, value.rmax as usize) - 1) as f64) + * probability_success } else { 0. } }) .fold(0., |a, b| a + b) - / dices as f64 } /// The precision infered for a damage calculation event @@ -186,8 +200,25 @@ impl DiceNumber { #[cfg(test)] mod test { + use crate::weaponry_structs::{ + equipement_advanced_repr::DamageMatrix, equipement_structs::InnerEquipementStats, + }; + #[test] - fn test_binomial() {} + fn test_binomial() { + let damage = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 3, + armor_break: 2, + ..Default::default() + }; + let mat: DamageMatrix = DamageMatrix::from(&damage); + println!("{:#?}", damage); + println!("{:#?}", mat); + panic!() + } #[test] fn test_creation() {} diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index eab2fce..d4e6f5e 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -66,7 +66,7 @@ pub struct InnerEquipementStats { pub(super) tier: u8, pub(super) damage: u8, pub(super) p_damage: u8, - pub(super) precision: u8, + pub(super) precision: i8, pub(super) rmax: u8, pub(super) armor_break: u8, pub(super) armor_pierce: u8, @@ -101,12 +101,14 @@ impl InnerEquipementStats { } /// Shape of the equipement, first mandatory part of an equipement +#[derive(Default)] pub struct EqShape { /// The inner stats of the part pub(super) stats: InnerEquipementStats, } /// Material used for the equipement, all equipements are crafted with 1-2 materials +#[derive(Default)] pub struct EqMaterial { /// The inner stats of the part pub(super) stats: InnerEquipementStats, @@ -115,12 +117,14 @@ pub struct EqMaterial { /// Nature of the equipement, some natures are reserved and some can be chained /// /// Deciding on the combinaison can be tricky an will need an extra field +#[derive(Default)] pub struct EqNature { /// The inner stats of the part pub(super) stats: InnerEquipementStats, } /// Finishing touches, since all of them have a cost, they are treated in a special fashion +#[derive(Default)] pub struct EqFinishing { /// The inner stats of the part pub(super) stats: InnerEquipementStats, @@ -133,8 +137,7 @@ mod test { use crate::interfaces::RecipeCollection; use super::{ - EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, - InnerEquipementStats, + EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, }; // use pretty_assertions::assert_eq; @@ -159,30 +162,10 @@ mod test { #[test] fn test_creating_all_equipements() { - let shape = vec![ - EqShape { - stats: InnerEquipementStats::default(), - } - .into(), - ]; - let nature = vec![ - EqNature { - stats: InnerEquipementStats::default(), - } - .into(), - ]; - let material = vec![ - EqMaterial { - stats: InnerEquipementStats::default(), - } - .into(), - ]; - let finishing = vec![ - EqFinishing { - stats: InnerEquipementStats::default(), - } - .into(), - ]; + let shape = vec![EqShape::default().into(), EqShape::default().into()]; + let nature = vec![EqNature::default().into(), EqNature::default().into()]; + let material = vec![EqMaterial::default().into(), EqMaterial::default().into()]; + let finishing = vec![EqMaterial::default().into(), EqMaterial::default().into()]; let mut leq = InitialEquipementList::from_vectored(shape); leq.combine_all(&InitialEquipementList::from_vectored(nature)); -- 2.45.1 From 6cc0f27d3d100a9d591decaf13fdfcf8209df657 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 14 Feb 2025 03:54:18 +0100 Subject: [PATCH 21/97] Adds badges and finalises binomial distribution --- Cargo.toml | 3 + README.md | 4 +- badges/coverage.svg | 1 + badges/test.svg | 1 + badges/version.svg | 1 + .../equipement_advanced_repr.rs | 57 ++++++++++++------- 6 files changed, 45 insertions(+), 22 deletions(-) create mode 100644 badges/coverage.svg create mode 100644 badges/test.svg create mode 100644 badges/version.svg diff --git a/Cargo.toml b/Cargo.toml index f6e0776..e71620f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,9 @@ members = [ "cli_parser", "config", "graphs", "make", ] resolver = "3" +[workspace.package] +version = "0.2.0" + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [profile.dev] diff --git a/README.md b/README.md index 0229a44..64c2c63 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,10 @@ +![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) + # ravenous-tools Set of tools to handle ravenous rulebook creation # Installation Now depends on libsqlite3-dev and sqlite3 -A bundled implementation should be added +A bundled implementation should be added on all releases diff --git a/badges/coverage.svg b/badges/coverage.svg new file mode 100644 index 0000000..d621d76 --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: N/Atest-coverageN/A diff --git a/badges/test.svg b/badges/test.svg new file mode 100644 index 0000000..3a9c483 --- /dev/null +++ b/badges/test.svg @@ -0,0 +1 @@ +test: failingtestfailing diff --git a/badges/version.svg b/badges/version.svg new file mode 100644 index 0000000..a22915f --- /dev/null +++ b/badges/version.svg @@ -0,0 +1 @@ +version: 0.2.0version0.2.0 diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index cb4ffe1..3213d7e 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -14,7 +14,7 @@ use std::fmt::Display; use crate::interfaces::RefinedList; use probability::prelude::{Binomial, Discrete}; -use strum::{EnumIter, IntoEnumIterator}; +use strum::{Display, EnumIter, IntoEnumIterator}; use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats}; @@ -111,8 +111,26 @@ impl DamageMatrix { impl Display for DamageMatrix { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let _ = f; - todo!() + // "[{:.3}:{:.3}] {:5.2}", dices, precision, + write!( + f, + "{}", + DiceNumber::iter() + .map(|dices| { + Precision::iter() + .map(move |precision| format!("{:5.2}", self.get_damage(precision, dices))) + .fold(format!("[{:.3}]", dices.to_string()), |res, new| { + res + " " + &new + }) + }) + .fold( + Precision::iter().fold(String::from(" D\\P "), |res, new| format!( + "{} [{:.3}]", + res, new + )), + |res, new| res + "\n" + &new + ) + ) } } @@ -121,11 +139,11 @@ impl From<&InnerEquipementStats> for DamageMatrix { // let binomial_distribution = Binomial::new(dices, value.precision); // binomial_distribution.mass(i) // -> The chance to have this number of success DamageMatrix { - damage_matrix: (Precision::iter() - .flat_map(|precision| { - DiceNumber::iter() - .map(move |dices| { - binomial_dice_distribution(value, precision.value(), dices.value()) + damage_matrix: (DiceNumber::iter() + .flat_map(|dices| { + Precision::iter() + .map(move |prec| { + binomial_dice_distribution(value, prec.value(), dices.value()) }) .collect::>() }) @@ -136,15 +154,12 @@ impl From<&InnerEquipementStats> for DamageMatrix { /// Calculate the binomial distribution and average the damage from there fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, dices: usize) -> f64 { - let p = ((precision as i8 + value.precision) as f64 / 10.).clamp(0., 1. - 1E-10); - // println!("precision: {},{}", p, 9.99999); + let p = ((precision as i8 + value.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); let binomial = Binomial::new(dices, p); (0..dices + 1) .map(|target_dices| { - // TODO: This non rounding can be veird let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize; - println!("probability : {:?}", probability_success); if target_dices >= 1 { (value.damage as f64 + value.p_damage as f64 @@ -158,7 +173,7 @@ fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, di } /// The precision infered for a damage calculation event -#[derive(EnumIter, Clone, Copy)] +#[derive(EnumIter, Clone, Copy, Display)] #[allow(clippy::missing_docs_in_private_items)] pub enum Precision { High, @@ -167,12 +182,12 @@ pub enum Precision { } /// The number of dices rolled for a damage simulation -#[derive(EnumIter, Clone, Copy)] +#[derive(EnumIter, Clone, Copy, Display)] #[allow(clippy::missing_docs_in_private_items)] pub enum DiceNumber { - High, - Medium, - Low, + Many, + Average, + Few, } impl Precision { @@ -191,9 +206,9 @@ impl DiceNumber { /// Associate a value to the different values fn value(&self) -> usize { match self { - DiceNumber::High => 7, - DiceNumber::Medium => 5, - DiceNumber::Low => 3, + DiceNumber::Many => 7, + DiceNumber::Average => 5, + DiceNumber::Few => 3, } } } @@ -217,7 +232,7 @@ mod test { let mat: DamageMatrix = DamageMatrix::from(&damage); println!("{:#?}", damage); println!("{:#?}", mat); - panic!() + println!("{}", mat); } #[test] -- 2.45.1 From a5f796d2dd882bf5b5f73c255c138c02c0b61311 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 14 Feb 2025 20:07:48 +0100 Subject: [PATCH 22/97] Adds more test coverage and impls some displays --- weaponry/Cargo.toml | 1 + weaponry/src/interfaces.rs | 30 +--- weaponry/src/lib.rs | 1 + .../equipement_advanced_repr.rs | 74 +++++----- .../src/weaponry_structs/equipement_fields.rs | 20 ++- .../equipement_impl_basics.rs | 139 +++++++++++++++++- .../weaponry_structs/equipement_structs.rs | 12 +- 7 files changed, 215 insertions(+), 62 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index c15964e..9889c9a 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] +comfy-table = "7.1.4" fastrand = "2.3.0" iter-enum = "1.2.0" pretty_assertions = "1.4.1" diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index ee0b004..301f250 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -164,26 +164,10 @@ pub trait FixedRecipe: DbSerializable { fn get_elements() -> Vec<(Self::Database, Self::KeyList)>; } -// /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection -// /// -// /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch -// fn combine_all_par(&mut self, other: &G) -// where -// G: RecipeCollection + std::marker::Sync, -// { -// self.assign_inner( -// self.owned_inner() -// .par_iter() -// .flat_map(|inner_recipes| { -// other -// .ref_inner() -// .iter() -// .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes)) -// .map(|external_recipes: &Self::Recipes| { -// inner_recipes.add_ref_to_self(external_recipes) -// }) -// .collect::>() -// }) -// .collect::>(), -// ); -// } +/// Trait ensuring a status report can be inferred from the structure +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; +} diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index bf88e5e..7e4c707 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -3,6 +3,7 @@ //! Weaponry module, handling all weaponry creation and analysis #![warn(missing_docs, clippy::missing_docs_in_private_items)] +#![feature(iter_intersperse)] mod database; mod export; diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 3213d7e..21e5727 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -13,6 +13,7 @@ use core::f64; use std::fmt::Display; use crate::interfaces::RefinedList; +use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; use probability::prelude::{Binomial, Discrete}; use strum::{Display, EnumIter, IntoEnumIterator}; @@ -41,7 +42,7 @@ impl From for RefinedEquipement { /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements - inner: Vec, + pub(super) inner: Vec, } // Just a checkmark @@ -75,7 +76,8 @@ pub struct AdvancedStats { } impl From<&InnerEquipementStats> for AdvancedStats { fn from(value: &InnerEquipementStats) -> Self { - let damage_per_attack = (value.damage + value.p_damage * (value.rmax - 1)) as f64; + let damage_per_attack = + (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack); Self { damage_per_attack, @@ -111,33 +113,27 @@ impl DamageMatrix { impl Display for DamageMatrix { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - // "[{:.3}:{:.3}] {:5.2}", dices, precision, - write!( - f, - "{}", - DiceNumber::iter() - .map(|dices| { - Precision::iter() - .map(move |precision| format!("{:5.2}", self.get_damage(precision, dices))) - .fold(format!("[{:.3}]", dices.to_string()), |res, new| { - res + " " + &new - }) - }) - .fold( - Precision::iter().fold(String::from(" D\\P "), |res, new| format!( - "{} [{:.3}]", - res, new - )), - |res, new| res + "\n" + &new - ) - ) + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + let mut headers = vec![String::from("D\\P")]; + headers.append( + &mut Precision::iter() + .map(|e| format!("{:.3}", e)) + .collect::>(), + ); + table.set_header(headers); + table.add_rows(DiceNumber::iter().map(|dices| { + vec![format!("{:.3}", dices)].into_iter().chain( + Precision::iter() + .map(move |precision| format!("{:5.2}", self.get_damage(precision, dices))), + ) + })); + write!(f, "{}", table) } } impl From<&InnerEquipementStats> for DamageMatrix { fn from(value: &InnerEquipementStats) -> Self { - // let binomial_distribution = Binomial::new(dices, value.precision); - // binomial_distribution.mass(i) // -> The chance to have this number of success DamageMatrix { damage_matrix: (DiceNumber::iter() .flat_map(|dices| { @@ -163,7 +159,7 @@ fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, di if target_dices >= 1 { (value.damage as f64 + value.p_damage as f64 - * (target_dices.clamp(0, value.rmax as usize) - 1) as f64) + * (target_dices.clamp(0, value.rmax as usize).saturating_sub(1)) as f64) * probability_success } else { 0. @@ -216,25 +212,37 @@ impl DiceNumber { #[cfg(test)] mod test { use crate::weaponry_structs::{ - equipement_advanced_repr::DamageMatrix, equipement_structs::InnerEquipementStats, + equipement_advanced_repr::{DamageMatrix, DiceNumber, Precision}, + equipement_structs::InnerEquipementStats, }; #[test] fn test_binomial() { - let damage = InnerEquipementStats { + let damage = new_inner_eq(); + let mat: DamageMatrix = DamageMatrix::from(&damage); + println!("{:#?}", damage); + println!("{:#?}", mat); + } + + fn new_inner_eq() -> InnerEquipementStats { + InnerEquipementStats { damage: 10, p_damage: 2, precision: 0, rmax: 3, armor_break: 2, ..Default::default() - }; - let mat: DamageMatrix = DamageMatrix::from(&damage); - println!("{:#?}", damage); - println!("{:#?}", mat); - println!("{}", mat); + } } #[test] - fn test_creation() {} + fn test_creation() { + let mat = DamageMatrix::from(&new_inner_eq()); + println!("{}", mat); + println!( + "(High,Many): {}, (Low,Few): {}", + mat.get_damage(Precision::High, DiceNumber::Many), + mat.get_damage(Precision::Low, DiceNumber::Few) + ); + } } diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 0940494..a352e7e 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -2,6 +2,10 @@ // File: weaponry/src/weaponry_structs/equipement_fields.rs //! The inner fields used by the super structs +use std::fmt::Display; + +use strum::Display; + #[derive(Clone, Default, Debug)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only @@ -39,7 +43,7 @@ impl From<&str> for PhysicalDamageType { /// /// Signifying wether the damage is pure or [secondary] or [[tertiary]] #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Display)] #[cfg_attr(test, derive(PartialEq))] pub enum DamageMod { Primary(PhysicalDamageType), @@ -70,9 +74,21 @@ impl From<&str> for DamageType { } } +impl Display for DamageType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + self.0 + .iter() + .fold(String::new(), |res, new| format!("{res}, {new}")) + ) + } +} + /// List all weapon categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Display)] // #[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 252833a..9b7cb66 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -8,11 +8,15 @@ //! Implementations to transform all Specialized equipement into a generic Equipement //! A specific implementation could be preferable, but this simplicity might allow for easier developpement -use crate::interfaces::FilterFunction; +use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; +use std::fmt::Display; + +use crate::interfaces::{FilterFunction, Reportable}; use super::{ - Equipement, - equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}, + Equipement, InitialEquipementList, + equipement_advanced_repr::RefinedEquipementList, + equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, }; impl From for Equipement { @@ -55,3 +59,132 @@ impl From for Equipement { } } } + +impl Display for Equipement { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.stats) + } +} + +impl Display for InnerEquipementStats { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + table.add_row(vec![format!( + "Ids: {}, Names:{}", + self.id + .iter() + .fold(String::new(), |res, new| format!("{res} {new}")), + self.name.join(" & ") + )]); + table.add_row(vec![format!( + "Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}]", + self.rarity, + self.cost, + self.difficulty, + self.tier, + self.category + .clone() + .map_or_else(|| "ø".to_string(), |v| v.to_string()) + )]); + table.add_row_if( + |_, _| self.damage > 0, + vec![format!( + "Damage: {}/+{} P:{}, AB:{} AM:{} A:{} [{}]", + self.damage, + self.p_damage, + self.precision, + self.armor_break, + self.antimaterial, + self.action_cost, + self.clone() + .damage_type + .map_or_else(|| "ø".to_string(), |damage| damage.to_string()) + )], + ); + table.add_row_if( + |_, _| self.protection > 0, + vec![format!("Prot:{} Int:{}", self.protection, self.integrity)], + ); + table.add_row(vec![format!( + "T1/T2 {}/{} Dodge:{} Parry:{} Speed:{} Stealth:{} Agility: {}", + self.torque_one_handed, + self.torque_two_handed, + self.dodge, + self.parry, + self.speed, + self.stealth, + self.agility_bonus, + )]); + table.add_row_if( + |_, _| (self.range > 0) | (self.armor_pierce > 0), + vec![format!( + "Rg:{}, AP:{}, Rel:{}", + self.range, + self.armor_pierce, + self.reload_cost + .map_or_else(|| "ø".to_string(), |v| format!("{v}")) + )], + ); + table.add_row_if( + |_, _| !self.special.0.is_empty(), + vec![ + self.special + .0 + .iter() + .intersperse(&",".to_string()) + .fold(String::new(), |res, new| format!("{}; {}", res, new)), + ], + ); + write!(f, "{table}") + } +} + +impl Reportable for InitialEquipementList { + fn get_report(&self) -> String { + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + table.add_row(vec![format!("Refined Equipement List")]); + table.add_row(vec![format!("Rows: {}", self.inner.len())]); + table.to_string() + } +} + +impl Reportable for RefinedEquipementList { + fn get_report(&self) -> String { + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + table.add_row(vec![format!("Refined Equipement List")]); + table.add_row(vec![format!("Rows: {}", self.inner.len())]); + table.to_string() + } +} + +#[cfg(test)] +mod test { + use crate::{ + interfaces::{RecipeCollection, Reportable}, + weaponry_structs::{ + Equipement, InitialEquipementList, equipement_advanced_repr::RefinedEquipementList, + equipement_structs::InnerEquipementStats, + }, + }; + + #[test] + fn test_format() { + let equi = Equipement { + stats: InnerEquipementStats::random_new(), + ..Default::default() + }; + print!("{}", equi); + } + + #[test] + fn test_report() { + let eqlist = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); + let feqlist: RefinedEquipementList = eqlist.clone().into(); + + println!("{}", feqlist.get_report()); + println!("{}", eqlist.get_report()); + } +} diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index d4e6f5e..1a6b4de 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -89,12 +89,22 @@ pub struct InnerEquipementStats { pub(super) agility_bonus: u8, } +#[doc(hidden)] +macro_rules! r { + () => { + fastrand::u8(1..10) + }; +} // TODO: Make this a test requirement or hide it behind a profile impl InnerEquipementStats { /// Testing function to fuzz data pub fn random_new() -> Self { Self { - id: vec![fastrand::u8(..10)], + id: vec![r!()], + range: r!(), + damage: r!(), + p_damage: r!(), + protection: r!(), ..Default::default() } } -- 2.45.1 From 26d22037ae7804e2bc7ea8ea9d6303de77f951d4 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 14 Feb 2025 22:37:17 +0100 Subject: [PATCH 23/97] Implements Deserialize --- weaponry/Cargo.toml | 3 ++- weaponry/src/interfaces.rs | 2 +- weaponry/src/weaponry_structs/equipement_fields.rs | 11 ++++++----- weaponry/src/weaponry_structs/equipement_impl_io.rs | 12 ++++++++++++ weaponry/src/weaponry_structs/equipement_structs.rs | 3 ++- 5 files changed, 23 insertions(+), 8 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 9889c9a..6f59e85 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -6,11 +6,12 @@ edition = "2024" [dependencies] comfy-table = "7.1.4" fastrand = "2.3.0" -iter-enum = "1.2.0" +# iter-enum = "1.2.0" pretty_assertions = "1.4.1" probability = "0.20.3" rayon = "1.10.0" rusqlite = { version = "0.33.0", features = ["bundled"] } +serde = { version = "1.0.217", features = ["derive"] } struct-field-names-as-array = "0.3.0" strum = { version = "0.27.0", features = ["derive"] } diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 301f250..dd119b9 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -142,7 +142,7 @@ pub trait ToTex { /// This element can be converted to a csv for further analysis pub trait ToAnalysis { /// Convert this object into a csv - fn to_csv(&self) -> String; + fn write_csv(&self) -> String; } /// Garanties that a struct can be generated from a database diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index a352e7e..458b717 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -4,9 +4,10 @@ use std::fmt::Display; +use serde::Deserialize; use strum::Display; -#[derive(Clone, Default, Debug)] +#[derive(Clone, Default, Debug, Deserialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only pub struct SpecialCategory(pub(super) Vec); @@ -24,7 +25,7 @@ pub enum NatureTarget { /// Enum of all different physical weapon damage types #[allow(clippy::missing_docs_in_private_items)] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Deserialize)] #[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { Blunt, @@ -43,7 +44,7 @@ impl From<&str> for PhysicalDamageType { /// /// Signifying wether the damage is pure or [secondary] or [[tertiary]] #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Display)] +#[derive(Clone, Debug, Display, Deserialize)] #[cfg_attr(test, derive(PartialEq))] pub enum DamageMod { Primary(PhysicalDamageType), @@ -62,7 +63,7 @@ impl From<&str> for DamageMod { /// Combined damage type, as a vector of all damage types /// /// Meant to be serialised to tex and deserialized directly from the table -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Deserialize)] #[cfg_attr(test, derive(PartialEq))] pub struct DamageType(pub(super) Vec); @@ -88,7 +89,7 @@ impl Display for DamageType { /// List all weapon categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, PartialEq, Display)] +#[derive(Clone, Debug, PartialEq, Display, Deserialize)] // #[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs index 14c7ccd..c4f84eb 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -2,6 +2,18 @@ // File: weaponry/src/weaponry_structs/equipement_impl_io.rs //! All implementation IO specific (mainly export and serde) +// impl ToAnalysis for RefinedEquipementList{ +// fn write_csv(&self) -> String { +// let mut wtr = csv::Writer::from_writer(); +// } +// } + +// impl ToAnalysis for RefinedEquipement { +// fn write_csv(&self) -> String { + +// } +// } + #[cfg(test)] mod test { // use super::*; diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 1a6b4de..480caab 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -4,6 +4,7 @@ use std::rc::Rc; +use serde::Deserialize; use struct_field_names_as_array::FieldNamesAsArray; use crate::interfaces::{FilterFunction, FilterFunctionType}; @@ -55,7 +56,7 @@ impl FilterFunction { /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldNamesAsArray, Debug)] +#[derive(Clone, Default, FieldNamesAsArray, Debug, Deserialize)] #[cfg_attr(test, derive(PartialEq))] pub struct InnerEquipementStats { pub id: Vec, -- 2.45.1 From 1505a6c6f7be6b51cb3972d64a17da2a3819e965 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Sat, 15 Feb 2025 01:34:24 +0100 Subject: [PATCH 24/97] Rewrite of get data, creation of set_up func for testing --- weaponry/Cargo.toml | 1 + weaponry/src/database.rs | 47 +++++++++++++++++++++++++++++----------- weaponry/src/lib.rs | 2 +- 3 files changed, 36 insertions(+), 14 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 6f59e85..6ceef46 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -12,6 +12,7 @@ probability = "0.20.3" rayon = "1.10.0" rusqlite = { version = "0.33.0", features = ["bundled"] } serde = { version = "1.0.217", features = ["derive"] } +serde_rusqlite = "0.37.0" struct-field-names-as-array = "0.3.0" strum = { version = "0.27.0", features = ["derive"] } diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index ad2b81c..e29fded 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -5,8 +5,11 @@ //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] -use crate::weaponry_structs::equipement_structs::InnerEquipementStats; +//use crate::weaponry_structs::equipement_structs::InnerEquipementStats; use rusqlite::{self, Connection, Result}; +use serde::de::DeserializeOwned; +use serde_rusqlite::*; +use struct_field_names_as_array::FieldNamesAsArray; /// Generate a SELECT query with fields generated from a struct. Returns a String fn generate_query(fields: &[&str], table_name: &str) -> String { @@ -22,38 +25,54 @@ fn generate_query(fields: &[&str], table_name: &str) -> String { query } -/// Checks if database exists, and returns a rusqlite::Connection. If not, panics while insulting you. You deserved it. +/// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. fn initialize_database_conn(filename: Option) -> Result { if let Some(text) = filename { let conn = Connection::open(text)?; Ok(conn) } else { - panic!("No filename, you big oaf."); - //let conn = Connection::open_in_memory()?; - //Ok(conn) + let conn = Connection::open_in_memory()?; + Ok(conn) } } /// Public function to get data from db -pub fn get_data() -> Vec { - /* let gen_query = generate_query(&InnerStats::FIELD_NAMES_AS_ARRAY, "InnerStats"); - let db_conn = initialize_database_conn(Some("/tmp/data.sqlite3".to_owned())).unwrap(); - let mut query_result = db_conn.prepare(&gen_query);*/ - todo!() +pub fn get_data() -> Result> +where + T: FieldNamesAsArray<2> + DeserializeOwned, +{ + let gen_query = generate_query(&(T::FIELD_NAMES_AS_ARRAY), "InnerEquipementStats"); + let db_conn = initialize_database_conn(None)?; + let mut query_result = db_conn.prepare(&gen_query)?; + let res = from_rows::(query_result.query([])?) + .filter_map(|s| s.ok()) + .collect(); + Ok(res) } #[cfg(test)] mod test { use pretty_assertions::assert_eq; + use serde::Deserialize; use struct_field_names_as_array::FieldNamesAsArray; use super::*; - #[derive(FieldNamesAsArray)] + #[derive(FieldNamesAsArray, Deserialize)] struct TestStruct { id: usize, name: String, } + fn set_up() -> Result { + let conn = initialize_database_conn(None)?; + conn.execute("CREATE TABLE IF NOT EXISTS InnerEquipementStats (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",())?; + conn.execute( + "INSERT INTO TestStuct (id, name) VALUES (1, 'dupont'), (2, 'durand');", + (), + )?; + Ok(conn) + } + #[test] fn test_generate_query() { assert_eq!( @@ -74,9 +93,11 @@ mod test { todo!() } - #[ignore] + //#[ignore] #[test] fn test_get_data() { - todo!() + let _conn = set_up(); + let result = get_data::(); + assert!(result.unwrap().is_empty()) } } diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index 7e4c707..b3c7dfd 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -3,7 +3,7 @@ //! Weaponry module, handling all weaponry creation and analysis #![warn(missing_docs, clippy::missing_docs_in_private_items)] -#![feature(iter_intersperse)] +#![feature(iter_intersperse, generic_arg_infer)] mod database; mod export; -- 2.45.1 From 9d8beaf9b3f80c396f9cb3e0f1ff46a5717ed274 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 15 Feb 2025 02:26:02 +0100 Subject: [PATCH 25/97] Adds a little more serialization and coverage Provides examples for database shortening --- badges/coverage.svg | 2 +- badges/test.svg | 2 +- weaponry/Cargo.toml | 5 +- weaponry/src/database.rs | 51 ++++++++++--------- weaponry/src/interfaces.rs | 6 +-- .../equipement_advanced_repr.rs | 32 ++++++++++++ .../src/weaponry_structs/equipement_fields.rs | 12 ++--- .../equipement_impl_advanced.rs | 12 +++++ .../weaponry_structs/equipement_impl_io.rs | 43 ++++++++++++---- .../weaponry_structs/equipement_structs.rs | 16 +++--- 10 files changed, 123 insertions(+), 58 deletions(-) diff --git a/badges/coverage.svg b/badges/coverage.svg index d621d76..6fdcf57 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: N/Atest-coverageN/A +test-coverage: 16%test-coverage16% diff --git a/badges/test.svg b/badges/test.svg index 3a9c483..a7859aa 100644 --- a/badges/test.svg +++ b/badges/test.svg @@ -1 +1 @@ -test: failingtestfailing +test: passingtestpassing diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 6ceef46..9fe62d2 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -5,14 +5,15 @@ edition = "2024" [dependencies] comfy-table = "7.1.4" +csv = "1.3.1" fastrand = "2.3.0" -# iter-enum = "1.2.0" pretty_assertions = "1.4.1" probability = "0.20.3" -rayon = "1.10.0" +# rayon = "1.10.0" rusqlite = { version = "0.33.0", features = ["bundled"] } serde = { version = "1.0.217", features = ["derive"] } serde_rusqlite = "0.37.0" +serde_json = { version = "1.0.138", features = ["alloc"] } struct-field-names-as-array = "0.3.0" strum = { version = "0.27.0", features = ["derive"] } diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index e29fded..59cf8ee 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -9,40 +9,42 @@ use rusqlite::{self, Connection, Result}; use serde::de::DeserializeOwned; use serde_rusqlite::*; -use struct_field_names_as_array::FieldNamesAsArray; /// Generate a SELECT query with fields generated from a struct. Returns a String fn generate_query(fields: &[&str], table_name: &str) -> String { - let mut query = String::new(); - query.push_str("SELECT"); - for item in fields.iter() { - query.push(' '); - query.push_str(item); - query.push(','); - } - query.pop(); - query.push_str(format!(" FROM {};", table_name).as_str()); - query + // let mut query = String::new(); + // query.push_str("SELECT"); + // for item in fields.iter() { + // query.push(' '); + // query.push_str(item); + // query.push(','); + // } + // query.pop(); + // query.push_str(format!(" FROM {};", table_name).as_str()); + // query + format!("SELECT {} FROM {};", fields.join(", "), table_name) } /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. +// TODO: Remove this cursed dual purpose function fn initialize_database_conn(filename: Option) -> Result { - if let Some(text) = filename { - let conn = Connection::open(text)?; - Ok(conn) - } else { - let conn = Connection::open_in_memory()?; - Ok(conn) - } + // if let Some(text) = filename { + // let conn = Connection::open(text)?; + // Ok(conn) + // } else { + // let conn = Connection::open_in_memory()?; + // Ok(conn) + // } + filename.map_or_else(Connection::open_in_memory, Connection::open) } /// Public function to get data from db -pub fn get_data() -> Result> +pub fn get_data_from_fields(fields: &[&str], table_name: &str) -> Result> where - T: FieldNamesAsArray<2> + DeserializeOwned, + T: DeserializeOwned, { - let gen_query = generate_query(&(T::FIELD_NAMES_AS_ARRAY), "InnerEquipementStats"); - let db_conn = initialize_database_conn(None)?; + let gen_query = generate_query(fields, table_name); + let db_conn = initialize_database_conn(None)?; // TODO: Add an actual connection let mut query_result = db_conn.prepare(&gen_query)?; let res = from_rows::(query_result.query([])?) .filter_map(|s| s.ok()) @@ -93,11 +95,12 @@ mod test { todo!() } - //#[ignore] + #[ignore] #[test] fn test_get_data() { let _conn = set_up(); - let result = get_data::(); + let result = + get_data_from_fields::(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct"); assert!(result.unwrap().is_empty()) } } diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index dd119b9..27b7b65 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -5,7 +5,7 @@ //! handling of the whole crafting process when the times comes #![allow(dead_code)] -use std::rc::Rc; +use std::{path::Path, rc::Rc}; /// Trait representing a view table /// @@ -140,9 +140,9 @@ pub trait ToTex { } /// This element can be converted to a csv for further analysis -pub trait ToAnalysis { +pub trait ToCSV { /// Convert this object into a csv - fn write_csv(&self) -> String; + fn write_csv(&self, path: &Path) -> csv::Result<()>; } /// Garanties that a struct can be generated from a database diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 21e5727..c9efb83 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -15,6 +15,7 @@ use std::fmt::Display; use crate::interfaces::RefinedList; use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; use probability::prelude::{Binomial, Discrete}; +use serde::Serialize; use strum::{Display, EnumIter, IntoEnumIterator}; use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats}; @@ -24,12 +25,23 @@ pub struct RefinedEquipement { /// The original inner stats /// /// This structs takes ownership of the inner data + // #[serde(skip_deserializing)] inner: InnerEquipementStats, /// Advanced stats + // #[serde(flatten)] advanced: AdvancedStats, } +impl Serialize for RefinedEquipement { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + self.advanced.serialize(serializer) + } +} + impl From for RefinedEquipement { fn from(value: Equipement) -> Self { Self { @@ -60,8 +72,20 @@ impl From for RefinedEquipementList { } } +#[cfg(test)] +use crate::interfaces::RecipeCollection; + +#[cfg(test)] +impl Default for RefinedEquipementList { + fn default() -> Self { + let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); + RefinedEquipementList::from(eq) + } +} + /// The list of advanced stats infered from an Equipement #[allow(missing_docs, clippy::missing_docs_in_private_items)] +#[derive(Serialize)] pub struct AdvancedStats { damage_per_attack: f64, damage_per_turn: f64, @@ -110,6 +134,14 @@ impl DamageMatrix { self.damage_matrix[precision as usize + 3 * dices as usize] } } +impl Serialize for DamageMatrix { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_str(&format!("[{:?}]", self.damage_matrix)) + } +} impl Display for DamageMatrix { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 458b717..b8a9904 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -4,10 +4,10 @@ use std::fmt::Display; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use strum::Display; -#[derive(Clone, Default, Debug, Deserialize)] +#[derive(Clone, Default, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only pub struct SpecialCategory(pub(super) Vec); @@ -25,7 +25,7 @@ pub enum NatureTarget { /// Enum of all different physical weapon damage types #[allow(clippy::missing_docs_in_private_items)] -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { Blunt, @@ -44,7 +44,7 @@ impl From<&str> for PhysicalDamageType { /// /// Signifying wether the damage is pure or [secondary] or [[tertiary]] #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Display, Deserialize)] +#[derive(Clone, Debug, Display, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub enum DamageMod { Primary(PhysicalDamageType), @@ -63,7 +63,7 @@ impl From<&str> for DamageMod { /// Combined damage type, as a vector of all damage types /// /// Meant to be serialised to tex and deserialized directly from the table -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub struct DamageType(pub(super) Vec); @@ -89,7 +89,7 @@ impl Display for DamageType { /// List all weapon categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, PartialEq, Display, Deserialize)] +#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize)] // #[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, diff --git a/weaponry/src/weaponry_structs/equipement_impl_advanced.rs b/weaponry/src/weaponry_structs/equipement_impl_advanced.rs index c97cf7f..cf2e3a5 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_advanced.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_advanced.rs @@ -22,3 +22,15 @@ impl PartialEq for FilterFunction { true } } + +#[cfg(test)] +mod test { + use crate::{interfaces::FilterFunction, weaponry_structs::Equipement}; + + #[test] + fn test_filter_weapons() { + let _ = format!("{:?}", FilterFunction::::default()); + let r = FilterFunction::::new(&|_, _| false) == FilterFunction::default(); + assert!(r); + } +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs index c4f84eb..ee62cf8 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -2,26 +2,47 @@ // File: weaponry/src/weaponry_structs/equipement_impl_io.rs //! All implementation IO specific (mainly export and serde) -// impl ToAnalysis for RefinedEquipementList{ -// fn write_csv(&self) -> String { -// let mut wtr = csv::Writer::from_writer(); -// } -// } +use std::path::Path; -// impl ToAnalysis for RefinedEquipement { -// fn write_csv(&self) -> String { +use crate::interfaces::ToCSV; -// } -// } +use super::equipement_advanced_repr::RefinedEquipementList; + +impl ToCSV for RefinedEquipementList { + fn write_csv(&self, path: &Path) -> csv::Result<()> { + let mut wtr = csv::Writer::from_path(path)?; // wtr.serialize + for record in self.inner.iter() { + wtr.serialize(record)?; + } + Ok(()) + } +} #[cfg(test)] mod test { // use super::*; - #[ignore] + use std::path::Path; + + use crate::{ + interfaces::ToCSV, + weaponry_structs::{ + equipement_advanced_repr::{AdvancedStats, RefinedEquipementList}, + equipement_structs::InnerEquipementStats, + }, + }; + #[test] fn test_structs_serialisation() { - unimplemented!() + let adv = AdvancedStats::from(&InnerEquipementStats::default()); + // let mut wtr = csv::Writer::from_path("bob.csv").unwrap(); // wtr.serialize + let mut wtr = csv::Writer::from_writer(Vec::new()); + wtr.serialize(adv).unwrap(); + wtr.flush().unwrap(); + + RefinedEquipementList::default() + .write_csv(Path::new("/dev/null")) + .unwrap(); } #[ignore] diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 480caab..b97835c 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -4,7 +4,7 @@ use std::rc::Rc; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use struct_field_names_as_array::FieldNamesAsArray; use crate::interfaces::{FilterFunction, FilterFunctionType}; @@ -56,7 +56,7 @@ impl FilterFunction { /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldNamesAsArray, Debug, Deserialize)] +#[derive(Clone, Default, FieldNamesAsArray, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub struct InnerEquipementStats { pub id: Vec, @@ -143,15 +143,11 @@ pub struct EqFinishing { #[cfg(test)] mod test { - // use super::*; - - use crate::interfaces::RecipeCollection; - use super::{ - EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, + EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, + InnerEquipementStats, }; - - // use pretty_assertions::assert_eq; + use crate::interfaces::RecipeCollection; fn list_equip() -> Vec { (0..10) @@ -176,7 +172,7 @@ mod test { let shape = vec![EqShape::default().into(), EqShape::default().into()]; let nature = vec![EqNature::default().into(), EqNature::default().into()]; let material = vec![EqMaterial::default().into(), EqMaterial::default().into()]; - let finishing = vec![EqMaterial::default().into(), EqMaterial::default().into()]; + let finishing = vec![EqFinishing::default().into(), EqMaterial::default().into()]; let mut leq = InitialEquipementList::from_vectored(shape); leq.combine_all(&InitialEquipementList::from_vectored(nature)); -- 2.45.1 From f5534a77a27195572dff39eac2f13447f5fdbb71 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 17 Feb 2025 07:15:07 +0100 Subject: [PATCH 26/97] Adds more help on the workflow --- .gitignore | 1 + weaponry/Cargo.toml | 1 + weaponry/helpers/Implementation.drawio | 322 ++++++++++++++++++ weaponry/{ => helpers}/workflow.md | 5 + weaponry/src/error.rs | 31 ++ weaponry/src/interfaces.rs | 41 +++ weaponry/src/lib.rs | 1 + .../weaponry_structs/equipement_impl_logic.rs | 3 +- 8 files changed, 404 insertions(+), 1 deletion(-) create mode 100644 weaponry/helpers/Implementation.drawio rename weaponry/{ => helpers}/workflow.md (89%) create mode 100644 weaponry/src/error.rs diff --git a/.gitignore b/.gitignore index f690d27..deed149 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,4 @@ Cargo.lock callgrind* cache.out tarpaulin-report.html +*.bkp diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 9fe62d2..f76b28e 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -16,6 +16,7 @@ serde_rusqlite = "0.37.0" serde_json = { version = "1.0.138", features = ["alloc"] } struct-field-names-as-array = "0.3.0" strum = { version = "0.27.0", features = ["derive"] } +thiserror = "2.0.11" [dev-dependencies] criterion = { version = "0.5" } diff --git a/weaponry/helpers/Implementation.drawio b/weaponry/helpers/Implementation.drawio new file mode 100644 index 0000000..c480b0e --- /dev/null +++ b/weaponry/helpers/Implementation.drawio @@ -0,0 +1,322 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/weaponry/workflow.md b/weaponry/helpers/workflow.md similarity index 89% rename from weaponry/workflow.md rename to weaponry/helpers/workflow.md index 1fc616a..e253452 100644 --- a/weaponry/workflow.md +++ b/weaponry/helpers/workflow.md @@ -1,3 +1,8 @@ +# TO-Impl List + - Initial Object Representation + - Final Object Representation + + # Workflow A B C Database -> -> -> Balancing data diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs new file mode 100644 index 0000000..3d85c1e --- /dev/null +++ b/weaponry/src/error.rs @@ -0,0 +1,31 @@ +// Workspace: weaponry +// File: weaponry/src/error.rs +//! Inner weaponry error definition +#![allow(missing_docs, clippy::missing_docs_in_private_items)] + +use thiserror::Error; + +#[derive(Error, Debug)] +/// Unrecoverable Error, all these error cannot gracefully fail and must return to the User for further handling +pub enum FatalEquipementError { + #[error("Unkown error has errored")] + Unknown, +} + +#[derive(Error, Debug)] +/// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program +pub enum TrivialEquipementError { + #[error("Very simple error")] + Oops, +} + +#[derive(Error, Debug)] +/// An equipement error, either unrecoverable, indicating a that the execution +/// flow must be stopped and only an user input can solve the issue +pub enum EquipementError { + #[error("An unrecoverable error occured: {0}")] + Unrecoverable(#[from] FatalEquipementError), + + #[error("A recoverable error occured but wasn't caught by the programming: {0}")] + Recoverable(#[from] TrivialEquipementError), +} diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 27b7b65..f642d20 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -7,6 +7,8 @@ use std::{path::Path, rc::Rc}; +use crate::error::EquipementError; + /// Trait representing a view table /// /// These table exist to allow to link several point of interest to a RecipeCollection @@ -171,3 +173,42 @@ pub trait Reportable { /// This report should give detailled information about the inner data, without showing the actual inner data fn get_report(&self) -> String; } + +/// A recipe full stack scenario, from loading database through view table generation +/// +/// The inner working while somehow abstracted are very tied together and tied to the impl +pub trait Scenario { + /// The inner database type + type DatabaseType; //: Database; + /// The type of viewtable that must be returned by the scenario + // Could also use dyn dispatch but since all of it is so tied down... + type ViewTableType: ViewTable; + /// The type of the final recipe list + type FinalListType: RefinedList; + + /// Load all database into intermediate representation + fn load_from_database() -> Result + where + Self: std::marker::Sized; + + // All these steps should be implemented but not required + // enforcing them helps writing new impls more easily but is not really nice in any way + // + // /// Process the inner representations and get a list of results + // fn process_inner_representation(&self) -> Result<(), FatalEquipementError>; //Result<(), EquipementError> + + // /// Process inner recipes into a Final list + // /// + // /// This will generate the recipe list using the prefered method of the Scenario (Fixed Recipes or Cross Recipes or Whatever) + // fn process_recipes(&self); + + // /// Process the recipes into a Refined Recipes + // fn refine_recipes(&self); + + /// Generate the final list type + fn generate_refined_recipes(&self) -> Self::FinalListType; + + /// Gather the selected view tables + /// All the inner generation is done gradually and populate all section to finally generate the views + fn generate_view_tables(&self) -> Self::ViewTableType; +} diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index b3c7dfd..e78998c 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -6,6 +6,7 @@ #![feature(iter_intersperse, generic_arg_infer)] mod database; +pub mod error; mod export; pub mod interfaces; mod strategy; diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index 5e7b020..36cd772 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -53,7 +53,8 @@ mod test { interfaces::RecipeCollection, weaponry_structs::{ DamageMod, DamageType, Equipement, InitialEquipementList, SpecialCategory, - WeaponCategory, equipement_fields::PhysicalDamageType, equipement_structs::InnerEquipementStats, + WeaponCategory, equipement_fields::PhysicalDamageType, + equipement_structs::InnerEquipementStats, }, }; use pretty_assertions::assert_eq; -- 2.45.1 From 22d60f55598ab3da9ccc7df22aa7715d0d052ff3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Mon, 17 Feb 2025 18:35:04 +0100 Subject: [PATCH 27/97] Making get_data_from_fields work --- weaponry/src/database.rs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 59cf8ee..a9de8eb 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -39,12 +39,15 @@ fn initialize_database_conn(filename: Option) -> Result { } /// Public function to get data from db -pub fn get_data_from_fields(fields: &[&str], table_name: &str) -> Result> +pub fn get_data_from_fields( + db_conn: rusqlite::Connection, + fields: &[&str], + table_name: &str, +) -> Result> where T: DeserializeOwned, { let gen_query = generate_query(fields, table_name); - let db_conn = initialize_database_conn(None)?; // TODO: Add an actual connection let mut query_result = db_conn.prepare(&gen_query)?; let res = from_rows::(query_result.query([])?) .filter_map(|s| s.ok()) @@ -59,7 +62,7 @@ mod test { use struct_field_names_as_array::FieldNamesAsArray; use super::*; - #[derive(FieldNamesAsArray, Deserialize)] + #[derive(FieldNamesAsArray, Deserialize, Debug)] struct TestStruct { id: usize, name: String, @@ -67,9 +70,9 @@ mod test { fn set_up() -> Result { let conn = initialize_database_conn(None)?; - conn.execute("CREATE TABLE IF NOT EXISTS InnerEquipementStats (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",())?; + conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",())?; conn.execute( - "INSERT INTO TestStuct (id, name) VALUES (1, 'dupont'), (2, 'durand');", + "INSERT INTO TestStruct (id, name) VALUES (1, 'dupont'), (2, 'durand');", (), )?; Ok(conn) @@ -98,9 +101,14 @@ mod test { #[ignore] #[test] fn test_get_data() { - let _conn = set_up(); - let result = - get_data_from_fields::(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct"); - assert!(result.unwrap().is_empty()) + let _conn = set_up().unwrap(); + let result = get_data_from_fields::( + _conn, + &TestStruct::FIELD_NAMES_AS_ARRAY, + "TestStruct", + ) + .unwrap(); + println!("{:?}", result); + assert!(result.is_empty()) } } -- 2.45.1 From 813747d64302c90c7de54a420cb8bb5f16158645 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Mon, 17 Feb 2025 18:38:18 +0100 Subject: [PATCH 28/97] code cleanup on database.rs --- weaponry/src/database.rs | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index a9de8eb..0a3c366 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -12,29 +12,11 @@ use serde_rusqlite::*; /// Generate a SELECT query with fields generated from a struct. Returns a String fn generate_query(fields: &[&str], table_name: &str) -> String { - // let mut query = String::new(); - // query.push_str("SELECT"); - // for item in fields.iter() { - // query.push(' '); - // query.push_str(item); - // query.push(','); - // } - // query.pop(); - // query.push_str(format!(" FROM {};", table_name).as_str()); - // query format!("SELECT {} FROM {};", fields.join(", "), table_name) } /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. -// TODO: Remove this cursed dual purpose function fn initialize_database_conn(filename: Option) -> Result { - // if let Some(text) = filename { - // let conn = Connection::open(text)?; - // Ok(conn) - // } else { - // let conn = Connection::open_in_memory()?; - // Ok(conn) - // } filename.map_or_else(Connection::open_in_memory, Connection::open) } @@ -57,11 +39,11 @@ where #[cfg(test)] mod test { + use super::*; use pretty_assertions::assert_eq; use serde::Deserialize; use struct_field_names_as_array::FieldNamesAsArray; - use super::*; #[derive(FieldNamesAsArray, Deserialize, Debug)] struct TestStruct { id: usize, -- 2.45.1 From a5d44b82e47c8c96cde7f08d66a745cd528ec679 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 17 Feb 2025 18:59:37 +0100 Subject: [PATCH 29/97] Add basic database implementation and some Scenario skeleton --- weaponry/src/interfaces.rs | 26 +++++- .../equipement_impl_database.rs | 46 +++++----- .../weaponry_structs/equipement_scenario.rs | 85 +++++++++++++++++++ .../src/weaponry_structs/equipement_views.rs | 4 +- weaponry/src/weaponry_structs/mod.rs | 1 + 5 files changed, 133 insertions(+), 29 deletions(-) create mode 100644 weaponry/src/weaponry_structs/equipement_scenario.rs diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index f642d20..58e512a 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -20,13 +20,13 @@ pub trait ViewTable { /// The inner type of element that one would be peeking into /// /// Usually the final representation of an Item - type InterestElement: RefinedList; + type InterestElementList: RefinedList; /// Give a list of interesting element indicises to further analyse fn index_of_interest_points(&self) -> Vec; /// Interrogate the FinalRepresentation to find interesting elements - fn find_points_of_interest(&self, representation: &Self::InterestElement); + fn find_points_of_interest(&self, representation: &Self::InterestElementList); // An alternative, non Self::Typed way of doing since there is only one usage for now // fn find_points_of_interest(&self, representation: &impl FinalRepresentation); } @@ -148,13 +148,26 @@ pub trait ToCSV { } /// Garanties that a struct can be generated from a database +#[deprecated] pub trait DbSerializable { /// Serialize the object from a database fn from_database() -> Self; } +/// A generic database+connection, handling all the deserialization of the inner types +pub trait RecipeDatabase { + /// Serialize a vector of objects of the given type in the specified table of the underlying database + fn serialize_vec_from_table(table: &str) -> Result; + + /// Serialize a specified vector of objects of the given type with an additionnal restriction + fn serialize_vec_from_table_with_query( + table: &str, + query: &str, + ) -> Result; +} + /// Trait implemented by any struct aiming to be a public recipe -pub trait FixedRecipe: DbSerializable { +pub trait FixedRecipe { /// Struct representing the database type, most likely a string type Database; /// Struct representing the keylist type, most likely a usize @@ -179,18 +192,23 @@ pub trait Reportable { /// The inner working while somehow abstracted are very tied together and tied to the impl pub trait Scenario { /// The inner database type - type DatabaseType; //: Database; + type DatabaseType: RecipeDatabase; /// The type of viewtable that must be returned by the scenario // Could also use dyn dispatch but since all of it is so tied down... type ViewTableType: ViewTable; /// The type of the final recipe list type FinalListType: RefinedList; + /// Inner configuration + type Config; /// Load all database into intermediate representation fn load_from_database() -> Result where Self: std::marker::Sized; + /// Configure the scenario to the user's needs + fn configure_scenario(&mut self, config: Self::Config) -> Result<(), EquipementError>; + // All these steps should be implemented but not required // enforcing them helps writing new impls more easily but is not really nice in any way // diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 8ab55b2..271decd 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -2,29 +2,29 @@ // File: weaponry/src/weaponry_structs/equipement_impl_database.rs //! All database specific implementations -use crate::interfaces::DbSerializable; +// use crate::interfaces::DbSerializable; -use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; +// use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; -//TODO: Fred, make these and I'm happy +// //TODO: Fred, make these and I'm happy -impl DbSerializable for EqShape { - fn from_database() -> Self { - todo!() - } -} -impl DbSerializable for EqMaterial { - fn from_database() -> Self { - todo!() - } -} -impl DbSerializable for EqNature { - fn from_database() -> Self { - todo!() - } -} -impl DbSerializable for EqFinishing { - fn from_database() -> Self { - todo!() - } -} +// impl DbSerializable for EqShape { +// fn from_database() -> Self { +// todo!() +// } +// } +// impl DbSerializable for EqMaterial { +// fn from_database() -> Self { +// todo!() +// } +// } +// impl DbSerializable for EqNature { +// fn from_database() -> Self { +// todo!() +// } +// } +// impl DbSerializable for EqFinishing { +// fn from_database() -> Self { +// todo!() +// } +// } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs new file mode 100644 index 0000000..da91630 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -0,0 +1,85 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_scenario.rs +//! Implementations of a full scenario, +//! +//! These implementation must take care of everything from database retrieval to view exporting, +//! however all they mostly do is glue together all the parts designed in the interface, +//! and therefore mostly serves as a TO-DO list +//! + +#![allow(dead_code)] + +use crate::interfaces::{RecipeDatabase, Scenario, ViewTable}; + +use super::equipement_advanced_repr::RefinedEquipementList; + +/// Mock of the existing database +pub struct DatabaseMock {} +impl RecipeDatabase for DatabaseMock { + fn serialize_vec_from_table(table: &str) -> Result { + let _ = table; + todo!() + } + + fn serialize_vec_from_table_with_query( + table: &str, + query: &str, + ) -> Result { + let _ = table; + let _ = query; + todo!() + } +} +/// Mock config +pub struct ConfigMock {} +/// Mock Viewtable +pub struct ViewtableMock {} +impl ViewTable for ViewtableMock { + type InterestElementList = RefinedEquipementList; + + fn index_of_interest_points(&self) -> Vec { + todo!() + } + + fn find_points_of_interest(&self, representation: &Self::InterestElementList) { + let _ = representation; + todo!() + } +} + +/// A simple cross recipe scenario +#[allow(clippy::missing_docs_in_private_items)] +pub struct CrossRecipeScenario { + database: DatabaseMock, + config: ConfigMock, +} + +impl Scenario for CrossRecipeScenario { + type DatabaseType = DatabaseMock; + type ViewTableType = ViewtableMock; + type FinalListType = RefinedEquipementList; + type Config = ConfigMock; + + fn load_from_database() -> Result + where + Self: std::marker::Sized, + { + todo!() + } + + fn configure_scenario( + &mut self, + config: Self::Config, + ) -> Result<(), crate::error::EquipementError> { + self.config = config; + Ok(()) + } + + fn generate_refined_recipes(&self) -> Self::FinalListType { + todo!() + } + + fn generate_view_tables(&self) -> Self::ViewTableType { + todo!() + } +} diff --git a/weaponry/src/weaponry_structs/equipement_views.rs b/weaponry/src/weaponry_structs/equipement_views.rs index 3339038..f1162c7 100644 --- a/weaponry/src/weaponry_structs/equipement_views.rs +++ b/weaponry/src/weaponry_structs/equipement_views.rs @@ -15,13 +15,13 @@ use super::equipement_advanced_repr::RefinedEquipementList; struct EquipementFullView {} impl ViewTable for EquipementFullView { - type InterestElement = RefinedEquipementList; + type InterestElementList = RefinedEquipementList; fn index_of_interest_points(&self) -> Vec { todo!() } - fn find_points_of_interest(&self, representation: &Self::InterestElement) { + fn find_points_of_interest(&self, representation: &Self::InterestElementList) { let _ = representation; todo!() } diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 7040c4f..f702895 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -23,6 +23,7 @@ mod equipement_impl_database; mod equipement_impl_io; mod equipement_impl_logic; mod equipement_impl_math; +mod equipement_scenario; pub mod equipement_structs; pub mod equipement_tools; mod equipement_views; -- 2.45.1 From 862021e0b27c095013e0762f34d9ba23adb72c10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Mon, 17 Feb 2025 19:35:35 +0100 Subject: [PATCH 30/97] refactor database.rs into struct and impl --- weaponry/src/database.rs | 98 ++++++++++++------- weaponry/src/error.rs | 4 +- weaponry/src/interfaces.rs | 4 +- .../weaponry_structs/equipement_scenario.rs | 6 +- 4 files changed, 69 insertions(+), 43 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 0a3c366..ded6b6a 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -5,38 +5,65 @@ //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] -//use crate::weaponry_structs::equipement_structs::InnerEquipementStats; -use rusqlite::{self, Connection, Result}; +use crate::{error::FatalEquipementError, interfaces::RecipeDatabase}; +use rusqlite::{self, Connection}; use serde::de::DeserializeOwned; -use serde_rusqlite::*; + +/// Struct for database connection. +pub struct EquipementDatabase { + /// Connection parameter for rusqlite + pub conn: rusqlite::Connection, +} + +impl EquipementDatabase { + /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. + fn new(filename: Option) -> Result { + Ok(Self { + conn: filename.map_or_else(Connection::open_in_memory, Connection::open)?, + }) + } + + /// Public function to get data from db. Returns the result as a vec with structs + pub fn get_data_from_fields( + &self, + fields: &[&str], + table_name: &str, + ) -> Result, serde_rusqlite::Error> + where + T: DeserializeOwned, + { + let gen_query = { + let fields = fields; + let table_name = table_name; + format!("SELECT {} FROM {};", fields.join(", "), table_name) + }; + let mut query_result = self.conn.prepare(&gen_query)?; + let res = serde_rusqlite::from_rows::(query_result.query([])?) + .filter_map(|s| s.ok()) + .collect(); + Ok(res) + } +} + +impl RecipeDatabase for EquipementDatabase { + fn serialize_vec_from_table(table: &str) -> Result, crate::error::EquipementError> { + todo!() + } + + fn serialize_vec_from_table_with_query( + table: &str, + query: &str, + ) -> Result, crate::error::EquipementError> { + todo!() + } +} /// Generate a SELECT query with fields generated from a struct. Returns a String +#[inline] fn generate_query(fields: &[&str], table_name: &str) -> String { format!("SELECT {} FROM {};", fields.join(", "), table_name) } -/// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. -fn initialize_database_conn(filename: Option) -> Result { - filename.map_or_else(Connection::open_in_memory, Connection::open) -} - -/// Public function to get data from db -pub fn get_data_from_fields( - db_conn: rusqlite::Connection, - fields: &[&str], - table_name: &str, -) -> Result> -where - T: DeserializeOwned, -{ - let gen_query = generate_query(fields, table_name); - let mut query_result = db_conn.prepare(&gen_query)?; - let res = from_rows::(query_result.query([])?) - .filter_map(|s| s.ok()) - .collect(); - Ok(res) -} - #[cfg(test)] mod test { use super::*; @@ -50,14 +77,14 @@ mod test { name: String, } - fn set_up() -> Result { - let conn = initialize_database_conn(None)?; - conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",())?; - conn.execute( + fn set_up() -> Result { + let equip_db = EquipementDatabase::new(None)?; + equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",())?; + equip_db.conn.execute( "INSERT INTO TestStruct (id, name) VALUES (1, 'dupont'), (2, 'durand');", (), )?; - Ok(conn) + Ok(equip_db) } #[test] @@ -83,13 +110,10 @@ mod test { #[ignore] #[test] fn test_get_data() { - let _conn = set_up().unwrap(); - let result = get_data_from_fields::( - _conn, - &TestStruct::FIELD_NAMES_AS_ARRAY, - "TestStruct", - ) - .unwrap(); + let conn = set_up().unwrap(); + let result = conn + .get_data_from_fields::(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct") + .unwrap(); println!("{:?}", result); assert!(result.is_empty()) } diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index 3d85c1e..03a749e 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -8,8 +8,8 @@ use thiserror::Error; #[derive(Error, Debug)] /// Unrecoverable Error, all these error cannot gracefully fail and must return to the User for further handling pub enum FatalEquipementError { - #[error("Unkown error has errored")] - Unknown, + #[error("Rusqlite Error")] + RusqliteConnection(#[from] rusqlite::Error), } #[derive(Error, Debug)] diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 58e512a..c02bbf2 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -157,13 +157,13 @@ pub trait DbSerializable { /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { /// Serialize a vector of objects of the given type in the specified table of the underlying database - fn serialize_vec_from_table(table: &str) -> Result; + fn serialize_vec_from_table(table: &str) -> std::result::Result, EquipementError>; /// Serialize a specified vector of objects of the given type with an additionnal restriction fn serialize_vec_from_table_with_query( table: &str, query: &str, - ) -> Result; + ) -> std::result::Result, EquipementError>; } /// Trait implemented by any struct aiming to be a public recipe diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index da91630..3f107fd 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -16,7 +16,9 @@ use super::equipement_advanced_repr::RefinedEquipementList; /// Mock of the existing database pub struct DatabaseMock {} impl RecipeDatabase for DatabaseMock { - fn serialize_vec_from_table(table: &str) -> Result { + fn serialize_vec_from_table( + table: &str, + ) -> std::result::Result, crate::error::EquipementError> { let _ = table; todo!() } @@ -24,7 +26,7 @@ impl RecipeDatabase for DatabaseMock { fn serialize_vec_from_table_with_query( table: &str, query: &str, - ) -> Result { + ) -> std::result::Result, crate::error::EquipementError> { let _ = table; let _ = query; todo!() -- 2.45.1 From bfe9285b432855aabc21de6bcdec3c2ec6dc0850 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 17 Feb 2025 19:36:55 +0100 Subject: [PATCH 31/97] Adds some more info on the scenario --- weaponry/src/interfaces.rs | 5 +++++ weaponry/src/weaponry_structs/equipement_scenario.rs | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index c02bbf2..0de0c51 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -156,6 +156,11 @@ pub trait DbSerializable { /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { + /// Create the database from a file + fn new(origin: &str) -> Result + where + Self: std::marker::Sized; + /// Serialize a vector of objects of the given type in the specified table of the underlying database fn serialize_vec_from_table(table: &str) -> std::result::Result, EquipementError>; diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 3f107fd..06b6f55 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -31,6 +31,14 @@ impl RecipeDatabase for DatabaseMock { let _ = query; todo!() } + + fn new(origin: &str) -> Result + where + Self: std::marker::Sized, + { + let _ = origin; + todo!() + } } /// Mock config pub struct ConfigMock {} -- 2.45.1 From f044d26a10df9d998a12df17b9ba744d1dd79f7b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 17 Feb 2025 19:57:52 +0100 Subject: [PATCH 32/97] Adds a new impl in the interface --- weaponry/src/database.rs | 51 ++++++++++++++++++++-------------------- weaponry/src/error.rs | 34 ++++++++++++++------------- 2 files changed, 43 insertions(+), 42 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index ded6b6a..04c0dd7 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -5,7 +5,7 @@ //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] -use crate::{error::FatalEquipementError, interfaces::RecipeDatabase}; +use crate::{error::EquipementError, interfaces::RecipeDatabase}; use rusqlite::{self, Connection}; use serde::de::DeserializeOwned; @@ -16,13 +16,6 @@ pub struct EquipementDatabase { } impl EquipementDatabase { - /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. - fn new(filename: Option) -> Result { - Ok(Self { - conn: filename.map_or_else(Connection::open_in_memory, Connection::open)?, - }) - } - /// Public function to get data from db. Returns the result as a vec with structs pub fn get_data_from_fields( &self, @@ -32,16 +25,10 @@ impl EquipementDatabase { where T: DeserializeOwned, { - let gen_query = { - let fields = fields; - let table_name = table_name; - format!("SELECT {} FROM {};", fields.join(", "), table_name) - }; - let mut query_result = self.conn.prepare(&gen_query)?; - let res = serde_rusqlite::from_rows::(query_result.query([])?) + let mut query_result = self.conn.prepare(&generate_query(fields, table_name))?; + Ok(serde_rusqlite::from_rows::(query_result.query([])?) .filter_map(|s| s.ok()) - .collect(); - Ok(res) + .collect()) } } @@ -56,6 +43,13 @@ impl RecipeDatabase for EquipementDatabase { ) -> Result, crate::error::EquipementError> { todo!() } + + /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. + fn new(filename: &str) -> Result { + Ok(EquipementDatabase { + conn: Connection::open(filename)?, + }) + } } /// Generate a SELECT query with fields generated from a struct. Returns a String @@ -77,14 +71,19 @@ mod test { name: String, } - fn set_up() -> Result { - let equip_db = EquipementDatabase::new(None)?; - equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",())?; - equip_db.conn.execute( - "INSERT INTO TestStruct (id, name) VALUES (1, 'dupont'), (2, 'durand');", - (), - )?; - Ok(equip_db) + fn mock_set_up() -> EquipementDatabase { + let equip_db = EquipementDatabase { + conn: Connection::open_in_memory().unwrap(), + }; + equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",()).unwrap(); + equip_db + .conn + .execute( + "INSERT INTO TestStruct (id, name) VALUES (1, 'dupont'), (2, 'durand');", + (), + ) + .unwrap(); + equip_db } #[test] @@ -110,7 +109,7 @@ mod test { #[ignore] #[test] fn test_get_data() { - let conn = set_up().unwrap(); + let conn = mock_set_up(); let result = conn .get_data_from_fields::(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct") .unwrap(); diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index 03a749e..fda0aa6 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -5,27 +5,29 @@ use thiserror::Error; -#[derive(Error, Debug)] -/// Unrecoverable Error, all these error cannot gracefully fail and must return to the User for further handling -pub enum FatalEquipementError { - #[error("Rusqlite Error")] - RusqliteConnection(#[from] rusqlite::Error), -} +// #[derive(Error, Debug)] +// /// Unrecoverable Error, all these error cannot gracefully fail and must return to the User for further handling +// pub enum FatalEquipementError { +// #[error("Rusqlite failed to connect to the given path {0}")] +// RusqliteConnection(#[from] rusqlite::Error), +// } -#[derive(Error, Debug)] -/// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program -pub enum TrivialEquipementError { - #[error("Very simple error")] - Oops, -} +// #[derive(Error, Debug)] +// /// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program +// pub enum TrivialEquipementError { +// #[error("Very simple error")] +// Oops, +// } #[derive(Error, Debug)] /// An equipement error, either unrecoverable, indicating a that the execution /// flow must be stopped and only an user input can solve the issue pub enum EquipementError { - #[error("An unrecoverable error occured: {0}")] - Unrecoverable(#[from] FatalEquipementError), + // #[error("An unrecoverable error occured: {0}")] + // Unrecoverable(#[from] FatalEquipementError), - #[error("A recoverable error occured but wasn't caught by the programming: {0}")] - Recoverable(#[from] TrivialEquipementError), + // #[error("A recoverable error occured but wasn't caught by the programming: {0}")] + // Recoverable(#[from] TrivialEquipementError), + #[error("Rusqlite failed to connect to the given path {0}")] + RusqliteConnection(#[from] rusqlite::Error), } -- 2.45.1 From a0b0012d76c6c50af6ae8e97546c87e5f631cf75 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 17 Feb 2025 21:30:46 +0100 Subject: [PATCH 33/97] Correction of a genquery typo --- weaponry/src/database.rs | 14 +++++--- weaponry/src/error.rs | 34 +++++++++---------- weaponry/src/export.rs | 1 + weaponry/src/interfaces.rs | 17 ++++++---- .../equipement_impl_database.rs | 23 +------------ .../weaponry_structs/equipement_scenario.rs | 15 +++++--- .../src/weaponry_structs/equipement_tools.rs | 2 ++ 7 files changed, 51 insertions(+), 55 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 04c0dd7..5404d6a 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -5,7 +5,7 @@ //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] -use crate::{error::EquipementError, interfaces::RecipeDatabase}; +use crate::{error::FatalEquipementError, interfaces::RecipeDatabase}; use rusqlite::{self, Connection}; use serde::de::DeserializeOwned; @@ -33,23 +33,29 @@ impl EquipementDatabase { } impl RecipeDatabase for EquipementDatabase { - fn serialize_vec_from_table(table: &str) -> Result, crate::error::EquipementError> { + fn serialize_vec_from_table( + table: &str, + ) -> Result, crate::error::FatalEquipementError> { todo!() } fn serialize_vec_from_table_with_query( table: &str, query: &str, - ) -> Result, crate::error::EquipementError> { + ) -> Result, crate::error::FatalEquipementError> { todo!() } /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. - fn new(filename: &str) -> Result { + fn new(filename: &str) -> Result { Ok(EquipementDatabase { conn: Connection::open(filename)?, }) } + + fn initialize_empty_table(table: &str) -> Result<(), crate::error::EquipementError> { + todo!() + } } /// Generate a SELECT query with fields generated from a struct. Returns a String diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index fda0aa6..9465967 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -5,29 +5,27 @@ use thiserror::Error; -// #[derive(Error, Debug)] -// /// Unrecoverable Error, all these error cannot gracefully fail and must return to the User for further handling -// pub enum FatalEquipementError { -// #[error("Rusqlite failed to connect to the given path {0}")] -// RusqliteConnection(#[from] rusqlite::Error), -// } +#[derive(Error, Debug)] +/// Unrecoverable Error, all these error cannot gracefully fail and must return to the User for further handling +pub enum FatalEquipementError { + #[error("Rusqlite failed to connect to the given path {0}")] + RusqliteConnection(#[from] rusqlite::Error), +} -// #[derive(Error, Debug)] -// /// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program -// pub enum TrivialEquipementError { -// #[error("Very simple error")] -// Oops, -// } +#[derive(Error, Debug)] +/// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program +pub enum LocalEquipementError { + #[error("Very simple error")] + Oops, +} #[derive(Error, Debug)] /// An equipement error, either unrecoverable, indicating a that the execution /// flow must be stopped and only an user input can solve the issue pub enum EquipementError { - // #[error("An unrecoverable error occured: {0}")] - // Unrecoverable(#[from] FatalEquipementError), + #[error("An unrecoverable error occured: {0}")] + Fatal(#[from] FatalEquipementError), - // #[error("A recoverable error occured but wasn't caught by the programming: {0}")] - // Recoverable(#[from] TrivialEquipementError), - #[error("Rusqlite failed to connect to the given path {0}")] - RusqliteConnection(#[from] rusqlite::Error), + #[error("A local error occured an wasn't recovered from: {0}")] + Local(#[from] LocalEquipementError), } diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index 03cffb7..8b93802 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -1,3 +1,4 @@ // Workspace: weaponry // File: weaponry/src/export.rs //! Export module in charge of transforming data structure into their tex counterpart through the appropriate traits +// TODO: Consider deletion diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 0de0c51..1895c6d 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -7,7 +7,7 @@ use std::{path::Path, rc::Rc}; -use crate::error::EquipementError; +use crate::error::{EquipementError, FatalEquipementError}; /// Trait representing a view table /// @@ -157,18 +157,23 @@ pub trait DbSerializable { /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { /// Create the database from a file - fn new(origin: &str) -> Result + fn new(origin: &str) -> Result where Self: std::marker::Sized; /// Serialize a vector of objects of the given type in the specified table of the underlying database - fn serialize_vec_from_table(table: &str) -> std::result::Result, EquipementError>; + fn serialize_vec_from_table( + table: &str, + ) -> std::result::Result, FatalEquipementError>; /// Serialize a specified vector of objects of the given type with an additionnal restriction fn serialize_vec_from_table_with_query( table: &str, query: &str, - ) -> std::result::Result, EquipementError>; + ) -> std::result::Result, FatalEquipementError>; + + /// Initialize an empty database & table + fn initialize_empty_table(table: &str) -> Result<(), EquipementError>; } /// Trait implemented by any struct aiming to be a public recipe @@ -207,12 +212,12 @@ pub trait Scenario { type Config; /// Load all database into intermediate representation - fn load_from_database() -> Result + fn load_from_database() -> Result where Self: std::marker::Sized; /// Configure the scenario to the user's needs - fn configure_scenario(&mut self, config: Self::Config) -> Result<(), EquipementError>; + fn configure_scenario(&mut self, config: Self::Config) -> Result<(), FatalEquipementError>; // All these steps should be implemented but not required // enforcing them helps writing new impls more easily but is not really nice in any way diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 271decd..5e60565 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -6,25 +6,4 @@ // use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; -// //TODO: Fred, make these and I'm happy - -// impl DbSerializable for EqShape { -// fn from_database() -> Self { -// todo!() -// } -// } -// impl DbSerializable for EqMaterial { -// fn from_database() -> Self { -// todo!() -// } -// } -// impl DbSerializable for EqNature { -// fn from_database() -> Self { -// todo!() -// } -// } -// impl DbSerializable for EqFinishing { -// fn from_database() -> Self { -// todo!() -// } -// } +// TODO: Migrate from database to here diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 06b6f55..2998561 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -18,7 +18,7 @@ pub struct DatabaseMock {} impl RecipeDatabase for DatabaseMock { fn serialize_vec_from_table( table: &str, - ) -> std::result::Result, crate::error::EquipementError> { + ) -> std::result::Result, crate::error::FatalEquipementError> { let _ = table; todo!() } @@ -26,19 +26,24 @@ impl RecipeDatabase for DatabaseMock { fn serialize_vec_from_table_with_query( table: &str, query: &str, - ) -> std::result::Result, crate::error::EquipementError> { + ) -> std::result::Result, crate::error::FatalEquipementError> { let _ = table; let _ = query; todo!() } - fn new(origin: &str) -> Result + fn new(origin: &str) -> Result where Self: std::marker::Sized, { let _ = origin; todo!() } + + fn initialize_empty_table(table: &str) -> Result<(), crate::error::EquipementError> { + let _ = table; + todo!() + } } /// Mock config pub struct ConfigMock {} @@ -70,7 +75,7 @@ impl Scenario for CrossRecipeScenario { type FinalListType = RefinedEquipementList; type Config = ConfigMock; - fn load_from_database() -> Result + fn load_from_database() -> Result where Self: std::marker::Sized, { @@ -80,7 +85,7 @@ impl Scenario for CrossRecipeScenario { fn configure_scenario( &mut self, config: Self::Config, - ) -> Result<(), crate::error::EquipementError> { + ) -> Result<(), crate::error::FatalEquipementError> { self.config = config; Ok(()) } diff --git a/weaponry/src/weaponry_structs/equipement_tools.rs b/weaponry/src/weaponry_structs/equipement_tools.rs index 739aad5..fe2c698 100644 --- a/weaponry/src/weaponry_structs/equipement_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_tools.rs @@ -14,3 +14,5 @@ fn export_to_tex() {} /// Export the data generated to csv fn export_to_csv() {} + +// TODO: Consider deletion -- 2.45.1 From bb39660f6c727e32190734821bc57f2423e2bd23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Mon, 17 Feb 2025 21:21:49 +0100 Subject: [PATCH 34/97] Adding test_get_data_from_fields --- weaponry/src/database.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 5404d6a..e9d34d9 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -71,7 +71,7 @@ mod test { use serde::Deserialize; use struct_field_names_as_array::FieldNamesAsArray; - #[derive(FieldNamesAsArray, Deserialize, Debug)] + #[derive(FieldNamesAsArray, Deserialize, Debug, PartialEq)] struct TestStruct { id: usize, name: String, @@ -112,7 +112,6 @@ mod test { todo!() } - #[ignore] #[test] fn test_get_data() { let conn = mock_set_up(); @@ -120,6 +119,18 @@ mod test { .get_data_from_fields::(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct") .unwrap(); println!("{:?}", result); - assert!(result.is_empty()) + assert_eq!( + result, + vec![ + TestStruct { + id: 1, + name: "dupont".to_string() + }, + TestStruct { + id: 2, + name: "durand".to_string() + } + ] + ) } } -- 2.45.1 From 8389b21aec4291369462388639ba3fe1fcc14877 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Mon, 17 Feb 2025 21:34:20 +0100 Subject: [PATCH 35/97] Adding test_get_data_from_fields --- weaponry/src/database.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index e9d34d9..b9f5df1 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -113,7 +113,7 @@ mod test { } #[test] - fn test_get_data() { + fn get_data_from_fields() { let conn = mock_set_up(); let result = conn .get_data_from_fields::(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct") -- 2.45.1 From 45c31c23b4d01f8a3baa13253a44dfcb28afb922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Mon, 17 Feb 2025 22:05:38 +0100 Subject: [PATCH 36/97] Covering constructor with testing --- weaponry/src/database.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index b9f5df1..ea711da 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -77,10 +77,8 @@ mod test { name: String, } - fn mock_set_up() -> EquipementDatabase { - let equip_db = EquipementDatabase { - conn: Connection::open_in_memory().unwrap(), - }; + fn mock_set_up(db_filename: &str) -> EquipementDatabase { + let equip_db = EquipementDatabase::new(db_filename).unwrap(); equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",()).unwrap(); equip_db .conn @@ -91,6 +89,11 @@ mod test { .unwrap(); equip_db } + /// tearing down all test setup + fn tear_down(filename: &str, db_conn: rusqlite::Connection) { + db_conn.close().unwrap(); + std::fs::remove_file(filename).unwrap(); + } #[test] fn test_generate_query() { @@ -114,11 +117,12 @@ mod test { #[test] fn get_data_from_fields() { - let conn = mock_set_up(); + let filename = "test.db"; + let conn = mock_set_up(filename); let result = conn .get_data_from_fields::(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct") .unwrap(); - println!("{:?}", result); + tear_down(filename, conn.conn); assert_eq!( result, vec![ -- 2.45.1 From 27a9f1cb5c6027266bd65082ce02684fa1c9432c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Mon, 17 Feb 2025 22:30:18 +0100 Subject: [PATCH 37/97] Adding conditions for serialize_vec_from_table* --- weaponry/src/database.rs | 4 ++-- weaponry/src/interfaces.rs | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index ea711da..33e4597 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -33,13 +33,13 @@ impl EquipementDatabase { } impl RecipeDatabase for EquipementDatabase { - fn serialize_vec_from_table( + fn serialize_vec_from_table( table: &str, ) -> Result, crate::error::FatalEquipementError> { todo!() } - fn serialize_vec_from_table_with_query( + fn serialize_vec_from_table_with_query( table: &str, query: &str, ) -> Result, crate::error::FatalEquipementError> { diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 1895c6d..b08ecc1 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -7,6 +7,8 @@ use std::{path::Path, rc::Rc}; +use serde::de::DeserializeOwned; + use crate::error::{EquipementError, FatalEquipementError}; /// Trait representing a view table @@ -162,12 +164,12 @@ pub trait RecipeDatabase { Self: std::marker::Sized; /// Serialize a vector of objects of the given type in the specified table of the underlying database - fn serialize_vec_from_table( + fn serialize_vec_from_table( table: &str, ) -> std::result::Result, FatalEquipementError>; /// Serialize a specified vector of objects of the given type with an additionnal restriction - fn serialize_vec_from_table_with_query( + fn serialize_vec_from_table_with_query( table: &str, query: &str, ) -> std::result::Result, FatalEquipementError>; -- 2.45.1 From ece331b2b2e0e95135514ea94c3abcfd007cb310 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Mon, 17 Feb 2025 23:17:46 +0100 Subject: [PATCH 38/97] Huge refactor for database functions --- weaponry/src/database.rs | 86 +++++-------------- weaponry/src/error.rs | 2 + weaponry/src/interfaces.rs | 4 + .../equipement_impl_database.rs | 41 +++++++++ .../weaponry_structs/equipement_scenario.rs | 4 + weaponry/src/weaponry_structs/mod.rs | 2 +- 6 files changed, 72 insertions(+), 67 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 33e4597..754e98a 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -3,70 +3,36 @@ //! Database handiling module //! Implements the basics deserialisation from a database to the weaponry components //! Should dump whole database in a vec of structs from weaponry_structs -#![allow(dead_code)] - -use crate::{error::FatalEquipementError, interfaces::RecipeDatabase}; -use rusqlite::{self, Connection}; +use rusqlite::{self}; use serde::de::DeserializeOwned; -/// Struct for database connection. -pub struct EquipementDatabase { - /// Connection parameter for rusqlite - pub conn: rusqlite::Connection, -} - -impl EquipementDatabase { - /// Public function to get data from db. Returns the result as a vec with structs - pub fn get_data_from_fields( - &self, - fields: &[&str], - table_name: &str, - ) -> Result, serde_rusqlite::Error> - where - T: DeserializeOwned, - { - let mut query_result = self.conn.prepare(&generate_query(fields, table_name))?; - Ok(serde_rusqlite::from_rows::(query_result.query([])?) - .filter_map(|s| s.ok()) - .collect()) - } -} - -impl RecipeDatabase for EquipementDatabase { - fn serialize_vec_from_table( - table: &str, - ) -> Result, crate::error::FatalEquipementError> { - todo!() - } - - fn serialize_vec_from_table_with_query( - table: &str, - query: &str, - ) -> Result, crate::error::FatalEquipementError> { - todo!() - } - - /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. - fn new(filename: &str) -> Result { - Ok(EquipementDatabase { - conn: Connection::open(filename)?, - }) - } - - fn initialize_empty_table(table: &str) -> Result<(), crate::error::EquipementError> { - todo!() - } +/// Public function to get data from db. Returns the result as a vec with structs +pub fn get_data( + conn: &rusqlite::Connection, + fields: &[&str], + table_name: &str, +) -> Result, serde_rusqlite::Error> +where + T: DeserializeOwned, +{ + let mut query_result = conn.prepare(&generate_select_query(fields, table_name, None))?; + Ok(serde_rusqlite::from_rows::(query_result.query([])?) + .filter_map(|s| s.ok()) + .collect()) } /// Generate a SELECT query with fields generated from a struct. Returns a String #[inline] -fn generate_query(fields: &[&str], table_name: &str) -> String { +fn generate_select_query(fields: &[&str], table_name: &str, filter: Option<&str>) -> String { format!("SELECT {} FROM {};", fields.join(", "), table_name) } #[cfg(test)] mod test { use super::*; + use crate::{ + interfaces::RecipeDatabase, weaponry_structs::equipement_impl_database::EquipementDatabase, + }; use pretty_assertions::assert_eq; use serde::Deserialize; use struct_field_names_as_array::FieldNamesAsArray; @@ -98,29 +64,17 @@ mod test { #[test] fn test_generate_query() { assert_eq!( - generate_query(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct"), + generate_select_query(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct", None), "SELECT id, name FROM TestStruct;" ) } - #[ignore] - #[test] - fn test_initialize_database_conn() { - todo!() - } - - #[ignore] - #[test] - fn test_generate_table_from_struct() { - todo!() - } - #[test] fn get_data_from_fields() { let filename = "test.db"; let conn = mock_set_up(filename); let result = conn - .get_data_from_fields::(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct") + .serialize_vec_from_table::("TestStruct", &TestStruct::FIELD_NAMES_AS_ARRAY) .unwrap(); tear_down(filename, conn.conn); assert_eq!( diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index 9465967..eb1471c 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -10,6 +10,8 @@ use thiserror::Error; pub enum FatalEquipementError { #[error("Rusqlite failed to connect to the given path {0}")] RusqliteConnection(#[from] rusqlite::Error), + #[error("Deserialization from object : {0}")] + SerdeRusqlite(#[from] serde_rusqlite::Error), } #[derive(Error, Debug)] diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index b08ecc1..82a781b 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -165,12 +165,16 @@ pub trait RecipeDatabase { /// Serialize a vector of objects of the given type in the specified table of the underlying database fn serialize_vec_from_table( + &self, table: &str, + fields: &[&str], ) -> std::result::Result, FatalEquipementError>; /// Serialize a specified vector of objects of the given type with an additionnal restriction fn serialize_vec_from_table_with_query( + &self, table: &str, + fields: &[&str], query: &str, ) -> std::result::Result, FatalEquipementError>; diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 5e60565..efbb39a 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -7,3 +7,44 @@ // use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; // TODO: Migrate from database to here +use crate::database::get_data; +use crate::error::FatalEquipementError; +use crate::interfaces::RecipeDatabase; +use rusqlite::Connection; +use serde::de::DeserializeOwned; + +/// Struct for database connection. +pub struct EquipementDatabase { + /// Connection parameter for rusqlite + pub conn: rusqlite::Connection, +} + +impl RecipeDatabase for EquipementDatabase { + fn serialize_vec_from_table( + &self, + table: &str, + fields: &[&str], + ) -> Result, crate::error::FatalEquipementError> { + Ok(get_data(&self.conn, fields, table)?) + } + + fn serialize_vec_from_table_with_query( + &self, + table: &str, + fields: &[&str], + query: &str, + ) -> Result, crate::error::FatalEquipementError> { + todo!() + } + + /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. + fn new(filename: &str) -> Result { + Ok(EquipementDatabase { + conn: Connection::open(filename)?, + }) + } + + fn initialize_empty_table(table: &str) -> Result<(), crate::error::EquipementError> { + todo!() + } +} diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 2998561..f0116f6 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -17,14 +17,18 @@ use super::equipement_advanced_repr::RefinedEquipementList; pub struct DatabaseMock {} impl RecipeDatabase for DatabaseMock { fn serialize_vec_from_table( + &self, table: &str, + fields: &[&str], ) -> std::result::Result, crate::error::FatalEquipementError> { let _ = table; todo!() } fn serialize_vec_from_table_with_query( + &self, table: &str, + fields: &[&str], query: &str, ) -> std::result::Result, crate::error::FatalEquipementError> { let _ = table; diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index f702895..7208fd6 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -19,7 +19,7 @@ mod equipement_advanced_repr; mod equipement_fields; mod equipement_impl_advanced; mod equipement_impl_basics; -mod equipement_impl_database; +pub mod equipement_impl_database; mod equipement_impl_io; mod equipement_impl_logic; mod equipement_impl_math; -- 2.45.1 From d8d976dcdcd4ebb00e4b56f81a36bd0d083a8367 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 17 Feb 2025 23:43:20 +0100 Subject: [PATCH 39/97] Adds a basic (and very lame) static field type representation --- weaponry/src/interfaces.rs | 15 +++-- .../weaponry_structs/equipement_scenario.rs | 30 +++++----- .../weaponry_structs/equipement_structs.rs | 56 ++++++++++++++++++- 3 files changed, 79 insertions(+), 22 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 82a781b..7b0733a 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -217,13 +217,18 @@ pub trait Scenario { /// Inner configuration type Config; - /// Load all database into intermediate representation - fn load_from_database() -> Result + /// Create a Scenario from a given config + fn new_with_config(config: Self::Config) -> Result where - Self: std::marker::Sized; + Self: Sized; - /// Configure the scenario to the user's needs - fn configure_scenario(&mut self, config: Self::Config) -> Result<(), FatalEquipementError>; + // /// Load all database into intermediate representation + // fn load_from_database() -> Result + // where + // Self: std::marker::Sized; + + // /// Configure the scenario to the user's needs + // fn configure_scenario(&mut self, config: Self::Config) -> Result<(), FatalEquipementError>; // All these steps should be implemented but not required // enforcing them helps writing new impls more easily but is not really nice in any way diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index f0116f6..3c8ed18 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -9,7 +9,10 @@ #![allow(dead_code)] -use crate::interfaces::{RecipeDatabase, Scenario, ViewTable}; +use crate::{ + error::{EquipementError, FatalEquipementError}, + interfaces::{RecipeDatabase, Scenario, ViewTable}, +}; use super::equipement_advanced_repr::RefinedEquipementList; @@ -30,13 +33,13 @@ impl RecipeDatabase for DatabaseMock { table: &str, fields: &[&str], query: &str, - ) -> std::result::Result, crate::error::FatalEquipementError> { + ) -> std::result::Result, FatalEquipementError> { let _ = table; let _ = query; todo!() } - fn new(origin: &str) -> Result + fn new(origin: &str) -> Result where Self: std::marker::Sized, { @@ -44,7 +47,7 @@ impl RecipeDatabase for DatabaseMock { todo!() } - fn initialize_empty_table(table: &str) -> Result<(), crate::error::EquipementError> { + fn initialize_empty_table(table: &str) -> Result<(), EquipementError> { let _ = table; todo!() } @@ -79,22 +82,19 @@ impl Scenario for CrossRecipeScenario { type FinalListType = RefinedEquipementList; type Config = ConfigMock; - fn load_from_database() -> Result + fn new_with_config(config: Self::Config) -> Result where - Self: std::marker::Sized, + Self: Sized, { - todo!() - } - - fn configure_scenario( - &mut self, - config: Self::Config, - ) -> Result<(), crate::error::FatalEquipementError> { - self.config = config; - Ok(()) + Ok(Self { + // TODO: Correct this relative path abomination + database: Self::DatabaseType::new("./databases/weapons.db")?, + config, + }) } fn generate_refined_recipes(&self) -> Self::FinalListType { + let _all_parts = &self.database; todo!() } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index b97835c..1bb9c4d 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -2,7 +2,7 @@ // File: weaponry/src/weaponry_structs/equipement_structs.rs //! Base equipement structures -use std::rc::Rc; +use std::{collections::HashMap, rc::Rc, sync::LazyLock}; use serde::{Deserialize, Serialize}; use struct_field_names_as_array::FieldNamesAsArray; @@ -90,6 +90,49 @@ pub struct InnerEquipementStats { pub(super) agility_bonus: u8, } +#[allow(dead_code)] +/// A manually implemented hashmap of all values +// TODO: ADD A PROC MACRO TO AUTO_DERIVE THIS +static INNER_EQ_HASHMAP: LazyLock> = LazyLock::new(|| { + HashMap::from([ + ("id".to_string(), "TEXT".to_string()), + ("name".to_string(), "TEXT".to_string()), + ("rarity".to_string(), "TEXT".to_string()), + ("cost".to_string(), "TEXT".to_string()), + ("difficulty".to_string(), "TEXT".to_string()), + ("tier".to_string(), "TEXT".to_string()), + ("damage".to_string(), "TEXT".to_string()), + ("p_damage".to_string(), "TEXT".to_string()), + ("precision".to_string(), "TEXT".to_string()), + ("rmax".to_string(), "TEXT".to_string()), + ("armor_break".to_string(), "TEXT".to_string()), + ("armor_pierce".to_string(), "TEXT".to_string()), + ("antimaterial".to_string(), "TEXT".to_string()), + ("damage_type".to_string(), "TEXT".to_string()), + ("protection".to_string(), "TEXT".to_string()), + ("integrity".to_string(), "TEXT".to_string()), + ( + "torque_two_handed".to_string(), + "torque_two_handed".to_string(), + ), + ( + "torque_one_handed".to_string(), + "torque_one_handed".to_string(), + ), + ("dodge".to_string(), "TEXT".to_string()), + ("parry".to_string(), "TEXT".to_string()), + ("speed".to_string(), "TEXT".to_string()), + ("stealth".to_string(), "TEXT".to_string()), + ("category".to_string(), "TEXT".to_string()), + ("target".to_string(), "TEXT".to_string()), + ("special".to_string(), "TEXT".to_string()), + ("action_cost".to_string(), "TEXT".to_string()), + ("reload_cost".to_string(), "TEXT".to_string()), + ("range".to_string(), "TEXT".to_string()), + ("agility_bonus".to_string(), "TEXT".to_string()), + ]) +}); + #[doc(hidden)] macro_rules! r { () => { @@ -147,7 +190,9 @@ mod test { EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, }; - use crate::interfaces::RecipeCollection; + use crate::{ + interfaces::RecipeCollection, weaponry_structs::equipement_structs::INNER_EQ_HASHMAP, + }; fn list_equip() -> Vec { (0..10) @@ -185,4 +230,11 @@ mod test { fn test_default_behaviour() { unimplemented!() } + + #[test] + fn test_const_fields() { + let c = &INNER_EQ_HASHMAP; + assert!(!c.keys().len() > 0); + assert!(!c.values().len() > 0); + } } -- 2.45.1 From 02c76ca33a8df1773d68d77d872f9793d65231de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Tue, 18 Feb 2025 00:14:06 +0100 Subject: [PATCH 40/97] Adding generate_database_query --- weaponry/src/database.rs | 35 ++++++++++- .../weaponry_structs/equipement_structs.rs | 58 +++++++++---------- 2 files changed, 58 insertions(+), 35 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 754e98a..9cd1bd8 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -5,6 +5,7 @@ //! Should dump whole database in a vec of structs from weaponry_structs use rusqlite::{self}; use serde::de::DeserializeOwned; +use std::collections::HashMap; /// Public function to get data from db. Returns the result as a vec with structs pub fn get_data( @@ -22,9 +23,29 @@ where } /// Generate a SELECT query with fields generated from a struct. Returns a String +/// filter MUST contain "WHERE" else the query will fail #[inline] fn generate_select_query(fields: &[&str], table_name: &str, filter: Option<&str>) -> String { - format!("SELECT {} FROM {};", fields.join(", "), table_name) + format!( + "SELECT {} FROM {} {};", + fields.join(", "), + table_name, + filter.unwrap_or("") + ) +} + +/// Generate create table_name with fields as columns +/// This function expects a hash map containing (column name, sqlite type) +pub fn generate_database_query(table_name: &str, fields: HashMap) -> String { + format!( + "CREATE TABLE IF NOT EXISTS {} ({}, PRIMARY KEY('id' AUTOINCREMENT));", + table_name, + fields + .iter() + .map(|(k, v)| format!("{} {}", k, v)) + .collect::>() + .join(",") + ) } #[cfg(test)] @@ -65,8 +86,16 @@ mod test { fn test_generate_query() { assert_eq!( generate_select_query(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct", None), - "SELECT id, name FROM TestStruct;" - ) + "SELECT id, name FROM TestStruct ;" + ); + assert_eq!( + generate_select_query( + &TestStruct::FIELD_NAMES_AS_ARRAY, + "TestStruct", + Some("WHERE id=id") + ), + "SELECT id, name FROM TestStruct WHERE id=id;" + ); } #[test] diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 1bb9c4d..581440d 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -95,41 +95,35 @@ pub struct InnerEquipementStats { // TODO: ADD A PROC MACRO TO AUTO_DERIVE THIS static INNER_EQ_HASHMAP: LazyLock> = LazyLock::new(|| { HashMap::from([ - ("id".to_string(), "TEXT".to_string()), + ("id".to_string(), "INTEGER UNIQUE".to_string()), ("name".to_string(), "TEXT".to_string()), - ("rarity".to_string(), "TEXT".to_string()), - ("cost".to_string(), "TEXT".to_string()), - ("difficulty".to_string(), "TEXT".to_string()), - ("tier".to_string(), "TEXT".to_string()), - ("damage".to_string(), "TEXT".to_string()), - ("p_damage".to_string(), "TEXT".to_string()), - ("precision".to_string(), "TEXT".to_string()), - ("rmax".to_string(), "TEXT".to_string()), - ("armor_break".to_string(), "TEXT".to_string()), - ("armor_pierce".to_string(), "TEXT".to_string()), - ("antimaterial".to_string(), "TEXT".to_string()), - ("damage_type".to_string(), "TEXT".to_string()), - ("protection".to_string(), "TEXT".to_string()), - ("integrity".to_string(), "TEXT".to_string()), - ( - "torque_two_handed".to_string(), - "torque_two_handed".to_string(), - ), - ( - "torque_one_handed".to_string(), - "torque_one_handed".to_string(), - ), - ("dodge".to_string(), "TEXT".to_string()), - ("parry".to_string(), "TEXT".to_string()), - ("speed".to_string(), "TEXT".to_string()), - ("stealth".to_string(), "TEXT".to_string()), + ("rarity".to_string(), "INTEGER".to_string()), + ("cost".to_string(), "INTEGER".to_string()), + ("difficulty".to_string(), "INTEGER".to_string()), + ("tier".to_string(), "INTEGER".to_string()), + ("damage".to_string(), "INTEGER".to_string()), + ("p_damage".to_string(), "INTEGER".to_string()), + ("precision".to_string(), "INTEGER".to_string()), + ("rmax".to_string(), "INTEGER".to_string()), + ("armor_break".to_string(), "INTEGER".to_string()), + ("armor_pierce".to_string(), "INTEGER".to_string()), + ("antimaterial".to_string(), "INTEGER".to_string()), + ("damage_type".to_string(), "INTEGER".to_string()), + ("protection".to_string(), "INTEGER".to_string()), + ("integrity".to_string(), "INTEGER".to_string()), + ("torque_two_handed".to_string(), "INTEGER".to_string()), + ("torque_one_handed".to_string(), "INTEGER".to_string()), + ("dodge".to_string(), "INTEGER".to_string()), + ("parry".to_string(), "INTEGER".to_string()), + ("speed".to_string(), "INTEGER".to_string()), + ("stealth".to_string(), "INTEGER".to_string()), ("category".to_string(), "TEXT".to_string()), - ("target".to_string(), "TEXT".to_string()), + ("target".to_string(), "INTEGER".to_string()), ("special".to_string(), "TEXT".to_string()), - ("action_cost".to_string(), "TEXT".to_string()), - ("reload_cost".to_string(), "TEXT".to_string()), - ("range".to_string(), "TEXT".to_string()), - ("agility_bonus".to_string(), "TEXT".to_string()), + ("action_cost".to_string(), "INTEGER".to_string()), + ("reload_cost".to_string(), "INTEGER".to_string()), + ("range".to_string(), "INTEGER".to_string()), + ("agility_bonus".to_string(), "INTEGER".to_string()), ]) }); -- 2.45.1 From d4723e828ef416e787b8126d367826428b603808 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 18 Feb 2025 00:22:16 +0100 Subject: [PATCH 41/97] Final typos --- weaponry/src/interfaces.rs | 2 +- .../weaponry_structs/equipement_scenario.rs | 24 ++++++++++++++----- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 7b0733a..eb02d7b 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -249,5 +249,5 @@ pub trait Scenario { /// Gather the selected view tables /// All the inner generation is done gradually and populate all section to finally generate the views - fn generate_view_tables(&self) -> Self::ViewTableType; + fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType; } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 3c8ed18..1869c30 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -9,9 +9,12 @@ #![allow(dead_code)] +use struct_field_names_as_array::FieldNamesAsArray; + use crate::{ error::{EquipementError, FatalEquipementError}, interfaces::{RecipeDatabase, Scenario, ViewTable}, + weaponry_structs::equipement_structs::InnerEquipementStats, }; use super::equipement_advanced_repr::RefinedEquipementList; @@ -24,8 +27,9 @@ impl RecipeDatabase for DatabaseMock { table: &str, fields: &[&str], ) -> std::result::Result, crate::error::FatalEquipementError> { + let _ = fields; let _ = table; - todo!() + unimplemented!() } fn serialize_vec_from_table_with_query( @@ -34,9 +38,10 @@ impl RecipeDatabase for DatabaseMock { fields: &[&str], query: &str, ) -> std::result::Result, FatalEquipementError> { + let _ = fields; let _ = table; let _ = query; - todo!() + unimplemented!() } fn new(origin: &str) -> Result @@ -44,12 +49,12 @@ impl RecipeDatabase for DatabaseMock { Self: std::marker::Sized, { let _ = origin; - todo!() + unimplemented!() } fn initialize_empty_table(table: &str) -> Result<(), EquipementError> { let _ = table; - todo!() + unimplemented!() } } /// Mock config @@ -94,11 +99,18 @@ impl Scenario for CrossRecipeScenario { } fn generate_refined_recipes(&self) -> Self::FinalListType { - let _all_parts = &self.database; + let _all_parts = &self + .database + .serialize_vec_from_table_with_query::( + "bob", + &InnerEquipementStats::FIELD_NAMES_AS_ARRAY, + "WHERE CATEGOTY == 'Bobitty'", + ); todo!() } - fn generate_view_tables(&self) -> Self::ViewTableType { + fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType { + let _ = equipement_list; todo!() } } -- 2.45.1 From cef4741a0faef70b4eaece897046537dd758b9a3 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 18 Feb 2025 09:10:34 +0100 Subject: [PATCH 42/97] A huge work put into a derive macro for field data,types --- Cargo.toml | 2 +- badges/coverage.svg | 2 +- more_fields/Cargo.toml | 9 +++ more_fields/src/lib.rs | 50 ++++++++++++ more_fields_macro/Cargo.toml | 11 +++ more_fields_macro/src/lib.rs | 77 ++++++++++++++++++ weaponry/Cargo.toml | 3 +- weaponry/src/database.rs | 31 ++++---- weaponry/src/export.rs | 4 - weaponry/src/interfaces.rs | 7 +- weaponry/src/lib.rs | 1 - .../equipement_impl_database.rs | 17 ++-- .../weaponry_structs/equipement_scenario.rs | 7 -- .../weaponry_structs/equipement_structs.rs | 78 +++++++------------ .../src/weaponry_structs/equipement_tools.rs | 18 ----- weaponry/src/weaponry_structs/mod.rs | 1 - 16 files changed, 209 insertions(+), 109 deletions(-) create mode 100644 more_fields/Cargo.toml create mode 100644 more_fields/src/lib.rs create mode 100644 more_fields_macro/Cargo.toml create mode 100644 more_fields_macro/src/lib.rs delete mode 100644 weaponry/src/export.rs delete mode 100644 weaponry/src/weaponry_structs/equipement_tools.rs diff --git a/Cargo.toml b/Cargo.toml index e71620f..b294bf4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ # cargo-features = ["edition2024"] [workspace] -members = [ "cli_parser", "config", "graphs", "make", +members = [ "cli_parser", "config", "graphs", "make", "more_fields", "more_fields_macro", "ravenous-tools", "stats", "tablegen", "weaponry", ] diff --git a/badges/coverage.svg b/badges/coverage.svg index 6fdcf57..ea72a13 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 16%test-coverage16% +test-coverage: 19%test-coverage19% diff --git a/more_fields/Cargo.toml b/more_fields/Cargo.toml new file mode 100644 index 0000000..5783c92 --- /dev/null +++ b/more_fields/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "more_fields" +edition = "2024" +version.workspace = true + +[dependencies] +more_fields_macro = {path ="../more_fields_macro"} +pretty_assertions = "1.4.1" + diff --git a/more_fields/src/lib.rs b/more_fields/src/lib.rs new file mode 100644 index 0000000..8e1408c --- /dev/null +++ b/more_fields/src/lib.rs @@ -0,0 +1,50 @@ +// Workspace: more_fields +// File: more_fields/src/lib.rs +//! Get all the fields as a Vec<("attribute", "type")> +//! Note that this map is implemented without self, allowing us to use it only as a generic, +//! however this limitation is completely artificial + +pub use more_fields_macro::FieldsAsMap; + +pub trait FieldsAsMap { + fn attributes_map() -> Vec<(&'static str, &'static str)>; +} + +// fn iter(&self) -> std::vec::IntoIter<(&'static str, &'static str)>; + +#[cfg(test)] +mod test { + use crate::FieldsAsMap; + use pretty_assertions::assert_eq; + + #[allow(dead_code)] + #[derive(FieldsAsMap, Default)] + struct Bob { + #[TEXT] + field_ouane: u16, + #[INTEGER] + field_2: u16, + #[BLOB] + field_3: u16, + #[NULL] + field_4: u16, + #[REAL] + field_5: u16, + field_6: u16, + } + #[test] + fn test_derive_impl() { + println!("{:?}", Bob::attributes_map()); + // assert!( + let b_hash = vec![ + ("field_ouane", "TEXT"), + ("field_2", "INTEGER"), + ("field_3", "BLOB"), + ("field_4", "NULL"), + ("field_5", "REAL"), + ("field_6", "TEXT"), + ]; + + assert_eq!(Bob::attributes_map(), b_hash); + } +} diff --git a/more_fields_macro/Cargo.toml b/more_fields_macro/Cargo.toml new file mode 100644 index 0000000..aee9a23 --- /dev/null +++ b/more_fields_macro/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "more_fields_macro" +edition = "2024" +version.workspace = true + +[lib] +proc-macro = true + +[dependencies] +quote = "1.0.38" +syn = "2.0.98" diff --git a/more_fields_macro/src/lib.rs b/more_fields_macro/src/lib.rs new file mode 100644 index 0000000..ee2ec15 --- /dev/null +++ b/more_fields_macro/src/lib.rs @@ -0,0 +1,77 @@ +// Workspace: more_fields_macro +// File: more_fields_macro/src/lib.rs +//! A very simple proc macro in chage of giving a field iterator over ("name","sql_type") +//! This macro is a fork of the excellent work of : https://crates.io/crates/struct_iterable +//! +//! Other ressources include: +//! - https://github.com/rust-lang/reference/blob/master/src/procedural-macros.md#attribute-macros +//! - https://docs.rs/syn/latest/syn/struct.Attribute.html +//! - https://docs.rs/syn/latest/syn/struct.Attribute.html#parsing-from-tokens-to-attribute +//! - https://docs.rs/syn/latest/syn/struct.Ident.html +//! +// use proc_macro::TokenStream; +// use quote::quote; +// use syn::{Data, DeriveInput, Fields, parse_macro_input}; +extern crate proc_macro; + +use proc_macro::{Span, TokenStream}; +use quote::quote; +use syn::DeriveInput; +use syn::parse_macro_input; +use syn::{Data, Fields}; + +#[proc_macro_derive(FieldsAsMap, attributes(INTEGER, NULL, REAL, TEXT, BLOB))] +pub fn derive_iterable(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + + let struct_name = input.ident; + let fields = match input.data { + Data::Struct(data_struct) => { + // let list_attrs = input.attrs.iter().map(|v| v.path()); + match data_struct.fields { + Fields::Named(fields_named) => fields_named.named, + _ => panic!("Only structs with named fields are supported"), + } + } + _ => panic!("Only structs are supported"), + }; + + let fields_iter = fields.iter().map(|field| { + let field_ident = &field.ident; + let val = field + .attrs + .iter() + .map(|v| v.path().get_ident()) + .next() + .flatten() + .cloned() + .unwrap_or_else(|| syn::Ident::new("TEXT", Span::call_site().into())) + .to_string(); + let field_name = field_ident.as_ref().unwrap().to_string(); + quote! { + (#field_name, #val) + } + }); + + // static STATIC_FIELDS_OF_STRUCT_#struct_name: std::sync::LazyLock> = + // std::sync::LazyLock::new(|| vec![]); + // const FIELD_NAMES_AS_SLICE: &'static [&'static str] = &[#(#fields_iter),*]; + // and add Self::FIELD_NAMES_AS_SLICE + + let expanded = quote! { + impl FieldsAsMap for #struct_name { + fn attributes_map<'a>() -> Vec<(&'static str, &'static str)> { + vec![ + #(#fields_iter),* + ] + } + } + }; + + TokenStream::from(expanded) +} + +// As an hashmap (incorrect as of no ordering) +// let mut h = std::collections::HashMap::new(); +// #(h.insert(#fields_iter);)* +// h diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index f76b28e..184e041 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -4,17 +4,16 @@ version = "0.1.0" edition = "2024" [dependencies] +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" -# rayon = "1.10.0" rusqlite = { version = "0.33.0", features = ["bundled"] } serde = { version = "1.0.217", features = ["derive"] } serde_rusqlite = "0.37.0" serde_json = { version = "1.0.138", features = ["alloc"] } -struct-field-names-as-array = "0.3.0" strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 9cd1bd8..bca6039 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -3,6 +3,7 @@ //! Database handiling module //! Implements the basics deserialisation from a database to the weaponry components //! Should dump whole database in a vec of structs from weaponry_structs +#![allow(dead_code)] use rusqlite::{self}; use serde::de::DeserializeOwned; use std::collections::HashMap; @@ -10,13 +11,12 @@ use std::collections::HashMap; /// Public function to get data from db. Returns the result as a vec with structs pub fn get_data( conn: &rusqlite::Connection, - fields: &[&str], table_name: &str, ) -> Result, serde_rusqlite::Error> where - T: DeserializeOwned, + T: DeserializeOwned + more_fields::FieldsAsMap, { - let mut query_result = conn.prepare(&generate_select_query(fields, table_name, None))?; + let mut query_result = conn.prepare(&generate_select_query::(table_name, None))?; Ok(serde_rusqlite::from_rows::(query_result.query([])?) .filter_map(|s| s.ok()) .collect()) @@ -25,10 +25,17 @@ where /// Generate a SELECT query with fields generated from a struct. Returns a String /// filter MUST contain "WHERE" else the query will fail #[inline] -fn generate_select_query(fields: &[&str], table_name: &str, filter: Option<&str>) -> String { +fn generate_select_query( + table_name: &str, + filter: Option<&str>, +) -> String { format!( "SELECT {} FROM {} {};", - fields.join(", "), + T::attributes_map() + .into_iter() + .map(|(k, _v)| k) + .collect::>() + .join(", "), table_name, filter.unwrap_or("") ) @@ -54,11 +61,11 @@ mod test { use crate::{ interfaces::RecipeDatabase, weaponry_structs::equipement_impl_database::EquipementDatabase, }; + use more_fields::FieldsAsMap; use pretty_assertions::assert_eq; use serde::Deserialize; - use struct_field_names_as_array::FieldNamesAsArray; - #[derive(FieldNamesAsArray, Deserialize, Debug, PartialEq)] + #[derive(FieldsAsMap, Deserialize, Debug, PartialEq)] struct TestStruct { id: usize, name: String, @@ -85,15 +92,11 @@ mod test { #[test] fn test_generate_query() { assert_eq!( - generate_select_query(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct", None), + generate_select_query::("TestStruct", None), "SELECT id, name FROM TestStruct ;" ); assert_eq!( - generate_select_query( - &TestStruct::FIELD_NAMES_AS_ARRAY, - "TestStruct", - Some("WHERE id=id") - ), + generate_select_query::("TestStruct", Some("WHERE id=id")), "SELECT id, name FROM TestStruct WHERE id=id;" ); } @@ -103,7 +106,7 @@ mod test { let filename = "test.db"; let conn = mock_set_up(filename); let result = conn - .serialize_vec_from_table::("TestStruct", &TestStruct::FIELD_NAMES_AS_ARRAY) + .serialize_vec_from_table::("TestStruct") .unwrap(); tear_down(filename, conn.conn); assert_eq!( diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs deleted file mode 100644 index 8b93802..0000000 --- a/weaponry/src/export.rs +++ /dev/null @@ -1,4 +0,0 @@ -// Workspace: weaponry -// File: weaponry/src/export.rs -//! Export module in charge of transforming data structure into their tex counterpart through the appropriate traits -// TODO: Consider deletion diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index eb02d7b..229aa9d 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -7,6 +7,7 @@ use std::{path::Path, rc::Rc}; +use more_fields::FieldsAsMap; use serde::de::DeserializeOwned; use crate::error::{EquipementError, FatalEquipementError}; @@ -164,22 +165,20 @@ pub trait RecipeDatabase { Self: std::marker::Sized; /// Serialize a vector of objects of the given type in the specified table of the underlying database - fn serialize_vec_from_table( + fn serialize_vec_from_table( &self, table: &str, - fields: &[&str], ) -> std::result::Result, FatalEquipementError>; /// Serialize a specified vector of objects of the given type with an additionnal restriction fn serialize_vec_from_table_with_query( &self, table: &str, - fields: &[&str], query: &str, ) -> std::result::Result, FatalEquipementError>; /// Initialize an empty database & table - fn initialize_empty_table(table: &str) -> Result<(), EquipementError>; + fn initialize_empty_table(table: &str) -> Result<(), EquipementError>; } /// Trait implemented by any struct aiming to be a public recipe diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index e78998c..cf331bd 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -7,7 +7,6 @@ mod database; pub mod error; -mod export; pub mod interfaces; mod strategy; pub mod weaponry_structs; diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index efbb39a..a0c7ebc 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -6,7 +6,6 @@ // use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; -// TODO: Migrate from database to here use crate::database::get_data; use crate::error::FatalEquipementError; use crate::interfaces::RecipeDatabase; @@ -20,20 +19,20 @@ pub struct EquipementDatabase { } impl RecipeDatabase for EquipementDatabase { - fn serialize_vec_from_table( + fn serialize_vec_from_table( &self, table: &str, - fields: &[&str], ) -> Result, crate::error::FatalEquipementError> { - Ok(get_data(&self.conn, fields, table)?) + Ok(get_data(&self.conn, table)?) } fn serialize_vec_from_table_with_query( &self, table: &str, - fields: &[&str], query: &str, ) -> Result, crate::error::FatalEquipementError> { + let _ = table; + let _ = query; todo!() } @@ -44,7 +43,13 @@ impl RecipeDatabase for EquipementDatabase { }) } - fn initialize_empty_table(table: &str) -> Result<(), crate::error::EquipementError> { + fn initialize_empty_table( + table: &str, + ) -> Result<(), crate::error::EquipementError> { + // A vector of + let _attr_map = T::attributes_map(); + + let _ = table; todo!() } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 1869c30..c343129 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -9,8 +9,6 @@ #![allow(dead_code)] -use struct_field_names_as_array::FieldNamesAsArray; - use crate::{ error::{EquipementError, FatalEquipementError}, interfaces::{RecipeDatabase, Scenario, ViewTable}, @@ -25,9 +23,7 @@ impl RecipeDatabase for DatabaseMock { fn serialize_vec_from_table( &self, table: &str, - fields: &[&str], ) -> std::result::Result, crate::error::FatalEquipementError> { - let _ = fields; let _ = table; unimplemented!() } @@ -35,10 +31,8 @@ impl RecipeDatabase for DatabaseMock { fn serialize_vec_from_table_with_query( &self, table: &str, - fields: &[&str], query: &str, ) -> std::result::Result, FatalEquipementError> { - let _ = fields; let _ = table; let _ = query; unimplemented!() @@ -103,7 +97,6 @@ impl Scenario for CrossRecipeScenario { .database .serialize_vec_from_table_with_query::( "bob", - &InnerEquipementStats::FIELD_NAMES_AS_ARRAY, "WHERE CATEGOTY == 'Bobitty'", ); todo!() diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 581440d..cdaa074 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -2,12 +2,11 @@ // File: weaponry/src/weaponry_structs/equipement_structs.rs //! Base equipement structures -use std::{collections::HashMap, rc::Rc, sync::LazyLock}; - -use serde::{Deserialize, Serialize}; -use struct_field_names_as_array::FieldNamesAsArray; +use std::rc::Rc; use crate::interfaces::{FilterFunction, FilterFunctionType}; +use more_fields::FieldsAsMap; +use serde::{Deserialize, Serialize}; use super::{DamageType, SpecialCategory, WeaponCategory}; @@ -56,77 +55,65 @@ impl FilterFunction { /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldNamesAsArray, Debug, Deserialize, Serialize)] +#[derive(Clone, Default, FieldsAsMap, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub struct InnerEquipementStats { + #[INTEGER] pub id: Vec, pub name: Vec, + #[INTEGER] pub(super) rarity: u8, + #[INTEGER] pub(super) cost: u8, + #[INTEGER] pub(super) difficulty: u8, + #[INTEGER] pub(super) tier: u8, + #[INTEGER] pub(super) damage: u8, + #[INTEGER] pub(super) p_damage: u8, + #[INTEGER] pub(super) precision: i8, + #[INTEGER] pub(super) rmax: u8, + #[INTEGER] pub(super) armor_break: u8, + #[INTEGER] pub(super) armor_pierce: u8, + #[INTEGER] pub(super) antimaterial: u8, pub(super) damage_type: Option, + #[INTEGER] pub(super) protection: u8, + #[INTEGER] pub(super) integrity: u8, + #[INTEGER] pub(super) torque_two_handed: u8, + #[INTEGER] pub(super) torque_one_handed: u8, + #[INTEGER] pub(super) dodge: u8, + #[INTEGER] pub(super) parry: u8, + #[INTEGER] pub(super) speed: u8, + #[INTEGER] pub(super) stealth: u8, pub(super) category: Option, pub(super) target: Option, pub(super) special: SpecialCategory, + #[INTEGER] pub(super) action_cost: u8, pub(super) reload_cost: Option, + #[INTEGER] pub(super) range: u8, + #[INTEGER] pub(super) agility_bonus: u8, } #[allow(dead_code)] /// A manually implemented hashmap of all values -// TODO: ADD A PROC MACRO TO AUTO_DERIVE THIS -static INNER_EQ_HASHMAP: LazyLock> = LazyLock::new(|| { - HashMap::from([ - ("id".to_string(), "INTEGER UNIQUE".to_string()), - ("name".to_string(), "TEXT".to_string()), - ("rarity".to_string(), "INTEGER".to_string()), - ("cost".to_string(), "INTEGER".to_string()), - ("difficulty".to_string(), "INTEGER".to_string()), - ("tier".to_string(), "INTEGER".to_string()), - ("damage".to_string(), "INTEGER".to_string()), - ("p_damage".to_string(), "INTEGER".to_string()), - ("precision".to_string(), "INTEGER".to_string()), - ("rmax".to_string(), "INTEGER".to_string()), - ("armor_break".to_string(), "INTEGER".to_string()), - ("armor_pierce".to_string(), "INTEGER".to_string()), - ("antimaterial".to_string(), "INTEGER".to_string()), - ("damage_type".to_string(), "INTEGER".to_string()), - ("protection".to_string(), "INTEGER".to_string()), - ("integrity".to_string(), "INTEGER".to_string()), - ("torque_two_handed".to_string(), "INTEGER".to_string()), - ("torque_one_handed".to_string(), "INTEGER".to_string()), - ("dodge".to_string(), "INTEGER".to_string()), - ("parry".to_string(), "INTEGER".to_string()), - ("speed".to_string(), "INTEGER".to_string()), - ("stealth".to_string(), "INTEGER".to_string()), - ("category".to_string(), "TEXT".to_string()), - ("target".to_string(), "INTEGER".to_string()), - ("special".to_string(), "TEXT".to_string()), - ("action_cost".to_string(), "INTEGER".to_string()), - ("reload_cost".to_string(), "INTEGER".to_string()), - ("range".to_string(), "INTEGER".to_string()), - ("agility_bonus".to_string(), "INTEGER".to_string()), - ]) -}); - #[doc(hidden)] macro_rules! r { () => { @@ -184,9 +171,7 @@ mod test { EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, }; - use crate::{ - interfaces::RecipeCollection, weaponry_structs::equipement_structs::INNER_EQ_HASHMAP, - }; + use crate::interfaces::RecipeCollection; fn list_equip() -> Vec { (0..10) @@ -224,11 +209,4 @@ mod test { fn test_default_behaviour() { unimplemented!() } - - #[test] - fn test_const_fields() { - let c = &INNER_EQ_HASHMAP; - assert!(!c.keys().len() > 0); - assert!(!c.values().len() > 0); - } } diff --git a/weaponry/src/weaponry_structs/equipement_tools.rs b/weaponry/src/weaponry_structs/equipement_tools.rs deleted file mode 100644 index fe2c698..0000000 --- a/weaponry/src/weaponry_structs/equipement_tools.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Workspace: weaponry -// File: weaponry/src/weaponry_structs/equipement_tools.rs -//! Tools user facing, implement all that a end user would need -//! -//! This file implements all the functions the main runner will eventually launch - -#![allow(dead_code)] - -/// Tooling utility -fn load_database() {} - -/// Export the data generated to tex -fn export_to_tex() {} - -/// Export the data generated to csv -fn export_to_csv() {} - -// TODO: Consider deletion diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 7208fd6..dfdbad8 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -25,7 +25,6 @@ mod equipement_impl_logic; mod equipement_impl_math; mod equipement_scenario; pub mod equipement_structs; -pub mod equipement_tools; mod equipement_views; // Republishes the most used symbols -- 2.45.1 From 433054dd7e8640ffbd471614f1816bf14280b9be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Tue, 18 Feb 2025 22:01:13 +0100 Subject: [PATCH 43/97] correcting generate_select_query additional blank space and its associated tests --- weaponry/src/database.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index bca6039..54e608f 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -30,14 +30,14 @@ fn generate_select_query( filter: Option<&str>, ) -> String { format!( - "SELECT {} FROM {} {};", + "SELECT {} FROM {}{};", T::attributes_map() .into_iter() .map(|(k, _v)| k) .collect::>() - .join(", "), + .join(","), table_name, - filter.unwrap_or("") + filter.map_or_else(String::default, |j| " ".to_string() + j) ) } @@ -70,7 +70,7 @@ mod test { id: usize, name: String, } - + /// setting up test db and table, also adding arbitrary data inside fn mock_set_up(db_filename: &str) -> EquipementDatabase { let equip_db = EquipementDatabase::new(db_filename).unwrap(); equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",()).unwrap(); @@ -93,11 +93,11 @@ mod test { fn test_generate_query() { assert_eq!( generate_select_query::("TestStruct", None), - "SELECT id, name FROM TestStruct ;" + "SELECT id,name FROM TestStruct;" ); assert_eq!( generate_select_query::("TestStruct", Some("WHERE id=id")), - "SELECT id, name FROM TestStruct WHERE id=id;" + "SELECT id,name FROM TestStruct WHERE id=id;" ); } -- 2.45.1 From 84564a9199a528fd7ecaa52501a9772f764991dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Tue, 18 Feb 2025 22:05:01 +0100 Subject: [PATCH 44/97] rename function to more clear name and adding associated test as todo --- weaponry/src/database.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 54e608f..06903c7 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -43,7 +43,7 @@ fn generate_select_query( /// Generate create table_name with fields as columns /// This function expects a hash map containing (column name, sqlite type) -pub fn generate_database_query(table_name: &str, fields: HashMap) -> String { +pub fn generate_create_table_query(table_name: &str, fields: HashMap) -> String { format!( "CREATE TABLE IF NOT EXISTS {} ({}, PRIMARY KEY('id' AUTOINCREMENT));", table_name, @@ -123,4 +123,10 @@ mod test { ] ) } + + #[ignore = "todo"] + #[test] + fn test_generate_create_table_query() { + todo!() + } } -- 2.45.1 From 65502297b78c8c9db3886fc442d0a4cb8111ffde Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 18 Feb 2025 22:05:53 +0100 Subject: [PATCH 45/97] Switch the macro to be const instead of dynamic --- more_fields/Cargo.toml | 2 ++ more_fields/src/lib.rs | 30 ++++++++++++++----- more_fields_macro/src/lib.rs | 22 ++++++++------ weaponry/src/database.rs | 14 ++++----- weaponry/src/interfaces.rs | 6 ++-- .../equipement_impl_database.rs | 6 ++-- .../weaponry_structs/equipement_structs.rs | 4 +-- 7 files changed, 53 insertions(+), 31 deletions(-) diff --git a/more_fields/Cargo.toml b/more_fields/Cargo.toml index 5783c92..ba443ad 100644 --- a/more_fields/Cargo.toml +++ b/more_fields/Cargo.toml @@ -7,3 +7,5 @@ version.workspace = true more_fields_macro = {path ="../more_fields_macro"} pretty_assertions = "1.4.1" +[features] +expand_macro = [] diff --git a/more_fields/src/lib.rs b/more_fields/src/lib.rs index 8e1408c..6bfd4df 100644 --- a/more_fields/src/lib.rs +++ b/more_fields/src/lib.rs @@ -4,21 +4,37 @@ //! Note that this map is implemented without self, allowing us to use it only as a generic, //! however this limitation is completely artificial -pub use more_fields_macro::FieldsAsMap; +pub use more_fields_macro::FieldsAsSlice; -pub trait FieldsAsMap { - fn attributes_map() -> Vec<(&'static str, &'static str)>; +pub trait FieldsAsSlice { + fn attributes_slice() -> &'static [(&'static str, &'static str)]; } // fn iter(&self) -> std::vec::IntoIter<(&'static str, &'static str)>; +// #[cfg(feature = "expand_macro")] +// #[derive(FieldsAsSlice, Default)] +// struct Bob { +// #[TEXT] +// field_ouane: u16, +// #[INTEGER] +// field_2: u16, +// #[BLOB] +// field_3: u16, +// #[NULL] +// field_4: u16, +// #[REAL] +// field_5: u16, +// field_6: u16, +// } + #[cfg(test)] mod test { - use crate::FieldsAsMap; + use crate::FieldsAsSlice; use pretty_assertions::assert_eq; #[allow(dead_code)] - #[derive(FieldsAsMap, Default)] + #[derive(FieldsAsSlice, Default)] struct Bob { #[TEXT] field_ouane: u16, @@ -34,7 +50,7 @@ mod test { } #[test] fn test_derive_impl() { - println!("{:?}", Bob::attributes_map()); + println!("{:?}", Bob::attributes_slice()); // assert!( let b_hash = vec![ ("field_ouane", "TEXT"), @@ -45,6 +61,6 @@ mod test { ("field_6", "TEXT"), ]; - assert_eq!(Bob::attributes_map(), b_hash); + assert_eq!(Bob::attributes_slice(), b_hash); } } diff --git a/more_fields_macro/src/lib.rs b/more_fields_macro/src/lib.rs index ee2ec15..8f4aca3 100644 --- a/more_fields_macro/src/lib.rs +++ b/more_fields_macro/src/lib.rs @@ -17,10 +17,11 @@ extern crate proc_macro; use proc_macro::{Span, TokenStream}; use quote::quote; use syn::DeriveInput; +use syn::Ident; use syn::parse_macro_input; use syn::{Data, Fields}; -#[proc_macro_derive(FieldsAsMap, attributes(INTEGER, NULL, REAL, TEXT, BLOB))] +#[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB))] pub fn derive_iterable(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); @@ -53,17 +54,20 @@ pub fn derive_iterable(input: TokenStream) -> TokenStream { } }); + let name_of_static_str = struct_name.to_string().to_ascii_uppercase() + "_ATTR_SLICE"; + let name_of_static = Ident::new(&name_of_static_str, Span::call_site().into()); + // static STATIC_FIELDS_OF_STRUCT_#struct_name: std::sync::LazyLock> = // std::sync::LazyLock::new(|| vec![]); - // const FIELD_NAMES_AS_SLICE: &'static [&'static str] = &[#(#fields_iter),*]; - // and add Self::FIELD_NAMES_AS_SLICE - + // let expanded = quote! { - impl FieldsAsMap for #struct_name { - fn attributes_map<'a>() -> Vec<(&'static str, &'static str)> { - vec![ - #(#fields_iter),* - ] + const #name_of_static: &[(&str, &str)] = &[ + #(#fields_iter),* + ]; + + impl FieldsAsSlice for #struct_name { + fn attributes_slice<'a>() -> &'static [(&'static str, &'static str)] { + #name_of_static } } }; diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 06903c7..666364d 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -14,7 +14,7 @@ pub fn get_data( table_name: &str, ) -> Result, serde_rusqlite::Error> where - T: DeserializeOwned + more_fields::FieldsAsMap, + T: DeserializeOwned + more_fields::FieldsAsSlice, { let mut query_result = conn.prepare(&generate_select_query::(table_name, None))?; Ok(serde_rusqlite::from_rows::(query_result.query([])?) @@ -25,15 +25,15 @@ where /// Generate a SELECT query with fields generated from a struct. Returns a String /// filter MUST contain "WHERE" else the query will fail #[inline] -fn generate_select_query( +fn generate_select_query( table_name: &str, filter: Option<&str>, ) -> String { format!( "SELECT {} FROM {}{};", - T::attributes_map() - .into_iter() - .map(|(k, _v)| k) + T::attributes_slice() + .iter() + .map(|(k, _v)| k.to_owned()) .collect::>() .join(","), table_name, @@ -61,11 +61,11 @@ mod test { use crate::{ interfaces::RecipeDatabase, weaponry_structs::equipement_impl_database::EquipementDatabase, }; - use more_fields::FieldsAsMap; + use more_fields::FieldsAsSlice; use pretty_assertions::assert_eq; use serde::Deserialize; - #[derive(FieldsAsMap, Deserialize, Debug, PartialEq)] + #[derive(FieldsAsSlice, Deserialize, Debug, PartialEq)] struct TestStruct { id: usize, name: String, diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 229aa9d..4ef187a 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -7,7 +7,7 @@ use std::{path::Path, rc::Rc}; -use more_fields::FieldsAsMap; +use more_fields::FieldsAsSlice; use serde::de::DeserializeOwned; use crate::error::{EquipementError, FatalEquipementError}; @@ -165,7 +165,7 @@ pub trait RecipeDatabase { Self: std::marker::Sized; /// Serialize a vector of objects of the given type in the specified table of the underlying database - fn serialize_vec_from_table( + fn serialize_vec_from_table( &self, table: &str, ) -> std::result::Result, FatalEquipementError>; @@ -178,7 +178,7 @@ pub trait RecipeDatabase { ) -> std::result::Result, FatalEquipementError>; /// Initialize an empty database & table - fn initialize_empty_table(table: &str) -> Result<(), EquipementError>; + fn initialize_empty_table(table: &str) -> Result<(), EquipementError>; } /// Trait implemented by any struct aiming to be a public recipe diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index a0c7ebc..1e4bd3b 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -19,7 +19,7 @@ pub struct EquipementDatabase { } impl RecipeDatabase for EquipementDatabase { - fn serialize_vec_from_table( + fn serialize_vec_from_table( &self, table: &str, ) -> Result, crate::error::FatalEquipementError> { @@ -43,11 +43,11 @@ impl RecipeDatabase for EquipementDatabase { }) } - fn initialize_empty_table( + fn initialize_empty_table( table: &str, ) -> Result<(), crate::error::EquipementError> { // A vector of - let _attr_map = T::attributes_map(); + let _attr_map = T::attributes_slice(); let _ = table; todo!() diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index cdaa074..781991e 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -5,7 +5,7 @@ use std::rc::Rc; use crate::interfaces::{FilterFunction, FilterFunctionType}; -use more_fields::FieldsAsMap; +use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; use super::{DamageType, SpecialCategory, WeaponCategory}; @@ -55,7 +55,7 @@ impl FilterFunction { /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldsAsMap, Debug, Deserialize, Serialize)] +#[derive(Clone, Default, FieldsAsSlice, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub struct InnerEquipementStats { #[INTEGER] -- 2.45.1 From 36c7c8050b32b39eb098fe967cb1b65c56a611bf Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 18 Feb 2025 22:01:47 +0100 Subject: [PATCH 46/97] Adds doc --- more_fields_macro/src/lib.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/more_fields_macro/src/lib.rs b/more_fields_macro/src/lib.rs index 8f4aca3..4bfca29 100644 --- a/more_fields_macro/src/lib.rs +++ b/more_fields_macro/src/lib.rs @@ -1,6 +1,6 @@ // Workspace: more_fields_macro // File: more_fields_macro/src/lib.rs -//! A very simple proc macro in chage of giving a field iterator over ("name","sql_type") +//! A very simple proc macro in chage of giving a field slice over ("name","sql_type") //! This macro is a fork of the excellent work of : https://crates.io/crates/struct_iterable //! //! Other ressources include: @@ -57,15 +57,15 @@ pub fn derive_iterable(input: TokenStream) -> TokenStream { let name_of_static_str = struct_name.to_string().to_ascii_uppercase() + "_ATTR_SLICE"; let name_of_static = Ident::new(&name_of_static_str, Span::call_site().into()); - // static STATIC_FIELDS_OF_STRUCT_#struct_name: std::sync::LazyLock> = - // std::sync::LazyLock::new(|| vec![]); - // let expanded = quote! { + /// Derived implementation of a (attribute, type) slice + /// allowing a constant time serialisation & deserialisation into rusqlite const #name_of_static: &[(&str, &str)] = &[ #(#fields_iter),* ]; impl FieldsAsSlice for #struct_name { + /// Gives a precompiled slice of the &[(fields: &str, sqlite_type: &str)] fn attributes_slice<'a>() -> &'static [(&'static str, &'static str)] { #name_of_static } -- 2.45.1 From 72edbd4cf0c2b3b25e2d7168b77664693fd0323e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Tue, 18 Feb 2025 22:09:02 +0100 Subject: [PATCH 47/97] removing generate_select_query requierment for WHERE in filter --- weaponry/src/database.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 666364d..a5068ef 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -22,8 +22,7 @@ where .collect()) } -/// Generate a SELECT query with fields generated from a struct. Returns a String -/// filter MUST contain "WHERE" else the query will fail +/// Generate a SELECT query with fields generated from a struct. Returns a SQL request as a String #[inline] fn generate_select_query( table_name: &str, @@ -37,7 +36,7 @@ fn generate_select_query( .collect::>() .join(","), table_name, - filter.map_or_else(String::default, |j| " ".to_string() + j) + filter.map_or_else(String::default, |j| " WHERE ".to_string() + j) ) } @@ -96,7 +95,7 @@ mod test { "SELECT id,name FROM TestStruct;" ); assert_eq!( - generate_select_query::("TestStruct", Some("WHERE id=id")), + generate_select_query::("TestStruct", Some("id=id")), "SELECT id,name FROM TestStruct WHERE id=id;" ); } -- 2.45.1 From d9ab10c0a731bdeddee6bb1bede5602e14a53f2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Tue, 18 Feb 2025 22:29:58 +0100 Subject: [PATCH 48/97] Creating test for generate_create_table_query --- weaponry/src/database.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index a5068ef..ac67e3c 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -6,7 +6,6 @@ #![allow(dead_code)] use rusqlite::{self}; use serde::de::DeserializeOwned; -use std::collections::HashMap; /// Public function to get data from db. Returns the result as a vec with structs pub fn get_data( @@ -42,7 +41,7 @@ fn generate_select_query( /// Generate create table_name with fields as columns /// This function expects a hash map containing (column name, sqlite type) -pub fn generate_create_table_query(table_name: &str, fields: HashMap) -> String { +pub fn generate_create_table_query(table_name: &str, fields: &[(&str, &str)]) -> String { format!( "CREATE TABLE IF NOT EXISTS {} ({}, PRIMARY KEY('id' AUTOINCREMENT));", table_name, @@ -66,7 +65,9 @@ mod test { #[derive(FieldsAsSlice, Deserialize, Debug, PartialEq)] struct TestStruct { + #[INTEGER] id: usize, + #[TEXT] name: String, } /// setting up test db and table, also adding arbitrary data inside @@ -123,9 +124,11 @@ mod test { ) } - #[ignore = "todo"] #[test] fn test_generate_create_table_query() { - todo!() + let query = generate_create_table_query("TestStruct", TestStruct::attributes_slice()); + assert_eq!( + query, "CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER,name TEXT, PRIMARY KEY('id' AUTOINCREMENT));".to_string() + ) } } -- 2.45.1 From c9c6cbe40e2cc9867bf2b85d4abfa904c6ebfca1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Tue, 18 Feb 2025 22:43:20 +0100 Subject: [PATCH 49/97] Adding new field filter to serialize_vec_from_table and correcting all associated declarations and usages --- weaponry/src/database.rs | 5 +++-- weaponry/src/interfaces.rs | 10 ++-------- .../equipement_impl_database.rs | 14 ++------------ .../src/weaponry_structs/equipement_scenario.rs | 17 +++-------------- 4 files changed, 10 insertions(+), 36 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index ac67e3c..a372c66 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -11,11 +11,12 @@ use serde::de::DeserializeOwned; pub fn get_data( conn: &rusqlite::Connection, table_name: &str, + filter: Option<&str>, ) -> Result, serde_rusqlite::Error> where T: DeserializeOwned + more_fields::FieldsAsSlice, { - let mut query_result = conn.prepare(&generate_select_query::(table_name, None))?; + 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()) @@ -106,7 +107,7 @@ mod test { let filename = "test.db"; let conn = mock_set_up(filename); let result = conn - .serialize_vec_from_table::("TestStruct") + .serialize_vec_from_table::("TestStruct", None) .unwrap(); tear_down(filename, conn.conn); assert_eq!( diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 4ef187a..9e5f02c 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -164,17 +164,11 @@ pub trait RecipeDatabase { where Self: std::marker::Sized; - /// Serialize a vector of objects of the given type in the specified table of the underlying database + /// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database fn serialize_vec_from_table( &self, table: &str, - ) -> std::result::Result, FatalEquipementError>; - - /// Serialize a specified vector of objects of the given type with an additionnal restriction - fn serialize_vec_from_table_with_query( - &self, - table: &str, - query: &str, + filter: Option<&str>, ) -> std::result::Result, FatalEquipementError>; /// Initialize an empty database & table diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 1e4bd3b..6123195 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -22,18 +22,9 @@ impl RecipeDatabase for EquipementDatabase { fn serialize_vec_from_table( &self, table: &str, + filter: Option<&str>, ) -> Result, crate::error::FatalEquipementError> { - Ok(get_data(&self.conn, table)?) - } - - fn serialize_vec_from_table_with_query( - &self, - table: &str, - query: &str, - ) -> Result, crate::error::FatalEquipementError> { - let _ = table; - let _ = query; - todo!() + Ok(get_data(&self.conn, table, filter)?) } /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. @@ -48,7 +39,6 @@ impl RecipeDatabase for EquipementDatabase { ) -> Result<(), crate::error::EquipementError> { // A vector of let _attr_map = T::attributes_slice(); - let _ = table; todo!() } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index c343129..19f96bf 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -23,18 +23,10 @@ impl RecipeDatabase for DatabaseMock { fn serialize_vec_from_table( &self, table: &str, + filter: Option<&str>, ) -> std::result::Result, crate::error::FatalEquipementError> { let _ = table; - unimplemented!() - } - - fn serialize_vec_from_table_with_query( - &self, - table: &str, - query: &str, - ) -> std::result::Result, FatalEquipementError> { - let _ = table; - let _ = query; + let _ = filter; unimplemented!() } @@ -95,10 +87,7 @@ impl Scenario for CrossRecipeScenario { fn generate_refined_recipes(&self) -> Self::FinalListType { let _all_parts = &self .database - .serialize_vec_from_table_with_query::( - "bob", - "WHERE CATEGOTY == 'Bobitty'", - ); + .serialize_vec_from_table::("bob", Some("CATEGOTY == 'Bobitty'")); todo!() } -- 2.45.1 From dfa806acef4295c4ee176ec1bb88f0cc562868a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Tue, 18 Feb 2025 22:57:41 +0100 Subject: [PATCH 50/97] implement initialize_empty_table --- weaponry/src/interfaces.rs | 5 ++++- .../src/weaponry_structs/equipement_impl_database.rs | 12 +++++++----- weaponry/src/weaponry_structs/equipement_scenario.rs | 2 +- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 9e5f02c..a949259 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -172,7 +172,10 @@ pub trait RecipeDatabase { ) -> std::result::Result, FatalEquipementError>; /// Initialize an empty database & table - fn initialize_empty_table(table: &str) -> Result<(), EquipementError>; + fn initialize_empty_table( + &self, + table: &str, + ) -> Result<(), FatalEquipementError>; } /// Trait implemented by any struct aiming to be a public recipe diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 6123195..563d3fe 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -6,7 +6,7 @@ // use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; -use crate::database::get_data; +use crate::database::{generate_create_table_query, get_data}; use crate::error::FatalEquipementError; use crate::interfaces::RecipeDatabase; use rusqlite::Connection; @@ -35,11 +35,13 @@ impl RecipeDatabase for EquipementDatabase { } fn initialize_empty_table( + &self, table: &str, - ) -> Result<(), crate::error::EquipementError> { + ) -> Result<(), crate::error::FatalEquipementError> { // A vector of - let _attr_map = T::attributes_slice(); - let _ = table; - todo!() + let attr_map = T::attributes_slice(); + self.conn + .execute(generate_create_table_query(table, attr_map).as_str(), ())?; + Ok(()) } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 19f96bf..f651d3c 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -38,7 +38,7 @@ impl RecipeDatabase for DatabaseMock { unimplemented!() } - fn initialize_empty_table(table: &str) -> Result<(), EquipementError> { + fn initialize_empty_table(&self, table: &str) -> Result<(), FatalEquipementError> { let _ = table; unimplemented!() } -- 2.45.1 From 3af43de27eaa07099ecae5695bd9772641cc5051 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 18 Feb 2025 22:59:42 +0100 Subject: [PATCH 51/97] Implements a part of the scenarios --- weaponry/src/interfaces.rs | 4 +- .../weaponry_structs/equipement_scenario.rs | 51 +++++++++++++++---- .../src/weaponry_structs/equipement_views.rs | 2 +- 3 files changed, 44 insertions(+), 13 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index a949259..8168595 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -29,7 +29,7 @@ pub trait ViewTable { fn index_of_interest_points(&self) -> Vec; /// Interrogate the FinalRepresentation to find interesting elements - fn find_points_of_interest(&self, representation: &Self::InterestElementList); + fn find_points_of_interest(representation: &Self::InterestElementList) -> Self; // An alternative, non Self::Typed way of doing since there is only one usage for now // fn find_points_of_interest(&self, representation: &impl FinalRepresentation); } @@ -241,7 +241,7 @@ pub trait Scenario { // fn refine_recipes(&self); /// Generate the final list type - fn generate_refined_recipes(&self) -> Self::FinalListType; + fn generate_refined_recipes(&self) -> Result; /// Gather the selected view tables /// All the inner generation is done gradually and populate all section to finally generate the views diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index f651d3c..af7098c 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -9,10 +9,13 @@ #![allow(dead_code)] +use crate::weaponry_structs::Equipement; +use crate::weaponry_structs::InitialEquipementList; +use crate::weaponry_structs::equipement_structs::InnerEquipementStats; use crate::{ error::{EquipementError, FatalEquipementError}, - interfaces::{RecipeDatabase, Scenario, ViewTable}, - weaponry_structs::equipement_structs::InnerEquipementStats, + interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable}, + weaponry_structs::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}, }; use super::equipement_advanced_repr::RefinedEquipementList; @@ -54,7 +57,7 @@ impl ViewTable for ViewtableMock { todo!() } - fn find_points_of_interest(&self, representation: &Self::InterestElementList) { + fn find_points_of_interest(representation: &Self::InterestElementList) -> Self { let _ = representation; todo!() } @@ -67,6 +70,22 @@ pub struct CrossRecipeScenario { config: ConfigMock, } +/// Automatically deserialize into an equipement +// TODO: This macro only exists because no blanket implementation or function does this *relatively* easy step +macro_rules! deserde_into_equipement { + ( $db:expr, $name:expr, $type:ident) => { + InitialEquipementList::from_vectored( + $db.serialize_vec_from_table::( + "Equipement", + Some(&format!("CATEGORY == {}", $name)), + )? + .into_iter() + .map(|eq| $type { stats: eq }.into()) + .collect::>(), + ) + }; +} + impl Scenario for CrossRecipeScenario { type DatabaseType = DatabaseMock; type ViewTableType = ViewtableMock; @@ -84,15 +103,27 @@ impl Scenario for CrossRecipeScenario { }) } - fn generate_refined_recipes(&self) -> Self::FinalListType { - let _all_parts = &self - .database - .serialize_vec_from_table::("bob", Some("CATEGOTY == 'Bobitty'")); - todo!() + 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_nature = deserde_into_equipement!(self.database, "Nature", EqNature); + let eq_finishing = deserde_into_equipement!(self.database, "Finishing", EqFinishing); + + // No op, just clarity + // TODO: Depending on config this step might differ + let mut f_list = eq_shape; + f_list.combine_all(&eq_material); + f_list.combine_all(&eq_nature); + f_list.combine_all(&eq_finishing); + + // This oneline is neat + Ok(f_list.into()) } fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType { - let _ = equipement_list; - todo!() + // TODO: Change this depending on the config ? or maybe a scenario is inerently tied to a viewtable ? + // The polymorphism will depend on many factors not yet known :( + Self::ViewTableType::find_points_of_interest(&equipement_list) } } diff --git a/weaponry/src/weaponry_structs/equipement_views.rs b/weaponry/src/weaponry_structs/equipement_views.rs index f1162c7..f217e98 100644 --- a/weaponry/src/weaponry_structs/equipement_views.rs +++ b/weaponry/src/weaponry_structs/equipement_views.rs @@ -21,7 +21,7 @@ impl ViewTable for EquipementFullView { todo!() } - fn find_points_of_interest(&self, representation: &Self::InterestElementList) { + fn find_points_of_interest(representation: &Self::InterestElementList) -> Self { let _ = representation; todo!() } -- 2.45.1 From 8bb6d09b15ecc72477827e9a7339c1a2a1290296 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 18 Feb 2025 23:50:22 +0100 Subject: [PATCH 52/97] Lay the groundwork for the database intermediate object representation --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/serde_loading.rs | 27 ++++++++++ .../equipement_impl_database.rs | 1 + .../weaponry_structs/equipement_structs.rs | 49 +++++++++++++++--- 4 files changed, 70 insertions(+), 7 deletions(-) create mode 100644 weaponry/examples/serde_loading.rs diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index f361221defc013df358aa2cb237d2de131edd91b..9ddfd1985b8da960e01c8e1208ff646d29976378 100644 GIT binary patch literal 28672 zcmeI)O>f&a7zc34Z;IV!E|6_TkPcvcsf}bsi*_r9qG+9l&4fB~YRl__9Rx;VTw%84 z$n?@;r*s{#eT03Mop;!WSU*KiJB@m=WqU}M0=;@+D!4w9Pd z5Zy589&K-XY`}?0zcsf57P#WYw8HjBV!GqF$H%Tc?$6WrY$8*RsTmVKS0o;0tbx z*~__};Jvx=2|qX)b4#51)-&cgJS9nLe2*{IIKDGGN)`mE*J#LR&M^|4^~JMkjJ6EA z=ga01wO~Pyi?}TN+2LrS3Km6e&DjUM?=vSpmfR?BCJNSb`|`e7N4_^6O|M4|+WLN@ zeMlbD!`e01xkegYv!xp{ANHwX*6WvVWNvPJzPWPtqX^tyj|UF#bHS~V2*$RsTu1jj z9&`i~qe%|6^*xy}WU(PB5xF!TnX+z|HmOXvmO;|)r5(Db8&RXA`cb>JPjtZtx5}{jnT4KaEc} z3o%y{S)3`WT4jA*J^L=2MTT@{ZYz<`94Y1Rwwb2tWV=5P$##AOHafER{ehj8?w?FaKSBvs8g2 zSO`D>0uX=z1Rwwb2tWV=5P$##E+CN4s_M$hA1mut8Uk4=utA{Gch z00Izz00bZa0SG_<0uX=z1eR8ykXJC^dkv-Cbrk+`c-=sL<=MhaIXxfkpbk2o?iD zZ5A@_Yqi3|M;d^I$AwiF6z~6o2g=^o-LNm2hb0vZyPD#=2}>Rav>3r!X}i`98VD|_ zE&KamzNF5;R3sM%4Qk0lZtY>8P@)<9u-vErv4oSqxkSm311y9-_AsD*mxhvJSMF&> zwuFgwL55P$zYv36LbvY(hd62;VUwcV+*kP_(3#-okM)>QWna!#t1UUfE z2YOM<_Kf1yk(("Eq_test") + .unwrap(); + let v = db.serialize_vec_from_table::("InnerStats", None); + db.conn + .execute( + "INSERT INTO example (id, name) VALUES (?,?)", + to_params(InnerEquipementStats::random_new()).unwrap(), + ) + .unwrap(); + // let mut r = db.conn.prepare("SELECT * FROM InnerStats").unwrap(); + // let mut v = r.query([]).unwrap(); + // println!("{:?}:\n {:#?}", db, r); + + println!("{:?}", v); +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 563d3fe..7b4aa33 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -13,6 +13,7 @@ use rusqlite::Connection; use serde::de::DeserializeOwned; /// Struct for database connection. +#[derive(Debug)] pub struct EquipementDatabase { /// Connection parameter for rusqlite pub conn: rusqlite::Connection, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 781991e..5fc278a 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -52,15 +52,50 @@ impl FilterFunction { Self(Box::new(Rc::new(filter))) } } - /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Default, FieldsAsSlice, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub struct InnerEquipementStats { - #[INTEGER] 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) precision: i8, + pub(super) rmax: u8, + pub(super) armor_break: u8, + pub(super) armor_pierce: u8, + pub(super) antimaterial: u8, + 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) special: SpecialCategory, + pub(super) action_cost: u8, + pub(super) reload_cost: Option, + pub(super) range: u8, + pub(super) agility_bonus: u8, +} + +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Default, FieldsAsSlice, Debug, Deserialize, Serialize)] +#[cfg_attr(test, derive(PartialEq))] +pub struct DatabaseEquipementStats { + #[INTEGER] + pub id: u8, + pub meta_category: String, + pub name: String, #[INTEGER] pub(super) rarity: u8, #[INTEGER] @@ -83,7 +118,7 @@ pub struct InnerEquipementStats { pub(super) armor_pierce: u8, #[INTEGER] pub(super) antimaterial: u8, - pub(super) damage_type: Option, + pub(super) damage_type: String, #[INTEGER] pub(super) protection: u8, #[INTEGER] @@ -100,12 +135,12 @@ pub struct InnerEquipementStats { pub(super) speed: u8, #[INTEGER] pub(super) stealth: u8, - pub(super) category: Option, - pub(super) target: Option, - pub(super) special: SpecialCategory, + pub(super) category: String, + pub(super) target: String, + pub(super) special: String, #[INTEGER] pub(super) action_cost: u8, - pub(super) reload_cost: Option, + pub(super) reload_cost: String, #[INTEGER] pub(super) range: u8, #[INTEGER] -- 2.45.1 From c97425cb6f832af573d65fbd8f2750bcc46df16e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 19 Feb 2025 09:28:59 +0100 Subject: [PATCH 53/97] Implements a little of the needed database serde --- weaponry/Cargo.toml | 2 +- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/serde_loading.rs | 65 ++++++++-- weaponry/src/error.rs | 6 +- weaponry/src/interfaces.rs | 5 +- .../src/weaponry_structs/equipement_fields.rs | 36 +----- .../equipement_impl_database.rs | 41 +++++++ .../weaponry_structs/equipement_scenario.rs | 12 +- .../weaponry_structs/equipement_structs.rs | 115 +++++++++++++----- weaponry/src/weaponry_structs/mod.rs | 3 +- 10 files changed, 205 insertions(+), 80 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 184e041..915b59d 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -10,7 +10,7 @@ csv = "1.3.1" fastrand = "2.3.0" pretty_assertions = "1.4.1" probability = "0.20.3" -rusqlite = { version = "0.33.0", features = ["bundled"] } +rusqlite = { version = "0.33.0" } # , features = ["bundled"] serde = { version = "1.0.217", features = ["derive"] } serde_rusqlite = "0.37.0" serde_json = { version = "1.0.138", features = ["alloc"] } diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 9ddfd1985b8da960e01c8e1208ff646d29976378..f0862ffbb83007ef0f13f8c1e7db1b49184fdc40 100644 GIT binary patch delta 674 zcmZp8z}WDBae}m<0RsaAI}o!0F$)k|Ow=(33hIS>@$wijFmc~w;J(MZYGc7+ZpNyK zjozExVC4&9;J?pr$G?NW zjxPuVHwy~b@YP2&*2y#Q@^SzHBO{39FlPc&92~N;>KuZM9Nc-))k*P zoRL_Ns>kpnuQVqo4n%-(bS#KuIBDL<3=1tLh)$p$2ml+v$iZ;c6Rh+;s#YddeYi%5 z4xl4}zz~R`PG-2s@YdK~o&lx~Vk`&Pxga)J83)HE1r`AgM*epU{O|bh0^{%zzmNbU bvoaG>nqc_1$w6FzkqIdKkbm>fcy<8*6>gcv delta 178 zcmZp8z}WDBae}m<3("Eq_test") - .unwrap(); - let v = db.serialize_vec_from_table::("InnerStats", None); - db.conn - .execute( - "INSERT INTO example (id, name) VALUES (?,?)", - to_params(InnerEquipementStats::random_new()).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); - - println!("{:?}", v); } diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index eb1471c..a410c4d 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -10,8 +10,12 @@ use thiserror::Error; pub enum FatalEquipementError { #[error("Rusqlite failed to connect to the given path {0}")] RusqliteConnection(#[from] rusqlite::Error), - #[error("Deserialization from object : {0}")] + + #[error("Deserialization from object failed : {0}")] SerdeRusqlite(#[from] serde_rusqlite::Error), + + #[error("Deserialisation from json failed : {0}")] + SerdeJSON(#[from] serde_json::Error), } #[derive(Error, Debug)] diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 8168595..a1d1ffc 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -165,11 +165,12 @@ pub trait RecipeDatabase { Self: std::marker::Sized; /// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database - fn serialize_vec_from_table( + /// The FROM type is the original data, directly deserialized from the table + fn serialize_vec_from_table( &self, table: &str, filter: Option<&str>, - ) -> std::result::Result, FatalEquipementError>; + ) -> std::result::Result, FatalEquipementError>; /// Initialize an empty database & table fn initialize_empty_table( diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index b8a9904..af2ebe1 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -10,7 +10,8 @@ use strum::Display; #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only -pub struct SpecialCategory(pub(super) Vec); +// TODO: avoid pub make an impl ? +pub struct SpecialCategory(pub Vec); /// The kind of target this nature can apply to #[derive(Clone)] @@ -24,7 +25,7 @@ pub enum NatureTarget { } /// Enum of all different physical weapon damage types -#[allow(clippy::missing_docs_in_private_items)] +#[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { @@ -32,13 +33,6 @@ pub enum PhysicalDamageType { Slash, Pierce, } -impl From<&str> for PhysicalDamageType { - fn from(value: &str) -> Self { - let _ = value; - // Matchcase for all damage types - todo!() - } -} /// Weapon damage, combining the base weapon damage type and it's level /// @@ -52,21 +46,15 @@ pub enum DamageMod { Tertiary(PhysicalDamageType), } -impl From<&str> for DamageMod { - fn from(value: &str) -> Self { - let _ = value; - // Detect [] and recurse from - todo!() - } -} - /// Combined damage type, as a vector of all damage types /// /// Meant to be serialised to tex and deserialized directly from the table #[derive(Clone, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] -pub struct DamageType(pub(super) Vec); +// TODO: avoid pub make an impl ? +pub struct DamageType(pub Vec); +// TODO: Find a better way to make an easy creation at least for tests impl From<&str> for DamageType { fn from(value: &str) -> Self { let _ = value; @@ -109,18 +97,6 @@ pub enum WeaponCategory { Cannon, } -impl From<&str> for WeaponCategory { - fn from(value: &str) -> Self { - let _ = value; - todo!() - } -} - -// TODO: Consider this for test -// impl Equipement{ -// fn random_equipement(){} -// } - #[cfg(test)] mod test { // use super::*; diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 7b4aa33..26659fd 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -12,6 +12,8 @@ use crate::interfaces::RecipeDatabase; use rusqlite::Connection; use serde::de::DeserializeOwned; +use super::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; + /// Struct for database connection. #[derive(Debug)] pub struct EquipementDatabase { @@ -46,3 +48,42 @@ impl RecipeDatabase for EquipementDatabase { Ok(()) } } + +// #[allow(clippy::useless_conversion)] +impl TryFrom for InnerEquipementStats { + type Error = FatalEquipementError; + + fn try_from(value: DatabaseEquipementStats) -> Result { + Ok(Self { + id: vec![value.id], // Special case where manual is better than serde + name: vec![value.name], + rarity: value.rarity, // Generic case, into(), serde or cast are equivalent + cost: value.cost, + difficulty: value.difficulty, + tier: value.tier, + damage: value.damage, + p_damage: value.p_damage, + precision: value.precision, + rmax: value.rmax, + 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 + protection: value.protection, + integrity: value.integrity, + torque_two_handed: value.torque_two_handed, + torque_one_handed: 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)?, + action_cost: value.action_cost, + reload_cost: serde_json::from_str(&value.reload_cost)?, + range: value.range, + agility_bonus: value.agility_bonus, + }) + } +} diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index af7098c..1d7f81e 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -11,7 +11,7 @@ use crate::weaponry_structs::Equipement; use crate::weaponry_structs::InitialEquipementList; -use crate::weaponry_structs::equipement_structs::InnerEquipementStats; +use crate::weaponry_structs::equipement_structs::DatabaseEquipementStats; use crate::{ error::{EquipementError, FatalEquipementError}, interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable}, @@ -72,15 +72,21 @@ pub struct CrossRecipeScenario { /// 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 macro_rules! deserde_into_equipement { ( $db:expr, $name:expr, $type:ident) => { InitialEquipementList::from_vectored( - $db.serialize_vec_from_table::( + $db.serialize_vec_from_table::( "Equipement", Some(&format!("CATEGORY == {}", $name)), )? .into_iter() - .map(|eq| $type { stats: eq }.into()) + .map(|eq| { + $type { + stats: eq.try_into().unwrap(), + } + .into() + }) .collect::>(), ) }; diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 5fc278a..0fd7c2d 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -54,7 +54,7 @@ impl FilterFunction { } /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldsAsSlice, Debug, Deserialize, Serialize)] +#[derive(Clone, Default, FieldsAsSlice, Debug)] #[cfg_attr(test, derive(PartialEq))] pub struct InnerEquipementStats { pub id: Vec, @@ -88,8 +88,12 @@ pub struct InnerEquipementStats { pub(super) agility_bonus: u8, } +// TODO: This implementation of default is painfull +// TODO: Have either an auto-macro implementation or a manual one +// TODO: This implementation is Quasi-redondant +// TODO: Have a way to limit code duplication #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldsAsSlice, Debug, Deserialize, Serialize)] +#[derive(Clone, FieldsAsSlice, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] pub struct DatabaseEquipementStats { #[INTEGER] @@ -97,54 +101,91 @@ pub struct DatabaseEquipementStats { pub meta_category: String, pub name: String, #[INTEGER] - pub(super) rarity: u8, + pub rarity: u8, #[INTEGER] - pub(super) cost: u8, + pub cost: u8, #[INTEGER] - pub(super) difficulty: u8, + pub difficulty: u8, #[INTEGER] - pub(super) tier: u8, + pub tier: u8, #[INTEGER] - pub(super) damage: u8, + pub damage: u8, #[INTEGER] - pub(super) p_damage: u8, + pub p_damage: u8, #[INTEGER] - pub(super) precision: i8, + pub precision: i8, #[INTEGER] - pub(super) rmax: u8, + pub rmax: u8, #[INTEGER] - pub(super) armor_break: u8, + pub armor_break: u8, #[INTEGER] - pub(super) armor_pierce: u8, + pub armor_pierce: u8, #[INTEGER] - pub(super) antimaterial: u8, - pub(super) damage_type: String, + pub antimaterial: u8, + pub damage_type: String, #[INTEGER] - pub(super) protection: u8, + pub protection: u8, #[INTEGER] - pub(super) integrity: u8, + pub integrity: u8, #[INTEGER] - pub(super) torque_two_handed: u8, + pub torque_two_handed: u8, #[INTEGER] - pub(super) torque_one_handed: u8, + pub torque_one_handed: u8, #[INTEGER] - pub(super) dodge: u8, + pub dodge: u8, #[INTEGER] - pub(super) parry: u8, + pub parry: u8, #[INTEGER] - pub(super) speed: u8, + pub speed: u8, #[INTEGER] - pub(super) stealth: u8, - pub(super) category: String, - pub(super) target: String, - pub(super) special: String, + pub stealth: u8, + pub category: String, + pub target: String, + pub special: String, #[INTEGER] - pub(super) action_cost: u8, - pub(super) reload_cost: String, + pub action_cost: u8, + pub reload_cost: String, #[INTEGER] - pub(super) range: u8, + pub range: u8, #[INTEGER] - pub(super) agility_bonus: u8, + pub agility_bonus: u8, +} + +impl Default for DatabaseEquipementStats { + fn default() -> Self { + Self { + id: 0, + meta_category: "EqShape".to_string(), + name: String::new(), + damage_type: 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(), + rarity: 0, + cost: 0, + difficulty: 0, + tier: 0, + damage: 0, + p_damage: 0, + precision: 0, + rmax: 0, + armor_break: 0, + armor_pierce: 0, + antimaterial: 0, + protection: 0, + integrity: 0, + torque_two_handed: 0, + torque_one_handed: 0, + dodge: 0, + parry: 0, + speed: 0, + stealth: 0, + range: 0, + agility_bonus: 0, + action_cost: 0, + } + } } #[allow(dead_code)] @@ -152,7 +193,7 @@ pub struct DatabaseEquipementStats { #[doc(hidden)] macro_rules! r { () => { - fastrand::u8(1..10) + fastrand::u8(1..u8::MAX) }; } // TODO: Make this a test requirement or hide it behind a profile @@ -169,6 +210,20 @@ impl InnerEquipementStats { } } } +// TODO: Make this a test requirement or hide it behind a profile +impl DatabaseEquipementStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: r!(), + range: r!(), + damage: r!(), + p_damage: r!(), + protection: r!(), + ..Default::default() + } + } +} /// Shape of the equipement, first mandatory part of an equipement #[derive(Default)] diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index dfdbad8..d9203c8 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -32,5 +32,6 @@ mod equipement_views; pub use equipement_structs::{Equipement, InitialEquipementList}; // All generic fields -#[allow(unused_imports)] +// #[allow(unused_imports)] +pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory}; -- 2.45.1 From 58061b8b9b5ca073ae61ab5ff76c1c47d8848a76 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 19 Feb 2025 09:54:50 +0100 Subject: [PATCH 54/97] Adds a mock implementation of fixed recipes --- weaponry/src/interfaces.rs | 21 +++++++-------- .../src/weaponry_structs/equipement_fields.rs | 9 ------- .../equipement_impl_database.rs | 26 ++++++++++++++++++- .../weaponry_structs/equipement_scenario.rs | 8 ++++++ 4 files changed, 43 insertions(+), 21 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index a1d1ffc..92126cf 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -150,13 +150,6 @@ pub trait ToCSV { fn write_csv(&self, path: &Path) -> csv::Result<()>; } -/// Garanties that a struct can be generated from a database -#[deprecated] -pub trait DbSerializable { - /// Serialize the object from a database - fn from_database() -> Self; -} - /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { /// Create the database from a file @@ -177,19 +170,25 @@ pub trait RecipeDatabase { &self, table: &str, ) -> Result<(), FatalEquipementError>; + + /// Insert a row inside the database, while mostly unused this function is needed to initialize the empty table with an empty row if needed + fn insert_row(&self, row: T) -> Result<(), FatalEquipementError>; } /// Trait implemented by any struct aiming to be a public recipe pub trait FixedRecipe { - /// Struct representing the database type, most likely a string - type Database; + // /// Struct representing the database type, most likely a string + // type Database; /// Struct representing the keylist type, most likely a usize - type KeyList; + type KeyList; // TODO: Add the restriction &traits to use the result afterwards /// Get the list of elements corresponding to the recipe /// /// These elements will either be iteratively fetched from the database or scoured through in the data depending on the scenario - fn get_elements() -> Vec<(Self::Database, Self::KeyList)>; + fn get_elements_from_table( + &self, + table: &str, + ) -> Result, FatalEquipementError>; } /// Trait ensuring a status report can be inferred from the structure diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index af2ebe1..e1d9e1b 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -54,15 +54,6 @@ pub enum DamageMod { // TODO: avoid pub make an impl ? pub struct DamageType(pub Vec); -// TODO: Find a better way to make an easy creation at least for tests -impl From<&str> for DamageType { - fn from(value: &str) -> Self { - let _ = value; - // Split by , then recurse from and collect - todo!() - } -} - impl Display for DamageType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 26659fd..47afd3f 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -8,7 +8,7 @@ use crate::database::{generate_create_table_query, get_data}; use crate::error::FatalEquipementError; -use crate::interfaces::RecipeDatabase; +use crate::interfaces::{FixedRecipe, RecipeDatabase}; use rusqlite::Connection; use serde::de::DeserializeOwned; @@ -47,6 +47,30 @@ impl RecipeDatabase for EquipementDatabase { .execute(generate_create_table_query(table, attr_map).as_str(), ())?; Ok(()) } + + fn insert_row(&self, row: T) -> Result<(), FatalEquipementError> { + let _ = row; + todo!() + } +} +#[allow(missing_docs)] +pub struct EquipementFixedRecipe { + pub conn: rusqlite::Connection, +} + +#[allow(missing_docs)] +pub struct MockRecipe {} + +impl FixedRecipe for EquipementFixedRecipe { + type KeyList = MockRecipe; + + fn get_elements_from_table( + &self, + table: &str, + ) -> Result, FatalEquipementError> { + let _ = table; + todo!() + } } // #[allow(clippy::useless_conversion)] diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 1d7f81e..5670c0f 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -45,6 +45,14 @@ impl RecipeDatabase for DatabaseMock { let _ = table; unimplemented!() } + + fn insert_row( + &self, + row: T, + ) -> Result<(), FatalEquipementError> { + let _ = row; + todo!() + } } /// Mock config pub struct ConfigMock {} -- 2.45.1 From 5738f0fd74ff34d3916cfc37b67526c9cbfad51f Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 20 Feb 2025 02:20:05 +0100 Subject: [PATCH 55/97] Wip on the firt import fn --- more_fields/Cargo.toml | 2 + weaponry/Cargo.toml | 3 +- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/.rustfmt.toml | 1 + weaponry/examples/serde_loading.rs | 175 ++++++++++++++++++++++------- 5 files changed, 141 insertions(+), 40 deletions(-) create mode 100644 weaponry/examples/.rustfmt.toml 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..56c961e 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"] } @@ -19,6 +18,8 @@ thiserror = "2.0.11" [dev-dependencies] criterion = { version = "0.5" } +regex = "1.11.1" +pretty_assertions = "^1.4" [[bench]] name = "iter_creation" diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index f0862ffbb83007ef0f13f8c1e7db1b49184fdc40..5fea0f35eea85fe0ae67cd0919efb5579bfde3e7 100644 GIT binary patch delta 671 zcmZXRKTpCy7>9d*fIGA;Xb2&gpd^kYKwKS4qq3N|8xt!Yk))_;X>==&ZaOpRq;WEi zj(iCw!#D6N_+DE=@osq28{VhS?|0)l8qd*F70sTvY&82ke=#eXrg43uncwEUxo7+u zAI7DztN-Yeubsk!9$LJnm8&c{h_NDqAy2hbWF^K9Z@i(fykX!8pEO!HU$AkzjTTwkP$(S&luBg6Wv18!L{?0ukGIozK?rHmbyHzj z7#Q%3QK?IlMVdkKz+J~5Q7k?3s)vo1X&}#{5yV$Kj=Vv?FMLefm}H3}^16NU2Xaw} AWdHyG delta 483 zcmZp8z}WDBae_3X!9*EnMuUwB3;9L))-tg21u^j7=eOhE!C%K01cI9d6>RwGBO2@E z8F+a)fPj$^L~@ujfhi6SSy^=sK}HVlyy$ABfTGOY#G*8V9ZFgjW(FF#*NM=1$N#u^%_GB7YqgqjR7(i~y|+~jPA7xh@pHi8)mqtT3x1R8w< z)o7Tbd4a;bj2zw!AF-Hhrzp=L4e={Py=XnmNur{H9HLAdu7$xFi3O>83_tQpb8_N9 z1PDjRf=Gsw=8ep-&|-q<1nPkRumOx53|BqDO7Ej;Wm46LYlP?kIuZyBff(v!hKmeu ZjqT+bVCo>oa)6x+VuO`&a4b>?000xhVN?JB 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/serde_loading.rs b/weaponry/examples/serde_loading.rs index d9dde9f..c5de52f 100644 --- a/weaponry/examples/serde_loading.rs +++ b/weaponry/examples/serde_loading.rs @@ -4,31 +4,92 @@ //! use more_fields::FieldsAsSlice; +use serde::Serialize; use serde_rusqlite::to_params_named; use weaponry::interfaces::RecipeDatabase; +use weaponry::weaponry_structs::WeaponCategory; use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase; -use weaponry::weaponry_structs::equipement_structs::{ - DatabaseEquipementStats, InnerEquipementStats, -}; +use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; +// const BASE_DATA: &[[&str; 17]] = &[ +// // {Forme} & {Maniement} & {\damagew} & + & {R.Max} & \arbreakw & \protection & \integrite & $\mathbb{T}$2 & $\mathbb{T}$1 & {Modes} & {Esq.} & {Par.} & {Vit.} & {Disc.} & {Spécial} & {Diff.} \\ +// // % Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff +// ["Griffes", "Tranchantes", "2", "1", "4", "1", "1", "2", "3", "6", "slash", "2", "0", "3", "1", "-", "1"], +// ["Hast", "Hast", "4", "1", "2", "1", "4", "3", "10", "18", "pierce, [slash]", "-1", "-3", "1", "0", "-", "1"], +// ["Épée", "Tranchantes", "3", "1", "3", "1", "3", "4", "12", "15", "slash, [pierce]", "0", "1", "0", "0", "-", "1"], +// ["Marteau", "Contondantes", "5", "1", "1", "1", "4", "3", "11", "18", "blunt", "-1", "-1", "0", "-2", "-", "1"], +// ["Hache", "Tranchantes", "4", "2", "1", "3", "4", "3", "9", "14", "slash", "0", "-1", "1", "0", "-", "1"], +// ["Arbalète", "Distance", "4", "1", "3", "0", "3", "1", "8", "16", "pierce", "-1", "-1", "0", "-1", "2reload, Gls{parmure} 2, 80m", "1"], +// ["Arc", "Distance", "3", "1", "4", "0", "2", "1", "-", "7", "pierce", "0", "0", "0", "0", "1reload, Gls{parmure} 2, 120m", "1"], +// ["Biers", " -", "1", "1", "2", "0", "3", "2", "6", "8", "blunt", "-2", "0", "-1", "-2", "-", "1"], +// ["Armures", " -", " ", " ", " ", " ", "3", "2", "10", "-", "blunt", "-1", "0", "0", "-1", "-", "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}" +// ]; +// +const BASE_FORME: &[&str] = &[ + // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", + "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 & - & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ", + "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} ", +]; 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); + let mut global_index = 0; + let b = load_base(&mut global_index); + // println!("{b:?}"); // Equipements - db.initialize_empty_table::("Equipements") - .unwrap(); + let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); + db.initialize_empty_table::("Equipements").unwrap(); + db.conn.execute("DELETE FROM Equipements", []).unwrap(); + println!("Processed {global_index} ids"); + b.iter().for_each(|v| database_shnn(&db, v)); + let v = db.serialize_vec_from_table::("Equipements", None); + println!("{:#?}", v); + + // Final deserialisation + let final_s = v.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); + let v = final_s + .iter() + .scan(0, |status, eq| { + if eq.is_ok() { + *status += 1; + } + Some(*status) + }) + .sum::(); + println!("{:#?}, {:#?}", final_s, v); +} + +#[allow(dead_code)] +#[derive(Default)] +struct FoundFields { + reload: Option, + range: Option, + parmor: Option, +} +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 database_shnn(db: &EquipementDatabase, row: T) { + // let mut row = DatabaseEquipementStats::random_new(); let sql = &format!( "INSERT INTO Equipements ({}) VALUES ({})", @@ -45,24 +106,60 @@ fn main() { .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); + // println!("{}", sql); + let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice()); + println!("Loaded {:?} entries into the database", r); +} + +fn load_base(index: &mut u8) -> Vec { + // 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(); + BASE_FORME + .iter() + .map(|row| { + let fields = row.split("&").map(|field| field.trim()).collect::>(); + let FoundFields { reload, range, parmor } = parse_special_field(fields[16]); + *index += 1; + DatabaseEquipementStats { + id: *index, + meta_category: "Forme".into(), + name: fields[0].to_string(), + category: format!("\"{}\"", fields[1]), + rarity: 0, + cost: 0, + difficulty: fields[16].parse().unwrap_or_default(), + tier: 0, + damage: fields[2].parse().unwrap_or_default(), + p_damage: fields[3].parse().unwrap_or_default(), + precision: fields[4].parse().unwrap_or_default(), + rmax: fields[5].parse().unwrap_or_default(), + armor_break: fields[6].parse().unwrap_or_default(), + protection: fields[7].parse().unwrap_or_default(), + integrity: fields[8].parse().unwrap_or_default(), + + torque_two_handed: fields[10].parse().unwrap_or_default(), + torque_one_handed: fields[9].parse().unwrap_or_default(), // The or default is a problem + damage_type: fields[11].parse().unwrap(), + + dodge: fields[12].parse().unwrap_or_default(), + parry: fields[13].parse().unwrap_or_default(), + speed: fields[14].parse().unwrap_or_default(), + stealth: fields[15].parse().unwrap_or_default(), + reload_cost: serde_json::to_string(&reload).unwrap(), + range: range.unwrap_or_default(), + + // target: fields[5].parse().unwrap(), // Armors ? + ..Default::default() + } + }) + .collect::>() } -- 2.45.1 From a2269ccb87f433f27f76c153cc41df5e9e3f185d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 21 Feb 2025 01:22:54 +0100 Subject: [PATCH 56/97] A lot of shitcode to get the first import working --- weaponry/Cargo.toml | 2 + weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes .../{serde_loading.rs => first_import.rs} | 121 +++++++++++------- weaponry/src/database.rs | 9 +- weaponry/src/error.rs | 6 + .../src/weaponry_structs/equipement_fields.rs | 81 +++++++++++- .../equipement_impl_basics.rs | 2 +- .../equipement_impl_database.rs | 26 ++-- .../weaponry_structs/equipement_impl_logic.rs | 6 +- .../weaponry_structs/equipement_impl_math.rs | 7 +- .../weaponry_structs/equipement_structs.rs | 26 ++-- weaponry/src/weaponry_structs/mod.rs | 4 +- 12 files changed, 206 insertions(+), 84 deletions(-) rename weaponry/examples/{serde_loading.rs => first_import.rs} (62%) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 56c961e..ae487b4 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -15,11 +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 5fea0f35eea85fe0ae67cd0919efb5579bfde3e7..6d0843fc1fb807b939f132659d4bc921cab0bcda 100644 GIT binary patch delta 1002 zcmZ{iUu)A)7{+swv`yA#X(qL38J+2ECr#D1+m#(mcQYvK&}tbaOV4aEO}hLMWlAb| zp?B)=R?rL4t63`e0g88i1;@k>uq*FW7p{deo2!k@ zyrmnvHg4$}Zgpg>joSIqoZ`aIwU}=u+}c;`}W( zOQbW*n_KStE(4UT z3t?FX!3QWj@9wiHfk`pU4c+MB72Q_UE;dZ^Kj>0LtarLtZJWS$0{BJ@;OATz^5IK} z_2KgX=aCPu8VW^EacfXY!JwI3EQ=emb`Q5tBufwPL<7Mgrr_2%Wjdg^YHZ8u_@jks z>TEPskxJ9-V(oSW*lABMVpwp)H3QfzlL?uzCMz9GlhfR~Dw`cpOjApeb5-=W6Pp_} zkiB7nYH->m3!dsQd0jRvEZdPO#lie&N|L0?$v7uuodWU&PcwK7WQ-ga4S!+u_(gyG z2~%f^&hLqJtms#=Kb};AJ4=3!2kdN delta 899 zcmZ{iy>HV%7{>2>j&n|GJ4p$qR3cwOLV}n@FB9iT-wxd>E z(nuiDjgYY$6CV@G21}*<6D&j(J7r=;ymnHOV)dl=d}sUlJFlBmAt#xpFNZo3W$r2QFJVQ{M;Tz@ovBO$P!fVRfKMw6VwM8jG9)1?KoRT z(`7ZiLZPl`vz2@q!Q!CEa!c|#N?=GDwa+$f>0D*rc2obg4+kNut{9;(mWbppB zt8W@?hMTQIm8Vs0y_#Ov%8#q*?Ce1{eI+7hn=jY+u$s%^*XHnxRKtTq`txlpl#~vT z@>SVUZpy#pPjW-PERCguVLaWFx|*0m>N1@UOlcg$DrZ>~~6q&$fzVmd|mka#yidMwhxVJaCdaYP^! m::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() -// const BASE_DATA: &[[&str; 17]] = &[ -// // {Forme} & {Maniement} & {\damagew} & + & {R.Max} & \arbreakw & \protection & \integrite & $\mathbb{T}$2 & $\mathbb{T}$1 & {Modes} & {Esq.} & {Par.} & {Vit.} & {Disc.} & {Spécial} & {Diff.} \\ -// // % Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff -// ["Griffes", "Tranchantes", "2", "1", "4", "1", "1", "2", "3", "6", "slash", "2", "0", "3", "1", "-", "1"], -// ["Hast", "Hast", "4", "1", "2", "1", "4", "3", "10", "18", "pierce, [slash]", "-1", "-3", "1", "0", "-", "1"], -// ["Épée", "Tranchantes", "3", "1", "3", "1", "3", "4", "12", "15", "slash, [pierce]", "0", "1", "0", "0", "-", "1"], -// ["Marteau", "Contondantes", "5", "1", "1", "1", "4", "3", "11", "18", "blunt", "-1", "-1", "0", "-2", "-", "1"], -// ["Hache", "Tranchantes", "4", "2", "1", "3", "4", "3", "9", "14", "slash", "0", "-1", "1", "0", "-", "1"], -// ["Arbalète", "Distance", "4", "1", "3", "0", "3", "1", "8", "16", "pierce", "-1", "-1", "0", "-1", "2reload, Gls{parmure} 2, 80m", "1"], -// ["Arc", "Distance", "3", "1", "4", "0", "2", "1", "-", "7", "pierce", "0", "0", "0", "0", "1reload, Gls{parmure} 2, 120m", "1"], -// ["Biers", " -", "1", "1", "2", "0", "3", "2", "6", "8", "blunt", "-2", "0", "-1", "-2", "-", "1"], -// ["Armures", " -", " ", " ", " ", " ", "3", "2", "10", "-", "blunt", "-1", "0", "0", "-1", "-", "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}" -// ]; -// 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} ", @@ -37,8 +33,8 @@ const BASE_FORME: &[&str] = &[ "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 & - & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ", - "Armures & - & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & 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} ", @@ -51,23 +47,26 @@ fn main() { let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); db.initialize_empty_table::("Equipements").unwrap(); db.conn.execute("DELETE FROM Equipements", []).unwrap(); - println!("Processed {global_index} ids"); + println!("Added {global_index} ids to the new database"); b.iter().for_each(|v| database_shnn(&db, v)); let v = db.serialize_vec_from_table::("Equipements", None); - println!("{:#?}", v); - + // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", v); + println!("First entry: {:?}", v.as_ref().unwrap()[0]); // Final deserialisation let final_s = v.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); let v = final_s .iter() .scan(0, |status, eq| { if eq.is_ok() { - *status += 1; + *status = 1; + } else { + *status = 0; } Some(*status) }) .sum::(); - println!("{:#?}, {:#?}", final_s, v); + println!("Final data {:#?}", final_s); + println!("Succeded in parsing {:#?} over {}", v, global_index); } #[allow(dead_code)] @@ -79,7 +78,7 @@ struct FoundFields { } 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(); + 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()), @@ -106,9 +105,14 @@ fn database_shnn(db: &EquipementDatabase, row: T) { .collect::>() .join(", ") ); - // println!("{}", sql); + // println!("Database Request {}", sql); let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice()); - println!("Loaded {:?} entries into the database", r); + 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 { @@ -127,35 +131,39 @@ fn load_base(index: &mut u8) -> Vec { .iter() .map(|row| { let fields = row.split("&").map(|field| field.trim()).collect::>(); - let FoundFields { reload, range, parmor } = parse_special_field(fields[16]); + 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: format!("\"{}\"", fields[1]), + category: serde_json::to_string(&parse_to_type(fields[1]).unwrap()).unwrap(), rarity: 0, cost: 0, - difficulty: fields[16].parse().unwrap_or_default(), - tier: 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(), - precision: fields[4].parse().unwrap_or_default(), - rmax: fields[5].parse().unwrap_or_default(), - armor_break: fields[6].parse().unwrap_or_default(), - protection: fields[7].parse().unwrap_or_default(), - integrity: fields[8].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: fields[10].parse().unwrap_or_default(), + torque_two_handed: fields[8].parse().unwrap_or_default(), torque_one_handed: fields[9].parse().unwrap_or_default(), // The or default is a problem - damage_type: fields[11].parse().unwrap(), + damage_type: serde_json::to_string(&parse_to_damagetype(fields[10])).unwrap(), - dodge: fields[12].parse().unwrap_or_default(), - parry: fields[13].parse().unwrap_or_default(), - speed: fields[14].parse().unwrap_or_default(), - stealth: fields[15].parse().unwrap_or_default(), + 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() @@ -163,3 +171,30 @@ fn load_base(index: &mut u8) -> Vec { }) .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, + } +} diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index a372c66..aec7348 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -16,10 +16,11 @@ pub fn get_data( 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()) + serde_rusqlite::from_rows::( + conn.prepare(&generate_select_query::(table_name, filter))? + .query([])?, + ) + .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..ede0006 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -16,6 +16,12 @@ pub enum FatalEquipementError { #[error("Deserialisation from json failed : {0}")] SerdeJSON(#[from] serde_json::Error), + + #[error("Deserialisation from json failed at line {0} : {1}]")] + SerdeJSONAt(String, serde_json::Error), + + #[error("Couldn't convert into type {0} with data {1}")] + Conversion(String, String), } #[derive(Error, Debug)] diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index e1d9e1b..cf78892 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -2,11 +2,13 @@ // 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; +use crate::error::FatalEquipementError; + #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only @@ -26,14 +28,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( + std::any::type_name::().to_owned(), + 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 +84,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 +141,22 @@ 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 WeaponMetaCategory { + Staves, + Blunt, + Slash, + Ranged, + Armor, + Shields, + Exotic, } #[cfg(test)] diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 9b7cb66..3d27023 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -107,7 +107,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..f06a714 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -73,6 +73,15 @@ 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(|e| { + FatalEquipementError::SerdeJSONAt(format!("{} line {}", file!(), line!()), e) + }) + }; +} + // #[allow(clippy::useless_conversion)] impl TryFrom for InnerEquipementStats { type Error = FatalEquipementError; @@ -84,7 +93,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 +102,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)?, + 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..a42b3f9 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, WeaponMetaCategory}, equipement_structs::InnerEquipementStats, }, }; @@ -94,7 +94,7 @@ mod test { integrity: 2, range: 3, agility_bonus: 4, - category: Some(WeaponCategory::Dagger), + category: Some(WeaponMetaCategory::Staves), special: SpecialCategory(vec!["zero".into()]), damage_type: Some(DamageType(vec![DamageMod::Secondary( PhysicalDamageType::Slash, @@ -119,7 +119,7 @@ mod test { agility_bonus: 9, damage: 10, range: 3, - category: Some(WeaponCategory::Dagger), + category: Some(WeaponMetaCategory::Staves), special: SpecialCategory(vec!["zero".into(), "one".into(), "two".into()]), damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index ac6c4a6..8da15c6 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), } }}; } @@ -53,7 +50,7 @@ impl std::ops::Add for &InnerEquipementStats { 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_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, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 0fd7c2d..3f5b285 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::WeaponMetaCategory}; /// The final equipement list /// @@ -73,18 +73,18 @@ pub struct InnerEquipementStats { 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) torque_two_handed: u8, // Might be option (single claw) + pub(super) torque_one_handed: Option, // Should be option (bows) 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) category: Option, + 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) reload_cost: Option, // Shouldn't it be Option ? + pub(super) range: u8, // Shoudln't it be Option ? pub(super) agility_bonus: u8, } @@ -127,10 +127,8 @@ pub struct DatabaseEquipementStats { pub protection: u8, #[INTEGER] pub integrity: u8, - #[INTEGER] - pub torque_two_handed: u8, - #[INTEGER] - pub torque_one_handed: u8, + pub torque_two_handed: String, + pub torque_one_handed: String, #[INTEGER] pub dodge: u8, #[INTEGER] @@ -158,7 +156,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,8 +173,8 @@ impl Default for DatabaseEquipementStats { antimaterial: 0, protection: 0, integrity: 0, - torque_two_handed: 0, - torque_one_handed: 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, diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index d9203c8..cf3aab5 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, WeaponMetaCategory, +}; -- 2.45.1 From 22b46f6c07a28e07f0548b5717a119a04bd9bae2 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 21 Feb 2025 03:48:50 +0100 Subject: [PATCH 57/97] More work on the serialisation and the entry datatypes --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/first_import.rs | 371 +++++++++--------- weaponry/examples/test_serialisation_wl.rs | 31 ++ weaponry/src/database.rs | 17 +- weaponry/src/error.rs | 18 +- .../src/weaponry_structs/equipement_fields.rs | 8 +- .../equipement_impl_database.rs | 7 +- .../weaponry_structs/equipement_impl_logic.rs | 2 +- .../weaponry_structs/equipement_impl_math.rs | 2 +- .../weaponry_structs/equipement_structs.rs | 104 ++--- 10 files changed, 309 insertions(+), 251 deletions(-) create mode 100644 weaponry/examples/test_serialisation_wl.rs diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 6d0843fc1fb807b939f132659d4bc921cab0bcda..d0343f193cd15f2ecd4c903207456e5b6c37d814 100644 GIT binary patch literal 28672 zcmeI3-*4O26~{@Dl1TrE>Uf@;d7e0>MP)cCqNI+KZdfOKs_i9CU0d1WxtVrFUE5qJ zQYNV+u93HHNcPZwp~W7C>Mz)UJ_>!^-uuu!7kwNC>|sN9E-C)F`r&oJP}JFBz=*t; z`kr$>_uO+y8rpgLw&782-*%eB)2<0G2%;$bSknYSS`q{y3ws833HCDVGVI|dh6kfR zLF3im7AGgJ2$K4~F#g$OQGGxAF#I?Ad)R{nkN^@u0!ZL_B=FvAv)S3XIq~Tm9;utO za#ZuE>-9detJ{@wwW3waE4M3JuTd)+4Q=C2wX#;(zGRUm)vA?y)k_X>4DUGV&~4X? zP8!DkzM;3xM89WHC+;UrazLZgR;|(3;85Lg4cm$?fqR6<(Ft*ywo|J+lsxEbYk?I# z7ABTwz|9493}QxC2DWP6ajO?e%dtJGdr5PK<sb6Z3Lg->mF|Lu@Y%Z4h$0}daZ6-Z8x%~ZEbICmbZ7cTb147D@NlLt$ero*2W!3kj=`S z>cYa7l$l*z6nFh>a*sfQ)?5lx$kJ)wsmx_nUuTh}&L#Nf0?e0xe6!}v*W=A^?xwR0 zf5=@w_sO{j=gv?5aq?G_@7Zp+I zZBvReGsBK&X5LWXU^BRBZa===w%EOd~`3F zskT@O3>|$7485!l4Q7`!v}L!QmP1{*zj5SY;gof~`;n`4KkPFVM;MsgpJK6bCP&1! z3J($R_|a}cXkQM7w%zRjKt8Sn!;N!bXI@d%Xq?o@&J-6~_nA%%)18yPloPe)JU;YnY{c@BK zV;x~L|NXBbv|~5x4$2Rg*Eq_&SSE_AH!om5bUT-c>(XW&ri4j@ zYE}YNxt*9&L^B_Vk4D)X6$Qae}x<7 zye~HXBjGkw`>1G*7E4z90pz~c+6&;=g(OuqqRJP~a-$h68^eX*UgW2+G(;=IXs6<( zVYpIx5?q2cKa!dfl_}uGZU%UlR@;UH3(V!E%S)kDP*S1(t&g$5lw@g-Qj=F%act{d z3Z;E;J@gS(CO~O6>CZ?+tgMeH>ZU0OtK*r24E^M>cL5-ep>G5tRbUBvI`RT&T)`{8u$fL3}TwJ&bk!gu;FHVsND^5Z{hR9@1nM z-4he&Sb)naWGF19YBInz2j2KoH^paCsGYiYJtYl9G6^M2o#+UI&;QTOa~1}I1dsp{ zKmter2_OL^fCP}hStEeY|M>h5FBb6m-+#gJKYjjBHV%9KCbeI(F<_90XNA0@u(Xm6|GL0Er5Tw7CWg#|Fn~5ey+Drz)a}z;Vg| zQW9WdqOw?#Sh}GC9vGSUFCZ#nrvof>;+zDfjfBKmKY#q*^ZC7ZzV-oZAHbK>QSLPW zfM+$qYK+z8-Ng%MS$D~PBTFg3g}NZrmEZ9@!^4}yM-$!-{{p(pp|>q5#VyYy=YpNb zj$Pf_qIQLDQ->BCj@>Lf#cD;Z*QuR%N={?VBx#Fa%T%*jV&YLE7BL&?b&Fvcq7gSaoPkt>DdT#3Z<0s!@Ce8(L<`zg-cDo_Q*q=6#9JjDf_m zO-uhJag=ymqN?YKX|?{Tv5#X_w~T?rgs*4;Z=|&X$>W4hHhUTuRz#t2BjZOiG>h}Z z!qp09UJ`j0##--*86NT5>KWG5>&!ZR)SvHo6eo~g8XX|>lT%Z$bH^#&+ot{W`e*L% z3Z+*yg5&*W94AB}UaiChW`+0*ryCa53z~)tx~kkPkVS_3GU9?oZdvXZH1Bpp76;q! zJ5ONXd2Y{9P%>FMy+6QP4T?~H?-w#LSk8)Y&rF~CHy^_vs2{ND r`rna)VBkC?51Z8ov_|VrL;P@+k0=4g8)xNT{e8eO@;BuDF7lB-pP$~> diff --git a/weaponry/examples/first_import.rs b/weaponry/examples/first_import.rs index a3294dc..73b7ca4 100644 --- a/weaponry/examples/first_import.rs +++ b/weaponry/examples/first_import.rs @@ -1,200 +1,215 @@ // Workspace: weaponry // File: examples/typical_wl_recipe.rs -//! Example of a typical workload -//! +//! 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 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}; -use weaponry::weaponry_structs::{DamageMod, DamageType, PhysicalDamageType, WeaponMetaCategory}; -#[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), -} +// #[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() -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} ", -]; fn main() { - let mut global_index = 0; - let b = load_base(&mut global_index); - // println!("{b:?}"); // Equipements - let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); - 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| database_shnn(&db, v)); - let v = db.serialize_vec_from_table::("Equipements", None); - // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", v); - println!("First entry: {:?}", v.as_ref().unwrap()[0]); - // Final deserialisation - let final_s = v.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); - let v = final_s - .iter() - .scan(0, |status, eq| { - if eq.is_ok() { - *status = 1; - } else { - *status = 0; - } - Some(*status) - }) - .sum::(); - println!("Final data {:#?}", final_s); - println!("Succeded in parsing {:#?} over {}", v, global_index); + // 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); } -#[allow(dead_code)] -#[derive(Default)] -struct FoundFields { - reload: Option, - range: Option, - parmor: Option, -} -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()), - }) -} +// #[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(); -#[allow(dead_code)] -fn database_shnn(db: &EquipementDatabase, row: T) { - // let mut row = DatabaseEquipementStats::random_new(); +// db.conn.execute("DELETE FROM Equipements", []).unwrap(); +// println!("Added {global_index} ids to the new database"); - 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), - }; -} +// 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()), +// }) +// } -fn load_base(index: &mut u8) -> Vec { - // 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(); - 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(), +// #[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), +// }; +// } - torque_two_handed: fields[8].parse().unwrap_or_default(), - torque_one_handed: fields[9].parse().unwrap_or_default(), // The or default is a problem - damage_type: serde_json::to_string(&parse_to_damagetype(fields[10])).unwrap(), +// // 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(), - 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]), +// // 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(), - // target: fields[5].parse().unwrap(), // Armors ? - ..Default::default() - } - }) - .collect::>() -} +// // 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]), -fn parse_to_damagetype(fields: &str) -> DamageType { - DamageType(fields.split(",").map(|v| ModeParser::lexer(v.trim()).next().unwrap().unwrap().into()).collect::>()) -} +// // // target: fields[5].parse().unwrap(), // Armors ? +// // ..Default::default() +// // } +// // }) +// // .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_damagetype(fields: &str) -> DamageType { +// DamageType(fields.split(",").map(|v| ModeParser::lexer(v.trim()).next().unwrap().unwrap().into()).collect::>()) +// } -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, - } -} +// 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/test_serialisation_wl.rs b/weaponry/examples/test_serialisation_wl.rs new file mode 100644 index 0000000..abd1d3f --- /dev/null +++ b/weaponry/examples/test_serialisation_wl.rs @@ -0,0 +1,31 @@ +// 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!("Succeded in parsing {}/{}", f.0, f.1); +} diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index aec7348..b6fdc44 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -7,20 +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, { - serde_rusqlite::from_rows::( - conn.prepare(&generate_select_query::(table_name, filter))? - .query([])?, - ) - .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 ede0006..dff152a 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -11,17 +11,23 @@ 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 {0} : {1}]")] - SerdeJSONAt(String, serde_json::Error), + #[error("Deserialisation from json failed at line {line} : {error}]")] + SerdeJSONAt { + line: String, + error: serde_json::Error, + }, - #[error("Couldn't convert into type {0} with data {1}")] - Conversion(String, 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 cf78892..dd6efeb 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -44,10 +44,10 @@ impl TryFrom<&str> for PhysicalDamageType { "blunt" => Ok(Self::Blunt), "slash" => Ok(Self::Slash), "pierce" => Ok(Self::Pierce), - _ => Err(FatalEquipementError::Conversion( - std::any::type_name::().to_owned(), - value.to_string(), - )), + _ => Err(FatalEquipementError::Conversion { + origin_type: std::any::type_name::().to_owned(), + data: value.to_string(), + }), } } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index f06a714..9541279 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. @@ -76,8 +76,9 @@ 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(|e| { - FatalEquipementError::SerdeJSONAt(format!("{} line {}", file!(), line!()), e) + serde_json::from_str(&$value).map_err(|error| FatalEquipementError::SerdeJSONAt { + line: format!("{} line {}", file!(), line!()), + error, }) }; } diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index a42b3f9..a7f5d6a 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -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 8da15c6..8a677e8 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -49,7 +49,7 @@ 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_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, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 3f5b285..d74ddfd 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -59,33 +59,33 @@ 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, // Might be option (single claw) - pub(super) torque_one_handed: Option, // Should be option (bows) - pub(super) dodge: u8, - pub(super) parry: u8, - pub(super) speed: u8, - pub(super) stealth: u8, + 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: i8, + pub(super) parry: i8, + pub(super) speed: i8, + pub(super) stealth: i8, pub(super) category: Option, 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, // Shouldn't it be Option ? - pub(super) range: u8, // Shoudln't it be Option ? - 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: i8, } // TODO: This implementation of default is painfull @@ -101,52 +101,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, #[INTEGER] - pub dodge: u8, + pub dodge: i8, #[INTEGER] - pub parry: u8, + pub parry: i8, #[INTEGER] - pub speed: u8, + pub speed: i8, #[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, + pub range: i8, #[INTEGER] - pub agility_bonus: u8, + pub agility_bonus: i8, } impl Default for DatabaseEquipementStats { @@ -191,7 +191,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 @@ -199,11 +199,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() } } @@ -213,11 +213,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() } } -- 2.45.1 From 06b8fa7979dd983f7c5dc68b1ed045660ab1059d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 21 Feb 2025 05:42:43 +0100 Subject: [PATCH 58/97] Sucessfully imports data on napkin example --- .ignore | 1 + weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/test_serialisation_wl.rs | 3 +- weaponry/src/error.rs | 6 ++- .../src/weaponry_structs/equipement_fields.rs | 35 +++++++++--------- .../equipement_impl_basics.rs | 7 +++- .../equipement_impl_database.rs | 6 ++- .../weaponry_structs/equipement_impl_logic.rs | 12 +++--- .../weaponry_structs/equipement_impl_math.rs | 6 +-- .../weaponry_structs/equipement_structs.rs | 25 +++++++------ weaponry/src/weaponry_structs/mod.rs | 2 +- 11 files changed, 58 insertions(+), 45 deletions(-) create mode 100644 .ignore diff --git a/.ignore b/.ignore new file mode 100644 index 0000000..8e062ad --- /dev/null +++ b/.ignore @@ -0,0 +1 @@ +*.drawio diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index d0343f193cd15f2ecd4c903207456e5b6c37d814..7e68296556a73157c15701a56fda77c29bc0a713 100644 GIT binary patch literal 28672 zcmeHQTWlOx8Qz=i9mmer1Y?2;o^DcX<2d!&aW18huAR+=*sg1DXoGFc?C!BWWOimV z7uRW2fhBH5+{6n);-TW9ssRCSh)1-l#3K^CfW$>SAR#0k5E9T5%y-V2+u5B>TW$h0 zlkCpUWxxMF-}(RloZ0#3_v%v%s!ilA!>lW|Jd=1RkxV9@kmW?8>w}3zq6e>Typnho z@yg)kEp*@OEWkMPsj>dPsYF`(LgL6T`p2X%^z3^7Ugyj4;h2G#ftZ1qftZ2+GX_3! zcBp4)csTi)OSV$cNa@a|O)T48^~|r7ish1AF3v5KWOt`Lrq<-^OXbql(#mOFsS~+e zdZv8ZR7};r>mR5ZmhErU)U7SG>S&?kwo1(4xKdZPiND#{thMYgNmaE}L-$X?9AVGj zP|UhvZdOd9+-}*|fRt(gtmw9i$ptZ0Mf1<(vNr9z4Ywr?)38a^4vSNDn`{g1vkmi( zLpJSajm;fJuaSTf_lTjB)+05e7H*|tngL%{b)wr= z>5l&~)nXt10l`M<#8x(|pncmwgPF0!X5*U;9!Sf zo7kLss{vnv`7;3uGxJTsSxurDN{#PhCz*;KGFxR^)!^ux6+?F{U!J_Ya(%J5a!bBZ zx-~Yc)<)&x&GM7imtY`^rKR%t_;R{?XksFHi&>L(2M}b_B5)zSN?JBEf>pH~9HXXl z8s8j;zx?^X%V+*G+I;e6R}ZD~vu&Qasgq|z-bpvp0+;!gqj`C(SIVokyyV4mYzpq0 zmzW7)H|0Ip;?Z9C9yKCiM-cUe-8AwGJ9q#Vc6lR!xYHX2guQem5O#z{gNXfnL=X>z zMg`$OXk-Xl9*hpcx&8}?w*0-QFN4-PT67jPPMtPu9VjfvQAZU_+0^1?uX%|k)3 z?S_M3M<^r+P@%98oXkRlaGDSv!bidZf|^`Qfao3Xg8L+MuTdxJ$-Q>;_R+WWf3N=| z{h7X(`quk~j{NAz=a0o9QP~KTqwY-ktnu^3%!FiQgx_nJ@(ZeC*MY#7IHdC2m|%b=BHY_3af> zS9FyPezI-Yh@HhV`0gd~bYUypdfh z<1^W8GRt4tfn;)EFq=#!hX)6;_^_ndj!BAU9q;n0(;()gW;kYzqz>0M(&?F5-O;qy z{`zVjrx<3QZmn(5_rv9JK#yj#k`FCOouL;PC@>2%^xOCUcE26*#uyOC0p~3P*=%l* zZg6F@g0hRoU83t`ZDWc8wxKPL0&J42$MAT|rL4rkBmr!pd9dAl85FE-93D;k#flqv)REx{2v@VPPxpk@)6SqCUVKDDs@-_Cd_G08%1t?<(DuA%=6>QBM<@( z-h_~Oqh3+<=D`~kp`HRWk5UmZ0}0)C5jHVEHwFg>l3|-@v4}Km;$FT?Oj}hDWgg4V zX^w8^pWjHOrl+Q7@87@gwQOx8ML!;1Jqb}KX(uE>JV+amq?{*80%aktxP_$FHZBwj ze>*%3py;RhJb)f?d8aFC8aes_I=27?hQTa@ew}l>{xCq8#e&@=UeqK8dhmgR^n|r> z4dRgc0Zd|ca^}*nxZ|;=1*qQc56f`Whe0aUiY@~Z2&Eqe2WO~xEbQG-^6|=5SAr0RNFNe%8ll=GTI+sS2h{natWo#zXej zoDT9X03H_rp(D`ZSa5VY$JOoE z5u;S@T9zneYq(8_y=lMX_f2WZS#VLZfIxH0d5oDO{g znxrCo<}x+muiF-*?OAGkXwO8!W$bucWBkq+8AInA)txsch4;HJWc%%HLVS}I8GA}W zP~YiMKBp}w)GrBPFp znfYIR8)OYdcaP|YWffjS+x*oz;3M4(00-Z51zDk`w1Uq1?@ z6XCg0FjR?1%@?YQs%e;IwKtqW75f2&LBs7@I;LhZnZSZERWPV|M>PS1k(A9TY1??a zN_~JB3PW@xh>n>N9>6r2KLVIzE;V!&awk!fE1f~E^#bI$F#Yn4LIjyJ4gEPnCkI|H zd26oVx-^m)8V;#*p3S_mV|bV$UBUfJcj9efTD1(r7iU%JR3SXIb!WI7{X z;Aj8=I-d`XaM~IAoZ(b8P-dk%2sn2kzq*5fShGSi`HaAEIOx2JLdi@6{c5w@ae&6jPGNk@aHFBHy+ z(9_FLcL5p}#AbC8RHkeITJkO&n8w$X>JG`IMBG(Pv38(yCVjDRHqW;L(|jfaVAhFr z{t6qXoyc@{uSgj1A_gy_I9-Cm-rP8oE))tE+^KSaY@~qmyY@eJ{UCs<=qxR^zju&J?B#vu#b$QxM2zcY;80MCr!?mm|y0h}Pl(x5x{KD@>t% ztG2RB!dCQ5GDID1;CTraieb~e{^Ihkn)t<^SSitxJnYoWxl}sb5=_9mCj0R&^&KQ~ zFXhf1eI<1Lf57MG@q5fb%s|XQ%s|XQ%s|XQ%s|XQ%s|Y*f1H6^oqqxdU2^ezZ*S-) zfZ*~mzWxt>T8OXz>Ag7bGJWI!`TC#z&_}QTQ@Nida=*h{yu=K|48#n?48#n?48#n? z48#n?48#n?48#n?4E&EVkV~geCPR;&l#iv-6X6~7NfoI-wU?Mk{Gk2*|38}l|J&4; z{QUnPAp8H{o&T@0lzy7~;V#H1@sgQYTI2&$`jPM+B6HL_Kv7=l=)KCdK*xw2X$c7w7-e zCvUOD`Tzc71#$j=od5r3^8eZW|Im*bwALSerQBEOQ2a4wAZ8$DAZ8$DAZ8$DAZ8$D zAZ8$DAZ8$DAZFlyl7a5@F=@`I(ER_=#7pV!cO{3rK9_klW97b|vvMbo{y5W(-QPXB zf3zPJ0WbCaq3`Q`*OK2l@`oeOr%v_$rT25a@0WfeeJJ~ztdc#Ju6F;j`-?rV^f*0} z>9?i6_OE8dx`0X|v-I~qcM09(XO(vRoBU-IN35bYuq~_ghNe_$$*-21{AcFQps12; zIVOrZS+ryYN;#oW>-u_w72WV^ZS5a@R7SBvPbAhMsr$!RnTO8R3PqvwPzmK+HNrCs zkX)dRqGTqKQJ&CO;xs;1Xcailsw&hY$$-6B|+h}P$}pbj2`B9@FIVyq6ICF(M< zzP_VqTlb!?$+c0GfpyefB9HkeBmF@|g;-i6Y21~28FDX1$~|#YklTEL!cg{6HFSs8 z2BR>Zc(2k3y)zgbm1`=}EF9EV1S@qzwbkYUm%CSn-1$hkgHH=`1w54BR8acJXzb8- zc*5D^UZP->K9g&PQ-RL3A8b-@SX}arRY*p4LVw{sk2~FNAs*k}7Eze8c>oSIwPK>Y z2o>iS!s2&&ZY;KUn^4uq2cz94+p4YTv|E6MN`OIn3j4jTd=X$pUoUEtl9%qnD~|*w zsc#vmA;ap(2~{u!N*LK2N|Rc%sZ+Ex^^LO@^(&)4-W zO@+ZvOv{#{ZtF}7m)!l-G^BO#t8JlQL())?uX(`keYghNV%4GC9q&x{M0u=C%l62# za`Q#`f@{;WGyAy$)Id2;e+jww$KHS%J9jIlS|ibVpxWr3tT;A`e#t0)?y0W0e$P5( ztUNhQbvop-4v^(Ct=>KPvC2G3H6Ccz%t6k zqlz2RWL2lNh<2L?s2>%|=3<7uumn7m=kyoU%ZzrHD~gJt0(ByRhXQ4^7V2RuT4@Dn zsKDtj9knazRaTc0Q0+>MEIsA5(na!cP##NcWf{t#D!++hs;a&PwG`C(nwommOSIq- zW?{LlmE3*X@NS|SE^*|FiGZacPBZQNqFXN70?-P68z0aIE*g!sGB0$ywlUjMkZeD7 z190b~;hq(2Xi;%?71e^rpki;sKoLVjZ!zj+f@-?Y$=a_!{#Al|9f;qfG+WPeFgk=Z zG*n2hC>8=Kyq?E%^8+0SM?4qj4UlMZZ8XDOnvVsPnt}`mn zwR+d#?JJ$po@!+bWhYJA4cpBFzzJyi%XCo36ibmC;1s0duTij8FcNw9>?cc*7CoyO zv;=AM1^^oDPg9^UHIwI9Eh5oRK2@HDOcp%zkgE!6)Ur{)VzHX*V9j?{L7d>Qu@ z41L>yjl((G#@uDTQ>N1z#o4C89p|*os>*YnS$;S>h>CRH41x)5o!t15C%-^>HF-;p zKl6k?nDQi1FQm22m_lQE5iX8DQ38jrAtos`l<5^Zl7;Z4OVHOF6e)H`>}`j_PWyiHiq(cu-*4{?!gVgh(ZIlA1Z87z5E>e>kcfo zphT)?JVI=dIp5{SA@@>5P;HC&A-Sp!|D}Iqg$?L%=?a+U`K<# f9(@VRT3MP2P#6|RiO}kbqis9%vY6R#i!y%)eF6&D delta 675 zcmY*WOH30{6n$^rOy|>fhEk^Obc$073k)Wrq$P@Cgb+T8!RV$zA{~4rBSUL{64MZI zhdan!xP*l<)|E{cYFM+qTs@}Ig+ZXX}3cW&B`N{7o zH;#to(&%@e-AtKr_3t1M1?_*t@egOtUr#0$k?0dyx zWj)^4KXAMc9*1){59bXNry*@jhT8SSLbmL>%YnuQ8EWBP$VW$E%)A6g(HYru4vko0 zEJ<)x55gNm4P19Jd`Utyn*(uP|Is_|F16oRa=52PIM#^E#{d$SsQ&;7erUAA+aGj_e&pmze{& ztyCE=IE=$#Y8wjRS@ep`K5@qCmgII5xTXT1^#E*|Q;?3$!h3Vl=OQ%jWpqL5uWxWM zW^%4uub!AEbw2*pO2mU48Nd_yvU7*7(rl@CGfUTGKche$2x|)?p2zB4wk;b8pde7VkZF?*68<#P% A3;+NC diff --git a/weaponry/examples/test_serialisation_wl.rs b/weaponry/examples/test_serialisation_wl.rs index abd1d3f..d5d9ad0 100644 --- a/weaponry/examples/test_serialisation_wl.rs +++ b/weaponry/examples/test_serialisation_wl.rs @@ -26,6 +26,7 @@ fn main() { // }) // .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!("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/error.rs b/weaponry/src/error.rs index dff152a..808b9d8 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -20,10 +20,14 @@ pub enum FatalEquipementError { #[error("Deserialisation from json failed : {0}")] SerdeJSON(#[from] serde_json::Error), - #[error("Deserialisation from json failed at line {line} : {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}")] diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index dd6efeb..cd52da0 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -7,8 +7,6 @@ use std::fmt::Display; use std::ops::Add; use strum::Display; -use crate::error::FatalEquipementError; - #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only @@ -36,21 +34,21 @@ pub enum PhysicalDamageType { Pierce, } -impl TryFrom<&str> for PhysicalDamageType { - type Error = FatalEquipementError; +// 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(), - }), - } - } -} +// 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 /// @@ -149,7 +147,7 @@ pub enum WeaponCategory { /// 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 WeaponMetaCategory { +pub enum WeaponMacroCategory { Staves, Blunt, Slash, @@ -157,6 +155,9 @@ pub enum WeaponMetaCategory { 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 3d27023..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()) )]); diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 9541279..58611ac 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -77,7 +77,9 @@ impl FixedRecipe for EquipementFixedRecipe { macro_rules! from_serde { ($value: expr) => { serde_json::from_str(&$value).map_err(|error| FatalEquipementError::SerdeJSONAt { - line: format!("{} line {}", file!(), line!()), + line: line!().to_string(), + file: file!().to_string(), + parsed_value: $value.to_string(), error, }) }; @@ -112,7 +114,7 @@ impl TryFrom for InnerEquipementStats { parry: value.parry, speed: value.speed, stealth: value.stealth, - category: from_serde!(&value.category)?, + macro_category: from_serde!(&value.category)?, target: from_serde!(&value.target)?, special: from_serde!(&value.special)?, action_cost: value.action_cost, diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index a7f5d6a..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, - equipement_fields::{PhysicalDamageType, WeaponMetaCategory}, + equipement_fields::{PhysicalDamageType, WeaponMacroCategory}, equipement_structs::InnerEquipementStats, }, }; @@ -93,8 +93,8 @@ mod test { rarity: 1, integrity: 2, range: 3, - agility_bonus: 4, - category: Some(WeaponMetaCategory::Staves), + 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(WeaponMetaCategory::Staves), + macro_category: Some(WeaponMacroCategory::Staves), special: SpecialCategory(vec!["zero".into(), "one".into(), "two".into()]), damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 8a677e8..e6e376d 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -55,9 +55,9 @@ impl std::ops::Add for &InnerEquipementStats { 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 d74ddfd..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, equipement_fields::WeaponMetaCategory}; +use super::{DamageType, SpecialCategory, WeaponCategory, equipement_fields::WeaponMacroCategory}; /// The final equipement list /// @@ -75,17 +75,18 @@ pub struct InnerEquipementStats { 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: i8, + pub(super) dodge: f32, // I could also use a custom HalfValue pub(super) parry: i8, pub(super) speed: i8, pub(super) stealth: i8, - pub(super) category: Option, - pub(super) target: Option, // TODO: This might be incorrect, to check + /// 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: i8, pub(super) reload_cost: Option, // Shouldn't it be Option ? pub(super) range: i8, // Shoudln't it be Option ? - pub(super) agility_bonus: i8, + pub(super) agility_bonus: f32, // Also convert this one to HalfValue } // TODO: This implementation of default is painfull @@ -129,8 +130,8 @@ pub struct DatabaseEquipementStats { pub integrity: i8, pub torque_two_handed: String, pub torque_one_handed: String, - #[INTEGER] - pub dodge: i8, + #[REAL] + pub dodge: f32, #[INTEGER] pub parry: i8, #[INTEGER] @@ -145,8 +146,8 @@ pub struct DatabaseEquipementStats { pub reload_cost: String, #[INTEGER] pub range: i8, - #[INTEGER] - pub agility_bonus: i8, + #[REAL] + pub agility_bonus: f32, } impl Default for DatabaseEquipementStats { @@ -156,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,12 +176,12 @@ impl Default for DatabaseEquipementStats { integrity: 0, torque_two_handed: serde_json::to_string(&0).unwrap(), torque_one_handed: serde_json::to_string(&None::).unwrap(), - dodge: 0, + dodge: 0., parry: 0, speed: 0, stealth: 0, range: 0, - agility_bonus: 0, + agility_bonus: 0., action_cost: 0, } } diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index cf3aab5..e4ab206 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -35,5 +35,5 @@ pub use equipement_structs::{Equipement, InitialEquipementList}; // #[allow(unused_imports)] pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{ - DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMetaCategory, + DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMacroCategory, }; -- 2.45.1 From bb3041ed8ddc4a71dc1ad634e4d381ee081d0c87 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 21 Feb 2025 18:14:13 +0100 Subject: [PATCH 59/97] First draft of a scenario --- badges/coverage.svg | 2 +- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes ...sation_wl.rs => bench_serialisation_wl.rs} | 11 --- .../{first_import.rs => usage_import_tex.rs} | 2 +- weaponry/examples/usage_scenario.rs | 30 +++++++ weaponry/src/database.rs | 4 +- weaponry/src/interfaces.rs | 2 +- .../src/weaponry_structs/equipement_fields.rs | 26 +++++- .../equipement_impl_basics.rs | 67 +++++++++++--- .../equipement_impl_database.rs | 2 +- .../weaponry_structs/equipement_scenario.rs | 82 ++++++++---------- .../weaponry_structs/equipement_structs.rs | 4 +- weaponry/src/weaponry_structs/mod.rs | 5 +- 13 files changed, 156 insertions(+), 81 deletions(-) rename weaponry/examples/{test_serialisation_wl.rs => bench_serialisation_wl.rs} (81%) rename weaponry/examples/{first_import.rs => usage_import_tex.rs} (99%) create mode 100644 weaponry/examples/usage_scenario.rs 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 7e68296556a73157c15701a56fda77c29bc0a713..1ad235a301c6a91c31f9aefb22ec8b527a47bebb 100644 GIT binary patch delta 876 zcmZWmOHUI~6uvW4WuS#&Ix~g7=tIF0I|O4Q36Vet7bS?0R31siWKsthGo99HF~JqY zpgSHp3x9wKD>tSKcSbbEg$ZHd#s&>+TxcQ-F(xjo_x75IcqcdKyXQOKckY?Hyw5D} zGaEs11tHXc_i4OYytU2bMV#z;kZAVwBDQf2xj#0pJuSX;v)u0H%26fJyyxXmE2=a^ ze+q8l3u1&S5~@PA5}Vi&pgJhJu#EzTgKfNtge~Dx%WG(9?eAjmyT-U0w~kEq6WhhS zXC5+1w2cb*qid=&g1X_W7HYYsmlqvF%@mECsaxQd!tg=!!1mB8s{|n}s&0GHvf?Qx zUvT2EEXGLsv3R!USUNjP4z(DO;mQ~`OoqQvmQI3&>OULn4oxm6h7Pra~;RFwl#lB_WrOlBd}+cpwdF`C z(D1HpzAk9Ljoq%B*q^Ooe+gc-tIarLIC;Y^o3`Ql)0KyH+)MTM5!syIA))F|0d{J_B3BCnXJk6L{UT{o{rUrubS}Qn0B+r7W1}w>$ zhEo@KLv=P48pcy;PQkus)UvZRxDfEcRw(AmEa*kpNhaY(sD~c9!!s1DhBFlGg{LX# h>zJfqqhpGK&mDORvJs1dx8s*jG5C?Wif7^|@*61Q4W9r2 delta 228 zcmZp8z}WDBae}m97y|~^)+{~`U% 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; -- 2.45.1 From 7f98215bc227e83c26e075d109718d2137955cc2 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 21 Feb 2025 18:55:26 +0100 Subject: [PATCH 60/97] Work on scenario --- badges/coverage.svg | 2 +- weaponry/examples/usage_scenario.rs | 12 ++++++++---- .../src/weaponry_structs/equipement_advanced_repr.rs | 10 +++++++++- weaponry/src/weaponry_structs/equipement_scenario.rs | 2 ++ weaponry/src/weaponry_structs/equipement_structs.rs | 6 ++++-- 5 files changed, 24 insertions(+), 8 deletions(-) diff --git a/badges/coverage.svg b/badges/coverage.svg index 6fdcf57..950fe17 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 16%test-coverage16% +test-coverage: 17%test-coverage17% diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 95b1f2f..f12cdb3 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -4,15 +4,19 @@ //! //! +use std::path::Path; + // TODO : All of these should likely be in the prelude if used like this -use weaponry::interfaces::{Reportable, Scenario}; +use weaponry::interfaces::{Reportable, Scenario, ToCSV}; 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"))); + let save_path = "data/first_data.csv"; + let scenarios = CrossRecipeScenario::new_with_config(ConfigMock {}).unwrap(); + let refined_list = scenarios.generate_refined_recipes().unwrap(); + println!("{}", refined_list.get_report(Some("Refined List"))); + println!("Saved initial data as {}: {:?}", save_path, refined_list.write_csv(Path::new(save_path))); } // // Load DB diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index c9efb83..d03f9c2 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -84,9 +84,11 @@ impl Default for RefinedEquipementList { } /// The list of advanced stats infered from an Equipement +// TODO: The two philosophies to drop the old inner or convert the useful fields are considered right now #[allow(missing_docs, clippy::missing_docs_in_private_items)] #[derive(Serialize)] pub struct AdvancedStats { + display_name: String, damage_per_attack: f64, damage_per_turn: f64, damage_per_action: f64, @@ -104,6 +106,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack); Self { + display_name: value.name.join(" "), damage_per_attack, damage_per_turn: damage_per_attack * 2., damage_per_action: damage_per_attack / (value.action_cost as f64), @@ -139,7 +142,12 @@ impl Serialize for DamageMatrix { where S: serde::Serializer, { - serializer.serialize_str(&format!("[{:?}]", self.damage_matrix)) + // TODO: Not sure of the right way to do this + // serializer.serialize_str(&format!("[{:?}]", self.damage_matrix)) + serializer.serialize_str(&format!( + "{:?}", + self.damage_matrix.iter().sum::() / self.damage_matrix.len() as f64 + )) } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 480c3ea..66a4e70 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -9,6 +9,7 @@ #![allow(dead_code)] +#[allow(unused_imports)] use crate::interfaces::Reportable; use crate::weaponry_structs::InitialEquipementList; use crate::weaponry_structs::equipement_structs::DatabaseEquipementStats; @@ -96,6 +97,7 @@ impl Scenario for CrossRecipeScenario { let eq_shape = deserde_into_equipement!(self.database, "Shape", EqShape); let eq_material = deserde_into_equipement!(self.database, "Materials", EqMaterial); let eq_nature = deserde_into_equipement!(self.database, "Nature", EqNature); + #[allow(unused_variables)] let eq_finishing = deserde_into_equipement!(self.database, "Finishing", EqFinishing); // println!( diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 57533f6..ca67614 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -283,12 +283,14 @@ mod test { #[test] fn test_creating_all_equipements() { let shape = vec![EqShape::default().into(), EqShape::default().into()]; - let nature = vec![EqNature::default().into(), EqNature::default().into()]; + // Commented because of the generic nature and the from not a tryfrom + // TODO: Reinstate this part + // let nature = vec![EqNature::default().into(), EqNature::default().into()]; let material = vec![EqMaterial::default().into(), EqMaterial::default().into()]; let finishing = vec![EqFinishing::default().into(), EqMaterial::default().into()]; let mut leq = InitialEquipementList::from_vectored(shape); - leq.combine_all(&InitialEquipementList::from_vectored(nature)); + // leq.combine_all(&InitialEquipementList::from_vectored(nature)); leq.combine_all(&InitialEquipementList::from_vectored(material)); leq.combine_all(&InitialEquipementList::from_vectored(finishing)); } -- 2.45.1 From fde34be744d42babcedd652b654d264258892e64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20CAMPO?= Date: Sat, 22 Feb 2025 00:02:45 +0100 Subject: [PATCH 61/97] Tranforming deserde_into_equipment into function --- .../weaponry_structs/equipement_scenario.rs | 61 ++++++++++--------- .../weaponry_structs/equipement_structs.rs | 24 ++++++++ 2 files changed, 55 insertions(+), 30 deletions(-) diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 66a4e70..5e11109 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -8,7 +8,7 @@ //! #![allow(dead_code)] - +use crate::error::FatalEquipementError; #[allow(unused_imports)] use crate::interfaces::Reportable; use crate::weaponry_structs::InitialEquipementList; @@ -17,14 +17,15 @@ 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, interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable}, }; +use super::Equipement; use super::equipement_advanced_repr::RefinedEquipementList; use super::equipement_impl_database::EquipementDatabase; +use super::equipement_structs::InnerEquipementStats; /// Mock config pub struct ConfigMock {} @@ -50,29 +51,30 @@ pub struct CrossRecipeScenario { 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::( - "Equipements", - Some(&format!("META_CATEGORY LIKE '{}'", $name)), - // None, - )? - .into_iter() - // TODO: This is the lamest way to init this data - .map(|v| { - $type { - stats: InnerEquipementStats::try_from(v).unwrap(), - } - .into() - }) - .collect::>(), - ) - }; +impl CrossRecipeScenario { + /// Automatically deserialize into an equipement + fn deserde_into_equipement( + &self, + name: &str, + ) -> Result + where + T: TryFrom + From + Into, + { + Ok(InitialEquipementList::from_vectored( + self.database + .serialize_vec_from_table::( + &name, + Some(&format!("META_CATEGORY LIKE '{}'", name)), + )? + .into_iter() + .map(|v| { + InnerEquipementStats::try_from(v) + .map(|w| T::from(w)) + .map(|v| v.into()) + }) + .collect::, FatalEquipementError>>()?, + )) + } } impl Scenario for CrossRecipeScenario { @@ -94,11 +96,11 @@ 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, "Materials", EqMaterial); - let eq_nature = deserde_into_equipement!(self.database, "Nature", EqNature); + let eq_shape = self.deserde_into_equipement::("Shape")?; + let eq_material = self.deserde_into_equipement::("Materials")?; + let eq_nature = self.deserde_into_equipement::("Nature")?; #[allow(unused_variables)] - let eq_finishing = deserde_into_equipement!(self.database, "Finishing", EqFinishing); + let eq_finishing = self.deserde_into_equipement::("Finishing")?; // println!( // "{}\n{}\n{}\n{}", @@ -121,7 +123,6 @@ impl Scenario for CrossRecipeScenario { // 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 - Ok(f_list.into()) } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index ca67614..4e92388 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -231,6 +231,12 @@ pub struct EqShape { pub(super) stats: InnerEquipementStats, } +impl From for EqShape { + fn from(value: InnerEquipementStats) -> Self { + Self { stats: value } + } +} + /// Material used for the equipement, all equipements are crafted with 1-2 materials #[derive(Default)] pub struct EqMaterial { @@ -238,6 +244,12 @@ pub struct EqMaterial { pub(super) stats: InnerEquipementStats, } +impl From for EqMaterial { + fn from(value: InnerEquipementStats) -> Self { + Self { stats: value } + } +} + /// Nature of the equipement, some natures are reserved and some can be chained /// /// Deciding on the combinaison can be tricky an will need an extra field @@ -247,6 +259,12 @@ pub struct EqNature { pub(super) stats: InnerEquipementStats, } +impl From for EqNature { + fn from(value: InnerEquipementStats) -> Self { + Self { stats: value } + } +} + /// Finishing touches, since all of them have a cost, they are treated in a special fashion #[derive(Default)] pub struct EqFinishing { @@ -254,6 +272,12 @@ pub struct EqFinishing { pub(super) stats: InnerEquipementStats, } +impl From for EqFinishing { + fn from(value: InnerEquipementStats) -> Self { + Self { stats: value } + } +} + #[cfg(test)] mod test { use super::{ -- 2.45.1 From a231dfdd194139e9b32f0666c580d938a5826dd7 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 22 Feb 2025 01:51:36 +0100 Subject: [PATCH 62/97] Adds a draft of an html render --- weaponry/Cargo.toml | 4 + weaponry/examples/graph.rs | 149 ++++++++++++++++++ weaponry/examples/usage_scenario.rs | 58 ++++++- .../equipement_advanced_repr.rs | 74 ++++++--- .../weaponry_structs/equipement_scenario.rs | 8 +- .../weaponry_structs/equipement_structs.rs | 5 +- weaponry/src/weaponry_structs/mod.rs | 1 + 7 files changed, 269 insertions(+), 30 deletions(-) create mode 100644 weaponry/examples/graph.rs diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index ae487b4..0146cdd 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -16,6 +16,10 @@ serde_json = { version = "1.0.138", features = ["alloc"] } strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" regex = "1.11.1" +charming = { version = "0.4.0", features = ["deno_core", "image", "resvg", "ssr", "wasm"] } +chrono = "0.4.39" +leptos = { version = "0.7.7", features = ["csr"] } +leptos-use = "0.15" [dev-dependencies] criterion = { version = "0.5" } diff --git a/weaponry/examples/graph.rs b/weaponry/examples/graph.rs new file mode 100644 index 0000000..c4a20fb --- /dev/null +++ b/weaponry/examples/graph.rs @@ -0,0 +1,149 @@ +// use charming::{ +// Chart, WasmRenderer, +// component::{Axis, Title}, +// element::AxisType, +// series::Line, +// }; +// use leptos::prelude::*; +// use leptos_use::use_interval_fn; +// use leptos_use::utils::Pausable; + +// #[component] +// fn App() -> impl IntoView { +// let data = RwSignal::new(vec![150, 230, 224, 218, 135, 147, 260]); +// let action = Action::new(move |_input: &()| { +// let local = data.get(); +// async move { +// let chart = Chart::new() +// .title(Title::new().text("Demo: Leptos + Charming")) +// .x_axis(Axis::new().type_(AxisType::Category).data(vec!["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])) +// .y_axis(Axis::new().type_(AxisType::Value)) +// .series(Line::new().data(local)); + +// let renderer = WasmRenderer::new(600, 400); +// renderer.render("chart", &chart).unwrap(); +// } +// }); + +// let Pausable { pause, resume, is_active: _ } = use_interval_fn( +// move || { +// data.update(|d| d.rotate_right(1)); +// action.dispatch(()); +// }, +// 1000, +// ); + +// action.dispatch(()); + +// view! { +//
+//
+// +// +//
+// } +// } + +// fn main() { +// mount_to_body(|| view! { }) +// } +use charming::{ + Chart, + component::{Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, ToolboxDataZoom, VisualMap, VisualMapType}, + element::{AxisType, Tooltip, Trigger}, + series::Line, +}; +// use rand::Rng; + +pub fn chart() -> Chart { + let raw_data = vec![ + ("2000-06-05", 116), + ("2000-06-06", 129), + ("2000-06-07", 135), + ("2000-06-08", 86), + ("2000-06-09", 73), + ("2000-06-10", 85), + ("2000-06-11", 73), + ("2000-06-12", 68), + ("2000-06-13", 92), + ("2000-06-14", 130), + ("2000-06-15", 245), + ("2000-06-16", 139), + ("2000-06-17", 115), + ("2000-06-18", 111), + ("2000-06-19", 309), + ("2000-06-20", 206), + ("2000-06-21", 137), + ("2000-06-22", 128), + ("2000-06-23", 85), + ("2000-06-24", 94), + ("2000-06-25", 71), + ("2000-06-26", 106), + ("2000-06-27", 84), + ("2000-06-28", 93), + ("2000-06-29", 85), + ("2000-06-30", 73), + ("2000-07-01", 83), + ("2000-07-02", 125), + ("2000-07-03", 107), + ("2000-07-04", 82), + ("2000-07-05", 44), + ("2000-07-06", 72), + ("2000-07-07", 106), + ("2000-07-08", 107), + ("2000-07-09", 66), + ("2000-07-10", 91), + ("2000-07-11", 92), + ("2000-07-12", 113), + ("2000-07-13", 107), + ("2000-07-14", 131), + ("2000-07-15", 111), + ("2000-07-16", 64), + ("2000-07-17", 69), + ("2000-07-18", 88), + ("2000-07-19", 77), + ("2000-07-20", 83), + ("2000-07-21", 111), + ("2000-07-22", 57), + ("2000-07-23", 55), + ("2000-07-24", 60), + ]; + + let mut data_list = vec![]; + let mut value_list = vec![]; + + raw_data.into_iter().for_each(|(date, value)| { + data_list.push(date); + value_list.push(value); + }); + + Chart::new() + .title(Title::new().text("Gradient along the y axis").left("center")) + // .title(Title::new().text("Gradient along the x axis").left("center").top("55%")) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) + .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(0).min(0).max(400)) + // .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(1).dimension(0).min(0).max(10).max((data_list.len() - 1) as f64)) + .x_axis(Axis::new().data(data_list.to_vec()).type_(AxisType::Category).boundary_gap(false)) + // .x_axis(Axis::new().data(data_list.to_vec()).grid_index(1)) + .y_axis(Axis::new()) + // .y_axis(Axis::new().grid_index(1)) + .grid(Grid::new()) + // .grid(Grid::new().top("60%")) + .series(Line::new().show_symbol(false).data(value_list.clone())) + .data_zoom(DataZoom::new().type_(DataZoomType::Inside).start(0).end(100)) + .data_zoom(DataZoom::new().start(0).end(100)) + .toolbox(Toolbox::new().feature(Feature::new().data_zoom(ToolboxDataZoom::new().y_axis_index("none")).restore(Restore::new()).save_as_image(SaveAsImage::new()))) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) + // .series(Line::new().show_symbol(false).x_axis_index(1).y_axis_index(1).data(value_list)) +} + +fn main() { + let chart = chart(); + use charming::HtmlRenderer; + + let mut renderer = HtmlRenderer::new("MOOO", 1800, 1800).theme(charming::theme::Theme::Dark); + // // Render the chart as HTML string. + // let html_str = renderer.render(&chart).unwrap(); + // Save the chart as HTML file. + renderer.save(&chart, "./chart.html").unwrap(); +} diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index f12cdb3..f5f6174 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -4,19 +4,69 @@ //! //! +use charming::HtmlRenderer; +use charming::{ + Chart, + component::{Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, ToolboxDataZoom, VisualMap, VisualMapType}, + element::{AxisType, Tooltip, Trigger}, + series::Line, +}; use std::path::Path; // TODO : All of these should likely be in the prelude if used like this -use weaponry::interfaces::{Reportable, Scenario, ToCSV}; use weaponry::weaponry_structs::CrossRecipeScenario; use weaponry::weaponry_structs::equipement_scenario::ConfigMock; +use weaponry::{ + interfaces::{Reportable, Scenario, ToCSV}, + weaponry_structs::RefinedEquipementList, +}; // use weaponry::interfaces:: fn main() { - let save_path = "data/first_data.csv"; + let save_path = "data/first_data"; let scenarios = CrossRecipeScenario::new_with_config(ConfigMock {}).unwrap(); - let refined_list = scenarios.generate_refined_recipes().unwrap(); + let mut refined_list = scenarios.generate_refined_recipes().unwrap(); + // Render as html + render_data(&mut refined_list, save_path); + // // Export as csv + // export_as_csv(&refined_list, save_path); +} + +#[allow(dead_code)] +fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { println!("{}", refined_list.get_report(Some("Refined List"))); - println!("Saved initial data as {}: {:?}", save_path, refined_list.write_csv(Path::new(save_path))); + println!("Saved initial data as {}.html: {:?}", save_path, refined_list.write_csv(Path::new(&format!("{save_path}.csv")))); +} + +pub fn make_chart(data: &mut RefinedEquipementList) -> Chart { + data.inner.sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + let raw_data = data.inner.iter().map(|refeq| (refeq.inner.name.join(" "), refeq.advanced.dps_safe)); + let mut data_list = vec![]; + let mut value_list = vec![]; + + raw_data.into_iter().for_each(|(date, value)| { + data_list.push(date); + value_list.push(value); + }); + + Chart::new() + .title(Title::new().text("Gradient along the y axis").left("center")) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) + .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(0).min(0).max(400)) + .x_axis(Axis::new().data(data_list.to_vec()).type_(AxisType::Category).boundary_gap(false)) + .y_axis(Axis::new()) + .grid(Grid::new()) + .series(Line::new().show_symbol(false).data(value_list.clone())) + .data_zoom(DataZoom::new().type_(DataZoomType::Inside).start(0).end(100)) + .data_zoom(DataZoom::new().start(0).end(100)) + .toolbox(Toolbox::new().feature(Feature::new().data_zoom(ToolboxDataZoom::new().y_axis_index("none")).restore(Restore::new()).save_as_image(SaveAsImage::new()))) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) +} + +fn render_data(data: &mut RefinedEquipementList, save_path: &str) { + let mut renderer = HtmlRenderer::new("MOOO", 1920, 1080).theme(charming::theme::Theme::Dark); + // Save the chart as HTML file. + println!("Saving to {save_path}.html"); + renderer.save(&make_chart(data), format!("{save_path}.html")).unwrap(); } // // Load DB diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index d03f9c2..0e79e09 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -18,19 +18,23 @@ use probability::prelude::{Binomial, Discrete}; use serde::Serialize; use strum::{Display, EnumIter, IntoEnumIterator}; -use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats}; +use super::{ + Equipement, InitialEquipementList, WeaponMacroCategory, + equipement_structs::InnerEquipementStats, +}; /// The final representation of the equipement inplementing all the fields needed for processing +// TODO: Add a public getter for the inner data pub struct RefinedEquipement { /// The original inner stats /// /// This structs takes ownership of the inner data // #[serde(skip_deserializing)] - inner: InnerEquipementStats, + pub inner: InnerEquipementStats, /// Advanced stats // #[serde(flatten)] - advanced: AdvancedStats, + pub advanced: AdvancedStats, } impl Serialize for RefinedEquipement { @@ -54,7 +58,8 @@ impl From for RefinedEquipement { /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements - pub(super) inner: Vec, + // TODO: Add a public getter in on of the traits + pub inner: Vec, } // Just a checkmark @@ -85,19 +90,25 @@ impl Default for RefinedEquipementList { /// The list of advanced stats infered from an Equipement // TODO: The two philosophies to drop the old inner or convert the useful fields are considered right now +// TODO: This whole public might be overkill ? A good inner view or scenario could implement what is needed #[allow(missing_docs, clippy::missing_docs_in_private_items)] #[derive(Serialize)] pub struct AdvancedStats { - display_name: String, - damage_per_attack: f64, - damage_per_turn: f64, - damage_per_action: f64, - armor_break_per_attack: f64, - armor_break_per_turn: f64, - armor_break_per_action: f64, - damage_matrix: DamageMatrix, + pub display_name: String, + pub damage_per_attack: f64, + pub damage_per_turn: f64, + pub damage_per_action: f64, + pub armor_break_per_attack: f64, + pub armor_break_per_turn: f64, + pub armor_break_per_action: f64, + pub damage_matrix: DamageMatrix, + pub category: Option, /// Armor break factoring in the damage output: While a weapon might have high AB, not having any damage will seriously hinder that AB - expected_armor_break_per_turn: f64, + pub expected_armor_break_per_turn: f64, + /// Dps with two actions and 5 dices + pub dps_safe: f64, + /// Dps with four actions and 11 dices + pub dps_unsafe: f64, // All other criterias are already in the inner as raw criterias } impl From<&InnerEquipementStats> for AdvancedStats { @@ -105,7 +116,9 @@ impl From<&InnerEquipementStats> for AdvancedStats { let damage_per_attack = (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack); + let damage_matrix = DamageMatrix::calculate_for(value); Self { + category: value.macro_category.clone(), display_name: value.name.join(" "), damage_per_attack, damage_per_turn: damage_per_attack * 2., @@ -117,8 +130,9 @@ impl From<&InnerEquipementStats> for AdvancedStats { // Adds the base strength, substracts the expected protection expected_armor_break_per_turn: (damage_per_attack + 6. - 8.) .min(armor_break_per_attack), - damage_matrix: value.into(), - // armor_break_matrix: , + dps_safe: damage_matrix.get_safe_dmg(value.action_cost), + dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), + damage_matrix, } } } @@ -127,7 +141,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { /// /// This simulation does only calculate a very limited preset of damage values #[cfg_attr(test, derive(Debug))] -struct DamageMatrix { +pub struct DamageMatrix { /// The inner damage matrix damage_matrix: Vec, } @@ -136,6 +150,25 @@ impl DamageMatrix { pub fn get_damage(&self, precision: Precision, dices: DiceNumber) -> f64 { self.damage_matrix[precision as usize + 3 * dices as usize] } + + /// The "safe" damage, as in 5 dices, 2 attacks + // TODO: This safe damage actually uses 5 dices * 2 instead of doing max(5 * 1 , 2 * 1 + 3 * 1) + pub fn get_safe_dmg(&self, attack_cost: i8) -> f64 { + let _ = attack_cost; + (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3. + } + /// The "unsage" damage, as in, full dice, 2 attacks + // TODO: This damages does max(Max dices * 1, 5 dices * 2), which might not be optimal + pub fn get_unsafe_dmg(&self, attack_cost: i8) -> f64 { + match attack_cost { + 1 => f64::max( + self.get_safe_dmg(attack_cost) * 2., + (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3., + ), + 2 => (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3., + _ => 0., + } + } } impl Serialize for DamageMatrix { fn serialize(&self, serializer: S) -> Result @@ -172,8 +205,9 @@ impl Display for DamageMatrix { } } -impl From<&InnerEquipementStats> for DamageMatrix { - fn from(value: &InnerEquipementStats) -> Self { +impl DamageMatrix { + /// Calculate the DamageMatrix for a given InnerEquipementStats + fn calculate_for(value: &InnerEquipementStats) -> Self { DamageMatrix { damage_matrix: (DiceNumber::iter() .flat_map(|dices| { @@ -259,7 +293,7 @@ mod test { #[test] fn test_binomial() { let damage = new_inner_eq(); - let mat: DamageMatrix = DamageMatrix::from(&damage); + let mat: DamageMatrix = DamageMatrix::calculate_for(&damage); println!("{:#?}", damage); println!("{:#?}", mat); } @@ -277,7 +311,7 @@ mod test { #[test] fn test_creation() { - let mat = DamageMatrix::from(&new_inner_eq()); + let mat = DamageMatrix::calculate_for(&new_inner_eq()); println!("{}", mat); println!( "(High,Many): {}, (Low,Few): {}", diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 5e11109..d21b8d6 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -113,11 +113,13 @@ impl Scenario for CrossRecipeScenario { // 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 "))); + println!("{}", f_list.get_report(Some("Initial Weapons "))); f_list.combine_all(&eq_material); - // println!("{}", f_list.get_report(Some("Combined with Materials"))); + println!("{}", f_list.get_report(Some("Combined with Materials"))); + f_list.combine_all(&eq_material); + println!("{}", f_list.get_report(Some("Combined with Materials"))); f_list.combine_all(&eq_nature); - // println!("{}", f_list.get_report(Some("Combined with Natures "))); + 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 diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 4e92388..3fc66ce 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -42,7 +42,7 @@ impl Default for Equipement { /// The default filter to use, usefull to implement a new filter function that also uses the default filter pub(crate) fn default_filter() -> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { - &|self_, lhs| !self_.id.iter().any(|a| *a == lhs.id[0]) + &|self_, lhs| lhs.id.iter().all(|a| *a != self_.id[0]) } impl FilterFunction { @@ -281,8 +281,7 @@ impl From for EqFinishing { #[cfg(test)] mod test { use super::{ - EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, - InnerEquipementStats, + EqFinishing, EqMaterial, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, }; use crate::interfaces::RecipeCollection; diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index f347a40..5a09399 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -33,6 +33,7 @@ pub use equipement_structs::{Equipement, InitialEquipementList}; // All generic fields // #[allow(unused_imports)] +pub use crate::weaponry_structs::equipement_advanced_repr::RefinedEquipementList; pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{ DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMacroCategory, -- 2.45.1 From 04bc4d57ecb4eb95d35974e5d6e2dd700b16415f Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 22 Feb 2025 02:06:22 +0100 Subject: [PATCH 63/97] Bad database selected --- weaponry/Cargo.toml | 8 ++++---- weaponry/src/weaponry_structs/equipement_scenario.rs | 5 ++++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 0146cdd..291e2c0 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -16,10 +16,10 @@ serde_json = { version = "1.0.138", features = ["alloc"] } strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" regex = "1.11.1" -charming = { version = "0.4.0", features = ["deno_core", "image", "resvg", "ssr", "wasm"] } -chrono = "0.4.39" -leptos = { version = "0.7.7", features = ["csr"] } -leptos-use = "0.15" +charming = { version = "0.4.0", features = [] } +# chrono = "0.4.39" +# leptos = { version = "0.7.7", features = ["csr"] } +# leptos-use = "0.15" [dev-dependencies] criterion = { version = "0.5" } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index d21b8d6..d48a426 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -47,6 +47,8 @@ impl ViewTable for ViewtableMock { /// A simple cross recipe scenario #[allow(clippy::missing_docs_in_private_items)] pub struct CrossRecipeScenario { + // TODO: Should obv be inside the config + database_name: String, database: EquipementDatabase, config: ConfigMock, } @@ -63,7 +65,7 @@ impl CrossRecipeScenario { Ok(InitialEquipementList::from_vectored( self.database .serialize_vec_from_table::( - &name, + &self.database_name, Some(&format!("META_CATEGORY LIKE '{}'", name)), )? .into_iter() @@ -89,6 +91,7 @@ impl Scenario for CrossRecipeScenario { { Ok(Self { // TODO: Correct this relative path abomination + database_name: "Equipements".into(), database: Self::DatabaseType::new("./databases/weapons.db")?, config, }) -- 2.45.1 From 5b3972a906fad2a3a015bf2c7d0545603dc63eb1 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 22 Feb 2025 05:45:42 +0100 Subject: [PATCH 64/97] Adds more to the graph --- weaponry/Cargo.toml | 4 +- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/.rustfmt.toml | 2 +- weaponry/examples/usage_scenario.rs | 108 +++++++++++++++--- .../equipement_advanced_repr.rs | 32 +++--- .../equipement_impl_basics.rs | 30 +---- .../weaponry_structs/equipement_structs.rs | 31 ++++- 7 files changed, 145 insertions(+), 62 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 291e2c0..d7f70a4 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -17,15 +17,13 @@ strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" regex = "1.11.1" charming = { version = "0.4.0", features = [] } -# chrono = "0.4.39" -# leptos = { version = "0.7.7", features = ["csr"] } -# leptos-use = "0.15" [dev-dependencies] criterion = { version = "0.5" } regex = "1.11.1" pretty_assertions = "^1.4" logos = "^0.15" +clap = { version = "4.5.30", features = ["derive"] } [[bench]] name = "iter_creation" diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 1ad235a301c6a91c31f9aefb22ec8b527a47bebb..2dd403301c8450cdaeccac0c60f736c15d055347 100644 GIT binary patch delta 221 zcmZp8z}WDBae_2s^F$eE#^#L)3+;J1|1xMZN74%Id=Mgr$+iocSelC9@*aai&rx4aRGX)r1xtS2@3BOq^^bA~kuQlgH%gA{v|byL@C}0b1%cd5fppW_PchssOK{ BKu`bx delta 181 zcmZp8z}WDBae_2s<3t%}#>R~a3+;KCDj2jGG8y=n@tg4-oy;d-rO4FG;>-M>xt}4E z=^2w6<4wkPMjeKO4EaC^0h1M-BQ^^-ZfE3Xc3|LE*X7_~*NWptef4vcB%pZU1KzS diff --git a/weaponry/examples/.rustfmt.toml b/weaponry/examples/.rustfmt.toml index 98b9e7f..9a9035c 100644 --- a/weaponry/examples/.rustfmt.toml +++ b/weaponry/examples/.rustfmt.toml @@ -1 +1 @@ -max_width = 278 +# max_width = 278 diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index f5f6174..4ccdb25 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -3,11 +3,24 @@ //! Test use case of a scenario //! //! +use charming::component::Legend; +use charming::element::Orient; +use clap::Parser; + +#[derive(Parser, Debug)] +/// Basic cli +pub struct ParserCLIArgs { + /// The path to save to. + pub path: Option, +} use charming::HtmlRenderer; use charming::{ Chart, - component::{Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, ToolboxDataZoom, VisualMap, VisualMapType}, + component::{ + Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, + ToolboxDataZoom, + }, element::{AxisType, Tooltip, Trigger}, series::Line, }; @@ -34,39 +47,100 @@ fn main() { #[allow(dead_code)] fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { println!("{}", refined_list.get_report(Some("Refined List"))); - println!("Saved initial data as {}.html: {:?}", save_path, refined_list.write_csv(Path::new(&format!("{save_path}.csv")))); + println!( + "Saved initial data as {}.html: {:?}", + save_path, + refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) + ); } pub fn make_chart(data: &mut RefinedEquipementList) -> Chart { - data.inner.sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); - let raw_data = data.inner.iter().map(|refeq| (refeq.inner.name.join(" "), refeq.advanced.dps_safe)); + data.inner + .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + let raw_data = data.inner.iter().map(|refeq| { + ( + &refeq.advanced.display_name, + refeq.advanced.dps_safe, + refeq.advanced.max_damage_per_action, + refeq.advanced.armor_break_per_turn, + ) + }); let mut data_list = vec![]; - let mut value_list = vec![]; + let mut dps_safe = vec![]; + let mut max_damage_per_action = vec![]; + let mut armor_break_per_turn = vec![]; - raw_data.into_iter().for_each(|(date, value)| { - data_list.push(date); - value_list.push(value); + raw_data.into_iter().for_each(|(index, dps_s, dpa, abpt)| { + data_list.push(index); + dps_safe.push(dps_s); + max_damage_per_action.push(dpa); + armor_break_per_turn.push(abpt); }); Chart::new() - .title(Title::new().text("Gradient along the y axis").left("center")) + .title( + Title::new() + .text("Damage for all cross-gen products") + .left("center"), + ) + .legend( + Legend::new() + .left(10) + .top("middle") + .orient(Orient::Vertical) + .data(vec![ + "dps_safe", + "max_damage_per_action", + "armor_break_per_turn", + ]), + ) .tooltip(Tooltip::new().trigger(Trigger::Axis)) - .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(0).min(0).max(400)) - .x_axis(Axis::new().data(data_list.to_vec()).type_(AxisType::Category).boundary_gap(false)) + .x_axis( + Axis::new() + .data(data_list.to_vec()) + .type_(AxisType::Category), + ) .y_axis(Axis::new()) - .grid(Grid::new()) - .series(Line::new().show_symbol(false).data(value_list.clone())) - .data_zoom(DataZoom::new().type_(DataZoomType::Inside).start(0).end(100)) + .grid(Grid::new().contain_label(true)) + .series( + Line::new().data(dps_safe).name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), + ) + .series( + Line::new() + .data(max_damage_per_action) + .name("max_damage_per_action"), + ) + .series( + Line::new() + .data(armor_break_per_turn) + .name("armor_break_per_turn"), + ) + .data_zoom( + DataZoom::new() + .type_(DataZoomType::Inside) + .start(0) + .end(100), + ) .data_zoom(DataZoom::new().start(0).end(100)) - .toolbox(Toolbox::new().feature(Feature::new().data_zoom(ToolboxDataZoom::new().y_axis_index("none")).restore(Restore::new()).save_as_image(SaveAsImage::new()))) + .toolbox( + Toolbox::new().feature( + Feature::new() + .data_zoom(ToolboxDataZoom::new().y_axis_index("none")) + .restore(Restore::new()) + .save_as_image(SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) .tooltip(Tooltip::new().trigger(Trigger::Axis)) } fn render_data(data: &mut RefinedEquipementList, save_path: &str) { - let mut renderer = HtmlRenderer::new("MOOO", 1920, 1080).theme(charming::theme::Theme::Dark); + let mut renderer = + HtmlRenderer::new("Ravenous Balancing", 4000, 2000).theme(charming::theme::Theme::Dark); // Save the chart as HTML file. println!("Saving to {save_path}.html"); - renderer.save(&make_chart(data), format!("{save_path}.html")).unwrap(); + renderer + .save(&make_chart(data), format!("{save_path}.html")) + .unwrap(); } // // Load DB diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 0e79e09..5221e02 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -97,7 +97,7 @@ pub struct AdvancedStats { pub display_name: String, pub damage_per_attack: f64, pub damage_per_turn: f64, - pub damage_per_action: f64, + pub max_damage_per_action: f64, pub armor_break_per_attack: f64, pub armor_break_per_turn: f64, pub armor_break_per_action: f64, @@ -107,8 +107,8 @@ pub struct AdvancedStats { pub expected_armor_break_per_turn: f64, /// Dps with two actions and 5 dices pub dps_safe: f64, - /// Dps with four actions and 11 dices - pub dps_unsafe: f64, + // /// Dps with four actions and 11 dices + // pub dps_unsafe: f64, // All other criterias are already in the inner as raw criterias } impl From<&InnerEquipementStats> for AdvancedStats { @@ -122,7 +122,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { display_name: value.name.join(" "), damage_per_attack, damage_per_turn: damage_per_attack * 2., - damage_per_action: damage_per_attack / (value.action_cost as f64), + max_damage_per_action: damage_per_attack / (value.action_cost as f64), armor_break_per_attack, armor_break_per_turn: armor_break_per_attack * 2., armor_break_per_action: armor_break_per_attack / value.action_cost as f64, @@ -131,7 +131,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { expected_armor_break_per_turn: (damage_per_attack + 6. - 8.) .min(armor_break_per_attack), dps_safe: damage_matrix.get_safe_dmg(value.action_cost), - dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), + // dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), damage_matrix, } } @@ -155,19 +155,21 @@ impl DamageMatrix { // TODO: This safe damage actually uses 5 dices * 2 instead of doing max(5 * 1 , 2 * 1 + 3 * 1) pub fn get_safe_dmg(&self, attack_cost: i8) -> f64 { let _ = attack_cost; - (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3. + (self.get_damage(Precision::Low, DiceNumber::Few) + + self.get_damage(Precision::Medium, DiceNumber::Few) + + self.get_damage(Precision::High, DiceNumber::Few)) + / 3. } /// The "unsage" damage, as in, full dice, 2 attacks // TODO: This damages does max(Max dices * 1, 5 dices * 2), which might not be optimal pub fn get_unsafe_dmg(&self, attack_cost: i8) -> f64 { - match attack_cost { - 1 => f64::max( - self.get_safe_dmg(attack_cost) * 2., - (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3., - ), - 2 => (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3., - _ => 0., - } + f64::max( + self.get_safe_dmg(attack_cost) * 2., + (self.get_damage(Precision::Low, DiceNumber::Many) + + self.get_damage(Precision::Medium, DiceNumber::Many) + + self.get_damage(Precision::High, DiceNumber::Many)) + / 3., + ) } } impl Serialize for DamageMatrix { @@ -267,7 +269,7 @@ impl Precision { match self { Precision::High => 9, Precision::Medium => 6, - Precision::Low => 3, + Precision::Low => 4, } } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 4e199f4..dc7870d 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -16,7 +16,10 @@ use crate::interfaces::{FilterFunction, Reportable}; use super::{ Equipement, InitialEquipementList, equipement_advanced_repr::RefinedEquipementList, - equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, + equipement_structs::{ + EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats, + filter_id_unique_and_right_category, + }, }; impl From for Equipement { @@ -31,7 +34,7 @@ impl From for Equipement { fn from(val: EqMaterial) -> Self { Self { stats: val.stats, - ..Default::default() + filter_function: FilterFunction::new(filter_id_unique_and_right_category()), } } } @@ -44,28 +47,7 @@ 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| { - // 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, - } - }), + filter_function: FilterFunction::new(filter_id_unique_and_right_category()), } } } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 3fc66ce..15ceb05 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -33,18 +33,45 @@ pub struct Equipement { impl Default for Equipement { fn default() -> Self { Self { - filter_function: FilterFunction::new(default_filter()), + filter_function: FilterFunction::new(filter_id_unique()), stats: InnerEquipementStats::random_new(), } } } /// The default filter to use, usefull to implement a new filter function that also uses the default filter -pub(crate) fn default_filter() +pub(crate) fn filter_id_unique() -> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { &|self_, lhs| lhs.id.iter().all(|a| *a != self_.id[0]) } +/// Create a new filter function mandating the object be of the right category +pub(crate) fn filter_id_unique_and_right_category() +-> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { + &|sel, lhs| { + // println!( + // "Trying to match {:?} with {:?}. {:?} {:?}", + // sel.name, lhs.name, sel.target, lhs.macro_category + // ); + lhs.id.iter().all(|a| *a != sel.id[0]) + & 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 + // TODO: Testing a generic anyway + (None, _) => true, // 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, + } + } +} impl FilterFunction { /// Generate a new filter // TODO: This static lifetime is basically telling us that an owned value is needed -- 2.45.1 From f3bb2c9d8007fc4b95f246c46ded0628f708694e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 00:19:44 +0100 Subject: [PATCH 65/97] Cleaning up the scenario and progressive integration into the main impl --- weaponry/examples/usage_scenario.rs | 167 ++++-------------- weaponry/src/error.rs | 37 ++-- weaponry/src/interfaces.rs | 47 ++--- .../equipement_advanced_repr.rs | 144 ++++++++++++++- .../equipement_impl_basics.rs | 13 -- .../weaponry_structs/equipement_impl_io.rs | 6 +- .../weaponry_structs/equipement_scenario.rs | 144 +++++++-------- 7 files changed, 280 insertions(+), 278 deletions(-) diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 4ccdb25..bb614ca 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -3,46 +3,56 @@ //! Test use case of a scenario //! //! -use charming::component::Legend; -use charming::element::Orient; use clap::Parser; - -#[derive(Parser, Debug)] -/// Basic cli -pub struct ParserCLIArgs { - /// The path to save to. - pub path: Option, -} - -use charming::HtmlRenderer; -use charming::{ - Chart, - component::{ - Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, - ToolboxDataZoom, - }, - element::{AxisType, Tooltip, Trigger}, - series::Line, -}; use std::path::Path; +use weaponry::interfaces::ToAnalysis; // TODO : All of these should likely be in the prelude if used like this use weaponry::weaponry_structs::CrossRecipeScenario; -use weaponry::weaponry_structs::equipement_scenario::ConfigMock; +use weaponry::weaponry_structs::equipement_scenario::ConfigEquipementScenario; use weaponry::{ interfaces::{Reportable, Scenario, ToCSV}, weaponry_structs::RefinedEquipementList, }; // use weaponry::interfaces:: fn main() { - let save_path = "data/first_data"; - let scenarios = CrossRecipeScenario::new_with_config(ConfigMock {}).unwrap(); - let mut refined_list = scenarios.generate_refined_recipes().unwrap(); - // Render as html - render_data(&mut refined_list, save_path); - // // Export as csv + let args = CLIArgs::parse(); + let save_path = args.path.unwrap_or("data/first_data".into()); + let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario { + table_name: "Equipements".into(), + db_path: "./databases/weapons.db".into(), + shape: args.shapes.then_some(()), + materials: args.materials, + nature: args.natures.then_some(()), + finishing: args.finishing.then_some(()), + }) + .unwrap(); + let refined_list = scenarios.generate_refined_recipes().unwrap(); + + // if args.html_export{} + refined_list.write_html(&save_path).unwrap(); + + // if args.csv_export{} // export_as_csv(&refined_list, save_path); } +#[derive(Parser, Debug)] +/// Basic cli +pub struct CLIArgs { + /// The path to save to. + pub path: Option, + /// Wether to generate shapes + #[arg(short, long, default_value_t = true)] + pub shapes: bool, + /// Wether to generate materials + #[arg(short, long)] + pub materials: Option, + /// Wether to generate all natures + #[arg(short, long, default_value_t = true)] + pub natures: bool, + /// Wether to generate all finishing + #[arg(short, long, default_value_t = false)] + pub finishing: bool, +} #[allow(dead_code)] fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { @@ -53,106 +63,3 @@ fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) ); } - -pub fn make_chart(data: &mut RefinedEquipementList) -> Chart { - data.inner - .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); - let raw_data = data.inner.iter().map(|refeq| { - ( - &refeq.advanced.display_name, - refeq.advanced.dps_safe, - refeq.advanced.max_damage_per_action, - refeq.advanced.armor_break_per_turn, - ) - }); - let mut data_list = vec![]; - let mut dps_safe = vec![]; - let mut max_damage_per_action = vec![]; - let mut armor_break_per_turn = vec![]; - - raw_data.into_iter().for_each(|(index, dps_s, dpa, abpt)| { - data_list.push(index); - dps_safe.push(dps_s); - max_damage_per_action.push(dpa); - armor_break_per_turn.push(abpt); - }); - - Chart::new() - .title( - Title::new() - .text("Damage for all cross-gen products") - .left("center"), - ) - .legend( - Legend::new() - .left(10) - .top("middle") - .orient(Orient::Vertical) - .data(vec![ - "dps_safe", - "max_damage_per_action", - "armor_break_per_turn", - ]), - ) - .tooltip(Tooltip::new().trigger(Trigger::Axis)) - .x_axis( - Axis::new() - .data(data_list.to_vec()) - .type_(AxisType::Category), - ) - .y_axis(Axis::new()) - .grid(Grid::new().contain_label(true)) - .series( - Line::new().data(dps_safe).name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), - ) - .series( - Line::new() - .data(max_damage_per_action) - .name("max_damage_per_action"), - ) - .series( - Line::new() - .data(armor_break_per_turn) - .name("armor_break_per_turn"), - ) - .data_zoom( - DataZoom::new() - .type_(DataZoomType::Inside) - .start(0) - .end(100), - ) - .data_zoom(DataZoom::new().start(0).end(100)) - .toolbox( - Toolbox::new().feature( - Feature::new() - .data_zoom(ToolboxDataZoom::new().y_axis_index("none")) - .restore(Restore::new()) - .save_as_image(SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), - ), - ) - .tooltip(Tooltip::new().trigger(Trigger::Axis)) -} - -fn render_data(data: &mut RefinedEquipementList, save_path: &str) { - let mut renderer = - HtmlRenderer::new("Ravenous Balancing", 4000, 2000).theme(charming::theme::Theme::Dark); - // Save the chart as HTML file. - println!("Saving to {save_path}.html"); - renderer - .save(&make_chart(data), format!("{save_path}.html")) - .unwrap(); -} - -// // 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/error.rs b/weaponry/src/error.rs index 808b9d8..fba7e58 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -3,6 +3,7 @@ //! Inner weaponry error definition #![allow(missing_docs, clippy::missing_docs_in_private_items)] +use charming::EchartsError; use thiserror::Error; #[derive(Error, Debug)] @@ -32,22 +33,28 @@ pub enum FatalEquipementError { #[error("Couldn't convert into type {origin_type} with data {data}")] Conversion { origin_type: String, data: String }, + + #[error("An error occured with your current CLI configuration: {0}")] + CLISelection(String), + + #[error("Couldn't save the chart as an error occured during the process : {0}")] + SaveCharmingChart(#[from] EchartsError), } -#[derive(Error, Debug)] -/// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program -pub enum LocalEquipementError { - #[error("Very simple error")] - Oops, -} +// #[derive(Error, Debug)] +// /// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program +// pub enum LocalEquipementError { +// #[error("Very simple error")] +// Oops, +// } -#[derive(Error, Debug)] -/// An equipement error, either unrecoverable, indicating a that the execution -/// flow must be stopped and only an user input can solve the issue -pub enum EquipementError { - #[error("An unrecoverable error occured: {0}")] - Fatal(#[from] FatalEquipementError), +// #[derive(Error, Debug)] +// /// An equipement error, either unrecoverable, indicating a that the execution +// /// flow must be stopped and only an user input can solve the issue +// pub enum EquipementError { +// #[error("An unrecoverable error occured: {0}")] +// Fatal(#[from] FatalEquipementError), - #[error("A local error occured an wasn't recovered from: {0}")] - Local(#[from] LocalEquipementError), -} +// #[error("A local error occured an wasn't recovered from: {0}")] +// Local(#[from] LocalEquipementError), +// } diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 05a8d0e..b4a4a75 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -10,7 +10,7 @@ use std::{path::Path, rc::Rc}; use more_fields::FieldsAsSlice; use serde::de::DeserializeOwned; -use crate::error::{EquipementError, FatalEquipementError}; +use crate::error::FatalEquipementError; /// Trait representing a view table /// @@ -42,7 +42,7 @@ pub trait ViewTable { /// While it is possible to enforce from_recipe_collection, doing so would require the viewtable /// lock itseld to a particular recipe. /// While it is the case as of now, matters are not yet set in stone -pub trait RefinedList { +pub trait RefinedList: ToTex + ToCSV + ToAnalysis { // Must implement From, is it worth adding as a prerequite type ? // type OriginCollection: Into; } @@ -150,6 +150,14 @@ pub trait ToCSV { fn write_csv(&self, path: &Path) -> csv::Result<()>; } +/// This element can be converted to an interactive .html +pub trait ToAnalysis { + /// Write as html + fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>; + + // TODO: Add sorting methods as no analysis can be done without filtering and sorting +} + /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { /// Create the database from a file @@ -205,45 +213,16 @@ pub trait Reportable { pub trait Scenario { /// The inner database type type DatabaseType: RecipeDatabase; - /// The type of viewtable that must be returned by the scenario - // Could also use dyn dispatch but since all of it is so tied down... - type ViewTableType: ViewTable; /// The type of the final recipe list - type FinalListType: RefinedList; + type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis; /// Inner configuration type Config; /// Create a Scenario from a given config - fn new_with_config(config: Self::Config) -> Result + fn new_with_config(config: Self::Config) -> Result where Self: Sized; - // /// Load all database into intermediate representation - // fn load_from_database() -> Result - // where - // Self: std::marker::Sized; - - // /// Configure the scenario to the user's needs - // fn configure_scenario(&mut self, config: Self::Config) -> Result<(), FatalEquipementError>; - - // All these steps should be implemented but not required - // enforcing them helps writing new impls more easily but is not really nice in any way - // - // /// Process the inner representations and get a list of results - // fn process_inner_representation(&self) -> Result<(), FatalEquipementError>; //Result<(), EquipementError> - - // /// Process inner recipes into a Final list - // /// - // /// This will generate the recipe list using the prefered method of the Scenario (Fixed Recipes or Cross Recipes or Whatever) - // fn process_recipes(&self); - - // /// Process the recipes into a Refined Recipes - // fn refine_recipes(&self); - /// Generate the final list type - fn generate_refined_recipes(&self) -> Result; - - /// Gather the selected view tables - /// All the inner generation is done gradually and populate all section to finally generate the views - fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType; + fn generate_refined_recipes(&self) -> Result; } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 5221e02..f680f8b 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -12,7 +12,11 @@ use core::f64; use std::fmt::Display; -use crate::interfaces::RefinedList; +use crate::{ + error::FatalEquipementError, + interfaces::{RefinedList, ToAnalysis, ToTex}, +}; +use charming::element::Orient; use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; use probability::prelude::{Binomial, Discrete}; use serde::Serialize; @@ -64,6 +68,126 @@ pub struct RefinedEquipementList { // Just a checkmark impl RefinedList for RefinedEquipementList {} +impl ToTex for RefinedEquipementList { + fn to_tex(&self) -> String { + todo!() + } +} +impl ToAnalysis for RefinedEquipementList { + fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { + let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) + .theme(charming::theme::Theme::Dark); + // Save the chart as HTML file. + renderer.save(&make_chart(self), format!("{save_path}.html"))?; + return Ok(()); + + // TODO: Migrate this into the view / renderer + // TODO: End the view idea and only focus on this renderer + pub fn make_chart(data: &RefinedEquipementList) -> charming::Chart { + // TODO: Add back sorting + // data.inner + // .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + + // TODO: Convert to macro + let raw_data = data.inner.iter().map(|refeq| { + ( + &refeq.advanced.display_name, + refeq.advanced.dps_safe, + refeq.advanced.max_damage_per_action, + refeq.advanced.damage_per_turn, + refeq.advanced.armor_break_per_turn, + ) + }); + let mut data_list = vec![]; + let mut dps_safe = vec![]; + let mut max_damage_per_action = vec![]; + let mut max_damage_per_turn = vec![]; + let mut armor_break_per_turn = vec![]; + + raw_data + .into_iter() + .for_each(|(index, dps_s, dpa, dpt, abpt)| { + data_list.push(index); + dps_safe.push(dps_s); + max_damage_per_action.push(dpa); + max_damage_per_turn.push(dpt); + armor_break_per_turn.push(abpt); + }); + + // TODO: End of macro conversion + + // TODO: Call this iteratively with all elements in macro + charming::Chart::new() + .title( + charming::component::Title::new() + .text("Damage for all cross-gen products") + .left("center"), + ) + .legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(Orient::Vertical) + .data(vec![ + "dps_safe", + "max_damage_per_action", + "max_damage_per_turn", + "armor_break_per_turn", + ]), + ) + .tooltip( + charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis), + ) + .x_axis( + charming::component::Axis::new() + .data(data_list.to_vec()) + .type_(charming::element::AxisType::Category), + ) + .y_axis(charming::component::Axis::new()) + .grid(charming::component::Grid::new().contain_label(true)) + .series( + charming::series::Line::new() + .data(dps_safe) + .name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), + ) + .series( + charming::series::Line::new() + .data(max_damage_per_action) + .name("max_damage_per_action"), + ) + .series( + charming::series::Line::new() + .data(max_damage_per_turn) + .name("max_damage_per_turn"), + ) + .series( + charming::series::Line::new() + .data(armor_break_per_turn) + .name("armor_break_per_turn"), + ) + .data_zoom( + charming::component::DataZoom::new() + .type_(charming::component::DataZoomType::Inside) + .start(0) + .end(100), + ) + .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .toolbox( + charming::component::Toolbox::new().feature( + charming::component::Feature::new() + .data_zoom( + charming::component::ToolboxDataZoom::new().y_axis_index("none"), + ) + .restore(charming::component::Restore::new()) + .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) + .tooltip( + charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis), + ) + } + } +} impl From for RefinedEquipementList { fn from(value: InitialEquipementList) -> Self { @@ -225,17 +349,23 @@ impl DamageMatrix { } /// Calculate the binomial distribution and average the damage from there -fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, dices: usize) -> f64 { - let p = ((precision as i8 + value.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); +fn binomial_dice_distribution( + equipement: &InnerEquipementStats, + precision: usize, + dices: usize, +) -> f64 { + let p = ((precision as i8 + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); let binomial = Binomial::new(dices, p); (0..dices + 1) .map(|target_dices| { let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize; if target_dices >= 1 { - (value.damage as f64 - + value.p_damage as f64 - * (target_dices.clamp(0, value.rmax as usize).saturating_sub(1)) as f64) + (equipement.damage as f64 + + equipement.p_damage as f64 + * (target_dices + .clamp(0, equipement.rmax as usize) + .saturating_sub(1)) as f64) * probability_success } else { 0. @@ -244,6 +374,8 @@ fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, di .fold(0., |a, b| a + b) } +// TODO: Change this to be a thin type and replace enum by new(nb) et high(), med() etc.. +// : And add a way to do ranges easily /// The precision infered for a damage calculation event #[derive(EnumIter, Clone, Copy, Display)] #[allow(clippy::missing_docs_in_private_items)] diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index dc7870d..4c069e9 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -39,29 +39,16 @@ impl From for Equipement { } } -// TODO: Change this into tryfrom impl From for Equipement { fn from(val: EqNature) -> Self { Self { stats: val.stats, - // 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(filter_id_unique_and_right_category()), } } } -// (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 { diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs index ee62cf8..e7a5215 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -2,11 +2,9 @@ // File: weaponry/src/weaponry_structs/equipement_impl_io.rs //! All implementation IO specific (mainly export and serde) -use std::path::Path; - -use crate::interfaces::ToCSV; - use super::equipement_advanced_repr::RefinedEquipementList; +use crate::interfaces::ToCSV; +use std::path::Path; impl ToCSV for RefinedEquipementList { fn write_csv(&self, path: &Path) -> csv::Result<()> { diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index d48a426..4e180cb 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -7,54 +7,48 @@ //! and therefore mostly serves as a TO-DO list //! -#![allow(dead_code)] -use crate::error::FatalEquipementError; -#[allow(unused_imports)] -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::{ - error::EquipementError, - interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable}, + error::FatalEquipementError, + interfaces::{RecipeCollection, RecipeDatabase, Scenario}, + weaponry_structs::{ + Equipement, InitialEquipementList, RefinedEquipementList, + equipement_impl_database::EquipementDatabase, + equipement_structs::{ + DatabaseEquipementStats, EqFinishing, EqMaterial, EqNature, EqShape, + InnerEquipementStats, + }, + }, }; -use super::Equipement; -use super::equipement_advanced_repr::RefinedEquipementList; -use super::equipement_impl_database::EquipementDatabase; -use super::equipement_structs::InnerEquipementStats; - -/// Mock config -pub struct ConfigMock {} -/// Mock Viewtable -pub struct ViewtableMock {} -impl ViewTable for ViewtableMock { - type InterestElementList = RefinedEquipementList; - - fn index_of_interest_points(&self) -> Vec { - todo!() - } - - fn find_points_of_interest(representation: &Self::InterestElementList) -> Self { - let _ = representation; - todo!() - } +/// Base Equipement Scenario config +pub struct ConfigEquipementScenario { + /// Table Name + pub table_name: String, + /// Database path + pub db_path: String, + // TODO[2]: Add something smart here to take care of the selection process + /// Wether the shapes are selected + pub shape: Option<()>, + /// Wether the materials are selected, and how many iteration there are + pub materials: Option, + /// Wether the natures are selected + pub nature: Option<()>, + /// Wether the finishing touches are selected + pub finishing: Option<()>, } /// A simple cross recipe scenario #[allow(clippy::missing_docs_in_private_items)] pub struct CrossRecipeScenario { // TODO: Should obv be inside the config - database_name: String, database: EquipementDatabase, - config: ConfigMock, + config: ConfigEquipementScenario, } impl CrossRecipeScenario { /// Automatically deserialize into an equipement + // TODO: Add to trait + // TODO: Add an optionnal filter fn deserde_into_equipement( &self, name: &str, @@ -62,10 +56,12 @@ impl CrossRecipeScenario { where T: TryFrom + From + Into, { + // TODO: This likely has too high a complexity and should either be a blanket implementation + // : or require the inner workings to implement methods to easily allow this deserialisation Ok(InitialEquipementList::from_vectored( self.database .serialize_vec_from_table::( - &self.database_name, + &self.config.table_name, Some(&format!("META_CATEGORY LIKE '{}'", name)), )? .into_iter() @@ -77,63 +73,59 @@ impl CrossRecipeScenario { .collect::, FatalEquipementError>>()?, )) } + + /// Generate all the operations to be processed with the current config + // TODO: Defer this to a custom type in the config some sort of OperationSelector + fn generate_selected_operation( + &self, + ) -> Result, FatalEquipementError> { + let mut operations = Vec::with_capacity(8); + if self.config.shape.is_some() { + operations.push(self.deserde_into_equipement::("Shape")?); + } + if let Some(qt) = self.config.materials { + for _ in 0..qt { + operations.push(self.deserde_into_equipement::("Materials")?); + } + } + if self.config.nature.is_some() { + operations.push(self.deserde_into_equipement::("Nature")?); + } + if self.config.finishing.is_some() { + operations.push(self.deserde_into_equipement::("Finishing")?); + } + if operations.is_empty() { + return Err(FatalEquipementError::CLISelection( + "No step was selected for generation, please select at least one step".into(), + )); + }; + Ok(operations) + } } impl Scenario for CrossRecipeScenario { type DatabaseType = EquipementDatabase; - type ViewTableType = ViewtableMock; type FinalListType = RefinedEquipementList; - type Config = ConfigMock; + type Config = ConfigEquipementScenario; - fn new_with_config(config: Self::Config) -> Result + fn new_with_config(config: Self::Config) -> Result where Self: Sized, { Ok(Self { - // TODO: Correct this relative path abomination - database_name: "Equipements".into(), - database: Self::DatabaseType::new("./databases/weapons.db")?, + database: Self::DatabaseType::new(&config.db_path)?, config, }) } - fn generate_refined_recipes(&self) -> Result { - // TODO: Depending on config, a different filter might be given here - let eq_shape = self.deserde_into_equipement::("Shape")?; - let eq_material = self.deserde_into_equipement::("Materials")?; - let eq_nature = self.deserde_into_equipement::("Nature")?; - #[allow(unused_variables)] - let eq_finishing = self.deserde_into_equipement::("Finishing")?; + fn generate_refined_recipes(&self) -> Result { + let operations = self.generate_selected_operation()?; - // 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")) - // ); + let mut opertation_it = operations.into_iter(); + let mut refined_list = opertation_it.next().unwrap(); - // 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_material); - println!("{}", f_list.get_report(Some("Combined with Materials"))); - f_list.combine_all(&eq_nature); - 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 - Ok(f_list.into()) - } + opertation_it.for_each(|operation| refined_list.combine_all(&operation)); - fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType { - // TODO: Change this depending on the config ? or maybe a scenario is inerently tied to a viewtable ? - // The polymorphism will depend on many factors not yet known :( - Self::ViewTableType::find_points_of_interest(&equipement_list) + Ok(refined_list.into()) } } -- 2.45.1 From 8825587e537c195bcf39cd255010e0af2570c446 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 06:14:51 +0100 Subject: [PATCH 66/97] First working commit on the macro --- weaponry/examples/usage_scenario.rs | 1 + weaponry/src/export.rs | 109 +++++++++ weaponry/src/lib.rs | 1 + .../equipement_advanced_repr.rs | 210 +++++++++--------- .../equipement_impl_database.rs | 2 + 5 files changed, 216 insertions(+), 107 deletions(-) create mode 100644 weaponry/src/export.rs diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index bb614ca..8a0646a 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -29,6 +29,7 @@ fn main() { .unwrap(); let refined_list = scenarios.generate_refined_recipes().unwrap(); + let b = RefinedEquipementList::default(); // if args.html_export{} refined_list.write_html(&save_path).unwrap(); diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs new file mode 100644 index 0000000..dea3e48 --- /dev/null +++ b/weaponry/src/export.rs @@ -0,0 +1,109 @@ +// Workspace: weaponry +// File: weaponry/src/export.rs +//! Module regrouping all generic function related to the exporting +//! +//! Mostly graphs and csv auto conversion + +/// A very complex macro created to add criterias to the graph +/// without repeating self explanatory parameter names in strings +/// +/// The syntax involved in the usage of this macro hence become esoteric +/// +/// # Example +/// ``` +/// # use weaponry::interfaces::RecipeCollection; +/// # use weaponry::add_field_to_chart; +/// # use weaponry::weaponry_structs::RefinedEquipementList; +/// # use weaponry::export::initial_chart; +/// # let self_ = RefinedEquipementList::default(); +/// # let initial_chart: charming::Chart = initial_chart("Damage for all cross-gen products"); +/// add_field_to_chart!( +/// self_, // Usually used inside the implementation and therefore self there +/// initial_chart, +/// ( +/// index # &String, +/// dps_safe # f64, +/// max_damage_per_action # f64, +/// armor_break_per_turn # f64, +/// ), +/// |ref_equipement| { +/// ( +/// &ref_equipement.advanced.display_name, +/// ref_equipement.advanced.max_damage_per_action, +/// ref_equipement.advanced.damage_per_turn, +/// ref_equipement.advanced.armor_break_per_turn, +/// ) +/// } +/// ); +/// ``` +/// +/// # Complexity and maintanability +/// +/// While the added complexity cannot be understated, the whole existence of this macro is +/// first and foremost based on the desire NOT to iterate multiple times on a dataset +/// which could easily reach 600k elements +/// +/// Knowing this tradeoff, the difficulty to maintain is considered an acceptable tradeoff +#[macro_export] +macro_rules! add_field_to_chart { + ($base_struct:expr, $chart:ident, ($names:ident # $name_type:ty, $($table_names:ident # $table_type:ty),* $(,)*), | $closure_name:ident | {($($fields:expr,)*)} + ) => { + let data_collection = $base_struct.inner.iter().map(|$closure_name| ( $($fields,)*) ); + let ($names, $($table_names),*) = data_collection.collect::<(Vec<$name_type>, $(Vec<$table_type>,)*)>(); + let $chart = $chart + .x_axis( + charming::component::Axis::new() + .data($names.to_vec()) + .type_(charming::element::AxisType::Category), + ); + $( + let $chart = $chart + .series( + charming::series::Line::new() + .data($table_names) + .name(stringify!($table_names)), // .line_style(LineStyle::new().color("paleblue")), + ); + )* + } +} + +/// Generate a generic graph, ready to be filled with data +pub fn initial_chart(chart_name: &str) -> charming::Chart { + charming::Chart::new() + .title( + charming::component::Title::new() + .text(chart_name) + .left("center"), + ) + .legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(charming::element::Orient::Vertical) + .data(vec![ + "dps_safe", + "max_damage_per_action", + "max_damage_per_turn", + "armor_break_per_turn", + ]), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .data_zoom( + charming::component::DataZoom::new() + .type_(charming::component::DataZoomType::Inside) + .start(0) + .end(100), + ) + .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .toolbox( + charming::component::Toolbox::new().feature( + charming::component::Feature::new() + .data_zoom(charming::component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(charming::component::Restore::new()) + .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .y_axis(charming::component::Axis::new()) + .grid(charming::component::Grid::new().contain_label(true)) +} diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index cf331bd..4392409 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -7,6 +7,7 @@ mod database; pub mod error; +pub mod export; pub mod interfaces; mod strategy; pub mod weaponry_structs; diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index f680f8b..dafcd93 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -9,6 +9,7 @@ //! of all the fields even when the user will not be interested in them #![allow(dead_code)] +use crate::{add_field_to_chart, export::initial_chart, interfaces::RecipeCollection}; use core::f64; use std::fmt::Display; @@ -16,7 +17,7 @@ use crate::{ error::FatalEquipementError, interfaces::{RefinedList, ToAnalysis, ToTex}, }; -use charming::element::Orient; +use charming::Chart; use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; use probability::prelude::{Binomial, Discrete}; use serde::Serialize; @@ -73,119 +74,116 @@ impl ToTex for RefinedEquipementList { todo!() } } + impl ToAnalysis for RefinedEquipementList { + // TODO[3]: Consider wether the naming should be a parameter, + // or a config should be given or if the scenario should be fed again the Refined and ... fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) .theme(charming::theme::Theme::Dark); - // Save the chart as HTML file. - renderer.save(&make_chart(self), format!("{save_path}.html"))?; - return Ok(()); - // TODO: Migrate this into the view / renderer - // TODO: End the view idea and only focus on this renderer - pub fn make_chart(data: &RefinedEquipementList) -> charming::Chart { - // TODO: Add back sorting - // data.inner - // .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + let initial_chart: Chart = initial_chart("Damage for all cross-gen products"); - // TODO: Convert to macro - let raw_data = data.inner.iter().map(|refeq| { + // TODO[!]: Add sorting + // data.inner + // .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + + // let index: Vec<_>; + // let data_list: Vec<_>; + // (index, data_list) = self + // .inner + // .iter() + // .map(|ref_equipement| { + // ( + // &ref_equipement.advanced.display_name, + // &ref_equipement.advanced.damage_per_turn, + // ) + // }) + // .collect(); + + // // TODO[5]: This macro work is interesting while flawed and the optimisations are not worth more time invested now + // // TODO: Add this as a function and a macro + // // TODO: Convert to macro + // // TODO: Call this iteratively with all elements in macro + // let raw_data = self.inner.iter().map(|refeq| { + // ( + // &refeq.advanced.display_name, + // refeq.advanced.dps_safe, + // refeq.advanced.max_damage_per_action, + // refeq.advanced.damage_per_turn, + // refeq.advanced.armor_break_per_turn, + // ) + // }); + + add_field_to_chart!( + self, + initial_chart, + ( + index # &String, + dps_safe # f64, + max_damage_per_action # f64, + armor_break_per_turn # f64, + ), + |ref_equipement| { ( - &refeq.advanced.display_name, - refeq.advanced.dps_safe, - refeq.advanced.max_damage_per_action, - refeq.advanced.damage_per_turn, - refeq.advanced.armor_break_per_turn, + &ref_equipement.advanced.display_name, + ref_equipement.advanced.max_damage_per_action, + ref_equipement.advanced.damage_per_turn, + ref_equipement.advanced.armor_break_per_turn, ) - }); - let mut data_list = vec![]; - let mut dps_safe = vec![]; - let mut max_damage_per_action = vec![]; - let mut max_damage_per_turn = vec![]; - let mut armor_break_per_turn = vec![]; + } + ); + // add_field_to_chart!(dps_safe, graph); - raw_data - .into_iter() - .for_each(|(index, dps_s, dpa, dpt, abpt)| { - data_list.push(index); - dps_safe.push(dps_s); - max_damage_per_action.push(dpa); - max_damage_per_turn.push(dpt); - armor_break_per_turn.push(abpt); - }); + // let (data_list, dps_safe, max_damage_per_action, max_damage_per_turn, armor_break_per_turn) = + // raw_data.collect::<(Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>)>(); + // let mut data_list = vec![]; + // let mut dps_safe = vec![]; + // let mut max_damage_per_action = vec![]; + // let mut max_damage_per_turn = vec![]; + // let mut armor_break_per_turn = vec![]; - // TODO: End of macro conversion + // raw_data + // .into_iter() + // .for_each(|(index, dps_s, dpa, dpt, abpt)| { + // data_list.push(index); + // dps_safe.push(dps_s); + // max_damage_per_action.push(dpa); + // max_damage_per_turn.push(dpt); + // armor_break_per_turn.push(abpt); + // }); - // TODO: Call this iteratively with all elements in macro - charming::Chart::new() - .title( - charming::component::Title::new() - .text("Damage for all cross-gen products") - .left("center"), - ) - .legend( - charming::component::Legend::new() - .left(10) - .top("middle") - .orient(Orient::Vertical) - .data(vec![ - "dps_safe", - "max_damage_per_action", - "max_damage_per_turn", - "armor_break_per_turn", - ]), - ) - .tooltip( - charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis), - ) - .x_axis( - charming::component::Axis::new() - .data(data_list.to_vec()) - .type_(charming::element::AxisType::Category), - ) - .y_axis(charming::component::Axis::new()) - .grid(charming::component::Grid::new().contain_label(true)) - .series( - charming::series::Line::new() - .data(dps_safe) - .name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), - ) - .series( - charming::series::Line::new() - .data(max_damage_per_action) - .name("max_damage_per_action"), - ) - .series( - charming::series::Line::new() - .data(max_damage_per_turn) - .name("max_damage_per_turn"), - ) - .series( - charming::series::Line::new() - .data(armor_break_per_turn) - .name("armor_break_per_turn"), - ) - .data_zoom( - charming::component::DataZoom::new() - .type_(charming::component::DataZoomType::Inside) - .start(0) - .end(100), - ) - .data_zoom(charming::component::DataZoom::new().start(0).end(100)) - .toolbox( - charming::component::Toolbox::new().feature( - charming::component::Feature::new() - .data_zoom( - charming::component::ToolboxDataZoom::new().y_axis_index("none"), - ) - .restore(charming::component::Restore::new()) - .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), - ), - ) - .tooltip( - charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis), - ) - } + // TODO: End of macro conversion + + // let initial_chart = initial_chart + // .x_axis( + // charming::component::Axis::new() + // .data(data_list.to_vec()) + // .type_(charming::element::AxisType::Category), + // ) + // .series( + // charming::series::Line::new() + // .data(dps_safe) + // .name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), + // ) + // .series( + // charming::series::Line::new() + // .data(max_damage_per_action) + // .name("max_damage_per_action"), + // ) + // .series( + // charming::series::Line::new() + // .data(max_damage_per_turn) + // .name("max_damage_per_turn"), + // ) + // .series( + // charming::series::Line::new() + // .data(armor_break_per_turn) + // .name("armor_break_per_turn"), + // ); + + renderer.save(&initial_chart, format!("{save_path}.html"))?; + Ok(()) } } @@ -201,10 +199,8 @@ impl From for RefinedEquipementList { } } -#[cfg(test)] -use crate::interfaces::RecipeCollection; - -#[cfg(test)] +// #[cfg(test)] +// Used in exemples impl Default for RefinedEquipementList { fn default() -> Self { let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index ebc47db..7f4ef60 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -61,6 +61,7 @@ pub struct EquipementFixedRecipe { #[allow(missing_docs)] pub struct MockRecipe {} +// TODO[1] : Add fixed recipes impl FixedRecipe for EquipementFixedRecipe { type KeyList = MockRecipe; @@ -73,6 +74,7 @@ impl FixedRecipe for EquipementFixedRecipe { } } +// TODO[3]: Migrate ASAP from this manual implementation /// Macro converting a value using serde and mapping an in house error macro_rules! from_serde { ($value: expr) => { -- 2.45.1 From f726b7ce15e93f2343dfe00ae393c7860f56e7da Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 06:34:19 +0100 Subject: [PATCH 67/97] Cleans up most of the code of the html render --- weaponry/examples/usage_scenario.rs | 4 +- weaponry/src/interfaces.rs | 8 ++ .../equipement_advanced_repr.rs | 86 +++---------------- 3 files changed, 20 insertions(+), 78 deletions(-) diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 8a0646a..23800e1 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -27,9 +27,9 @@ fn main() { finishing: args.finishing.then_some(()), }) .unwrap(); - let refined_list = scenarios.generate_refined_recipes().unwrap(); + let mut refined_list = scenarios.generate_refined_recipes().unwrap(); + refined_list.inner_sort(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); - let b = RefinedEquipementList::default(); // if args.html_export{} refined_list.write_html(&save_path).unwrap(); diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index b4a4a75..44b93ee 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -152,6 +152,14 @@ pub trait ToCSV { /// This element can be converted to an interactive .html pub trait ToAnalysis { + /// The explicit type of the underlying data + type InnerData; + + /// Sort the inner data with a given closure + fn inner_sort(&mut self, closure: T) + where + T: FnMut(&Self::InnerData, &Self::InnerData) -> std::cmp::Ordering; + /// Write as html fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>; diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index dafcd93..5e73461 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -11,7 +11,7 @@ use crate::{add_field_to_chart, export::initial_chart, interfaces::RecipeCollection}; use core::f64; -use std::fmt::Display; +use std::{cmp::Ordering, fmt::Display}; use crate::{ error::FatalEquipementError, @@ -76,6 +76,15 @@ impl ToTex for RefinedEquipementList { } impl ToAnalysis for RefinedEquipementList { + type InnerData = RefinedEquipement; + + fn inner_sort(&mut self, closure: T) + where + T: FnMut(&RefinedEquipement, &RefinedEquipement) -> Ordering, + { + self.inner.sort_by(closure) + } + // TODO[3]: Consider wether the naming should be a parameter, // or a config should be given or if the scenario should be fed again the Refined and ... fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { @@ -88,33 +97,6 @@ impl ToAnalysis for RefinedEquipementList { // data.inner // .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); - // let index: Vec<_>; - // let data_list: Vec<_>; - // (index, data_list) = self - // .inner - // .iter() - // .map(|ref_equipement| { - // ( - // &ref_equipement.advanced.display_name, - // &ref_equipement.advanced.damage_per_turn, - // ) - // }) - // .collect(); - - // // TODO[5]: This macro work is interesting while flawed and the optimisations are not worth more time invested now - // // TODO: Add this as a function and a macro - // // TODO: Convert to macro - // // TODO: Call this iteratively with all elements in macro - // let raw_data = self.inner.iter().map(|refeq| { - // ( - // &refeq.advanced.display_name, - // refeq.advanced.dps_safe, - // refeq.advanced.max_damage_per_action, - // refeq.advanced.damage_per_turn, - // refeq.advanced.armor_break_per_turn, - // ) - // }); - add_field_to_chart!( self, initial_chart, @@ -133,54 +115,6 @@ impl ToAnalysis for RefinedEquipementList { ) } ); - // add_field_to_chart!(dps_safe, graph); - - // let (data_list, dps_safe, max_damage_per_action, max_damage_per_turn, armor_break_per_turn) = - // raw_data.collect::<(Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>)>(); - // let mut data_list = vec![]; - // let mut dps_safe = vec![]; - // let mut max_damage_per_action = vec![]; - // let mut max_damage_per_turn = vec![]; - // let mut armor_break_per_turn = vec![]; - - // raw_data - // .into_iter() - // .for_each(|(index, dps_s, dpa, dpt, abpt)| { - // data_list.push(index); - // dps_safe.push(dps_s); - // max_damage_per_action.push(dpa); - // max_damage_per_turn.push(dpt); - // armor_break_per_turn.push(abpt); - // }); - - // TODO: End of macro conversion - - // let initial_chart = initial_chart - // .x_axis( - // charming::component::Axis::new() - // .data(data_list.to_vec()) - // .type_(charming::element::AxisType::Category), - // ) - // .series( - // charming::series::Line::new() - // .data(dps_safe) - // .name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), - // ) - // .series( - // charming::series::Line::new() - // .data(max_damage_per_action) - // .name("max_damage_per_action"), - // ) - // .series( - // charming::series::Line::new() - // .data(max_damage_per_turn) - // .name("max_damage_per_turn"), - // ) - // .series( - // charming::series::Line::new() - // .data(armor_break_per_turn) - // .name("armor_break_per_turn"), - // ); renderer.save(&initial_chart, format!("{save_path}.html"))?; Ok(()) -- 2.45.1 From 8a2114da74d191467f45b764a962317f7462920a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 06:53:00 +0100 Subject: [PATCH 68/97] More cleanup on the scenarii impls --- .ignore | 1 + weaponry/helpers/workflow.md | 23 ------------------- weaponry/src/interfaces.rs | 9 ++++++-- .../equipement_advanced_repr.rs | 16 ++++++++----- .../weaponry_structs/equipement_scenario.rs | 2 +- 5 files changed, 19 insertions(+), 32 deletions(-) delete mode 100644 weaponry/helpers/workflow.md diff --git a/.ignore b/.ignore index 8e062ad..523ea06 100644 --- a/.ignore +++ b/.ignore @@ -1 +1,2 @@ *.drawio +*.db diff --git a/weaponry/helpers/workflow.md b/weaponry/helpers/workflow.md deleted file mode 100644 index e253452..0000000 --- a/weaponry/helpers/workflow.md +++ /dev/null @@ -1,23 +0,0 @@ -# TO-Impl List - - Initial Object Representation - - Final Object Representation - - -# Workflow - A B C -Database -> -> -> Balancing data - -> Exported data - -# Description - - A : Use structs defines in weaponry_structs - : impl From for all weapon parts - - B : Every part can be converted to a weapon(ish) - : Use the correct solver to add all parts - - C1 : Use the traits to generate the tex data - - -# Strategy -Since the structs will become more than just weapons but will become craft afterwards, polymorphism is the key - -The creation algorithm will pick a Strategy depending on the user's choice and build a final weapon depending on it -The creation will implement an iterator to go with itertools / rayon ? diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 44b93ee..9847d68 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -160,10 +160,15 @@ pub trait ToAnalysis { where T: FnMut(&Self::InnerData, &Self::InnerData) -> std::cmp::Ordering; + /// Apply a filter to the inner data + /// + /// Careful this filter will consume the original data to avoir reallocating + fn inner_filter(self, closure: T) -> Self + where + T: FnMut(&Self::InnerData) -> bool; + /// Write as html fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>; - - // TODO: Add sorting methods as no analysis can be done without filtering and sorting } /// A generic database+connection, handling all the deserialization of the inner types diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 5e73461..ea8cf36 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -85,6 +85,15 @@ impl ToAnalysis for RefinedEquipementList { self.inner.sort_by(closure) } + fn inner_filter(self, closure: T) -> Self + where + T: FnMut(&RefinedEquipement) -> bool, + { + Self { + inner: self.inner.into_iter().filter(closure).collect::>(), + } + } + // TODO[3]: Consider wether the naming should be a parameter, // or a config should be given or if the scenario should be fed again the Refined and ... fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { @@ -93,10 +102,6 @@ impl ToAnalysis for RefinedEquipementList { let initial_chart: Chart = initial_chart("Damage for all cross-gen products"); - // TODO[!]: Add sorting - // data.inner - // .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); - add_field_to_chart!( self, initial_chart, @@ -133,8 +138,7 @@ impl From for RefinedEquipementList { } } -// #[cfg(test)] -// Used in exemples +// #[cfg(test)] // Used in exemples impl Default for RefinedEquipementList { fn default() -> Self { let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 4e180cb..7098313 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -48,7 +48,7 @@ pub struct CrossRecipeScenario { impl CrossRecipeScenario { /// Automatically deserialize into an equipement // TODO: Add to trait - // TODO: Add an optionnal filter + // TODO: Add an optionnal initial filter ? fn deserde_into_equipement( &self, name: &str, -- 2.45.1 From ab6515c7424c095a9fdd615003a104e7732a09e7 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 07:52:46 +0100 Subject: [PATCH 69/97] Stopped using rather risky usize,i8 into a binomial function --- .../equipement_advanced_repr.rs | 98 +++++++++++++------ 1 file changed, 66 insertions(+), 32 deletions(-) diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index ea8cf36..88de8a0 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -205,7 +205,7 @@ pub struct DamageMatrix { } impl DamageMatrix { /// Get the damage value from given condition - pub fn get_damage(&self, precision: Precision, dices: DiceNumber) -> f64 { + pub fn get_damage(&self, precision: FixedPrecision, dices: FixedDiceNumber) -> f64 { self.damage_matrix[precision as usize + 3 * dices as usize] } @@ -213,9 +213,9 @@ impl DamageMatrix { // TODO: This safe damage actually uses 5 dices * 2 instead of doing max(5 * 1 , 2 * 1 + 3 * 1) pub fn get_safe_dmg(&self, attack_cost: i8) -> f64 { let _ = attack_cost; - (self.get_damage(Precision::Low, DiceNumber::Few) - + self.get_damage(Precision::Medium, DiceNumber::Few) - + self.get_damage(Precision::High, DiceNumber::Few)) + (self.get_damage(FixedPrecision::Low, FixedDiceNumber::Few) + + self.get_damage(FixedPrecision::Medium, FixedDiceNumber::Few) + + self.get_damage(FixedPrecision::High, FixedDiceNumber::Few)) / 3. } /// The "unsage" damage, as in, full dice, 2 attacks @@ -223,9 +223,9 @@ impl DamageMatrix { pub fn get_unsafe_dmg(&self, attack_cost: i8) -> f64 { f64::max( self.get_safe_dmg(attack_cost) * 2., - (self.get_damage(Precision::Low, DiceNumber::Many) - + self.get_damage(Precision::Medium, DiceNumber::Many) - + self.get_damage(Precision::High, DiceNumber::Many)) + (self.get_damage(FixedPrecision::Low, FixedDiceNumber::Many) + + self.get_damage(FixedPrecision::Medium, FixedDiceNumber::Many) + + self.get_damage(FixedPrecision::High, FixedDiceNumber::Many)) / 3., ) } @@ -250,14 +250,14 @@ impl Display for DamageMatrix { table.apply_modifier(UTF8_ROUND_CORNERS); let mut headers = vec![String::from("D\\P")]; headers.append( - &mut Precision::iter() + &mut FixedPrecision::iter() .map(|e| format!("{:.3}", e)) .collect::>(), ); table.set_header(headers); - table.add_rows(DiceNumber::iter().map(|dices| { + table.add_rows(FixedDiceNumber::iter().map(|dices| { vec![format!("{:.3}", dices)].into_iter().chain( - Precision::iter() + FixedPrecision::iter() .map(move |precision| format!("{:5.2}", self.get_damage(precision, dices))), ) })); @@ -269,9 +269,9 @@ impl DamageMatrix { /// Calculate the DamageMatrix for a given InnerEquipementStats fn calculate_for(value: &InnerEquipementStats) -> Self { DamageMatrix { - damage_matrix: (DiceNumber::iter() + damage_matrix: (FixedDiceNumber::iter() .flat_map(|dices| { - Precision::iter() + FixedPrecision::iter() .map(move |prec| { binomial_dice_distribution(value, prec.value(), dices.value()) }) @@ -285,13 +285,13 @@ impl DamageMatrix { /// Calculate the binomial distribution and average the damage from there fn binomial_dice_distribution( equipement: &InnerEquipementStats, - precision: usize, - dices: usize, + precision: Precision, + dices: Dices, ) -> f64 { - let p = ((precision as i8 + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); - let binomial = Binomial::new(dices, p); + let p = ((*precision + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); + let binomial = Binomial::new(*dices, p); - (0..dices + 1) + (0..*dices + 1) .map(|target_dices| { let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize; if target_dices >= 1 { @@ -313,40 +313,74 @@ fn binomial_dice_distribution( /// The precision infered for a damage calculation event #[derive(EnumIter, Clone, Copy, Display)] #[allow(clippy::missing_docs_in_private_items)] -pub enum Precision { +pub enum FixedPrecision { High, Medium, Low, } +/// Thin representation of Precision to avoid mistakes +#[derive(Clone, Copy)] +pub struct Precision(i8); + +/// Thin representation of Dices to avoid mistakes +#[derive(Clone, Copy)] +pub struct Dices(usize); + +impl std::ops::Deref for Precision { + type Target = i8; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for Precision { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + +impl std::ops::Deref for Dices { + type Target = usize; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for Dices { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + /// The number of dices rolled for a damage simulation #[derive(EnumIter, Clone, Copy, Display)] #[allow(clippy::missing_docs_in_private_items)] -pub enum DiceNumber { +pub enum FixedDiceNumber { Many, Average, Few, } -impl Precision { +impl FixedPrecision { #[inline] /// Associate a value to the different values - fn value(&self) -> usize { + fn value(&self) -> Precision { match self { - Precision::High => 9, - Precision::Medium => 6, - Precision::Low => 4, + FixedPrecision::High => Precision(9), + FixedPrecision::Medium => Precision(6), + FixedPrecision::Low => Precision(4), } } } -impl DiceNumber { +impl FixedDiceNumber { #[inline] /// Associate a value to the different values - fn value(&self) -> usize { + fn value(&self) -> Dices { match self { - DiceNumber::Many => 7, - DiceNumber::Average => 5, - DiceNumber::Few => 3, + FixedDiceNumber::Many => Dices(7), + FixedDiceNumber::Average => Dices(5), + FixedDiceNumber::Few => Dices(3), } } } @@ -354,7 +388,7 @@ impl DiceNumber { #[cfg(test)] mod test { use crate::weaponry_structs::{ - equipement_advanced_repr::{DamageMatrix, DiceNumber, Precision}, + equipement_advanced_repr::{DamageMatrix, FixedDiceNumber, FixedPrecision}, equipement_structs::InnerEquipementStats, }; @@ -383,8 +417,8 @@ mod test { println!("{}", mat); println!( "(High,Many): {}, (Low,Few): {}", - mat.get_damage(Precision::High, DiceNumber::Many), - mat.get_damage(Precision::Low, DiceNumber::Few) + mat.get_damage(FixedPrecision::High, FixedDiceNumber::Many), + mat.get_damage(FixedPrecision::Low, FixedDiceNumber::Few) ); } } -- 2.45.1 From 21618a8782c744d76d614ef8a7f61d8e77180a25 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 08:18:46 +0100 Subject: [PATCH 70/97] Adds some fields in the categories --- weaponry/examples/usage_scenario.rs | 2 +- .../equipement_advanced_repr.rs | 11 +++-- .../src/weaponry_structs/equipement_fields.rs | 47 ++++++++++++++++++- 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 23800e1..62fa6a2 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -28,7 +28,7 @@ fn main() { }) .unwrap(); let mut refined_list = scenarios.generate_refined_recipes().unwrap(); - refined_list.inner_sort(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + refined_list.inner_sort(|a, b| a.advanced.avg_dps_safe.total_cmp(&b.advanced.avg_dps_safe)); // if args.html_export{} refined_list.write_html(&save_path).unwrap(); diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 88de8a0..ad6fd1a 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -164,10 +164,12 @@ pub struct AdvancedStats { /// Armor break factoring in the damage output: While a weapon might have high AB, not having any damage will seriously hinder that AB pub expected_armor_break_per_turn: f64, /// Dps with two actions and 5 dices - pub dps_safe: f64, + pub avg_dps_safe: f64, // /// Dps with four actions and 11 dices // pub dps_unsafe: f64, // All other criterias are already in the inner as raw criterias + /// Avg damage for bit attack + pub avg_huge_hit: f64, } impl From<&InnerEquipementStats> for AdvancedStats { fn from(value: &InnerEquipementStats) -> Self { @@ -188,8 +190,10 @@ impl From<&InnerEquipementStats> for AdvancedStats { // Adds the base strength, substracts the expected protection expected_armor_break_per_turn: (damage_per_attack + 6. - 8.) .min(armor_break_per_attack), - dps_safe: damage_matrix.get_safe_dmg(value.action_cost), - // dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), + + avg_huge_hit: damage_matrix.get_damage(FixedPrecision::High, FixedDiceNumber::Many), + avg_dps_safe: damage_matrix.get_safe_dmg(value.action_cost), + // avg_dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), damage_matrix, } } @@ -198,6 +202,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { /// A damage matrix, crossing damage conditions (high dice to low dice) with precision (high precision to low precision) /// /// This simulation does only calculate a very limited preset of damage values +// TODO[9]: Rewrite with (HashMap,HashMap) if it becomes needed #[cfg_attr(test, derive(Debug))] pub struct DamageMatrix { /// The inner damage matrix diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index d6aa96c..7e00926 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -119,7 +119,7 @@ impl Add for DamageType { } // TODO: Convert into this category at the end, depending on all important factors -/// List all weapon categories +/// List all the final weapon categories, this enum should be infered from and if they were defined #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize, strum::EnumString)] // #[cfg_attr(test, derive(PartialEq))] @@ -143,8 +143,28 @@ pub enum WeaponCategory { // Shield, } +// TODO[4]: Have a final weapon category tied to the speciality, if any appliable to the character +// : Since this is not needed for balencing, this will be left alone for a while +// impl WeaponCategory { +// fn from_category_and_size(macro_category: &WeaponBaseShape, size: &WeaponBaseSize) -> Self { +// match (macro_category, size) { +// (WeaponBaseShape::Axe, WeaponBaseSize::SuperHeavy) => Self::Kahml, +// (WeaponBaseShape::Blade, WeaponBaseSize::SuperHeavy) => Self::Haroth, +// (WeaponBaseShape::Hammer, WeaponBaseSize::SuperHeavy) => Self::Rhodarak, +// (WeaponBaseShape::Claws, WeaponBaseSize::SuperHeavy) => Self::Landscapper, +// (WeaponBaseShape::Staves, WeaponBaseSize::SuperHeavy) => Self::Landscapper, +// (WeaponBaseShape::Bow, WeaponBaseSize::SuperHeavy) => Self::Bow, +// (WeaponBaseShape::Crossbow, WeaponBaseSize::SuperHeavy) => Self::Crossbow, +// (WeaponBaseShape::Cannon, WeaponBaseSize::SuperHeavy) => Self::Cannon, + +// (WeaponBaseShape::Exotic, WeaponBaseSize::SuperHeavy) => Self::Exotic, +// } +// } +// } + // TODO: This is the real initial category /// The list of initial weapon meta categories +// TODO[!]: This enum should only include Weapons, Shields, Armors and no #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] pub enum WeaponMacroCategory { @@ -163,6 +183,31 @@ pub enum WeaponMacroCategory { None, } +/// The Base Shape of the weapon, used to infer the final category of the weapon +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] +pub enum WeaponBaseShape { + Staves, + Blunt, + Slash, + Ranged, + Armor, + Shields, + Exotic, + // TODO[!]: Check the soundness of this + None, +} + +/// The Base Size of the weapon, used to infer the final category of the weapon +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] +pub enum WeaponBaseSize { + Light, + Medium, + Heavy, + SuperHeavy, +} + // 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 { -- 2.45.1 From cb6c7ebc2ab5771c729837b42851006336b2d7d3 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 21:50:57 +0100 Subject: [PATCH 71/97] Silly bug on one macro, filter corrected and macroified --- weaponry/examples/usage_scenario.rs | 5 +- weaponry/src/export.rs | 24 +- weaponry/src/interfaces.rs | 3 + .../equipement_advanced_repr.rs | 15 +- .../src/weaponry_structs/equipement_fields.rs | 263 ++++++++++-------- .../weaponry_structs/equipement_impl_logic.rs | 8 +- .../weaponry_structs/equipement_impl_math.rs | 4 +- .../weaponry_structs/equipement_structs.rs | 6 +- .../src/weaponry_structs/equipement_views.rs | 1 + weaponry/src/weaponry_structs/mod.rs | 4 +- 10 files changed, 195 insertions(+), 138 deletions(-) diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 62fa6a2..fd8b2f0 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -5,7 +5,9 @@ //! use clap::Parser; use std::path::Path; +use weaponry::filter_by; use weaponry::interfaces::ToAnalysis; +use weaponry::weaponry_structs::RefinedEquipement; // TODO : All of these should likely be in the prelude if used like this use weaponry::weaponry_structs::CrossRecipeScenario; @@ -27,8 +29,9 @@ fn main() { finishing: args.finishing.then_some(()), }) .unwrap(); + let mut refined_list = scenarios.generate_refined_recipes().unwrap(); - refined_list.inner_sort(|a, b| a.advanced.avg_dps_safe.total_cmp(&b.advanced.avg_dps_safe)); + refined_list.inner_sort(filter_by!(max_damage_per_action)); // if args.html_export{} refined_list.write_html(&save_path).unwrap(); diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index dea3e48..f0cd10d 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -61,9 +61,19 @@ macro_rules! add_field_to_chart { .series( charming::series::Line::new() .data($table_names) - .name(stringify!($table_names)), // .line_style(LineStyle::new().color("paleblue")), + .name(stringify!($table_names)), ); )* + + let $chart = $chart.legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(charming::element::Orient::Vertical) + .data(vec![ + $(stringify!($table_names),)* + ]), + ); } } @@ -75,18 +85,6 @@ pub fn initial_chart(chart_name: &str) -> charming::Chart { .text(chart_name) .left("center"), ) - .legend( - charming::component::Legend::new() - .left(10) - .top("middle") - .orient(charming::element::Orient::Vertical) - .data(vec![ - "dps_safe", - "max_damage_per_action", - "max_damage_per_turn", - "armor_break_per_turn", - ]), - ) .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) .data_zoom( charming::component::DataZoom::new() diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 9847d68..d33eee2 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -156,6 +156,7 @@ pub trait ToAnalysis { type InnerData; /// Sort the inner data with a given closure + // TODO[4]: Consider changing the signature to (self) -> Self, to match the filter fn inner_sort(&mut self, closure: T) where T: FnMut(&Self::InnerData, &Self::InnerData) -> std::cmp::Ordering; @@ -163,6 +164,8 @@ pub trait ToAnalysis { /// Apply a filter to the inner data /// /// Careful this filter will consume the original data to avoir reallocating + // TODO[6]: Consider implementing base filters as a struct to allow implementation / choice to be polymorphic + // : Maybe more downsides over a dynamic choosing by default fn inner_filter(self, closure: T) -> Self where T: FnMut(&Self::InnerData) -> bool; diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index ad6fd1a..6558dd6 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -75,6 +75,17 @@ impl ToTex for RefinedEquipementList { } } +#[macro_export] +/// A simple macro to sort the inner advanced field by a specific field +// TODO[6] find a way to not have to import the refinedequipement +macro_rules! filter_by { + ($field:ident) => { + |a: &RefinedEquipement, b: &RefinedEquipement| { + a.advanced.$field.total_cmp(&b.advanced.$field) + } + }; +} + impl ToAnalysis for RefinedEquipementList { type InnerData = RefinedEquipement; @@ -110,13 +121,15 @@ impl ToAnalysis for RefinedEquipementList { dps_safe # f64, max_damage_per_action # f64, armor_break_per_turn # f64, + dps_huge # f64, ), |ref_equipement| { ( &ref_equipement.advanced.display_name, + ref_equipement.advanced.avg_dps_safe, ref_equipement.advanced.max_damage_per_action, - ref_equipement.advanced.damage_per_turn, ref_equipement.advanced.armor_break_per_turn, + ref_equipement.advanced.avg_huge_hit, ) } ); diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 7e00926..1f6be28 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -11,8 +11,11 @@ use strum::Display; #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only // TODO: avoid pub make an impl ? -pub struct SpecialCategory(pub Vec); +pub struct SpecialField(pub Vec); +// TODO[6]: This cross target specification existed for combines weapons, +// : that do not really need any balancing and only rendering +// : therefore migh need cleanup /// The kind of target this nature can apply to #[derive(Clone)] pub enum NatureTarget { @@ -34,22 +37,6 @@ pub enum PhysicalDamageType { 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]] @@ -82,34 +69,6 @@ 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; @@ -125,7 +84,8 @@ impl Add for DamageType { // #[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, - Dagger, + // HeavyExotic ? + Dagger, // Light sword ? Kill it tbh Claws, Blade, Haroth, @@ -143,72 +103,8 @@ pub enum WeaponCategory { // Shield, } -// TODO[4]: Have a final weapon category tied to the speciality, if any appliable to the character -// : Since this is not needed for balencing, this will be left alone for a while -// impl WeaponCategory { -// fn from_category_and_size(macro_category: &WeaponBaseShape, size: &WeaponBaseSize) -> Self { -// match (macro_category, size) { -// (WeaponBaseShape::Axe, WeaponBaseSize::SuperHeavy) => Self::Kahml, -// (WeaponBaseShape::Blade, WeaponBaseSize::SuperHeavy) => Self::Haroth, -// (WeaponBaseShape::Hammer, WeaponBaseSize::SuperHeavy) => Self::Rhodarak, -// (WeaponBaseShape::Claws, WeaponBaseSize::SuperHeavy) => Self::Landscapper, -// (WeaponBaseShape::Staves, WeaponBaseSize::SuperHeavy) => Self::Landscapper, -// (WeaponBaseShape::Bow, WeaponBaseSize::SuperHeavy) => Self::Bow, -// (WeaponBaseShape::Crossbow, WeaponBaseSize::SuperHeavy) => Self::Crossbow, -// (WeaponBaseShape::Cannon, WeaponBaseSize::SuperHeavy) => Self::Cannon, - -// (WeaponBaseShape::Exotic, WeaponBaseSize::SuperHeavy) => Self::Exotic, -// } -// } -// } - -// TODO: This is the real initial category -/// The list of initial weapon meta categories -// TODO[!]: This enum should only include Weapons, Shields, Armors and no -#[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] -pub enum WeaponMacroCategory { - Staves, - Blunt, - Slash, - Ranged, - 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, -} - -/// The Base Shape of the weapon, used to infer the final category of the weapon -#[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] -pub enum WeaponBaseShape { - Staves, - Blunt, - Slash, - Ranged, - Armor, - Shields, - Exotic, - // TODO[!]: Check the soundness of this - None, -} - -/// The Base Size of the weapon, used to infer the final category of the weapon -#[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] -pub enum WeaponBaseSize { - Light, - Medium, - Heavy, - SuperHeavy, -} - -// TODO: This is only needed as long as we dont have a special category for the target +// TODO[!]: This is only needed as long as we dont have a special category for the target +// TODO[!]: This part should be handled by a category filter instead, filtering Shape on Shape impl PartialEq for WeaponMacroCategory { fn eq(&self, other: &Self) -> bool { match (self, other) { @@ -245,3 +141,146 @@ mod test { unimplemented!() } } +// TODO[!]: Implement all the soundness below + +/// The final enum of all categories to be given to the character sheet +/// +/// This enum is only created at the end of the refining process with all the given information +/// Note that some weapons might not be created or might be too niche to be created by the recipes +/// however the full cross implementation should cover all weapons or reconsider the validity of said implementation +#[allow(dead_code, clippy::missing_docs_in_private_items)] +pub enum FinalWeaponCategory { + Hast(HastSpecialties), + Slash(SlashSpecialties), + Blunt(BluntSpecialties), + Collosal(ColossalSpeciaties), + Ranged(RangedSpecialties), + Throw(ThrowSpecialties), +} + +#[allow(dead_code, clippy::missing_docs_in_private_items)] +pub enum HastSpecialties { + Lance, + Staff, +} + +#[allow(dead_code, clippy::missing_docs_in_private_items)] +pub enum SlashSpecialties { + Sword, + #[deprecated] + Dagger, + Axe, + Claws, +} + +#[allow(dead_code, clippy::missing_docs_in_private_items)] +pub enum BluntSpecialties { + Hammer, + Improvised, +} + +#[allow(dead_code, clippy::missing_docs_in_private_items)] +pub enum ColossalSpeciaties { + Rhodarak, + Haroth, + Kahml, + Landscapper, +} + +#[allow(dead_code, clippy::missing_docs_in_private_items)] +pub enum RangedSpecialties { + Bow, + Crossbow, + Cannon, +} + +#[allow(dead_code, clippy::missing_docs_in_private_items)] +pub enum ThrowSpecialties { + Light, + Lances, + Improvised, +} + +// TODO[4]: Have a final weapon category tied to the speciality, if any appliable to the character +// : Since this is not needed for balencing, this will be left alone for a while +// impl FinalWeaponCategory{ +// fn from_category_and_size(macro_category: &WeaponBaseShape, size: &WeaponBaseSize) -> Self { +// match (macro_category, size) { +// (WeaponBaseShape::Axe, WeaponBaseSize::SuperHeavy) => Self::Colossal(..), +// } +// } +// } + +// TODO[!]: This is the real initial category for the shapes, as only shapes should be described by shapes +// TODO[!]: Shapes should also have a generic category of course (weapons/armor/shield) to help the filter to apply to it +/// The list of initial weapon meta categories +// TODO[!]: This enum should only include Weapons, Shields, Armors and no +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] +pub enum WeaponMacroCategory { + Staves, + Blunt, + Slash, + Ranged, + 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 the corrected real initial shape +// : This should replace the used MacroCategory +/// The Base Shape of the weapon, used to infer the final category of the weapon +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] +pub enum WeaponBaseShape { + Staves, + Blunt, + Slash, + Ranged, + Armor, + Shields, + Exotic, + // TODO[!]: Check the soundness of this + None, +} + +// TODO[!]: While maybe not directly filling a field these categories should be inferred by the BaseShape for comparison +// [!]: However using a new column for this Section will greatly help in the Serde soundness and avoidance on over-reliance of implicit conversions +/// Specifies the exact nature of the weapon, used for generic filter mainly +#[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)] +pub enum EquipementSection { + Weapon, + Armor, + Shield, +} +// TODO[!]: Add this as a target and nature instead of the old Type +// : Remember it's the applied into that specify wether they can be applied not the other way around +/// Specifies the exact nature of the target this element can be applied to +#[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)] +pub enum EquipementFilter { + /// This element can only be applied to a specific category + Target(EquipementSection), + /// This element exists only for recipes or for export to tex, it cannot be auto-applied + NoTarget, + /// This element can be applied to any target + AnyTarget, + // /// This element can only be applied to a specific base shape + // TargetShape(WeaponBaseShape) +} + +// TODO[!] : This part is initialized by the natures subtable and might be better of being a new column in the database +/// The Base Size of the weapon, used to infer the final category of the weapon +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] +pub enum WeaponBaseSize { + Light, + Medium, + Heavy, + SuperHeavy, +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index ae5370c..c3da801 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -52,7 +52,7 @@ mod test { use crate::{ interfaces::RecipeCollection, weaponry_structs::{ - DamageMod, DamageType, Equipement, InitialEquipementList, SpecialCategory, + DamageMod, DamageType, Equipement, InitialEquipementList, SpecialField, equipement_fields::{PhysicalDamageType, WeaponMacroCategory}, equipement_structs::InnerEquipementStats, }, @@ -95,7 +95,7 @@ mod test { range: 3, agility_bonus: 4., macro_category: Some(WeaponMacroCategory::Staves), - special: SpecialCategory(vec!["zero".into()]), + special: SpecialField(vec!["zero".into()]), damage_type: Some(DamageType(vec![DamageMod::Secondary( PhysicalDamageType::Slash, )])), @@ -108,7 +108,7 @@ mod test { damage_type: Some(DamageType(vec![DamageMod::Primary( PhysicalDamageType::Blunt, )])), - special: SpecialCategory(vec!["one".into(), "two".into()]), + special: SpecialField(vec!["one".into(), "two".into()]), ..Default::default() }; assert_eq!( @@ -120,7 +120,7 @@ mod test { damage: 10, range: 3, macro_category: Some(WeaponMacroCategory::Staves), - special: SpecialCategory(vec!["zero".into(), "one".into(), "two".into()]), + special: SpecialField(vec!["zero".into(), "one".into(), "two".into()]), damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index e6e376d..ab587fb 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -4,7 +4,7 @@ //! use super::equipement_structs::InnerEquipementStats; -use crate::weaponry_structs::SpecialCategory; +use crate::weaponry_structs::SpecialField; /// Add a new vector to a clone of a inner field macro_rules! add_to_vec { @@ -66,7 +66,7 @@ impl std::ops::Add for &InnerEquipementStats { } } -impl std::ops::Add for SpecialCategory { +impl std::ops::Add for SpecialField { type Output = Self; fn add(self, rhs: Self) -> Self::Output { diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 15ceb05..e1fe186 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, equipement_fields::WeaponMacroCategory}; +use super::{DamageType, SpecialField, WeaponCategory, equipement_fields::WeaponMacroCategory}; /// The final equipement list /// @@ -109,7 +109,7 @@ pub struct InnerEquipementStats { /// 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) special: SpecialField, pub(super) action_cost: i8, pub(super) reload_cost: Option, // Shouldn't it be Option ? pub(super) range: i16, // Shoudln't it be Option ? @@ -186,7 +186,7 @@ impl Default for DatabaseEquipementStats { damage_type: 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(), + special: serde_json::to_string(&SpecialField::default()).unwrap(), reload_cost: serde_json::to_string(&None::).unwrap(), rarity: 0, cost: 0, diff --git a/weaponry/src/weaponry_structs/equipement_views.rs b/weaponry/src/weaponry_structs/equipement_views.rs index f217e98..a5c4ec4 100644 --- a/weaponry/src/weaponry_structs/equipement_views.rs +++ b/weaponry/src/weaponry_structs/equipement_views.rs @@ -4,6 +4,7 @@ //! This list is imperative to allow several criterias to be looked up one after the other to gather as many points of data as possible //! //! It is mandatory that these points of interest link back to the original data by index and not by reference, to allow this operation to be thread safe +// TODO[3]: Consider deletion of this module and the associated view table #![allow(dead_code)] diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 5a09399..278d1d3 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -34,10 +34,10 @@ pub use equipement_structs::{Equipement, InitialEquipementList}; // All generic fields // #[allow(unused_imports)] pub use crate::weaponry_structs::equipement_advanced_repr::RefinedEquipementList; +pub use equipement_advanced_repr::RefinedEquipement; pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{ - DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMacroCategory, + DamageMod, DamageType, NatureTarget, SpecialField, WeaponCategory, WeaponMacroCategory, }; - // Likely ? Final Re-Exports pub use equipement_scenario::CrossRecipeScenario; -- 2.45.1 From 56289649a4832a08f60006029dd0506b30f6f50d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 24 Feb 2025 06:57:36 +0100 Subject: [PATCH 72/97] Many usefull impls on scenarios --- weaponry/examples/usage_scenario.rs | 26 +- weaponry/src/export.rs | 59 ++- weaponry/src/lib.rs | 9 + .../equipement_advanced_repr.rs | 425 +++++++++++------- 4 files changed, 328 insertions(+), 191 deletions(-) diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index fd8b2f0..9d52b50 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -5,8 +5,8 @@ //! use clap::Parser; use std::path::Path; -use weaponry::filter_by; use weaponry::interfaces::ToAnalysis; +use weaponry::sort_by; use weaponry::weaponry_structs::RefinedEquipement; // TODO : All of these should likely be in the prelude if used like this @@ -23,15 +23,23 @@ fn main() { let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario { table_name: "Equipements".into(), db_path: "./databases/weapons.db".into(), - shape: args.shapes.then_some(()), + shape: (!args.no_shapes).then_some(()), materials: args.materials, - nature: args.natures.then_some(()), + nature: (!args.no_natures).then_some(()), finishing: args.finishing.then_some(()), }) .unwrap(); let mut refined_list = scenarios.generate_refined_recipes().unwrap(); - refined_list.inner_sort(filter_by!(max_damage_per_action)); + + match args.sort.as_str() { + "max_per_turn" => refined_list.inner_sort(sort_by!(max_damage_per_turn)), + "avg_huge" => refined_list.inner_sort(sort_by!(avg_damage_single_huge_hit)), + "avg_safe" => refined_list.inner_sort(sort_by!(avg_damage_2a_safe)), + "max_armor" => refined_list.inner_sort(sort_by!(armor_break_per_attack)), + // "id" => refined_list.inner_sort(|a, b| a.inner.id[0].cmp(&b.inner.id[0])), // It's actually the natural sorted way + _ => (), + } // if args.html_export{} refined_list.write_html(&save_path).unwrap(); @@ -45,17 +53,19 @@ pub struct CLIArgs { /// The path to save to. pub path: Option, /// Wether to generate shapes - #[arg(short, long, default_value_t = true)] - pub shapes: bool, + #[arg(short('S'), long, default_value_t)] + pub no_shapes: bool, /// Wether to generate materials #[arg(short, long)] pub materials: Option, /// Wether to generate all natures - #[arg(short, long, default_value_t = true)] - pub natures: bool, + #[arg(short('N'), long)] + pub no_natures: bool, /// Wether to generate all finishing #[arg(short, long, default_value_t = false)] pub finishing: bool, + #[arg(long, default_value_t = String::from("safe"))] + pub sort: String, } #[allow(dead_code)] diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index f0cd10d..9a3ad79 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -23,15 +23,11 @@ /// ( /// index # &String, /// dps_safe # f64, -/// max_damage_per_action # f64, -/// armor_break_per_turn # f64, /// ), /// |ref_equipement| { /// ( /// &ref_equipement.advanced.display_name, -/// ref_equipement.advanced.max_damage_per_action, -/// ref_equipement.advanced.damage_per_turn, -/// ref_equipement.advanced.armor_break_per_turn, +/// ref_equipement.advanced.max_damage_per_turn, /// ) /// } /// ); @@ -44,36 +40,39 @@ /// which could easily reach 600k elements /// /// Knowing this tradeoff, the difficulty to maintain is considered an acceptable tradeoff +// TODO[4]: If the field accessed are only in advanced, remove the closure entirely and auto_generate it #[macro_export] macro_rules! add_field_to_chart { ($base_struct:expr, $chart:ident, ($names:ident # $name_type:ty, $($table_names:ident # $table_type:ty),* $(,)*), | $closure_name:ident | {($($fields:expr,)*)} ) => { - let data_collection = $base_struct.inner.iter().map(|$closure_name| ( $($fields,)*) ); - let ($names, $($table_names),*) = data_collection.collect::<(Vec<$name_type>, $(Vec<$table_type>,)*)>(); - let $chart = $chart - .x_axis( - charming::component::Axis::new() - .data($names.to_vec()) - .type_(charming::element::AxisType::Category), - ); - $( - let $chart = $chart - .series( - charming::series::Line::new() - .data($table_names) - .name(stringify!($table_names)), - ); - )* + let $chart = { + let data_collection = $base_struct.inner.iter().map(|$closure_name| ( $($fields,)*) ); + let ($names, $($table_names),*) = data_collection.collect::<(Vec<$name_type>, $(Vec<$table_type>,)*)>(); + let $chart = $chart + .x_axis( + charming::component::Axis::new() + .data($names.to_vec()) + .type_(charming::element::AxisType::Category), + ); + $( + let $chart = $chart + .series( + charming::series::Line::new() + .data($table_names) + .name(stringify!($table_names)), + ); + )* - let $chart = $chart.legend( - charming::component::Legend::new() - .left(10) - .top("middle") - .orient(charming::element::Orient::Vertical) - .data(vec![ - $(stringify!($table_names),)* - ]), - ); + $chart.legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(charming::element::Orient::Vertical) + .data(vec![ + $(stringify!($table_names),)* + ]), + ) + }; } } diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index 4392409..8d2e64e 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -2,6 +2,7 @@ // File: weaponry/src/lib.rs //! Weaponry module, handling all weaponry creation and analysis +#![feature(int_roundings)] #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![feature(iter_intersperse, generic_arg_infer)] @@ -11,3 +12,11 @@ pub mod export; pub mod interfaces; mod strategy; pub mod weaponry_structs; + +/// Signals the function running is unfinished +#[macro_export] +macro_rules! unfinished { + () => { + println!("UNFINISHED FUNCTION CALLED AT {} LINE {}", file!(), line!()); + }; +} diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 6558dd6..ec193fd 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -8,25 +8,27 @@ //! nothing prevents us to implement the trait for other objects and avoid massive computation //! of all the fields even when the user will not be interested in them #![allow(dead_code)] - -use crate::{add_field_to_chart, export::initial_chart, interfaces::RecipeCollection}; -use core::f64; -use std::{cmp::Ordering, fmt::Display}; - use crate::{ + add_field_to_chart, error::FatalEquipementError, - interfaces::{RefinedList, ToAnalysis, ToTex}, + export::initial_chart, + interfaces::{RecipeCollection, RefinedList, ToAnalysis, ToTex}, + unfinished, + weaponry_structs::{ + Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats, + }, }; +use core::f64; +use std::{ + cmp::Ordering, + fmt::{Debug, Display}, + ops::{Add, Deref}, +}; + use charming::Chart; -use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; use probability::prelude::{Binomial, Discrete}; use serde::Serialize; -use strum::{Display, EnumIter, IntoEnumIterator}; - -use super::{ - Equipement, InitialEquipementList, WeaponMacroCategory, - equipement_structs::InnerEquipementStats, -}; +use strum::{Display, EnumIter}; /// The final representation of the equipement inplementing all the fields needed for processing // TODO: Add a public getter for the inner data @@ -78,7 +80,7 @@ impl ToTex for RefinedEquipementList { #[macro_export] /// A simple macro to sort the inner advanced field by a specific field // TODO[6] find a way to not have to import the refinedequipement -macro_rules! filter_by { +macro_rules! sort_by { ($field:ident) => { |a: &RefinedEquipement, b: &RefinedEquipement| { a.advanced.$field.total_cmp(&b.advanced.$field) @@ -111,29 +113,44 @@ impl ToAnalysis for RefinedEquipementList { let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) .theme(charming::theme::Theme::Dark); - let initial_chart: Chart = initial_chart("Damage for all cross-gen products"); + let initial_chart: Chart = initial_chart(&format!( + "Damage for all cross-gen products ({} Elements)", + self.inner.len() + )); add_field_to_chart!( self, initial_chart, ( index # &String, - dps_safe # f64, - max_damage_per_action # f64, - armor_break_per_turn # f64, - dps_huge # f64, + // max_damage_per_turn # f64, + // max_damage_per_attack # f64, + // speed # f64, + // armor_break_per_attack # f64, + // expected_armor_break_per # f64, + avg_damage_safe # f64, + avg_damage_single_huge_hit # f64, + // scenario_damage # f64, + // defensive # f64, + mini_scenario_damage # f64 ), |ref_equipement| { ( &ref_equipement.advanced.display_name, - ref_equipement.advanced.avg_dps_safe, - ref_equipement.advanced.max_damage_per_action, - ref_equipement.advanced.armor_break_per_turn, - ref_equipement.advanced.avg_huge_hit, + // ref_equipement.advanced.max_damage_per_turn, + // ref_equipement.advanced.max_damage_per_attack, + // ref_equipement.advanced.speed, + // ref_equipement.advanced.armor_break_per_attack, + // ref_equipement.advanced.expected_armor_break_per_2a, + ref_equipement.advanced.avg_damage_2a_safe, + ref_equipement.advanced.avg_damage_single_huge_hit, + // ref_equipement.advanced.scenario_damage, + // ref_equipement.advanced.defensive, + ref_equipement.advanced.mini_scenario_damage, + ) } ); - renderer.save(&initial_chart, format!("{save_path}.html"))?; Ok(()) } @@ -166,137 +183,236 @@ impl Default for RefinedEquipementList { #[derive(Serialize)] pub struct AdvancedStats { pub display_name: String, - pub damage_per_attack: f64, - pub damage_per_turn: f64, - pub max_damage_per_action: f64, + pub max_damage_per_attack: f64, + pub max_damage_per_turn: f64, pub armor_break_per_attack: f64, - pub armor_break_per_turn: f64, - pub armor_break_per_action: f64, - pub damage_matrix: DamageMatrix, - pub category: Option, + // pub category: Option, /// Armor break factoring in the damage output: While a weapon might have high AB, not having any damage will seriously hinder that AB - pub expected_armor_break_per_turn: f64, + pub expected_armor_break_per_2a: f64, /// Dps with two actions and 5 dices - pub avg_dps_safe: f64, + pub avg_damage_2a_safe: f64, // /// Dps with four actions and 11 dices - // pub dps_unsafe: f64, - // All other criterias are already in the inner as raw criterias - /// Avg damage for bit attack - pub avg_huge_hit: f64, + pub avg_damage_single_huge_hit: f64, + pub speed: f64, + pub scenario_damage: f64, + pub defensive: f64, + pub mini_scenario_damage: f64, } impl From<&InnerEquipementStats> for AdvancedStats { fn from(value: &InnerEquipementStats) -> Self { - let damage_per_attack = + let max_damage_per_attack = (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; - let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack); - let damage_matrix = DamageMatrix::calculate_for(value); + let armor_break_per_attack = (value.armor_break as f64).min(max_damage_per_attack); Self { - category: value.macro_category.clone(), - display_name: value.name.join(" "), - damage_per_attack, - damage_per_turn: damage_per_attack * 2., - max_damage_per_action: damage_per_attack / (value.action_cost as f64), - armor_break_per_attack, - armor_break_per_turn: armor_break_per_attack * 2., - armor_break_per_action: armor_break_per_attack / value.action_cost as f64, - - // Adds the base strength, substracts the expected protection - expected_armor_break_per_turn: (damage_per_attack + 6. - 8.) - .min(armor_break_per_attack), - - avg_huge_hit: damage_matrix.get_damage(FixedPrecision::High, FixedDiceNumber::Many), - avg_dps_safe: damage_matrix.get_safe_dmg(value.action_cost), + // UNUSED METRICS // avg_dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), - damage_matrix, + max_damage_per_turn: max_damage_per_attack * 2., // TODO: Not Sure + // Defensive metrics + // SOL Metrics ? + + // IMPORTANT METRICS + display_name: value.name.join(" "), + speed: value.speed.into(), + armor_break_per_attack, + expected_armor_break_per_2a: (max_damage_per_attack + 6. - 8.) + .min(armor_break_per_attack) + * 2. + / value.action_cost as f64, // Adds the base strength, substracts the expected protection + max_damage_per_attack, + avg_damage_single_huge_hit: value.average_damage(&[Precision(9)], &[Dices(7)]), // A huge hit but definitely not a "FULL THROTTLE" hit + avg_damage_2a_safe: value.average_damage(&[Precision(7)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost), + // .average_damage(&[Precision(9), Precision(7), Precision(5)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost), + scenario_damage: get_damage_with_simulation(value), + mini_scenario_damage: (value.damage > 0) + .then(|| get_sustained_damage(value)) + .unwrap_or_default(), + defensive: (value.parry as f64).max(value.dodge.into()), // TODO[b]: Integrity and prot should be taken into account } } } -/// A damage matrix, crossing damage conditions (high dice to low dice) with precision (high precision to low precision) -/// -/// This simulation does only calculate a very limited preset of damage values -// TODO[9]: Rewrite with (HashMap,HashMap) if it becomes needed -#[cfg_attr(test, derive(Debug))] -pub struct DamageMatrix { - /// The inner damage matrix - damage_matrix: Vec, +/// Create the damage profile with the following simulation: +/// 10turns total +/// - 1 turn no damage +/// - 2 turns full damage (12 dice, 130% precision) +/// - 2 turns safe attacks (5 dice, 50%p) +/// - 1 turn highspeed/range hit (7 dice, 80% precision) +/// - 4 turns normal damage (7 dice, 90% precision) +// TODO[!] Implementation +fn get_damage_with_simulation(value: &InnerEquipementStats) -> f64 { + let _ = value; + // unfinished!(); + 0. } -impl DamageMatrix { - /// Get the damage value from given condition - pub fn get_damage(&self, precision: FixedPrecision, dices: FixedDiceNumber) -> f64 { - self.damage_matrix[precision as usize + 3 * dices as usize] - } - /// The "safe" damage, as in 5 dices, 2 attacks - // TODO: This safe damage actually uses 5 dices * 2 instead of doing max(5 * 1 , 2 * 1 + 3 * 1) - pub fn get_safe_dmg(&self, attack_cost: i8) -> f64 { - let _ = attack_cost; - (self.get_damage(FixedPrecision::Low, FixedDiceNumber::Few) - + self.get_damage(FixedPrecision::Medium, FixedDiceNumber::Few) - + self.get_damage(FixedPrecision::High, FixedDiceNumber::Few)) - / 3. +/// Sustained damage +/// +/// Average damage factoring reload, calculated with 9 dice and 90% precision +// TODO[!] Replace avg_damage with this +fn get_sustained_damage(value: &InnerEquipementStats) -> f64 { + // unfinished!(); + // Actions total and damage total are arbitrarely choosen + + // With reload, damage calculation is rather complicated, since you can half reload but cant half attack + // so a reload is valid even if you don't reload fully, but you have to start your turn with less actions + // instead of building a complex scenario, the attack pattern is always: Ac:Attack + Re:Reload(and maybe reminder) every turn + // value.damage.into() + BestDamageScenarios::from_action_constraints(value, 6, 3, Dices(14), Precision(7)) + .map_or(0., |v| v.damage_done) +} + +/// The best resulting attack pattern of a virtual scenrio where some conditions are given +#[derive(Debug)] +pub struct BestDamageScenarios { + /// How many actions were used by the best attack + actions_used: i8, + /// Attacks actions used by the scenario + attacks_used: i8, + /// Resulting damage + damage_done: f64, + /// Remaining actions that need to be used to finish reload + reload_remaining: i8, + /// A debug value, should be taken down in final builds + // TODO[6]: Remove debug once the tests are done + depth: u8, +} + +impl Add for BestDamageScenarios { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + actions_used: self.actions_used + rhs.actions_used, + attacks_used: self.attacks_used + rhs.attacks_used, + damage_done: self.damage_done + rhs.damage_done, + reload_remaining: self.reload_remaining + rhs.reload_remaining, + depth: self.depth + rhs.depth, + } } - /// The "unsage" damage, as in, full dice, 2 attacks - // TODO: This damages does max(Max dices * 1, 5 dices * 2), which might not be optimal - pub fn get_unsafe_dmg(&self, attack_cost: i8) -> f64 { - f64::max( - self.get_safe_dmg(attack_cost) * 2., - (self.get_damage(FixedPrecision::Low, FixedDiceNumber::Many) - + self.get_damage(FixedPrecision::Medium, FixedDiceNumber::Many) - + self.get_damage(FixedPrecision::High, FixedDiceNumber::Many)) - / 3., +} +impl Deref for BestDamageScenarios { + type Target = f64; + + fn deref(&self) -> &Self::Target { + &self.damage_done + } +} + +// TODO[!!]: Add a lot of testing +impl BestDamageScenarios { + /// Calculate the best alternative with a set of contraints + /// + /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) + fn from_action_constraints( + value: &InnerEquipementStats, + actions_allowed: i8, + attacks_allowed: i8, + dices_allowed: Dices, + precision: Precision, + ) -> Option { + Self::from_action_constraints_recursive( + value, + actions_allowed, + attacks_allowed, + dices_allowed, + precision, + 0, + 0, ) } -} -impl Serialize for DamageMatrix { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - // TODO: Not sure of the right way to do this - // serializer.serialize_str(&format!("[{:?}]", self.damage_matrix)) - serializer.serialize_str(&format!( - "{:?}", - self.damage_matrix.iter().sum::() / self.damage_matrix.len() as f64 - )) - } -} -impl Display for DamageMatrix { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let mut table = Table::new(); - table.apply_modifier(UTF8_ROUND_CORNERS); - let mut headers = vec![String::from("D\\P")]; - headers.append( - &mut FixedPrecision::iter() - .map(|e| format!("{:.3}", e)) - .collect::>(), - ); - table.set_header(headers); - table.add_rows(FixedDiceNumber::iter().map(|dices| { - vec![format!("{:.3}", dices)].into_iter().chain( - FixedPrecision::iter() - .map(move |precision| format!("{:5.2}", self.get_damage(precision, dices))), - ) - })); - write!(f, "{}", table) - } -} - -impl DamageMatrix { - /// Calculate the DamageMatrix for a given InnerEquipementStats - fn calculate_for(value: &InnerEquipementStats) -> Self { - DamageMatrix { - damage_matrix: (FixedDiceNumber::iter() - .flat_map(|dices| { - FixedPrecision::iter() - .map(move |prec| { - binomial_dice_distribution(value, prec.value(), dices.value()) - }) - .collect::>() - }) - .collect::>()), + /// Recursive part of the from_action_constraints call + /// + /// This algorithm takes a recursive approact to avoid too much forward complexity + fn from_action_constraints_recursive( + value: &InnerEquipementStats, + actions_allowed: i8, + attacks_allowed: i8, + dices_allowed: Dices, + precision: Precision, + reload_remaining: i8, + depth: u8, + ) -> Option { + // If we can't attack return early + if value.action_cost > actions_allowed || attacks_allowed == 0 || reload_remaining != 0 { + return None; } + + let atkreload_cost = value.reload_cost.unwrap_or_default() + value.action_cost; + + // We create our first contender, One attack only + let one_attack = Self { + // No matter what we try to reload, even if we overcap the attack was still valid + actions_used: (atkreload_cost).clamp(0, actions_allowed), + attacks_used: 1, + damage_done: binomial_dice_distribution(value, precision, dices_allowed), + // If the reload+attack exceed the actions, we must bookkeep it + // as a reminder that we have leftover actions to spend next turn + reload_remaining: (atkreload_cost - actions_allowed).clamp(0, actions_allowed), + depth, + }; + println!( + "[{depth}] > One attack ({}): {one_attack:?}", + Dices(*dices_allowed) + ); + + // We can only try two attacks if two attack would be valid aka: + // - We can spend: 2 attacks and (at least) 1 reload (as actions) + // - : 2 attacks (as attacks) + if atkreload_cost + value.action_cost < actions_allowed && attacks_allowed > 1 { + // Cumbersome because of rounding errors + if let (Some(a), Some(b)) = ( + (Self::from_action_constraints_recursive( + value, + actions_allowed - atkreload_cost, + attacks_allowed - 1, + Dices(dices_allowed.div_floor(2)), + precision, + reload_remaining, + depth + 1, + )), + (Self::from_action_constraints_recursive( + value, + actions_allowed - atkreload_cost, + attacks_allowed - 1, + Dices(dices_allowed.div_ceil(2)), + precision, + reload_remaining, + depth + 1, + )), + ) { + let sum_sub_attacks = a + b; + println!( + "[{depth}] > Two attacks ({} & {}) : {sum_sub_attacks:?}", + Dices(dices_allowed.div_floor(2)), + Dices(dices_allowed.div_ceil(2)) + ); + // The alternative was better + if one_attack.damage_done < sum_sub_attacks.damage_done { + return Some(sum_sub_attacks); + } + } + } + + // The alternative didn't exist or was worse + Some(one_attack) + } +} + +// TODO: Consider implementing something else instead ? +impl InnerEquipementStats { + /// Calculate the average damage expected for a set of precisions and dices + fn average_damage(&self, precisions: &[Precision], list_dices: &[Dices]) -> f64 { + precisions + .iter() + .map(|precision| { + list_dices + .iter() + .map(|dices| binomial_dice_distribution(self, *precision, *dices)) + .sum::() + }) + .sum::() + / (precisions.len() as f64 * list_dices.len() as f64) } } @@ -380,6 +496,7 @@ pub enum FixedDiceNumber { Few, } +// TODO[9] These implementations date back to the matrix code, rewriting them would be for the best impl FixedPrecision { #[inline] /// Associate a value to the different values @@ -396,9 +513,9 @@ impl FixedDiceNumber { /// Associate a value to the different values fn value(&self) -> Dices { match self { - FixedDiceNumber::Many => Dices(7), - FixedDiceNumber::Average => Dices(5), - FixedDiceNumber::Few => Dices(3), + FixedDiceNumber::Many => Dices(8), + FixedDiceNumber::Average => Dices(6), + FixedDiceNumber::Few => Dices(4), } } } @@ -406,18 +523,10 @@ impl FixedDiceNumber { #[cfg(test)] mod test { use crate::weaponry_structs::{ - equipement_advanced_repr::{DamageMatrix, FixedDiceNumber, FixedPrecision}, + equipement_advanced_repr::{FixedDiceNumber, FixedPrecision}, equipement_structs::InnerEquipementStats, }; - #[test] - fn test_binomial() { - let damage = new_inner_eq(); - let mat: DamageMatrix = DamageMatrix::calculate_for(&damage); - println!("{:#?}", damage); - println!("{:#?}", mat); - } - fn new_inner_eq() -> InnerEquipementStats { InnerEquipementStats { damage: 10, @@ -430,13 +539,23 @@ mod test { } #[test] - fn test_creation() { - let mat = DamageMatrix::calculate_for(&new_inner_eq()); - println!("{}", mat); - println!( - "(High,Many): {}, (Low,Few): {}", - mat.get_damage(FixedPrecision::High, FixedDiceNumber::Many), - mat.get_damage(FixedPrecision::Low, FixedDiceNumber::Few) + fn basic_binomial() { + let eq = new_inner_eq(); + assert!( + (eq.average_damage( + &[FixedPrecision::High.value()], + &[FixedDiceNumber::Many.value()] + ) - 13.99995162) + .abs() + < 1E-2 + ); + assert!( + (eq.average_damage( + &[FixedPrecision::Low.value()], + &[FixedDiceNumber::Few.value()] + ) - 10.1119999) + .abs() + < 1E-2 ); } } -- 2.45.1 From 101b8c778a60557dbb264e9f54e6d90583deb2f8 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 24 Feb 2025 21:42:31 +0100 Subject: [PATCH 73/97] Add a nice turn simulator and a base senario --- .../equipement_advanced_repr.rs | 344 +------------- .../equipement_advanced_tools.rs | 433 ++++++++++++++++++ .../weaponry_structs/equipement_structs.rs | 2 +- weaponry/src/weaponry_structs/mod.rs | 1 + 4 files changed, 441 insertions(+), 339 deletions(-) create mode 100644 weaponry/src/weaponry_structs/equipement_advanced_tools.rs diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index ec193fd..b894fde 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -13,22 +13,19 @@ use crate::{ error::FatalEquipementError, export::initial_chart, interfaces::{RecipeCollection, RefinedList, ToAnalysis, ToTex}, - unfinished, weaponry_structs::{ Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats, }, }; use core::f64; -use std::{ - cmp::Ordering, - fmt::{Debug, Display}, - ops::{Add, Deref}, -}; +use std::cmp::Ordering; use charming::Chart; -use probability::prelude::{Binomial, Discrete}; use serde::Serialize; -use strum::{Display, EnumIter}; + +use super::equipement_advanced_tools::{ + Dices, Precision, get_damage_with_simulation, get_sustained_damage, +}; /// The final representation of the equipement inplementing all the fields needed for processing // TODO: Add a public getter for the inner data @@ -223,339 +220,10 @@ impl From<&InnerEquipementStats> for AdvancedStats { avg_damage_2a_safe: value.average_damage(&[Precision(7)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost), // .average_damage(&[Precision(9), Precision(7), Precision(5)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost), scenario_damage: get_damage_with_simulation(value), - mini_scenario_damage: (value.damage > 0) + mini_scenario_damage: (value.damage + value.p_damage > 0) .then(|| get_sustained_damage(value)) .unwrap_or_default(), defensive: (value.parry as f64).max(value.dodge.into()), // TODO[b]: Integrity and prot should be taken into account } } } - -/// Create the damage profile with the following simulation: -/// 10turns total -/// - 1 turn no damage -/// - 2 turns full damage (12 dice, 130% precision) -/// - 2 turns safe attacks (5 dice, 50%p) -/// - 1 turn highspeed/range hit (7 dice, 80% precision) -/// - 4 turns normal damage (7 dice, 90% precision) -// TODO[!] Implementation -fn get_damage_with_simulation(value: &InnerEquipementStats) -> f64 { - let _ = value; - // unfinished!(); - 0. -} - -/// Sustained damage -/// -/// Average damage factoring reload, calculated with 9 dice and 90% precision -// TODO[!] Replace avg_damage with this -fn get_sustained_damage(value: &InnerEquipementStats) -> f64 { - // unfinished!(); - // Actions total and damage total are arbitrarely choosen - - // With reload, damage calculation is rather complicated, since you can half reload but cant half attack - // so a reload is valid even if you don't reload fully, but you have to start your turn with less actions - // instead of building a complex scenario, the attack pattern is always: Ac:Attack + Re:Reload(and maybe reminder) every turn - // value.damage.into() - BestDamageScenarios::from_action_constraints(value, 6, 3, Dices(14), Precision(7)) - .map_or(0., |v| v.damage_done) -} - -/// The best resulting attack pattern of a virtual scenrio where some conditions are given -#[derive(Debug)] -pub struct BestDamageScenarios { - /// How many actions were used by the best attack - actions_used: i8, - /// Attacks actions used by the scenario - attacks_used: i8, - /// Resulting damage - damage_done: f64, - /// Remaining actions that need to be used to finish reload - reload_remaining: i8, - /// A debug value, should be taken down in final builds - // TODO[6]: Remove debug once the tests are done - depth: u8, -} - -impl Add for BestDamageScenarios { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - Self { - actions_used: self.actions_used + rhs.actions_used, - attacks_used: self.attacks_used + rhs.attacks_used, - damage_done: self.damage_done + rhs.damage_done, - reload_remaining: self.reload_remaining + rhs.reload_remaining, - depth: self.depth + rhs.depth, - } - } -} -impl Deref for BestDamageScenarios { - type Target = f64; - - fn deref(&self) -> &Self::Target { - &self.damage_done - } -} - -// TODO[!!]: Add a lot of testing -impl BestDamageScenarios { - /// Calculate the best alternative with a set of contraints - /// - /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) - fn from_action_constraints( - value: &InnerEquipementStats, - actions_allowed: i8, - attacks_allowed: i8, - dices_allowed: Dices, - precision: Precision, - ) -> Option { - Self::from_action_constraints_recursive( - value, - actions_allowed, - attacks_allowed, - dices_allowed, - precision, - 0, - 0, - ) - } - - /// Recursive part of the from_action_constraints call - /// - /// This algorithm takes a recursive approact to avoid too much forward complexity - fn from_action_constraints_recursive( - value: &InnerEquipementStats, - actions_allowed: i8, - attacks_allowed: i8, - dices_allowed: Dices, - precision: Precision, - reload_remaining: i8, - depth: u8, - ) -> Option { - // If we can't attack return early - if value.action_cost > actions_allowed || attacks_allowed == 0 || reload_remaining != 0 { - return None; - } - - let atkreload_cost = value.reload_cost.unwrap_or_default() + value.action_cost; - - // We create our first contender, One attack only - let one_attack = Self { - // No matter what we try to reload, even if we overcap the attack was still valid - actions_used: (atkreload_cost).clamp(0, actions_allowed), - attacks_used: 1, - damage_done: binomial_dice_distribution(value, precision, dices_allowed), - // If the reload+attack exceed the actions, we must bookkeep it - // as a reminder that we have leftover actions to spend next turn - reload_remaining: (atkreload_cost - actions_allowed).clamp(0, actions_allowed), - depth, - }; - println!( - "[{depth}] > One attack ({}): {one_attack:?}", - Dices(*dices_allowed) - ); - - // We can only try two attacks if two attack would be valid aka: - // - We can spend: 2 attacks and (at least) 1 reload (as actions) - // - : 2 attacks (as attacks) - if atkreload_cost + value.action_cost < actions_allowed && attacks_allowed > 1 { - // Cumbersome because of rounding errors - if let (Some(a), Some(b)) = ( - (Self::from_action_constraints_recursive( - value, - actions_allowed - atkreload_cost, - attacks_allowed - 1, - Dices(dices_allowed.div_floor(2)), - precision, - reload_remaining, - depth + 1, - )), - (Self::from_action_constraints_recursive( - value, - actions_allowed - atkreload_cost, - attacks_allowed - 1, - Dices(dices_allowed.div_ceil(2)), - precision, - reload_remaining, - depth + 1, - )), - ) { - let sum_sub_attacks = a + b; - println!( - "[{depth}] > Two attacks ({} & {}) : {sum_sub_attacks:?}", - Dices(dices_allowed.div_floor(2)), - Dices(dices_allowed.div_ceil(2)) - ); - // The alternative was better - if one_attack.damage_done < sum_sub_attacks.damage_done { - return Some(sum_sub_attacks); - } - } - } - - // The alternative didn't exist or was worse - Some(one_attack) - } -} - -// TODO: Consider implementing something else instead ? -impl InnerEquipementStats { - /// Calculate the average damage expected for a set of precisions and dices - fn average_damage(&self, precisions: &[Precision], list_dices: &[Dices]) -> f64 { - precisions - .iter() - .map(|precision| { - list_dices - .iter() - .map(|dices| binomial_dice_distribution(self, *precision, *dices)) - .sum::() - }) - .sum::() - / (precisions.len() as f64 * list_dices.len() as f64) - } -} - -/// Calculate the binomial distribution and average the damage from there -fn binomial_dice_distribution( - equipement: &InnerEquipementStats, - precision: Precision, - dices: Dices, -) -> f64 { - let p = ((*precision + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); - let binomial = Binomial::new(*dices, p); - - (0..*dices + 1) - .map(|target_dices| { - let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize; - if target_dices >= 1 { - (equipement.damage as f64 - + equipement.p_damage as f64 - * (target_dices - .clamp(0, equipement.rmax as usize) - .saturating_sub(1)) as f64) - * probability_success - } else { - 0. - } - }) - .fold(0., |a, b| a + b) -} - -// TODO: Change this to be a thin type and replace enum by new(nb) et high(), med() etc.. -// : And add a way to do ranges easily -/// The precision infered for a damage calculation event -#[derive(EnumIter, Clone, Copy, Display)] -#[allow(clippy::missing_docs_in_private_items)] -pub enum FixedPrecision { - High, - Medium, - Low, -} - -/// Thin representation of Precision to avoid mistakes -#[derive(Clone, Copy)] -pub struct Precision(i8); - -/// Thin representation of Dices to avoid mistakes -#[derive(Clone, Copy)] -pub struct Dices(usize); - -impl std::ops::Deref for Precision { - type Target = i8; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Display for Precision { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { - ::fmt(&self.0, f) - } -} - -impl std::ops::Deref for Dices { - type Target = usize; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Display for Dices { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { - ::fmt(&self.0, f) - } -} - -/// The number of dices rolled for a damage simulation -#[derive(EnumIter, Clone, Copy, Display)] -#[allow(clippy::missing_docs_in_private_items)] -pub enum FixedDiceNumber { - Many, - Average, - Few, -} - -// TODO[9] These implementations date back to the matrix code, rewriting them would be for the best -impl FixedPrecision { - #[inline] - /// Associate a value to the different values - fn value(&self) -> Precision { - match self { - FixedPrecision::High => Precision(9), - FixedPrecision::Medium => Precision(6), - FixedPrecision::Low => Precision(4), - } - } -} -impl FixedDiceNumber { - #[inline] - /// Associate a value to the different values - fn value(&self) -> Dices { - match self { - FixedDiceNumber::Many => Dices(8), - FixedDiceNumber::Average => Dices(6), - FixedDiceNumber::Few => Dices(4), - } - } -} - -#[cfg(test)] -mod test { - use crate::weaponry_structs::{ - equipement_advanced_repr::{FixedDiceNumber, FixedPrecision}, - equipement_structs::InnerEquipementStats, - }; - - fn new_inner_eq() -> InnerEquipementStats { - InnerEquipementStats { - damage: 10, - p_damage: 2, - precision: 0, - rmax: 3, - armor_break: 2, - ..Default::default() - } - } - - #[test] - fn basic_binomial() { - let eq = new_inner_eq(); - assert!( - (eq.average_damage( - &[FixedPrecision::High.value()], - &[FixedDiceNumber::Many.value()] - ) - 13.99995162) - .abs() - < 1E-2 - ); - assert!( - (eq.average_damage( - &[FixedPrecision::Low.value()], - &[FixedDiceNumber::Few.value()] - ) - 10.1119999) - .abs() - < 1E-2 - ); - } -} diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs new file mode 100644 index 0000000..7206ce1 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -0,0 +1,433 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_advanced_tools.rs +//! Tools for the advanced representation, all grouped in a module for convenience +use crate::weaponry_structs::equipement_structs::InnerEquipementStats; +use probability::distribution::Discrete; +use probability::prelude::Binomial; +use std::fmt::Display; +use std::ops::Add; +use std::ops::Deref; +use strum::Display; +use strum::EnumIter; + +/// Create the damage profile with the following simulation: +/// 10turns total +/// - 1 turn no damage +/// - 2 turns full damage (12 dice, 130% precision) +/// - 2 turns safe attacks (5 dice, 50%p) +/// - 1 turn highspeed/range hit (7 dice, 80% precision) +/// - 4 turns normal damage (7 dice, 90% precision) +// TODO[!] Implementation +pub(super) fn get_damage_with_simulation(value: &InnerEquipementStats) -> f64 { + let _ = value; + // unfinished!(); + 0. +} + +/// Sustained damage +/// +/// Average damage factoring reload, calculated with 9 dice and 90% precision +// TODO[!] Replace avg_damage with this +pub(super) fn get_sustained_damage(value: &InnerEquipementStats) -> f64 { + // unfinished!(); + // Actions total and damage total are arbitrarely choosen + + // With reload, damage calculation is rather complicated, since you can half reload but cant half attack + // so a reload is valid even if you don't reload fully, but you have to start your turn with less actions + // instead of building a complex scenario, the attack pattern is always: Ac:Attack + Re:Reload(and maybe reminder) every turn + let mut reloading_left = 0; + let mut total_damage = 0.; + for _ in 0..10 { + if let Some(BestDamageScenarios { + actions_used: _, + attacks_used: _, + damage_done, + reload_remaining, + depth: _, + }) = BestDamageScenarios::from_action_constraints( + value, + 4 - reloading_left, + 2, + Dices(9), + Precision(8), + ) { + reloading_left = reload_remaining; + total_damage += damage_done; + } + } + total_damage / 10. + // Iterate 10 turns, every turn we need to substract the leftover reloading + // value.damage.into() +} + +/// The best resulting attack pattern of a virtual scenrio where some conditions are given +#[derive(Debug)] +#[cfg_attr(test, derive(Default, Clone))] +pub struct BestDamageScenarios { + /// How many actions were used by the best attack + actions_used: i8, + /// Attacks actions used by the scenario + attacks_used: i8, + /// Resulting damage + damage_done: f64, + /// Remaining actions that need to be used to finish reload + reload_remaining: i8, + /// A debug value, should be taken down in final builds + // TODO[6]: Remove debug once the tests are done + depth: u8, +} + +impl Add for BestDamageScenarios { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + actions_used: self.actions_used + rhs.actions_used, + attacks_used: self.attacks_used + rhs.attacks_used, + damage_done: self.damage_done + rhs.damage_done, + reload_remaining: self.reload_remaining + rhs.reload_remaining, + depth: self.depth + rhs.depth, + } + } +} +impl Deref for BestDamageScenarios { + type Target = f64; + + fn deref(&self) -> &Self::Target { + &self.damage_done + } +} + +// TODO[!!]: Add a lot of testing +impl BestDamageScenarios { + /// Calculate the best alternative with a set of contraints + /// + /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) + fn from_action_constraints( + value: &InnerEquipementStats, + actions_allowed: i8, + attacks_allowed: i8, + dices_allowed: Dices, + precision: Precision, + ) -> Option { + Self::from_action_constraints_recursive( + value, + actions_allowed, + attacks_allowed, + dices_allowed, + precision, + 0, + 0, + ) + } + + /// Recursive part of the from_action_constraints call + /// + /// This algorithm takes a recursive approact to avoid too much forward complexity + fn from_action_constraints_recursive( + value: &InnerEquipementStats, + actions_allowed: i8, + attacks_allowed: i8, + dices_allowed: Dices, + precision: Precision, + reload_remaining: i8, + depth: u8, + ) -> Option { + // If we can't attack return early + if value.action_cost > actions_allowed + || attacks_allowed == 0 + || reload_remaining > 0 + || *dices_allowed < 1 + { + println!( + "[{depth}] > Reach the end of recursion {}>{actions_allowed}, {attacks_allowed}a, {dices_allowed}d {reload_remaining}r", + value.action_cost + ); + return None; + } + + let atkreload_cost = value.reload_cost.unwrap_or_default() + value.action_cost; + + // We create our first contender, One attack only + let one_attack = Self { + // No matter what we try to reload, even if we overcap the attack was still valid + actions_used: (atkreload_cost).clamp(0, actions_allowed), + attacks_used: 1, + damage_done: binomial_dice_distribution(value, precision, dices_allowed), + // If the reload+attack exceed the actions, we must bookkeep it + // as a reminder that we have leftover actions to spend next turn + reload_remaining: (atkreload_cost - actions_allowed + reload_remaining) + .clamp(0, actions_allowed), + depth, + }; + println!( + "[{depth}] > One attack ({}): {one_attack:?}", + Dices(*dices_allowed) + ); + + // We can only try two attacks if two attack would be valid aka: + // - We can spend: 2 attacks and (at least) 1 reload (as actions) + // - : 2 attacks (as attacks) + if atkreload_cost + value.action_cost <= actions_allowed && attacks_allowed > 1 { + // Cumbersome because of rounding errors + if let (Some(a), Some(b)) = ( + (Self::from_action_constraints_recursive( + value, + actions_allowed - atkreload_cost, //.div_floor(2).div_floor(2) * 2 -value.reload_cost.unwrap_or_default(), + attacks_allowed.div_floor(2), + Dices(dices_allowed.div_floor(2)), + precision, + reload_remaining - value.reload_cost.unwrap_or_default(), + depth + 1, + )), + (Self::from_action_constraints_recursive( + value, + actions_allowed - atkreload_cost, // .div_ceil(2).div_ceil(2) * 2 -value.reload_cost.unwrap_or_default(), + attacks_allowed.div_ceil(2), + Dices(dices_allowed.div_ceil(2)), + precision, + reload_remaining, + depth + 1, + )), + ) { + let sum_sub_attacks = a + b; + // println!( + // "[{depth}] > Two attacks ({} & {}) : {sum_sub_attacks:?}", + // Dices(dices_allowed.div_floor(2)), + // Dices(dices_allowed.div_ceil(2)) + // ); + // The alternative was better + if one_attack.damage_done < sum_sub_attacks.damage_done { + return Some(sum_sub_attacks); + } + } + } + + // The alternative didn't exist or was worse + Some(one_attack) + } +} + +// TODO: Consider implementing something else instead ? +impl InnerEquipementStats { + /// Calculate the average damage expected for a set of precisions and dices + pub(super) fn average_damage(&self, precisions: &[Precision], list_dices: &[Dices]) -> f64 { + precisions + .iter() + .map(|precision| { + list_dices + .iter() + .map(|dices| binomial_dice_distribution(self, *precision, *dices)) + .sum::() + }) + .sum::() + / (precisions.len() as f64 * list_dices.len() as f64) + } +} + +/// Calculate the binomial distribution and average the damage from there +pub(super) fn binomial_dice_distribution( + equipement: &InnerEquipementStats, + precision: Precision, + dices: Dices, +) -> f64 { + let p = ((*precision + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); + let binomial = Binomial::new(*dices, p); + + (0..*dices + 1) + .map(|target_dices| { + let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize; + if target_dices >= 1 { + (equipement.damage as f64 + + equipement.p_damage as f64 + * (target_dices + .clamp(0, equipement.rmax as usize) + .saturating_sub(1)) as f64) + * probability_success + } else { + 0. + } + }) + .fold(0., |a, b| a + b) +} + +// TODO: Change this to be a thin type and replace enum by new(nb) et high(), med() etc.. +// : And add a way to do ranges easily +/// The precision infered for a damage calculation event +#[derive(EnumIter, Clone, Copy, Display)] +#[allow(clippy::missing_docs_in_private_items)] +pub enum FixedPrecision { + High, + Medium, + Low, +} + +/// Thin representation of Precision to avoid mistakes +#[derive(Clone, Copy)] +pub struct Precision(pub i8); + +/// Thin representation of Dices to avoid mistakes +#[derive(Clone, Copy)] +pub struct Dices(pub usize); + +impl std::ops::Deref for Precision { + type Target = i8; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for Precision { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + +impl std::ops::Deref for Dices { + type Target = usize; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for Dices { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + +/// The number of dices rolled for a damage simulation +#[derive(EnumIter, Clone, Copy, Display)] +#[allow(clippy::missing_docs_in_private_items)] +pub enum FixedDiceNumber { + Many, + Average, + Few, +} + +#[cfg(test)] +mod test { + use crate::weaponry_structs::equipement_structs::InnerEquipementStats; + + use super::{BestDamageScenarios, Dices, Precision}; + + fn new_inner_eq() -> InnerEquipementStats { + InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 3, + armor_break: 2, + ..Default::default() + } + } + + macro_rules! assert_close { + ($a:expr, $b:expr) => { + assert!(($a - $b).abs() < 1E-3); + }; + } + + #[test] + fn basic_binomial() { + let eq = new_inner_eq(); + assert_close!(eq.average_damage(&[Precision(9)], &[Dices(9)]), 13.99995162); + assert_close!(eq.average_damage(&[Precision(4)], &[Dices(4)]), 10.1119999); + } + + #[test] + fn test_damage_optimisation() { + let eq = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 3, + action_cost: 1, + ..Default::default() + }; + let eq2 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 3, + action_cost: 2, + ..Default::default() + }; + let eq3 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 3, + action_cost: 2, + reload_cost: Some(2), + ..Default::default() + }; + let known_data = &[ + ( + BestDamageScenarios::from_action_constraints(&eq, 2, 1, Dices(3), Precision(10)), + 14., + ), + ( + BestDamageScenarios::from_action_constraints(&eq, 2, 2, Dices(3), Precision(10)), + 22., + ), + ( + BestDamageScenarios::from_action_constraints(&eq, 3, 3, Dices(3), Precision(10)), + 30., + ), + ( + BestDamageScenarios::from_action_constraints(&eq, 3, 3, Dices(6), Precision(10)), + 36., + ), + ( + BestDamageScenarios::from_action_constraints(&eq, 3, 3, Dices(6), Precision(10)), + 36., + ), + ( + BestDamageScenarios::from_action_constraints(&eq2, 1, 1, Dices(3), Precision(10)), + 0., + ), + ( + BestDamageScenarios::from_action_constraints(&eq2, 2, 1, Dices(3), Precision(10)), + 14., + ), + ( + BestDamageScenarios::from_action_constraints(&eq2, 4, 2, Dices(3), Precision(10)), + 22., + ), + ( + BestDamageScenarios::from_action_constraints(&eq2, 5, 3, Dices(6), Precision(10)), + 28., + ), + ( + BestDamageScenarios::from_action_constraints(&eq2, 6, 3, Dices(6), Precision(10)), + 36., + ), + ( + BestDamageScenarios::from_action_constraints(&eq3, 2, 1, Dices(3), Precision(10)), + 14., + ), + ( + BestDamageScenarios::from_action_constraints(&eq3, 4, 2, Dices(3), Precision(10)), + 14., + ), + ( + BestDamageScenarios::from_action_constraints(&eq3, 6, 2, Dices(3), Precision(10)), + 22., + ), + ( + BestDamageScenarios::from_action_constraints(&eq3, 6, 3, Dices(6), Precision(10)), + 28., + ), + ( + BestDamageScenarios::from_action_constraints(&eq3, 10, 3, Dices(6), Precision(10)), + 36., + ), + ]; + known_data.iter().for_each(|(val, res)| { + println!("{:?} ~= {res}", val.clone().unwrap_or_default()); + assert_close!(val.clone().map_or(0., |v| v.damage_done), res); + }); + // todo!() + } +} diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index e1fe186..b6f17b6 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -219,7 +219,7 @@ impl Default for DatabaseEquipementStats { #[doc(hidden)] macro_rules! r { () => { - fastrand::i8(1..i8::MAX) + fastrand::i8(1..20) }; } // TODO: Make this a test requirement or hide it behind a profile diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 278d1d3..9197b22 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -16,6 +16,7 @@ // static GLOBAL: Jemalloc = Jemalloc; mod equipement_advanced_repr; +mod equipement_advanced_tools; mod equipement_fields; mod equipement_impl_advanced; mod equipement_impl_basics; -- 2.45.1 From 788f9fb1128453a9a28712ce238f553cc4d9daa0 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 24 Feb 2025 23:33:58 +0100 Subject: [PATCH 74/97] Lot of debug on scenarios&sustained --- weaponry/examples/usage_scenario.rs | 15 ++++++-- weaponry/src/export.rs | 11 +++++- .../equipement_advanced_repr.rs | 22 ++++++++++-- .../equipement_advanced_tools.rs | 36 +++++++++++-------- .../weaponry_structs/equipement_structs.rs | 2 +- 5 files changed, 64 insertions(+), 22 deletions(-) diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 9d52b50..18fc536 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -7,6 +7,7 @@ use clap::Parser; use std::path::Path; use weaponry::interfaces::ToAnalysis; use weaponry::sort_by; +use weaponry::sort_by_cat_then; use weaponry::weaponry_structs::RefinedEquipement; // TODO : All of these should likely be in the prelude if used like this @@ -30,14 +31,24 @@ fn main() { }) .unwrap(); - let mut refined_list = scenarios.generate_refined_recipes().unwrap(); + let mut refined_list = scenarios + .generate_refined_recipes() + .unwrap() + // .inner_filter(|e| (e.advanced.max_damage_per_attack > 0.)) + .inner_filter(|e| { + e.inner.macro_category.as_ref().is_some_and(|v| { + !matches!(v, weaponry::weaponry_structs::WeaponMacroCategory::Shields) + && !matches!(v, weaponry::weaponry_structs::WeaponMacroCategory::Armor) + }) + }); + // TODO[!]: Have an enum match args.sort.as_str() { "max_per_turn" => refined_list.inner_sort(sort_by!(max_damage_per_turn)), "avg_huge" => refined_list.inner_sort(sort_by!(avg_damage_single_huge_hit)), "avg_safe" => refined_list.inner_sort(sort_by!(avg_damage_2a_safe)), "max_armor" => refined_list.inner_sort(sort_by!(armor_break_per_attack)), - // "id" => refined_list.inner_sort(|a, b| a.inner.id[0].cmp(&b.inner.id[0])), // It's actually the natural sorted way + "cat+avg" => refined_list.inner_sort(sort_by_cat_then!(avg_damage_2a_safe)), _ => (), } diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index 9a3ad79..ba05733 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -41,6 +41,7 @@ /// /// Knowing this tradeoff, the difficulty to maintain is considered an acceptable tradeoff // TODO[4]: If the field accessed are only in advanced, remove the closure entirely and auto_generate it +// TODO[4]: A good part of this code shouldn't be generic and instead in weaponry #[macro_export] macro_rules! add_field_to_chart { ($base_struct:expr, $chart:ident, ($names:ident # $name_type:ty, $($table_names:ident # $table_type:ty),* $(,)*), | $closure_name:ident | {($($fields:expr,)*)} @@ -58,8 +59,16 @@ macro_rules! add_field_to_chart { let $chart = $chart .series( charming::series::Line::new() + .stack("Total") .data($table_names) - .name(stringify!($table_names)), + .name(stringify!($table_names)) + .mark_point(charming::element::MarkPoint::new().data(vec![("max", "Max"), ("min", "Min")])) + .mark_line(charming::element::MarkLine::new().data(vec![charming::element::MarkLineVariant::Simple( + charming::element::MarkLineData::new() + .type_(charming::element::MarkLineDataType::Average) + .name("Avg"), + )])), + ); )* diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index b894fde..45355da 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -84,6 +84,17 @@ macro_rules! sort_by { } }; } +#[macro_export] +/// A simple macro to sort the inner advanced field by a specific field +// TODO[6] find a way to not have to import the refinedequipement +macro_rules! sort_by_cat_then { + ($field:ident) => { + |a, b| match a.inner.id[0].cmp(&b.inner.id[0]) { + std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), + ord => ord, + } + }; +} impl ToAnalysis for RefinedEquipementList { type InnerData = RefinedEquipement; @@ -115,6 +126,11 @@ impl ToAnalysis for RefinedEquipementList { self.inner.len() )); + macro_rules! round { + ($a:expr) => { + ($a * 10.).round() / 10. + }; + } add_field_to_chart!( self, initial_chart, @@ -139,11 +155,11 @@ impl ToAnalysis for RefinedEquipementList { // ref_equipement.advanced.speed, // ref_equipement.advanced.armor_break_per_attack, // ref_equipement.advanced.expected_armor_break_per_2a, - ref_equipement.advanced.avg_damage_2a_safe, - ref_equipement.advanced.avg_damage_single_huge_hit, + round!(ref_equipement.advanced.avg_damage_2a_safe), + round!(ref_equipement.advanced.avg_damage_single_huge_hit), // ref_equipement.advanced.scenario_damage, // ref_equipement.advanced.defensive, - ref_equipement.advanced.mini_scenario_damage, + round!(ref_equipement.advanced.mini_scenario_damage), ) } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index 7206ce1..ec10713 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -120,7 +120,6 @@ impl BestDamageScenarios { 0, ) } - /// Recursive part of the from_action_constraints call /// /// This algorithm takes a recursive approact to avoid too much forward complexity @@ -139,13 +138,18 @@ impl BestDamageScenarios { || reload_remaining > 0 || *dices_allowed < 1 { - println!( - "[{depth}] > Reach the end of recursion {}>{actions_allowed}, {attacks_allowed}a, {dices_allowed}d {reload_remaining}r", - value.action_cost - ); + // println!( + // "[{depth}] > Reach the end of recursion {}>{actions_allowed}, {attacks_allowed}a, {dices_allowed}d {reload_remaining}r", + // value.action_cost + // ); return None; } + // if depth == 0 { + // println!( + // "Starting recursion: {actions_allowed}A {attacks_allowed}atk {dices_allowed}*" + // ); + // } let atkreload_cost = value.reload_cost.unwrap_or_default() + value.action_cost; // We create our first contender, One attack only @@ -160,10 +164,10 @@ impl BestDamageScenarios { .clamp(0, actions_allowed), depth, }; - println!( - "[{depth}] > One attack ({}): {one_attack:?}", - Dices(*dices_allowed) - ); + // println!( + // "[{depth}] > One attack ({}d): {one_attack:?}/{actions_allowed}A", + // Dices(*dices_allowed) + // ); // We can only try two attacks if two attack would be valid aka: // - We can spend: 2 attacks and (at least) 1 reload (as actions) @@ -173,20 +177,22 @@ impl BestDamageScenarios { if let (Some(a), Some(b)) = ( (Self::from_action_constraints_recursive( value, - actions_allowed - atkreload_cost, //.div_floor(2).div_floor(2) * 2 -value.reload_cost.unwrap_or_default(), + // TODO[9]: THIS APPROACH IS DEEPLY INCORRECT + // : It does however work for the values we will be using it + actions_allowed - atkreload_cost, attacks_allowed.div_floor(2), Dices(dices_allowed.div_floor(2)), precision, - reload_remaining - value.reload_cost.unwrap_or_default(), + reload_remaining, depth + 1, )), (Self::from_action_constraints_recursive( value, - actions_allowed - atkreload_cost, // .div_ceil(2).div_ceil(2) * 2 -value.reload_cost.unwrap_or_default(), + actions_allowed - atkreload_cost, attacks_allowed.div_ceil(2), Dices(dices_allowed.div_ceil(2)), precision, - reload_remaining, + reload_remaining - value.reload_cost.unwrap_or_default(), depth + 1, )), ) { @@ -424,8 +430,8 @@ mod test { 36., ), ]; - known_data.iter().for_each(|(val, res)| { - println!("{:?} ~= {res}", val.clone().unwrap_or_default()); + known_data.iter().enumerate().for_each(|(i, (val, res))| { + println!("[{i}] {:?} ~= {res}", val.clone().unwrap_or_default()); assert_close!(val.clone().map_or(0., |v| v.damage_done), res); }); // todo!() diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index b6f17b6..c26d605 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -107,7 +107,7 @@ pub struct InnerEquipementStats { 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 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: SpecialField, pub(super) action_cost: i8, -- 2.45.1 From 18c864efe539932ea72aacbf16caa3fda7c72aa9 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 25 Feb 2025 01:38:21 +0100 Subject: [PATCH 75/97] Refactoring and adds Attacks & Actions as thin types --- weaponry/examples/graph.rs | 43 ++- weaponry/examples/usage_scenario.rs | 1 - weaponry/src/export.rs | 2 +- .../equipement_advanced_repr.rs | 148 +++++--- .../equipement_advanced_tools.rs | 344 ++++++++++++------ .../weaponry_structs/equipement_thin_types.rs | 97 +++++ weaponry/src/weaponry_structs/mod.rs | 1 + 7 files changed, 468 insertions(+), 168 deletions(-) create mode 100644 weaponry/src/weaponry_structs/equipement_thin_types.rs diff --git a/weaponry/examples/graph.rs b/weaponry/examples/graph.rs index c4a20fb..053cb0a 100644 --- a/weaponry/examples/graph.rs +++ b/weaponry/examples/graph.rs @@ -49,7 +49,10 @@ // } use charming::{ Chart, - component::{Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, ToolboxDataZoom, VisualMap, VisualMapType}, + component::{ + Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, + ToolboxDataZoom, VisualMap, VisualMapType, + }, element::{AxisType, Tooltip, Trigger}, series::Line, }; @@ -118,21 +121,49 @@ pub fn chart() -> Chart { }); Chart::new() - .title(Title::new().text("Gradient along the y axis").left("center")) + .title( + Title::new() + .text("Gradient along the y axis") + .left("center"), + ) // .title(Title::new().text("Gradient along the x axis").left("center").top("55%")) .tooltip(Tooltip::new().trigger(Trigger::Axis)) - .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(0).min(0).max(400)) + .visual_map( + VisualMap::new() + .show(false) + .type_(VisualMapType::Continuous) + .series_index(0) + .min(0) + .max(400), + ) // .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(1).dimension(0).min(0).max(10).max((data_list.len() - 1) as f64)) - .x_axis(Axis::new().data(data_list.to_vec()).type_(AxisType::Category).boundary_gap(false)) + .x_axis( + Axis::new() + .data(data_list.to_vec()) + .type_(AxisType::Category) + .boundary_gap(false), + ) // .x_axis(Axis::new().data(data_list.to_vec()).grid_index(1)) .y_axis(Axis::new()) // .y_axis(Axis::new().grid_index(1)) .grid(Grid::new()) // .grid(Grid::new().top("60%")) .series(Line::new().show_symbol(false).data(value_list.clone())) - .data_zoom(DataZoom::new().type_(DataZoomType::Inside).start(0).end(100)) + .data_zoom( + DataZoom::new() + .type_(DataZoomType::Inside) + .start(0) + .end(100), + ) .data_zoom(DataZoom::new().start(0).end(100)) - .toolbox(Toolbox::new().feature(Feature::new().data_zoom(ToolboxDataZoom::new().y_axis_index("none")).restore(Restore::new()).save_as_image(SaveAsImage::new()))) + .toolbox( + Toolbox::new().feature( + Feature::new() + .data_zoom(ToolboxDataZoom::new().y_axis_index("none")) + .restore(Restore::new()) + .save_as_image(SaveAsImage::new()), + ), + ) .tooltip(Tooltip::new().trigger(Trigger::Axis)) // .series(Line::new().show_symbol(false).x_axis_index(1).y_axis_index(1).data(value_list)) } diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 18fc536..a3fc0f9 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -44,7 +44,6 @@ fn main() { // TODO[!]: Have an enum match args.sort.as_str() { - "max_per_turn" => refined_list.inner_sort(sort_by!(max_damage_per_turn)), "avg_huge" => refined_list.inner_sort(sort_by!(avg_damage_single_huge_hit)), "avg_safe" => refined_list.inner_sort(sort_by!(avg_damage_2a_safe)), "max_armor" => refined_list.inner_sort(sort_by!(armor_break_per_attack)), diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index ba05733..db193bb 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -27,7 +27,7 @@ /// |ref_equipement| { /// ( /// &ref_equipement.advanced.display_name, -/// ref_equipement.advanced.max_damage_per_turn, +/// ref_equipement.advanced.max_damage_per_attack, /// ) /// } /// ); diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 45355da..90e37c6 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -8,6 +8,8 @@ //! nothing prevents us to implement the trait for other objects and avoid massive computation //! of all the fields even when the user will not be interested in them #![allow(dead_code)] +use crate::weaponry_structs::equipement_thin_types::Dices; +use crate::weaponry_structs::equipement_thin_types::Precision; use crate::{ add_field_to_chart, error::FatalEquipementError, @@ -24,8 +26,10 @@ use charming::Chart; use serde::Serialize; use super::equipement_advanced_tools::{ - Dices, Precision, get_damage_with_simulation, get_sustained_damage, + BestDamageScenarios, get_damage_with_simulation, get_sustained_damage, }; +use super::equipement_thin_types::Actions; +use super::equipement_thin_types::Attacks; /// The final representation of the equipement inplementing all the fields needed for processing // TODO: Add a public getter for the inner data @@ -116,6 +120,7 @@ impl ToAnalysis for RefinedEquipementList { } // TODO[3]: Consider wether the naming should be a parameter, + // : Consider wether the closure should be a parameter // or a config should be given or if the scenario should be fed again the Refined and ... fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) @@ -128,7 +133,7 @@ impl ToAnalysis for RefinedEquipementList { macro_rules! round { ($a:expr) => { - ($a * 10.).round() / 10. + ($a * 100.).round() / 100. }; } add_field_to_chart!( @@ -136,31 +141,32 @@ impl ToAnalysis for RefinedEquipementList { initial_chart, ( index # &String, - // max_damage_per_turn # f64, - // max_damage_per_attack # f64, - // speed # f64, - // armor_break_per_attack # f64, - // expected_armor_break_per # f64, - avg_damage_safe # f64, + max_damage_per_attack # f64, + armor_break_per_attack # f64, + expected_armor_break_per_attack # f64, + avg_damage_2a_safe # f64, avg_damage_single_huge_hit # f64, - // scenario_damage # f64, - // defensive # f64, - mini_scenario_damage # f64 + speed # f64, + scenario_damage # f64, + defensive # f64, + earlygame_sustained_damage_per_turn # f64, + midgame_sustained_damage_per_turn # f64, + endgame_sustained_damage_per_turn # f64, ), |ref_equipement| { ( &ref_equipement.advanced.display_name, - // ref_equipement.advanced.max_damage_per_turn, - // ref_equipement.advanced.max_damage_per_attack, - // ref_equipement.advanced.speed, - // ref_equipement.advanced.armor_break_per_attack, - // ref_equipement.advanced.expected_armor_break_per_2a, - round!(ref_equipement.advanced.avg_damage_2a_safe), - round!(ref_equipement.advanced.avg_damage_single_huge_hit), - // ref_equipement.advanced.scenario_damage, - // ref_equipement.advanced.defensive, - round!(ref_equipement.advanced.mini_scenario_damage), - + round!(ref_equipement.advanced.max_damage_per_attack ), + round!(ref_equipement.advanced.armor_break_per_attack ), + round!(ref_equipement.advanced.expected_armor_break_per_attack ), + round!(ref_equipement.advanced.avg_damage_2a_safe ), + round!(ref_equipement.advanced.avg_damage_single_huge_hit ), + round!(ref_equipement.advanced.speed ), + round!(ref_equipement.advanced.scenario_damage ), + round!(ref_equipement.advanced.defensive ), + round!(ref_equipement.advanced.earlygame_sustained_damage_per_turn ), + round!(ref_equipement.advanced.midgame_sustained_damage_per_turn ), + round!(ref_equipement.advanced.endgame_sustained_damage_per_turn ), ) } ); @@ -192,54 +198,100 @@ impl Default for RefinedEquipementList { /// The list of advanced stats infered from an Equipement // TODO: The two philosophies to drop the old inner or convert the useful fields are considered right now // TODO: This whole public might be overkill ? A good inner view or scenario could implement what is needed -#[allow(missing_docs, clippy::missing_docs_in_private_items)] #[derive(Serialize)] pub struct AdvancedStats { + /// A simple name created by merging all components pub display_name: String, + /// The absolute maximum damage done with each attack pub max_damage_per_attack: f64, - pub max_damage_per_turn: f64, + // /// The absolute maximum damage done every turn (with two attacks) + // pub max_damage_per_turn: f64, + /// The armor break per attack pub armor_break_per_attack: f64, + // This category of every result, using this would be better than id shenenigans // pub category: Option, - /// Armor break factoring in the damage output: While a weapon might have high AB, not having any damage will seriously hinder that AB - pub expected_armor_break_per_2a: f64, - /// Dps with two actions and 5 dices + /// Armor break factoring in the damage output: + /// While a weapon might have high AB, not having any damage will seriously hinder that AB + pub expected_armor_break_per_attack: f64, + /// Dps with two actions and 5 dices over a variety of scenarios pub avg_damage_2a_safe: f64, - // /// Dps with four actions and 11 dices + /// Dps with four actions and 11 dices over a variety of scenarios pub avg_damage_single_huge_hit: f64, + /// The speed given by the weapon pub speed: f64, + /// The damage obtained after a 10 turn pseudo scenario pub scenario_damage: f64, + /// A defensive metric giving the best defense bonus for the weapon pub defensive: f64, - pub mini_scenario_damage: f64, + /// The sustained damage of an earlygame character, normalized over 10 turns + pub earlygame_sustained_damage_per_turn: f64, + /// The sustained damage of an earlygame character, normalized over 10 turns + pub midgame_sustained_damage_per_turn: f64, + /// The sustained damage of an endgame character, normalized over 10 turns + pub endgame_sustained_damage_per_turn: f64, + // QOL Metrics } impl From<&InnerEquipementStats> for AdvancedStats { fn from(value: &InnerEquipementStats) -> Self { let max_damage_per_attack = (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; - let armor_break_per_attack = (value.armor_break as f64).min(max_damage_per_attack); + let armor_break_per_attack = + (value.armor_break as f64 + value.antimaterial as f64).min(max_damage_per_attack); Self { - // UNUSED METRICS - // avg_dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), - max_damage_per_turn: max_damage_per_attack * 2., // TODO: Not Sure - // Defensive metrics - // SOL Metrics ? - - // IMPORTANT METRICS display_name: value.name.join(" "), + max_damage_per_attack, speed: value.speed.into(), armor_break_per_attack, - expected_armor_break_per_2a: (max_damage_per_attack + 6. - 8.) + // Adds the base strength, substracts the expected protection + expected_armor_break_per_attack: (max_damage_per_attack + 6. - 8.) .min(armor_break_per_attack) * 2. - / value.action_cost as f64, // Adds the base strength, substracts the expected protection - max_damage_per_attack, - avg_damage_single_huge_hit: value.average_damage(&[Precision(9)], &[Dices(7)]), // A huge hit but definitely not a "FULL THROTTLE" hit - avg_damage_2a_safe: value.average_damage(&[Precision(7)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost), - // .average_damage(&[Precision(9), Precision(7), Precision(5)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost), - scenario_damage: get_damage_with_simulation(value), - mini_scenario_damage: (value.damage + value.p_damage > 0) - .then(|| get_sustained_damage(value)) - .unwrap_or_default(), - defensive: (value.parry as f64).max(value.dodge.into()), // TODO[b]: Integrity and prot should be taken into account + / value.action_cost as f64, + scenario_damage: get_damage_with_simulation(value, Actions(4), Attacks(2)), + defensive: (value.parry as f64).max(value.dodge.into()), + avg_damage_2a_safe: BestDamageScenarios::from_action_constraints( + value, + Actions(2), + Attacks(2), + Dices(4), + Precision(8), + ) + .map(|f| *f) + .unwrap_or_default(), + avg_damage_single_huge_hit: BestDamageScenarios::from_action_constraints( + value, + Actions(2), + Attacks(2), + Dices(8), + Precision(9), + ) + .map(|f| *f) + .unwrap_or_default(), + earlygame_sustained_damage_per_turn: get_sustained_damage( + value, + Actions(4), + Attacks(2), + Dices(9), + Precision(8), + ), + midgame_sustained_damage_per_turn: get_sustained_damage( + value, + Actions(5), + Attacks(3), + Dices(11), + Precision(9), + ), + + endgame_sustained_damage_per_turn: get_sustained_damage( + value, + Actions(6), + Attacks(3), + Dices(13), + Precision(10), + ), } } } +// mini_scenario_damage: (value.damage + value.p_damage > 0) +// .then(|| get_sustained_damage(value)) +// .unwrap_or_default(), diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index ec10713..756beef 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -4,12 +4,16 @@ use crate::weaponry_structs::equipement_structs::InnerEquipementStats; use probability::distribution::Discrete; use probability::prelude::Binomial; -use std::fmt::Display; use std::ops::Add; use std::ops::Deref; use strum::Display; use strum::EnumIter; +use super::equipement_thin_types::Actions; +use super::equipement_thin_types::Attacks; +use super::equipement_thin_types::Dices; +use super::equipement_thin_types::Precision; + /// Create the damage profile with the following simulation: /// 10turns total /// - 1 turn no damage @@ -18,9 +22,24 @@ use strum::EnumIter; /// - 1 turn highspeed/range hit (7 dice, 80% precision) /// - 4 turns normal damage (7 dice, 90% precision) // TODO[!] Implementation -pub(super) fn get_damage_with_simulation(value: &InnerEquipementStats) -> f64 { - let _ = value; - // unfinished!(); +pub(super) fn get_damage_with_simulation( + value: &InnerEquipementStats, + actions: Actions, + attacks: Attacks, +) -> f64 { + let turns = &[ + (actions, attacks, Dices(0), Precision(0)), + (actions, attacks, Dices(12), Precision(13)), + (actions, attacks, Dices(12), Precision(13)), + (actions, attacks, Dices(5), Precision(5)), + (actions, attacks, Dices(7), Precision(8)), + (actions, attacks, Dices(7), Precision(9)), + (actions, attacks, Dices(7), Precision(9)), + (actions, attacks, Dices(7), Precision(9)), + (actions, attacks, Dices(7), Precision(9)), + (actions, attacks, Dices(7), Precision(9)), + ]; + 0. } @@ -28,16 +47,51 @@ pub(super) fn get_damage_with_simulation(value: &InnerEquipementStats) -> f64 { /// /// Average damage factoring reload, calculated with 9 dice and 90% precision // TODO[!] Replace avg_damage with this -pub(super) fn get_sustained_damage(value: &InnerEquipementStats) -> f64 { - // unfinished!(); +pub(super) fn get_sustained_damage( + value: &InnerEquipementStats, + actions: Actions, + attacks: Attacks, + dices: Dices, + precision: Precision, +) -> f64 { // Actions total and damage total are arbitrarely choosen + let l = &[TurnInfo { + actions, + attacks, + dices, + precision, + }; 10]; + let total_damage = damage_over_turns(value, l); + total_damage / 10. + // Iterate 10 turns, every turn we need to substract the leftover reloading + // value.damage.into() +} + +/// Exists internally to pass variables +#[derive(Clone, Copy)] +#[allow(clippy::missing_docs_in_private_items)] +struct TurnInfo { + actions: Actions, + attacks: Attacks, + dices: Dices, + precision: Precision, +} + +/// Calculate the damage over a series of consecutive turns using the given slice of turn info +fn damage_over_turns(value: &InnerEquipementStats, turn_info: &[TurnInfo]) -> f64 { // With reload, damage calculation is rather complicated, since you can half reload but cant half attack // so a reload is valid even if you don't reload fully, but you have to start your turn with less actions // instead of building a complex scenario, the attack pattern is always: Ac:Attack + Re:Reload(and maybe reminder) every turn - let mut reloading_left = 0; + let mut reloading_left = Actions(0); let mut total_damage = 0.; - for _ in 0..10 { + for TurnInfo { + actions, + attacks, + dices, + precision, + } in turn_info + { if let Some(BestDamageScenarios { actions_used: _, attacks_used: _, @@ -46,18 +100,16 @@ pub(super) fn get_sustained_damage(value: &InnerEquipementStats) -> f64 { depth: _, }) = BestDamageScenarios::from_action_constraints( value, - 4 - reloading_left, - 2, - Dices(9), - Precision(8), + *actions - reloading_left, + *attacks, + *dices, + *precision, ) { reloading_left = reload_remaining; total_damage += damage_done; } } - total_damage / 10. - // Iterate 10 turns, every turn we need to substract the leftover reloading - // value.damage.into() + total_damage } /// The best resulting attack pattern of a virtual scenrio where some conditions are given @@ -65,13 +117,13 @@ pub(super) fn get_sustained_damage(value: &InnerEquipementStats) -> f64 { #[cfg_attr(test, derive(Default, Clone))] pub struct BestDamageScenarios { /// How many actions were used by the best attack - actions_used: i8, + actions_used: Actions, /// Attacks actions used by the scenario - attacks_used: i8, + attacks_used: Attacks, /// Resulting damage damage_done: f64, /// Remaining actions that need to be used to finish reload - reload_remaining: i8, + reload_remaining: Actions, /// A debug value, should be taken down in final builds // TODO[6]: Remove debug once the tests are done depth: u8, @@ -103,15 +155,15 @@ impl BestDamageScenarios { /// Calculate the best alternative with a set of contraints /// /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) - fn from_action_constraints( - value: &InnerEquipementStats, - actions_allowed: i8, - attacks_allowed: i8, + pub fn from_action_constraints( + equipement_stats: &InnerEquipementStats, + actions_allowed: Actions, + attacks_allowed: Attacks, dices_allowed: Dices, precision: Precision, ) -> Option { Self::from_action_constraints_recursive( - value, + equipement_stats, actions_allowed, attacks_allowed, dices_allowed, @@ -124,17 +176,17 @@ impl BestDamageScenarios { /// /// This algorithm takes a recursive approact to avoid too much forward complexity fn from_action_constraints_recursive( - value: &InnerEquipementStats, - actions_allowed: i8, - attacks_allowed: i8, + equipement_stats: &InnerEquipementStats, + actions_allowed: Actions, + attacks_allowed: Attacks, dices_allowed: Dices, precision: Precision, reload_remaining: i8, depth: u8, ) -> Option { // If we can't attack return early - if value.action_cost > actions_allowed - || attacks_allowed == 0 + if equipement_stats.action_cost > *actions_allowed + || *attacks_allowed == 0 || reload_remaining > 0 || *dices_allowed < 1 { @@ -150,18 +202,20 @@ impl BestDamageScenarios { // "Starting recursion: {actions_allowed}A {attacks_allowed}atk {dices_allowed}*" // ); // } - let atkreload_cost = value.reload_cost.unwrap_or_default() + value.action_cost; + let atkreload_cost = + equipement_stats.reload_cost.unwrap_or_default() + equipement_stats.action_cost; // We create our first contender, One attack only let one_attack = Self { // No matter what we try to reload, even if we overcap the attack was still valid - actions_used: (atkreload_cost).clamp(0, actions_allowed), - attacks_used: 1, - damage_done: binomial_dice_distribution(value, precision, dices_allowed), + actions_used: Actions((atkreload_cost).clamp(0, *actions_allowed)), + attacks_used: Attacks(1), + damage_done: binomial_dice_distribution(equipement_stats, precision, dices_allowed), // If the reload+attack exceed the actions, we must bookkeep it // as a reminder that we have leftover actions to spend next turn - reload_remaining: (atkreload_cost - actions_allowed + reload_remaining) - .clamp(0, actions_allowed), + reload_remaining: Actions( + ((atkreload_cost) - *actions_allowed + reload_remaining).clamp(0, *actions_allowed), + ), depth, }; // println!( @@ -172,27 +226,28 @@ impl BestDamageScenarios { // We can only try two attacks if two attack would be valid aka: // - We can spend: 2 attacks and (at least) 1 reload (as actions) // - : 2 attacks (as attacks) - if atkreload_cost + value.action_cost <= actions_allowed && attacks_allowed > 1 { + if atkreload_cost + equipement_stats.action_cost <= *actions_allowed && *attacks_allowed > 1 + { // Cumbersome because of rounding errors if let (Some(a), Some(b)) = ( (Self::from_action_constraints_recursive( - value, + equipement_stats, // TODO[9]: THIS APPROACH IS DEEPLY INCORRECT // : It does however work for the values we will be using it - actions_allowed - atkreload_cost, - attacks_allowed.div_floor(2), + actions_allowed - Actions(atkreload_cost), + Attacks(attacks_allowed.div_floor(2)), Dices(dices_allowed.div_floor(2)), precision, reload_remaining, depth + 1, )), (Self::from_action_constraints_recursive( - value, - actions_allowed - atkreload_cost, - attacks_allowed.div_ceil(2), + equipement_stats, + actions_allowed - Actions(atkreload_cost), + Attacks(attacks_allowed.div_ceil(2)), Dices(dices_allowed.div_ceil(2)), precision, - reload_remaining - value.reload_cost.unwrap_or_default(), + reload_remaining - equipement_stats.reload_cost.unwrap_or_default(), depth + 1, )), ) { @@ -214,23 +269,6 @@ impl BestDamageScenarios { } } -// TODO: Consider implementing something else instead ? -impl InnerEquipementStats { - /// Calculate the average damage expected for a set of precisions and dices - pub(super) fn average_damage(&self, precisions: &[Precision], list_dices: &[Dices]) -> f64 { - precisions - .iter() - .map(|precision| { - list_dices - .iter() - .map(|dices| binomial_dice_distribution(self, *precision, *dices)) - .sum::() - }) - .sum::() - / (precisions.len() as f64 * list_dices.len() as f64) - } -} - /// Calculate the binomial distribution and average the damage from there pub(super) fn binomial_dice_distribution( equipement: &InnerEquipementStats, @@ -268,40 +306,6 @@ pub enum FixedPrecision { Low, } -/// Thin representation of Precision to avoid mistakes -#[derive(Clone, Copy)] -pub struct Precision(pub i8); - -/// Thin representation of Dices to avoid mistakes -#[derive(Clone, Copy)] -pub struct Dices(pub usize); - -impl std::ops::Deref for Precision { - type Target = i8; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Display for Precision { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { - ::fmt(&self.0, f) - } -} - -impl std::ops::Deref for Dices { - type Target = usize; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Display for Dices { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { - ::fmt(&self.0, f) - } -} - /// The number of dices rolled for a damage simulation #[derive(EnumIter, Clone, Copy, Display)] #[allow(clippy::missing_docs_in_private_items)] @@ -313,9 +317,12 @@ pub enum FixedDiceNumber { #[cfg(test)] mod test { - use crate::weaponry_structs::equipement_structs::InnerEquipementStats; + use crate::weaponry_structs::{ + equipement_structs::InnerEquipementStats, + equipement_thin_types::{Actions, Attacks}, + }; - use super::{BestDamageScenarios, Dices, Precision}; + use super::{BestDamageScenarios, Dices, Precision, binomial_dice_distribution}; fn new_inner_eq() -> InnerEquipementStats { InnerEquipementStats { @@ -334,11 +341,34 @@ mod test { }; } + pub(super) fn average_damage( + equipement: &InnerEquipementStats, + precisions: &[Precision], + list_dices: &[Dices], + ) -> f64 { + precisions + .iter() + .map(|precision| { + list_dices + .iter() + .map(|dices| binomial_dice_distribution(equipement, *precision, *dices)) + .sum::() + }) + .sum::() + / (precisions.len() as f64 * list_dices.len() as f64) + } + #[test] fn basic_binomial() { let eq = new_inner_eq(); - assert_close!(eq.average_damage(&[Precision(9)], &[Dices(9)]), 13.99995162); - assert_close!(eq.average_damage(&[Precision(4)], &[Dices(4)]), 10.1119999); + assert_close!( + average_damage(&eq, &[Precision(9)], &[Dices(9)]), + 13.99995162 + ); + assert_close!( + average_damage(&eq, &[Precision(4)], &[Dices(4)]), + 10.1119999 + ); } #[test] @@ -370,63 +400,153 @@ mod test { }; let known_data = &[ ( - BestDamageScenarios::from_action_constraints(&eq, 2, 1, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), 14., ), ( - BestDamageScenarios::from_action_constraints(&eq, 2, 2, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(2), + Attacks(2), + Dices(3), + Precision(10), + ), 22., ), ( - BestDamageScenarios::from_action_constraints(&eq, 3, 3, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(3), + Attacks(3), + Dices(3), + Precision(10), + ), 30., ), ( - BestDamageScenarios::from_action_constraints(&eq, 3, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(3), + Attacks(3), + Dices(6), + Precision(10), + ), 36., ), ( - BestDamageScenarios::from_action_constraints(&eq, 3, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(3), + Attacks(3), + Dices(6), + Precision(10), + ), 36., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 1, 1, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(1), + Attacks(1), + Dices(3), + Precision(10), + ), 0., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 2, 1, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), 14., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 4, 2, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(4), + Attacks(2), + Dices(3), + Precision(10), + ), 22., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 5, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(5), + Attacks(3), + Dices(6), + Precision(10), + ), 28., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 6, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(6), + Attacks(3), + Dices(6), + Precision(10), + ), 36., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 2, 1, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), 14., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 4, 2, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(4), + Attacks(2), + Dices(3), + Precision(10), + ), 14., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 6, 2, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(6), + Attacks(2), + Dices(3), + Precision(10), + ), 22., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 6, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(6), + Attacks(3), + Dices(6), + Precision(10), + ), 28., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 10, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(10), + Attacks(3), + Dices(6), + Precision(10), + ), 36., ), ]; diff --git a/weaponry/src/weaponry_structs/equipement_thin_types.rs b/weaponry/src/weaponry_structs/equipement_thin_types.rs new file mode 100644 index 0000000..19175f9 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_thin_types.rs @@ -0,0 +1,97 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_thin_types.rs +//! Important thin representation to avoid using direct and risky usage of usize,isize etc... + +use std::{ + fmt::Display, + ops::{Add, Sub}, +}; + +/// Thin representation of Precision to avoid mistakes +#[derive(Clone, Copy)] +pub struct Precision(pub i8); + +/// Thin representation of Dices to avoid mistakes +#[derive(Clone, Copy)] +pub struct Dices(pub usize); + +/// Thin representation of Attack to avoid mistakes +#[derive(Clone, Copy, Debug, Default)] +pub struct Attacks(pub i8); + +impl Add for Attacks { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self(self.0 + rhs.0) + } +} + +impl std::ops::Deref for Attacks { + type Target = i8; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl Display for Attacks { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} +/// Thin representation of Actions to avoid mistakes +#[derive(Clone, Copy, Default, Debug)] +pub struct Actions(pub i8); + +impl std::ops::Deref for Actions { + type Target = i8; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Add for Actions { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self(self.0 + rhs.0) + } +} +impl Sub for Actions { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + Self(self.0 - rhs.0) + } +} + +impl Display for Actions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + +impl std::ops::Deref for Precision { + type Target = i8; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for Precision { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + +impl std::ops::Deref for Dices { + type Target = usize; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for Dices { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 9197b22..66d8417 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -26,6 +26,7 @@ mod equipement_impl_logic; mod equipement_impl_math; pub mod equipement_scenario; pub mod equipement_structs; +pub mod equipement_thin_types; mod equipement_views; // Republishes the most used symbols -- 2.45.1 From b6de1aa1cd3a2bea67d4c59451587d570607df25 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 25 Feb 2025 03:05:00 +0100 Subject: [PATCH 76/97] Corrected some display and a nasty but in rmax reporting --- weaponry/src/export.rs | 3 +- .../equipement_advanced_repr.rs | 22 ++-- .../equipement_advanced_tools.rs | 102 ++++++++++++++---- .../weaponry_structs/equipement_thin_types.rs | 7 ++ 4 files changed, 105 insertions(+), 29 deletions(-) diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index db193bb..455d894 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -59,7 +59,7 @@ macro_rules! add_field_to_chart { let $chart = $chart .series( charming::series::Line::new() - .stack("Total") + // .stack("Total") .data($table_names) .name(stringify!($table_names)) .mark_point(charming::element::MarkPoint::new().data(vec![("max", "Max"), ("min", "Min")])) @@ -68,7 +68,6 @@ macro_rules! add_field_to_chart { .type_(charming::element::MarkLineDataType::Average) .name("Avg"), )])), - ); )* diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 90e37c6..fd1de68 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -146,9 +146,11 @@ impl ToAnalysis for RefinedEquipementList { expected_armor_break_per_attack # f64, avg_damage_2a_safe # f64, avg_damage_single_huge_hit # f64, - speed # f64, + // speed # f64, + variance # f64, + variance_pct # f64, scenario_damage # f64, - defensive # f64, + // defensive # f64, earlygame_sustained_damage_per_turn # f64, midgame_sustained_damage_per_turn # f64, endgame_sustained_damage_per_turn # f64, @@ -161,9 +163,11 @@ impl ToAnalysis for RefinedEquipementList { round!(ref_equipement.advanced.expected_armor_break_per_attack ), round!(ref_equipement.advanced.avg_damage_2a_safe ), round!(ref_equipement.advanced.avg_damage_single_huge_hit ), - round!(ref_equipement.advanced.speed ), + // round!(ref_equipement.advanced.speed), + round!(ref_equipement.advanced.variance), + round!(ref_equipement.advanced.variance_pct ), round!(ref_equipement.advanced.scenario_damage ), - round!(ref_equipement.advanced.defensive ), + // round!(ref_equipement.advanced.defensive ), round!(ref_equipement.advanced.earlygame_sustained_damage_per_turn ), round!(ref_equipement.advanced.midgame_sustained_damage_per_turn ), round!(ref_equipement.advanced.endgame_sustained_damage_per_turn ), @@ -229,14 +233,18 @@ pub struct AdvancedStats { pub midgame_sustained_damage_per_turn: f64, /// The sustained damage of an endgame character, normalized over 10 turns pub endgame_sustained_damage_per_turn: f64, + /// The damage variance between the base damage and the potential damage + pub variance: f64, + /// This same variance as a percent + pub variance_pct: f64, // QOL Metrics } impl From<&InnerEquipementStats> for AdvancedStats { fn from(value: &InnerEquipementStats) -> Self { - let max_damage_per_attack = - (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; + let max_damage_per_attack = (value.damage + value.p_damage * (value.rmax)) as f64; let armor_break_per_attack = (value.armor_break as f64 + value.antimaterial as f64).min(max_damage_per_attack); + let variance = (value.p_damage * value.rmax) as f64; Self { display_name: value.name.join(" "), max_damage_per_attack, @@ -249,6 +257,8 @@ impl From<&InnerEquipementStats> for AdvancedStats { / value.action_cost as f64, scenario_damage: get_damage_with_simulation(value, Actions(4), Attacks(2)), defensive: (value.parry as f64).max(value.dodge.into()), + variance, + variance_pct: variance / value.damage as f64, avg_damage_2a_safe: BestDamageScenarios::from_action_constraints( value, Actions(2), diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index 756beef..a4e7cef 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -27,20 +27,80 @@ pub(super) fn get_damage_with_simulation( actions: Actions, attacks: Attacks, ) -> f64 { - let turns = &[ - (actions, attacks, Dices(0), Precision(0)), - (actions, attacks, Dices(12), Precision(13)), - (actions, attacks, Dices(12), Precision(13)), - (actions, attacks, Dices(5), Precision(5)), - (actions, attacks, Dices(7), Precision(8)), - (actions, attacks, Dices(7), Precision(9)), - (actions, attacks, Dices(7), Precision(9)), - (actions, attacks, Dices(7), Precision(9)), - (actions, attacks, Dices(7), Precision(9)), - (actions, attacks, Dices(7), Precision(9)), + let mut turns = vec![ + TurnInfo { + actions: Actions(0), + attacks: Attacks(0), + dices: Dices(0), + precision: Precision(0), + }, + TurnInfo { + actions, + attacks, + dices: Dices(12), + precision: Precision(13), + }, + TurnInfo { + actions, + attacks, + dices: Dices(12), + precision: Precision(13), + }, + TurnInfo { + actions, + attacks: attacks - Attacks(1), + dices: Dices(5), + precision: Precision(5), + }, + TurnInfo { + actions, + attacks: attacks - Attacks(1), + dices: Dices(5), + precision: Precision(5), + }, + // Cuck turn + TurnInfo { + actions, + attacks, + dices: Dices(7), + precision: Precision(9), + }, + TurnInfo { + actions, + attacks, + dices: Dices(7), + precision: Precision(9), + }, + TurnInfo { + actions, + attacks, + dices: Dices(7), + precision: Precision(9), + }, + TurnInfo { + actions, + attacks, + dices: Dices(7), + precision: Precision(9), + }, ]; + if value.speed >= 0 { + turns.push(TurnInfo { + actions, + attacks, + dices: Dices(6), + precision: Precision(5), + }); + } else { + turns.push(TurnInfo { + actions: Actions(1), + attacks: Attacks(1), + dices: Dices(6), + precision: Precision(5), + }); + } - 0. + damage_over_turns(value, &turns) / 10. } /// Sustained damage @@ -62,8 +122,7 @@ pub(super) fn get_sustained_damage( dices, precision, }; 10]; - let total_damage = damage_over_turns(value, l); - total_damage / 10. + damage_over_turns(value, l) / 10. // Iterate 10 turns, every turn we need to substract the leftover reloading // value.damage.into() } @@ -285,8 +344,8 @@ pub(super) fn binomial_dice_distribution( (equipement.damage as f64 + equipement.p_damage as f64 * (target_dices - .clamp(0, equipement.rmax as usize) - .saturating_sub(1)) as f64) + .saturating_sub(1) + .clamp(0, equipement.rmax as usize)) as f64) * probability_success } else { 0. @@ -329,7 +388,7 @@ mod test { damage: 10, p_damage: 2, precision: 0, - rmax: 3, + rmax: 2, armor_break: 2, ..Default::default() } @@ -337,6 +396,7 @@ mod test { macro_rules! assert_close { ($a:expr, $b:expr) => { + println!("{} ~= {}", $a, $b); assert!(($a - $b).abs() < 1E-3); }; } @@ -363,7 +423,7 @@ mod test { let eq = new_inner_eq(); assert_close!( average_damage(&eq, &[Precision(9)], &[Dices(9)]), - 13.99995162 + 13.999999999 ); assert_close!( average_damage(&eq, &[Precision(4)], &[Dices(4)]), @@ -377,7 +437,7 @@ mod test { damage: 10, p_damage: 2, precision: 0, - rmax: 3, + rmax: 2, action_cost: 1, ..Default::default() }; @@ -385,7 +445,7 @@ mod test { damage: 10, p_damage: 2, precision: 0, - rmax: 3, + rmax: 2, action_cost: 2, ..Default::default() }; @@ -393,7 +453,7 @@ mod test { damage: 10, p_damage: 2, precision: 0, - rmax: 3, + rmax: 2, action_cost: 2, reload_cost: Some(2), ..Default::default() diff --git a/weaponry/src/weaponry_structs/equipement_thin_types.rs b/weaponry/src/weaponry_structs/equipement_thin_types.rs index 19175f9..201ce45 100644 --- a/weaponry/src/weaponry_structs/equipement_thin_types.rs +++ b/weaponry/src/weaponry_structs/equipement_thin_types.rs @@ -26,6 +26,13 @@ impl Add for Attacks { Self(self.0 + rhs.0) } } +impl Sub for Attacks { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + Self(self.0 - rhs.0) + } +} impl std::ops::Deref for Attacks { type Target = i8; -- 2.45.1 From 9cbdc25df498a05a061ccc2d7a4b2a273fbb8bb6 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 25 Feb 2025 04:00:13 +0100 Subject: [PATCH 77/97] Rewrites the example parser --- cli_parser/src/lib.rs | 2 + weaponry/examples/usage_scenario.rs | 68 ++++++-- weaponry/src/error.rs | 3 + .../equipement_advanced_repr.rs | 147 +++++++++--------- 4 files changed, 133 insertions(+), 87 deletions(-) diff --git a/cli_parser/src/lib.rs b/cli_parser/src/lib.rs index f23ffdd..1a04de7 100644 --- a/cli_parser/src/lib.rs +++ b/cli_parser/src/lib.rs @@ -42,6 +42,8 @@ pub enum Commands { Make(MakeConfig), /// Make all graphs Graphs(GraphConfig), + // /// Generate analysis data + // Analysis(AnalysisConfig) } #[derive(Debug, Args)] diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index a3fc0f9..bd52679 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -4,20 +4,22 @@ //! //! use clap::Parser; +use std::cmp::Ordering; use std::path::Path; +use weaponry::error::FatalEquipementError; use weaponry::interfaces::ToAnalysis; use weaponry::sort_by; use weaponry::sort_by_cat_then; use weaponry::weaponry_structs::RefinedEquipement; -// TODO : All of these should likely be in the prelude if used like this +// TODO[!] : All of these should likely be in the prelude if used like this use weaponry::weaponry_structs::CrossRecipeScenario; use weaponry::weaponry_structs::equipement_scenario::ConfigEquipementScenario; use weaponry::{ interfaces::{Reportable, Scenario, ToCSV}, weaponry_structs::RefinedEquipementList, }; -// use weaponry::interfaces:: + fn main() { let args = CLIArgs::parse(); let save_path = args.path.unwrap_or("data/first_data".into()); @@ -42,15 +44,15 @@ fn main() { }) }); - // TODO[!]: Have an enum - match args.sort.as_str() { - "avg_huge" => refined_list.inner_sort(sort_by!(avg_damage_single_huge_hit)), - "avg_safe" => refined_list.inner_sort(sort_by!(avg_damage_2a_safe)), - "max_armor" => refined_list.inner_sort(sort_by!(armor_break_per_attack)), - "cat+avg" => refined_list.inner_sort(sort_by_cat_then!(avg_damage_2a_safe)), - _ => (), + match cmd_to_filter(&args.sort) { + Ok(cmd) => { + refined_list.inner_sort(cmd); + } + Err(FatalEquipementError::CLIParseError(a)) => { + println!("Argument incorrect '{a}'. Ignoring the sort.") + } + Err(e) => panic!("{e}"), } - // if args.html_export{} refined_list.write_html(&save_path).unwrap(); @@ -76,6 +78,17 @@ pub struct CLIArgs { pub finishing: bool, #[arg(long, default_value_t = String::from("safe"))] pub sort: String, + // An html export path -h or -o + // A csv export path -c or --csv + // A presort --sort + // A prefilter with some filters ? + // - weapons + // - shields + // - armors + // - damage + // Data manipulation ?? + // - decimate + // - average per category } #[allow(dead_code)] @@ -87,3 +100,38 @@ fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) ); } + +type DynamicFilterType = Box Ordering>; + +fn cmd_to_filter(og_entry: &str) -> Result { + let (category, entry) = if og_entry.starts_with("cat+") { + (true, og_entry.split_at(4).1) + } else { + (false, og_entry) + }; + + macro_rules! return_if_starts_with { + ($iden:ident) => { + if stringify!($iden).starts_with(entry) { + return match category { + true => Ok(Box::new(sort_by_cat_then!($iden))), + false => Ok(Box::new(sort_by!($iden))), + }; + }; + }; + } + return_if_starts_with!(max_damage_per_attack); + return_if_starts_with!(armor_break_per_attack); + return_if_starts_with!(expected_armor_break_per_attack); + return_if_starts_with!(avg_damage_2a_safe); + return_if_starts_with!(avg_damage_single_huge_hit); + return_if_starts_with!(speed); + return_if_starts_with!(scenario_damage); + return_if_starts_with!(defensive); + return_if_starts_with!(earlygame_sustained_damage_per_turn); + return_if_starts_with!(midgame_sustained_damage_per_turn); + return_if_starts_with!(endgame_sustained_damage_per_turn); + return_if_starts_with!(variance); + return_if_starts_with!(variance_pct); + Err(FatalEquipementError::CLIParseError(og_entry.to_string())) +} diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index fba7e58..d2396e7 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -39,6 +39,9 @@ pub enum FatalEquipementError { #[error("Couldn't save the chart as an error occured during the process : {0}")] SaveCharmingChart(#[from] EchartsError), + + #[error("Couldn't parse the CLI argument given \"{0}\"")] + CLIParseError(String), } // #[derive(Error, Debug)] diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index fd1de68..982b22c 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -8,28 +8,27 @@ //! nothing prevents us to implement the trait for other objects and avoid massive computation //! of all the fields even when the user will not be interested in them #![allow(dead_code)] -use crate::weaponry_structs::equipement_thin_types::Dices; -use crate::weaponry_structs::equipement_thin_types::Precision; +use super::{ + equipement_advanced_tools::{ + BestDamageScenarios, get_damage_with_simulation, get_sustained_damage, + }, + equipement_thin_types::{Actions, Attacks}, +}; use crate::{ add_field_to_chart, error::FatalEquipementError, export::initial_chart, interfaces::{RecipeCollection, RefinedList, ToAnalysis, ToTex}, weaponry_structs::{ - Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats, + Equipement, InitialEquipementList, + equipement_structs::InnerEquipementStats, + equipement_thin_types::{Dices, Precision}, }, }; -use core::f64; -use std::cmp::Ordering; - use charming::Chart; +use core::f64; use serde::Serialize; - -use super::equipement_advanced_tools::{ - BestDamageScenarios, get_damage_with_simulation, get_sustained_damage, -}; -use super::equipement_thin_types::Actions; -use super::equipement_thin_types::Attacks; +use std::cmp::Ordering; /// The final representation of the equipement inplementing all the fields needed for processing // TODO: Add a public getter for the inner data @@ -45,24 +44,6 @@ pub struct RefinedEquipement { pub advanced: AdvancedStats, } -impl Serialize for RefinedEquipement { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - self.advanced.serialize(serializer) - } -} - -impl From for RefinedEquipement { - fn from(value: Equipement) -> Self { - Self { - advanced: AdvancedStats::from(&value.stats), - inner: value.stats, - } - } -} - /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements @@ -78,28 +59,6 @@ impl ToTex for RefinedEquipementList { } } -#[macro_export] -/// A simple macro to sort the inner advanced field by a specific field -// TODO[6] find a way to not have to import the refinedequipement -macro_rules! sort_by { - ($field:ident) => { - |a: &RefinedEquipement, b: &RefinedEquipement| { - a.advanced.$field.total_cmp(&b.advanced.$field) - } - }; -} -#[macro_export] -/// A simple macro to sort the inner advanced field by a specific field -// TODO[6] find a way to not have to import the refinedequipement -macro_rules! sort_by_cat_then { - ($field:ident) => { - |a, b| match a.inner.id[0].cmp(&b.inner.id[0]) { - std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), - ord => ord, - } - }; -} - impl ToAnalysis for RefinedEquipementList { type InnerData = RefinedEquipement; @@ -179,29 +138,7 @@ impl ToAnalysis for RefinedEquipementList { } } -impl From for RefinedEquipementList { - fn from(value: InitialEquipementList) -> Self { - Self { - inner: value - .inner - .into_iter() - .map(RefinedEquipement::from) - .collect(), - } - } -} - -// #[cfg(test)] // Used in exemples -impl Default for RefinedEquipementList { - fn default() -> Self { - let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); - RefinedEquipementList::from(eq) - } -} - /// The list of advanced stats infered from an Equipement -// TODO: The two philosophies to drop the old inner or convert the useful fields are considered right now -// TODO: This whole public might be overkill ? A good inner view or scenario could implement what is needed #[derive(Serialize)] pub struct AdvancedStats { /// A simple name created by merging all components @@ -302,6 +239,62 @@ impl From<&InnerEquipementStats> for AdvancedStats { } } } -// mini_scenario_damage: (value.damage + value.p_damage > 0) -// .then(|| get_sustained_damage(value)) -// .unwrap_or_default(), + +impl Serialize for RefinedEquipement { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + self.advanced.serialize(serializer) + } +} + +impl From for RefinedEquipement { + fn from(value: Equipement) -> Self { + Self { + advanced: AdvancedStats::from(&value.stats), + inner: value.stats, + } + } +} + +impl From for RefinedEquipementList { + fn from(value: InitialEquipementList) -> Self { + Self { + inner: value + .inner + .into_iter() + .map(RefinedEquipement::from) + .collect(), + } + } +} + +// #[cfg(test)] // Used in exemples +impl Default for RefinedEquipementList { + fn default() -> Self { + let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); + RefinedEquipementList::from(eq) + } +} +#[macro_export] +/// A simple macro to sort the inner advanced field by a specific field +// TODO[6] find a way to not have to import the refinedequipement +macro_rules! sort_by { + ($field:ident) => { + |a: &RefinedEquipement, b: &RefinedEquipement| { + a.advanced.$field.total_cmp(&b.advanced.$field) + } + }; +} +#[macro_export] +/// A simple macro to sort the inner advanced field by a specific field +// TODO[6] find a way to not have to import the refinedequipement +macro_rules! sort_by_cat_then { + ($field:ident) => { + |a, b| match a.inner.id[0].cmp(&b.inner.id[0]) { + std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), + ord => ord, + } + }; +} -- 2.45.1 From e99d723e5d6203896e33c185baa1ff5b8e9392e7 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 25 Feb 2025 18:27:00 +0100 Subject: [PATCH 78/97] Not fearless refactoring of Categories --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/usage_scenario.rs | 6 +- .../src/weaponry_structs/equipement_fields.rs | 155 +++++++++--------- .../equipement_impl_basics.rs | 7 +- .../equipement_impl_database.rs | 37 ++++- .../weaponry_structs/equipement_impl_logic.rs | 6 +- .../weaponry_structs/equipement_impl_math.rs | 69 +++----- .../weaponry_structs/equipement_structs.rs | 44 ++--- weaponry/src/weaponry_structs/mod.rs | 3 +- 9 files changed, 171 insertions(+), 156 deletions(-) diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 2dd403301c8450cdaeccac0c60f736c15d055347..e1924d36cf44cba642d2cc9b13c86e237650d0ec 100644 GIT binary patch delta 466 zcmZp8z}WDBae_2s-$WT_#=eaS3+-bW7#Oq}7BcWJ<2U0w%9qV2#Jin0ftQ7enP(SI zDUTlaYwiWyVcfi2OPMw?C36{a?&U1uZ3&w#>l@Y{R!x@sEE8E2 znNKq3Gp=QfW@Kep$jmaa(U~!6vaX;cld9}w4?#V%;L?KBB9GL>vPvZ-$D-W)qGF}! z*u2u5oc|%3@(hyd92`KyIT(SMLy(hGP?Up_kx^Q9@?t?%L#(<2G=RD^LCT>(kb{F? z6vUR5o%~f$(a<+FC9^aa&9V@6pe|jAU0{8JjEq3LI5{|hc1?6rwNmoQOwTAm(-p@l z&mb-hwFg9*gLMHJva*64Kud!&5(_4u)6o_zM$_p#d84G%=A1644S$elP7qJ zOtx{B-2B^#iJd)7P@X|vo^$d>amCH~Ugk`jS$zKrF)^u3W==3-)Yxp6@Q#rU7)>li XE|VQ|r6xNh=}dl^B)qvfsg@T2_aSp= delta 313 zcmZp8z}WDBae_2s^F$eE#^#L)3+;J1|1xMZN74%Id=Mgr$+iocSelC9@*aai&rx4aRGX)rj+9QiAqo2>!8b>SDKTf6ep`V=}-P9qrX|z_l^(~1H)wI1S3Y3&1MPj7@5jkCOhUzGRjVNNz&m^3QEjN NPfbzUT$0qo3jnQ3S 0.)) .inner_filter(|e| { - e.inner.macro_category.as_ref().is_some_and(|v| { - !matches!(v, weaponry::weaponry_structs::WeaponMacroCategory::Shields) - && !matches!(v, weaponry::weaponry_structs::WeaponMacroCategory::Armor) + e.inner.category_base.as_ref().is_some_and(|v| { + !matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Shields) + && !matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Armors) }) }); diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 1f6be28..84679d9 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -29,8 +29,8 @@ 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, PartialEq)] -// #[cfg_attr(test, derive(PartialEq))] +#[derive(Clone, Debug, Deserialize, Serialize)] +#[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { Blunt, Slash, @@ -77,53 +77,27 @@ impl Add for DamageType { } } -// TODO: Convert into this category at the end, depending on all important factors -/// List all the final weapon categories, this enum should be infered from and if they were defined -#[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize, strum::EnumString)] -// #[cfg_attr(test, derive(PartialEq))] -pub enum WeaponCategory { - Exotic, - // HeavyExotic ? - Dagger, // Light sword ? Kill it tbh - Claws, - Blade, - Haroth, - Axe, - Kahml, - Hammer, - Rhodarak, - Staff, - Lance, - Landscapper, - Bow, - Crossbow, - Cannon, - // Armor, - // Shield, -} - -// TODO[!]: This is only needed as long as we dont have a special category for the target -// TODO[!]: This part should be handled by a category filter instead, filtering Shape on Shape -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, - } - } -} +// // TODO[!]: This is only needed as long as we dont have a special category for the target +// // TODO[!]: This part should be handled by a category filter instead, filtering Shape on Shape +// impl PartialEq for EquipementSerializedCategory { +// fn eq(&self, other: &Self) -> bool { +// match (self, other) { +// (&Self::None, _) => false, +// (_, Self::None) => false, +// (&Self::Armors, &Self::Armors) => true, +// (&Self::Armors, _) => false, +// (_, &Self::Armors) => 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 { @@ -217,20 +191,27 @@ pub enum ThrowSpecialties { // TODO[!]: This enum should only include Weapons, Shields, Armors and no #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] -pub enum WeaponMacroCategory { +pub enum EquipementSerializedCategory { Staves, Blunt, Slash, Ranged, - 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 + /// Armor generic category, will be converted into EquipementSection + Armors, + /// Shield generic category, will be converted into EquipementSection + Shields, + /// A custom None category, used to forbid a part to be cast upon or from // TODO: Check the soundness of this implementation None, + /// Light size, will be converted to a WeaponBaseSize + Light, + /// Medium size, will be converted to a WeaponBaseSize + Medium, + /// Heavy size, will be converted to a WeaponBaseSize + Heavy, + /// SuperHeavy size, will be converted to a WeaponBaseSize + SuperHeavy, } // TODO[!] : This is the corrected real initial shape @@ -238,49 +219,73 @@ pub enum WeaponMacroCategory { /// The Base Shape of the weapon, used to infer the final category of the weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] +#[cfg_attr(test, derive(PartialEq))] pub enum WeaponBaseShape { Staves, Blunt, Slash, Ranged, - Armor, + Armors, Shields, Exotic, - // TODO[!]: Check the soundness of this + // TODO[!]: Check the soundness of this, as it is not used currently None, } // TODO[!]: While maybe not directly filling a field these categories should be inferred by the BaseShape for comparison // [!]: However using a new column for this Section will greatly help in the Serde soundness and avoidance on over-reliance of implicit conversions /// Specifies the exact nature of the weapon, used for generic filter mainly +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)] -pub enum EquipementSection { - Weapon, - Armor, - Shield, +pub enum EquipementTargets { + Weapons, + Armors, + Shields, + Ranged, } -// TODO[!]: Add this as a target and nature instead of the old Type -// : Remember it's the applied into that specify wether they can be applied not the other way around -/// Specifies the exact nature of the target this element can be applied to -#[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)] -pub enum EquipementFilter { - /// This element can only be applied to a specific category - Target(EquipementSection), - /// This element exists only for recipes or for export to tex, it cannot be auto-applied - NoTarget, - /// This element can be applied to any target - AnyTarget, - // /// This element can only be applied to a specific base shape - // TargetShape(WeaponBaseShape) + +impl EquipementTargets { + /// Assert wether a target can be applied to an original shape + pub fn can_apply_onto(&self, lsh: &WeaponBaseShape) -> bool { + match (self, lsh) { + (EquipementTargets::Weapons, WeaponBaseShape::Staves) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Blunt) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Slash) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Ranged) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Exotic) => true, + // You can apply weapon modifiers to shields, not the best behaviour but well + (EquipementTargets::Weapons, WeaponBaseShape::Shields) => true, + (EquipementTargets::Armors, WeaponBaseShape::Armors) => true, + (EquipementTargets::Shields, WeaponBaseShape::Shields) => true, + (EquipementTargets::Ranged, WeaponBaseShape::Ranged) => true, + _ => false, + } + } } // TODO[!] : This part is initialized by the natures subtable and might be better of being a new column in the database /// The Base Size of the weapon, used to infer the final category of the weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] +#[cfg_attr(test, derive(PartialEq))] pub enum WeaponBaseSize { Light, Medium, Heavy, SuperHeavy, } + +// // TODO[!]: Add this as a target and nature instead of the old Type +// // : Remember it's the applied into that specify wether they can be applied not the other way around +// /// Specifies the exact nature of the target this element can be applied to +// #[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)] +// pub enum EquipementFilter { +// /// This element can only be applied to a specific category +// Target(EquipementSection), +// /// This element exists only for recipes or for export to tex, it cannot be auto-applied +// NoTarget, +// /// This element can be applied to any target +// AnyTarget, +// // /// This element can only be applied to a specific base shape +// // TargetShape(WeaponBaseShape) +// } diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 4c069e9..5aae715 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -76,12 +76,15 @@ impl Display for InnerEquipementStats { self.name.join(" & ") )]); table.add_row(vec![format!( - "Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}]", + "Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}+{}]", self.rarity, self.cost, self.difficulty, self.tier, - self.macro_category + self.category_base + .clone() + .map_or_else(|| "ø".to_string(), |v| v.to_string()), + self.category_size .clone() .map_or_else(|| "ø".to_string(), |v| v.to_string()) )]); diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 7f4ef60..b4a6c7a 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -12,6 +12,8 @@ use crate::interfaces::{FixedRecipe, RecipeDatabase}; use rusqlite::Connection; use serde::de::DeserializeOwned; +use super::EquipementSerializedCategory; +use super::equipement_fields::{WeaponBaseShape, WeaponBaseSize}; use super::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; /// Struct for database connection. @@ -92,6 +94,8 @@ impl TryFrom for InnerEquipementStats { type Error = FatalEquipementError; fn try_from(value: DatabaseEquipementStats) -> Result { + let (category_base, category_size): SubCategories = + get_sub_categories_from_serde(&value.category)?; Ok(Self { id: vec![value.id], // Special case where manual is better than serde name: vec![value.name], @@ -116,13 +120,42 @@ impl TryFrom for InnerEquipementStats { parry: value.parry, speed: value.speed, stealth: value.stealth, - macro_category: from_serde!(&value.category)?, - target: from_serde!(&value.target)?, + // macro_category: from_serde!(&value.category)?, + // target: from_serde!(&value.target)?, special: from_serde!(&value.special)?, action_cost: value.action_cost, reload_cost: from_serde!(&value.reload_cost)?, range: value.range as i16, agility_bonus: value.agility_bonus, + category_base, + category_size, + target_category: from_serde!(value.target)?, }) } } + +/// A type englobing the three subcategores +type SubCategories = (Option, Option); + +/// Infer all subcategories from a deserialized DatabaseCategory +fn get_sub_categories_from_serde(category: &str) -> Result { + Ok(if let Some(category) = from_serde!(category)? { + match category { + EquipementSerializedCategory::Staves => (Some(WeaponBaseShape::Staves), None), + EquipementSerializedCategory::Blunt => (Some(WeaponBaseShape::Blunt), None), + EquipementSerializedCategory::Slash => (Some(WeaponBaseShape::Slash), None), + EquipementSerializedCategory::Ranged => (Some(WeaponBaseShape::Ranged), None), + EquipementSerializedCategory::Exotic => (Some(WeaponBaseShape::Exotic), None), + EquipementSerializedCategory::Armors => (Some(WeaponBaseShape::Armors), None), + EquipementSerializedCategory::Shields => (Some(WeaponBaseShape::Shields), None), + // EquipementSerializedCategory::Weapons => todo!(), + EquipementSerializedCategory::None => (Some(WeaponBaseShape::None), None), + EquipementSerializedCategory::Light => (None, Some(WeaponBaseSize::Light)), + EquipementSerializedCategory::Medium => (None, Some(WeaponBaseSize::Medium)), + EquipementSerializedCategory::Heavy => (None, Some(WeaponBaseSize::Heavy)), + EquipementSerializedCategory::SuperHeavy => (None, Some(WeaponBaseSize::SuperHeavy)), + } + } else { + (None, None) + }) +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index c3da801..561f38a 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, SpecialField, - equipement_fields::{PhysicalDamageType, WeaponMacroCategory}, + equipement_fields::{PhysicalDamageType, WeaponBaseShape}, equipement_structs::InnerEquipementStats, }, }; @@ -94,7 +94,7 @@ mod test { integrity: 2, range: 3, agility_bonus: 4., - macro_category: Some(WeaponMacroCategory::Staves), + category_base: Some(WeaponBaseShape::Staves), special: SpecialField(vec!["zero".into()]), damage_type: Some(DamageType(vec![DamageMod::Secondary( PhysicalDamageType::Slash, @@ -119,7 +119,7 @@ mod test { agility_bonus: 9., damage: 10, range: 3, - macro_category: Some(WeaponMacroCategory::Staves), + category_base: Some(WeaponBaseShape::Staves), special: SpecialField(vec!["zero".into(), "one".into(), "two".into()]), damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index ab587fb..008d151 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -18,15 +18,26 @@ macro_rules! add_to_vec { /// Adds either of the vectors or merge them macro_rules! add_two_options { ($self: expr, $rhs: expr) => {{ - match ($self.clone(), $rhs.clone()) { + match ($self.as_ref(), $rhs.as_ref()) { (None, None) => None, - (None, Some(a)) => Some(a), - (Some(a), None) => Some(a), - (Some(a), Some(b)) => Some(a + b), + (None, Some(a)) => Some(a.clone()), + (Some(a), None) => Some(a.clone()), + (Some(a), Some(b)) => Some(a.clone() + b.clone()), } }}; } +/// Clones the first option that has some data +macro_rules! first_correct_option { + ($self:expr, $rhs:expr) => { + match ($self.as_ref(), $rhs.as_ref()) { + (Some(a), _) => Some(a.clone()), + (_, Some(b)) => Some(b.clone()), + _ => None, + } + }; +} + impl std::ops::Add for &InnerEquipementStats { type Output = InnerEquipementStats; @@ -55,13 +66,16 @@ impl std::ops::Add for &InnerEquipementStats { parry: self.parry + rhs.parry, speed: self.speed + rhs.speed, stealth: self.stealth + rhs.stealth, - 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 + // 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, agility_bonus: self.agility_bonus + rhs.agility_bonus, + category_base: first_correct_option!(self.category_base, rhs.category_base), + category_size: first_correct_option!(self.category_size, rhs.category_size), + target_category: first_correct_option!(self.target_category, rhs.target_category), } } } @@ -76,46 +90,3 @@ impl std::ops::Add for SpecialField { c } } - -// impl std::ops::AddAssign for SpecialCategory { -// fn add_assign(&mut self, rhs: Self) { -// todo!() -// } -// } - -// impl std::ops::Add for OptionnalReloadType { -// type Output = OptionnalReloadType; - -// fn add(self, rhs: Self) -> Self::Output { -// todo!() -// } -// } -// impl std::ops::AddAssign for OptionnalReloadType { -// fn add_assign(&mut self, rhs: Self) { -// todo!() -// } -// } -// impl std::ops::Add for OptionnalWeaponCategory { -// type Output = OptionnalWeaponCategory; - -// fn add(self, rhs: Self) -> Self::Output { -// todo!() -// } -// } -// impl std::ops::AddAssign for OptionnalWeaponCategory { -// fn add_assign(&mut self, rhs: Self) { -// todo!() -// } -// } -// impl std::ops::Add for OptionnalDamageType { -// type Output = OptionnalDamageType; - -// fn add(self, rhs: Self) -> Self::Output { -// todo!() -// } -// } -// impl std::ops::AddAssign for OptionnalDamageType { -// fn add_assign(&mut self, rhs: Self) { -// todo!() -// } -// } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index c26d605..5e70554 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -8,7 +8,12 @@ use crate::interfaces::{FilterFunction, FilterFunctionType}; use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; -use super::{DamageType, SpecialField, WeaponCategory, equipement_fields::WeaponMacroCategory}; +use super::{ + DamageType, SpecialField, + equipement_fields::{ + EquipementSerializedCategory, EquipementTargets, WeaponBaseShape, WeaponBaseSize, + }, +}; /// The final equipement list /// @@ -46,29 +51,18 @@ pub(crate) fn filter_id_unique() } /// Create a new filter function mandating the object be of the right category +// TODO[5]: Testing this method should be a priority for refactoring pub(crate) fn filter_id_unique_and_right_category() -> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { &|sel, lhs| { - // println!( - // "Trying to match {:?} with {:?}. {:?} {:?}", - // sel.name, lhs.name, sel.target, lhs.macro_category - // ); lhs.id.iter().all(|a| *a != sel.id[0]) - & match (&sel.target, &lhs.macro_category) { + & match (&sel.target_category, &lhs.category_base) { // 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 + (Some(a), Some(b)) => a.can_apply_onto(b), // TODO: Unsound to have a generic nature, this should be caught at serialisation - // TODO: Testing a generic anyway + // There is no target and the part about to be added is generic (None, _) => true, // 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, } } } @@ -106,9 +100,17 @@ pub struct InnerEquipementStats { 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 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 + /// The category as [WeaponBaseShape] representing what kind of equipement is used + /// + /// The categories are: Staves, Blunt, Slash, Ranged, Armors, Shields, Exotic, None, + pub category_base: Option, + /// The category size as [WeaponBaseSize] + /// + /// Categories are : (Light, Medium, Heavy and SuperHeavy) + pub category_size: Option, + /// The section of an equipement (Weapon, Shield, Armor) + /// The Section the target applies to + pub target_category: Option, pub(super) special: SpecialField, pub(super) action_cost: i8, pub(super) reload_cost: Option, // Shouldn't it be Option ? @@ -184,8 +186,8 @@ 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(), - target: 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(&SpecialField::default()).unwrap(), reload_cost: serde_json::to_string(&None::).unwrap(), rarity: 0, diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 66d8417..c2280af 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -39,7 +39,8 @@ pub use crate::weaponry_structs::equipement_advanced_repr::RefinedEquipementList pub use equipement_advanced_repr::RefinedEquipement; pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{ - DamageMod, DamageType, NatureTarget, SpecialField, WeaponCategory, WeaponMacroCategory, + DamageMod, DamageType, EquipementSerializedCategory, NatureTarget, SpecialField, + WeaponBaseShape, }; // Likely ? Final Re-Exports pub use equipement_scenario::CrossRecipeScenario; -- 2.45.1 From 32ff0ef11550b7fdad51537ad421cfb3606617ac Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 25 Feb 2025 23:23:31 +0100 Subject: [PATCH 79/97] Adds a better sort (still miles from real custom cli) --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/usage_scenario.rs | 2 +- .../equipement_advanced_repr.rs | 52 ++++++++++++++---- .../src/weaponry_structs/equipement_fields.rs | 6 +- 4 files changed, 47 insertions(+), 13 deletions(-) diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index e1924d36cf44cba642d2cc9b13c86e237650d0ec..6b5528b07512de047d84d29509c2d1205d2ff241 100644 GIT binary patch delta 1023 zcmZva%TE(Q9LGB|EuDcvZM0x1uw{{m2~`#ZN@4`sDoB7DNfgpFWNimpQ`%2dLyl+goiR z+qUKMgRgHAFGlA#kn^Rpzv+F`Vw1J;Rb#~Q%TaRNbfAWJ4Qma(^*`#j>oxYBl~^0y zrHl4M`(t}|-G{n)+oA25t;hP!x`v*ku;tLQVO7XSk|pi<6ONU3&3SvW~Qex33oMU=Ql z_(GBWow55!WJ7QFpWg7;L_D}7CR%&;KTi!~L4wVQiPm86EYbR;JQWVk8hQ2j8jZ=P zF{)Tv6bg$mnJ67b$mx_@#qFYQO6QV#jt8^Fcsj+6yop6$usLKM3Sd*6OQv`_kyjK#3^%o9flZ9Q6dEC&=E0c1Pk z%S;O=?9E@DqQ$ju@yo&AJVjdsRq-rmhk*vAKwFS62;vNs$&JkSxUES&Umygs@=sx{ wPpec_&{uhFQ%nKm&ca~X2($%rddjnK5ayuAt=RS|<<2$rF6U7&#^{_tBaBMu(TXSV_sTC^x^T zSSfmPx92kEOkMfO6H+B7i#YjDKI*)QF>kV?uoR>Gr>R6P_%rZINUv%;US&PXheEB9n ill6tDF_#O4Feb=_K^U*(av_Xp`5Xx2w7%)000jV3RCn(H diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 7644c7e..42a3a5e 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -124,7 +124,7 @@ fn cmd_to_filter(og_entry: &str) -> Result for AdvancedStats { ) .map(|f| *f) .unwrap_or_default(), - avg_damage_single_huge_hit: BestDamageScenarios::from_action_constraints( + avg_damage_2a_huge_hit: BestDamageScenarios::from_action_constraints( value, Actions(2), Attacks(2), - Dices(8), + Dices(10), Precision(9), ) .map(|f| *f) @@ -290,7 +290,7 @@ macro_rules! sort_by { #[macro_export] /// A simple macro to sort the inner advanced field by a specific field // TODO[6] find a way to not have to import the refinedequipement -macro_rules! sort_by_cat_then { +macro_rules! sort_by_weapon_then { ($field:ident) => { |a, b| match a.inner.id[0].cmp(&b.inner.id[0]) { std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), @@ -298,3 +298,35 @@ macro_rules! sort_by_cat_then { } }; } + +#[macro_export] +/// Sort by size first, then by the given field +macro_rules! sort_by_cat_then { + ($field:ident) => { + |a, b| { + if let (Some(c), Some(d)) = ( + a.inner.category_size.as_ref(), + b.inner.category_size.as_ref(), + ) { + match c.cmp(d) { + std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), + ord => ord, + } + } else { + a.advanced.$field.total_cmp(&b.advanced.$field) + } + } + }; +} + +#[macro_export] +/// A simple macro to sort the inner advanced field by a specific field +// TODO[6] find a way to not have to import the refinedequipement +macro_rules! sort_by_size_then { + ($field:ident) => { + |a, b| match a.inner.category_size.cmp(&b.inner.category_size) { + std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), + ord => ord, + } + }; +} diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 84679d9..4f436ac 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -266,8 +266,10 @@ impl EquipementTargets { // TODO[!] : This part is initialized by the natures subtable and might be better of being a new column in the database /// The Base Size of the weapon, used to infer the final category of the weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] -#[cfg_attr(test, derive(PartialEq))] +#[derive( + Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Display, Deserialize, Serialize, strum::EnumString, +)] +// #[cfg_attr(test, derive(PartialEq))] pub enum WeaponBaseSize { Light, Medium, -- 2.45.1 From b5fb986b5f63978a43a4e46205742ab212b6ddee Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 26 Feb 2025 01:07:29 +0100 Subject: [PATCH 80/97] Adds a new damage algorithm calculator, more precise way less optimized --- weaponry/src/export.rs | 27 ++ .../equipement_advanced_repr.rs | 4 +- .../equipement_advanced_tools.rs | 321 +++++++++++------- 3 files changed, 227 insertions(+), 125 deletions(-) diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index 455d894..1bb8a72 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -112,3 +112,30 @@ pub fn initial_chart(chart_name: &str) -> charming::Chart { .y_axis(charming::component::Axis::new()) .grid(charming::component::Grid::new().contain_label(true)) } + +/// Generate a new plot chart +pub fn initial_plot_chart(chart_name: &str) -> charming::Chart { + charming::Chart::new() + .title( + charming::component::Title::new() + .text(chart_name) + .left("center"), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .data_zoom( + charming::component::DataZoom::new() + .type_(charming::component::DataZoomType::Inside) + .start(0) + .end(100), + ) + .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .toolbox( + charming::component::Toolbox::new().feature( + charming::component::Feature::new() + .data_zoom(charming::component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(charming::component::Restore::new()) + .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) +} diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 3c60121..915d039 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -196,7 +196,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { defensive: (value.parry as f64).max(value.dodge.into()), variance, variance_pct: variance / value.damage as f64, - avg_damage_2a_safe: BestDamageScenarios::from_action_constraints( + avg_damage_2a_safe: BestDamageScenarios::from_action_constraints_it( value, Actions(2), Attacks(2), @@ -205,7 +205,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { ) .map(|f| *f) .unwrap_or_default(), - avg_damage_2a_huge_hit: BestDamageScenarios::from_action_constraints( + avg_damage_2a_huge_hit: BestDamageScenarios::from_action_constraints_it( value, Actions(2), Attacks(2), diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index a4e7cef..5a33f5f 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -156,8 +156,7 @@ fn damage_over_turns(value: &InnerEquipementStats, turn_info: &[TurnInfo]) -> f6 attacks_used: _, damage_done, reload_remaining, - depth: _, - }) = BestDamageScenarios::from_action_constraints( + }) = BestDamageScenarios::from_action_constraints_it( value, *actions - reloading_left, *attacks, @@ -183,9 +182,6 @@ pub struct BestDamageScenarios { damage_done: f64, /// Remaining actions that need to be used to finish reload reload_remaining: Actions, - /// A debug value, should be taken down in final builds - // TODO[6]: Remove debug once the tests are done - depth: u8, } impl Add for BestDamageScenarios { @@ -197,7 +193,6 @@ impl Add for BestDamageScenarios { attacks_used: self.attacks_used + rhs.attacks_used, damage_done: self.damage_done + rhs.damage_done, reload_remaining: self.reload_remaining + rhs.reload_remaining, - depth: self.depth + rhs.depth, } } } @@ -214,118 +209,198 @@ impl BestDamageScenarios { /// Calculate the best alternative with a set of contraints /// /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) - pub fn from_action_constraints( + // TODO[!]: Clean this cursed abomination + pub fn from_action_constraints_it( equipement_stats: &InnerEquipementStats, actions_allowed: Actions, attacks_allowed: Attacks, dices_allowed: Dices, precision: Precision, ) -> Option { - Self::from_action_constraints_recursive( - equipement_stats, - actions_allowed, - attacks_allowed, - dices_allowed, - precision, - 0, - 0, - ) - } - /// Recursive part of the from_action_constraints call - /// - /// This algorithm takes a recursive approact to avoid too much forward complexity - fn from_action_constraints_recursive( - equipement_stats: &InnerEquipementStats, - actions_allowed: Actions, - attacks_allowed: Attacks, - dices_allowed: Dices, - precision: Precision, - reload_remaining: i8, - depth: u8, - ) -> Option { - // If we can't attack return early - if equipement_stats.action_cost > *actions_allowed - || *attacks_allowed == 0 - || reload_remaining > 0 - || *dices_allowed < 1 - { - // println!( - // "[{depth}] > Reach the end of recursion {}>{actions_allowed}, {attacks_allowed}a, {dices_allowed}d {reload_remaining}r", - // value.action_cost - // ); + let full_attack_cost = + equipement_stats.action_cost + equipement_stats.reload_cost.unwrap_or_default(); + if full_attack_cost == 0 { return None; } - - // if depth == 0 { - // println!( - // "Starting recursion: {actions_allowed}A {attacks_allowed}atk {dices_allowed}*" - // ); - // } - let atkreload_cost = - equipement_stats.reload_cost.unwrap_or_default() + equipement_stats.action_cost; - - // We create our first contender, One attack only - let one_attack = Self { - // No matter what we try to reload, even if we overcap the attack was still valid - actions_used: Actions((atkreload_cost).clamp(0, *actions_allowed)), - attacks_used: Attacks(1), - damage_done: binomial_dice_distribution(equipement_stats, precision, dices_allowed), - // If the reload+attack exceed the actions, we must bookkeep it - // as a reminder that we have leftover actions to spend next turn - reload_remaining: Actions( - ((atkreload_cost) - *actions_allowed + reload_remaining).clamp(0, *actions_allowed), - ), - depth, - }; - // println!( - // "[{depth}] > One attack ({}d): {one_attack:?}/{actions_allowed}A", - // Dices(*dices_allowed) - // ); - - // We can only try two attacks if two attack would be valid aka: - // - We can spend: 2 attacks and (at least) 1 reload (as actions) - // - : 2 attacks (as attacks) - if atkreload_cost + equipement_stats.action_cost <= *actions_allowed && *attacks_allowed > 1 + let nb_max_attacks_reload = actions_allowed.div_euclid(full_attack_cost); + let remaining_actions = actions_allowed.rem_euclid(full_attack_cost); + let (remaining_reload, extra_attack) = if remaining_actions >= equipement_stats.action_cost { - // Cumbersome because of rounding errors - if let (Some(a), Some(b)) = ( - (Self::from_action_constraints_recursive( - equipement_stats, - // TODO[9]: THIS APPROACH IS DEEPLY INCORRECT - // : It does however work for the values we will be using it - actions_allowed - Actions(atkreload_cost), - Attacks(attacks_allowed.div_floor(2)), - Dices(dices_allowed.div_floor(2)), - precision, - reload_remaining, - depth + 1, - )), - (Self::from_action_constraints_recursive( - equipement_stats, - actions_allowed - Actions(atkreload_cost), - Attacks(attacks_allowed.div_ceil(2)), - Dices(dices_allowed.div_ceil(2)), - precision, - reload_remaining - equipement_stats.reload_cost.unwrap_or_default(), - depth + 1, - )), - ) { - let sum_sub_attacks = a + b; - // println!( - // "[{depth}] > Two attacks ({} & {}) : {sum_sub_attacks:?}", - // Dices(dices_allowed.div_floor(2)), - // Dices(dices_allowed.div_ceil(2)) - // ); - // The alternative was better - if one_attack.damage_done < sum_sub_attacks.damage_done { - return Some(sum_sub_attacks); - } - } - } + (-(remaining_actions - *attacks_allowed), Attacks(1)) + } else { + (0, Attacks(0)) + }; - // The alternative didn't exist or was worse - Some(one_attack) + // print!( + // "[{actions_allowed}A, {attacks_allowed}a, {}A/a {nb_max_attacks_reload}#, {rem}rem] => ", + // equipement_stats.action_cost + // ); + // Loop from the extra attack and go down + let mut values: Vec<(i8, i8, f64)> = (1..=(nb_max_attacks_reload + *extra_attack) + .clamp(0, *attacks_allowed)) + .map(|attacks| { + ( + attacks, + { + if nb_max_attacks_reload + *extra_attack == attacks { + remaining_reload + } else { + 0 + } + }, + stack_binomials(equipement_stats, dices_allowed, precision, attacks), + ) + }) + .collect(); + values.sort_by(|(_, _, v1), (_, _, v2)| v2.total_cmp(v1)); + // println!("{:?}", values); + (!values.is_empty()).then(|| Self { + actions_used: Actions((values[0].0 * full_attack_cost).clamp(0, *actions_allowed)), + attacks_used: Attacks(values[0].0), + damage_done: values[0].2, + reload_remaining: Actions(values[0].1), + }) } + + // /// Calculate the best alternative with a set of contraints + // /// + // /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) + // #[deprecated] + // pub fn from_action_constraints( + // equipement_stats: &InnerEquipementStats, + // actions_allowed: Actions, + // attacks_allowed: Attacks, + // dices_allowed: Dices, + // precision: Precision, + // ) -> Option { + // Self::from_action_constraints_recursive( + // equipement_stats, + // actions_allowed, + // attacks_allowed, + // dices_allowed, + // precision, + // 0, + // 0, + // ) + // } + // /// Recursive part of the from_action_constraints call + // /// + // /// This algorithm takes a recursive approact to avoid too much forward complexity + // #[deprecated] + // fn from_action_constraints_recursive( + // equipement_stats: &InnerEquipementStats, + // actions_allowed: Actions, + // attacks_allowed: Attacks, + // dices_allowed: Dices, + // precision: Precision, + // reload_remaining: i8, + // depth: u8, + // ) -> Option { + // // If we can't attack return early + // if equipement_stats.action_cost > *actions_allowed + // || *attacks_allowed == 0 + // || reload_remaining > 0 + // || *dices_allowed < 1 + // { + // // println!( + // // "[{depth}] > Reach the end of recursion {}>{actions_allowed}, {attacks_allowed}a, {dices_allowed}d {reload_remaining}r", + // // value.action_cost + // // ); + // return None; + // } + + // // if depth == 0 { + // // println!( + // // "Starting recursion: {actions_allowed}A {attacks_allowed}atk {dices_allowed}*" + // // ); + // // } + // let atkreload_cost = + // equipement_stats.reload_cost.unwrap_or_default() + equipement_stats.action_cost; + + // // We create our first contender, One attack only + // let one_attack = Self { + // // No matter what we try to reload, even if we overcap the attack was still valid + // actions_used: Actions((atkreload_cost).clamp(0, *actions_allowed)), + // attacks_used: Attacks(1), + // damage_done: binomial_dice_distribution(equipement_stats, precision, dices_allowed), + // // If the reload+attack exceed the actions, we must bookkeep it + // // as a reminder that we have leftover actions to spend next turn + // reload_remaining: Actions( + // ((atkreload_cost) - *actions_allowed + reload_remaining).clamp(0, *actions_allowed), + // ), + // depth, + // }; + // // println!( + // // "[{depth}] > One attack ({}d): {one_attack:?}/{actions_allowed}A", + // // Dices(*dices_allowed) + // // ); + + // // We can only try two attacks if two attack would be valid aka: + // // - We can spend: 2 attacks and (at least) 1 reload (as actions) + // // - : 2 attacks (as attacks) + // if atkreload_cost + equipement_stats.action_cost <= *actions_allowed && *attacks_allowed > 1 + // { + // // Cumbersome because of rounding errors + // if let (Some(a), Some(b)) = ( + // (Self::from_action_constraints_recursive( + // equipement_stats, + // // TODO[9]: THIS APPROACH IS DEEPLY INCORRECT + // // : It does however work for the values we will be using it + // actions_allowed - Actions(atkreload_cost), + // Attacks(attacks_allowed.div_floor(2)), + // Dices(dices_allowed.div_floor(2)), + // precision, + // reload_remaining, + // depth + 1, + // )), + // (Self::from_action_constraints_recursive( + // equipement_stats, + // actions_allowed - Actions(atkreload_cost), + // Attacks(attacks_allowed.div_ceil(2)), + // Dices(dices_allowed.div_ceil(2)), + // precision, + // reload_remaining - equipement_stats.reload_cost.unwrap_or_default(), + // depth + 1, + // )), + // ) { + // let sum_sub_attacks = a + b; + // // println!( + // // "[{depth}] > Two attacks ({} & {}) : {sum_sub_attacks:?}", + // // Dices(dices_allowed.div_floor(2)), + // // Dices(dices_allowed.div_ceil(2)) + // // ); + // // The alternative was better + // if one_attack.damage_done < sum_sub_attacks.damage_done { + // return Some(sum_sub_attacks); + // } + // } + // } + + // // The alternative didn't exist or was worse + // Some(one_attack) + // } +} + +/// Do as many binomials as there are attacks +fn stack_binomials( + equipement_stats: &InnerEquipementStats, + dices_allowed: Dices, + precision: Precision, + attacks: i8, +) -> f64 { + (binomial_dice_distribution( + equipement_stats, + precision, + Dices(dices_allowed.div_euclid(attacks.try_into().unwrap())), + ) * (attacks - 1) as f64) + + (binomial_dice_distribution( + equipement_stats, + precision, + Dices( + dices_allowed.div_euclid(attacks.try_into().unwrap()) + + dices_allowed.rem_euclid(attacks.try_into().unwrap()), + ), + )) } /// Calculate the binomial distribution and average the damage from there @@ -432,7 +507,7 @@ mod test { } #[test] - fn test_damage_optimisation() { + fn test_damage_optimisation_it() { let eq = InnerEquipementStats { damage: 10, p_damage: 2, @@ -460,7 +535,7 @@ mod test { }; let known_data = &[ ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(2), Attacks(1), @@ -470,7 +545,7 @@ mod test { 14., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(2), Attacks(2), @@ -480,7 +555,7 @@ mod test { 22., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(3), Attacks(3), @@ -490,7 +565,7 @@ mod test { 30., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(3), Attacks(3), @@ -500,7 +575,7 @@ mod test { 36., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(3), Attacks(3), @@ -510,7 +585,7 @@ mod test { 36., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(1), Attacks(1), @@ -520,7 +595,7 @@ mod test { 0., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(2), Attacks(1), @@ -530,7 +605,7 @@ mod test { 14., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(4), Attacks(2), @@ -540,7 +615,7 @@ mod test { 22., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(5), Attacks(3), @@ -550,7 +625,7 @@ mod test { 28., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(6), Attacks(3), @@ -560,7 +635,7 @@ mod test { 36., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(2), Attacks(1), @@ -570,7 +645,7 @@ mod test { 14., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(4), Attacks(2), @@ -580,7 +655,7 @@ mod test { 14., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(6), Attacks(2), @@ -590,7 +665,7 @@ mod test { 22., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(6), Attacks(3), @@ -600,7 +675,7 @@ mod test { 28., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(10), Attacks(3), -- 2.45.1 From 6526d164514899346f409e44ba452736a275306f Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 26 Feb 2025 05:26:12 +0100 Subject: [PATCH 81/97] Adds sub plots ? --- weaponry/benches/iter_creation.rs | 58 --------- weaponry/src/export.rs | 110 ++++++++++++------ .../equipement_advanced_repr.rs | 85 +++++++++++++- .../equipement_advanced_tools.rs | 13 +-- 4 files changed, 163 insertions(+), 103 deletions(-) diff --git a/weaponry/benches/iter_creation.rs b/weaponry/benches/iter_creation.rs index 7ca9b5b..801cb45 100644 --- a/weaponry/benches/iter_creation.rs +++ b/weaponry/benches/iter_creation.rs @@ -50,61 +50,3 @@ criterion_group! { targets= criterion_benchmark } criterion_main!(benches); - -// TODO: Add to a How to add new Lists - -// #[derive(Clone)] -// struct Equipo { -// stats: InnerStats, -// } - -// impl Equipo { -// fn newish(i: u8) -> Self { -// let mut stats = InnerStats::default(); -// stats.id = i; -// Equipo { stats } -// } -// } - -// struct ListStatic { -// inner: Vec, -// } -// struct ListParIter { -// inner: Vec, -// } - -// impl RecipeCollection for ListStatic { -// type Recipes = Equipo; - -// fn combine_all(&mut self, other: G) -// where -// G: RecipeCollection, -// { -// todo!() -// } - -// fn inner(&self) -> Vec { -// self.inner.clone() -// } - -// fn from_vectored(list: Vec) -> Self { -// Self { inner: list } -// } -// } - -// impl Combineable for Equipo { -// type Inner = InnerStats; - -// fn clone_combinable_part(&self) -> Self::Inner { -// self.stats.clone() -// } - -// fn add_to_self(&self, rhs: T) -> Self -// where -// T: Combineable, -// { -// Equipo { -// stats: self.clone_combinable_part() + rhs.clone_combinable_part(), -// } -// } -// } diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index 1bb8a72..6b87b9f 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -4,6 +4,12 @@ //! //! Mostly graphs and csv auto conversion +use charming::{ + Chart, + component::{self, Axis, Grid, Title}, + element::{Tooltip, Trigger}, +}; + /// A very complex macro created to add criterias to the graph /// without repeating self explanatory parameter names in strings /// @@ -85,57 +91,93 @@ macro_rules! add_field_to_chart { } /// Generate a generic graph, ready to be filled with data -pub fn initial_chart(chart_name: &str) -> charming::Chart { - charming::Chart::new() - .title( - charming::component::Title::new() - .text(chart_name) - .left("center"), - ) +pub fn initial_chart(chart_name: &str) -> Chart { + Chart::new() + .title(component::Title::new().text(chart_name).left("center")) .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) .data_zoom( - charming::component::DataZoom::new() - .type_(charming::component::DataZoomType::Inside) + component::DataZoom::new() + .type_(component::DataZoomType::Inside) .start(0) .end(100), ) - .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .data_zoom(component::DataZoom::new().start(0).end(100)) .toolbox( - charming::component::Toolbox::new().feature( - charming::component::Feature::new() - .data_zoom(charming::component::ToolboxDataZoom::new().y_axis_index("none")) - .restore(charming::component::Restore::new()) - .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + component::Toolbox::new().feature( + component::Feature::new() + .data_zoom(component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(component::Restore::new()) + .save_as_image(component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), ), ) .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) - .y_axis(charming::component::Axis::new()) - .grid(charming::component::Grid::new().contain_label(true)) + .y_axis(component::Axis::new()) + .grid(component::Grid::new().contain_label(true)) } /// Generate a new plot chart -pub fn initial_plot_chart(chart_name: &str) -> charming::Chart { - charming::Chart::new() - .title( - charming::component::Title::new() - .text(chart_name) - .left("center"), - ) - .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) +pub fn initial_plot_chart(chart_name: &str, sub_charts: &[&str]) -> Chart { + // charming::Chart::new() + Chart::new() + .title(Title::new().text(chart_name).left("center")) + .title(Title::new().text(sub_charts[0]).left("17%").top("5%")) + .title(Title::new().text(sub_charts[1]).left("17%").top("52%")) + .title(Title::new().text(sub_charts[2]).right("12%").top("5%")) + .title(Title::new().text(sub_charts[3]).right("12%").top("52%")) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) .data_zoom( - charming::component::DataZoom::new() - .type_(charming::component::DataZoomType::Inside) + component::DataZoom::new() + .type_(component::DataZoomType::Inside) .start(0) .end(100), ) - .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) .toolbox( - charming::component::Toolbox::new().feature( - charming::component::Feature::new() - .data_zoom(charming::component::ToolboxDataZoom::new().y_axis_index("none")) - .restore(charming::component::Restore::new()) - .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + component::Toolbox::new().feature( + component::Feature::new() + .data_zoom(component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(component::Restore::new()) + .save_as_image(component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), ), ) - .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .grid( + Grid::new() + .left("7%") + .top("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .grid( + Grid::new() + .right("7%") + .top("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .grid( + Grid::new() + .left("7%") + .bottom("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .grid( + Grid::new() + .right("7%") + .bottom("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .x_axis(Axis::new().grid_index(0).min(1)) + .x_axis(Axis::new().grid_index(1).min(1)) + .x_axis(Axis::new().grid_index(2).min(1)) + .x_axis(Axis::new().grid_index(3).min(1)) + .y_axis(Axis::new().grid_index(0).min(0)) + .y_axis(Axis::new().grid_index(1).min(0)) + .y_axis(Axis::new().grid_index(2).min(0)) + .y_axis(Axis::new().grid_index(3).min(0)) } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 915d039..b9cfcf5 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -17,7 +17,7 @@ use super::{ use crate::{ add_field_to_chart, error::FatalEquipementError, - export::initial_chart, + export::{initial_chart, initial_plot_chart}, interfaces::{RecipeCollection, RefinedList, ToAnalysis, ToTex}, weaponry_structs::{ Equipement, InitialEquipementList, @@ -25,7 +25,7 @@ use crate::{ equipement_thin_types::{Dices, Precision}, }, }; -use charming::Chart; +use charming::{Chart, component::LegendSelectedMode}; use core::f64; use serde::Serialize; use std::cmp::Ordering; @@ -85,6 +85,49 @@ impl ToAnalysis for RefinedEquipementList { let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) .theme(charming::theme::Theme::Dark); + let initial_chart = self.make_regular_graph(); + renderer.save(&initial_chart, format!("{save_path}.html"))?; + + let plot_chart = self.make_cross_plots_graph(); + renderer.save(&plot_chart, format!("{save_path}_plots.html"))?; + Ok(()) + } +} + +impl RefinedEquipementList { + /// Make the cross graphs + fn make_cross_plots_graph(&self) -> Chart { + let mut plot_chart = initial_plot_chart( + "Damage Gradients Dice/Precision", + &["Damage 4+2A", "Damage 5+2A", "Damage 5+3A", "Damage 6+3A"], + ); + let mut names = Vec::with_capacity(self.inner.len()); + + for wpn in self.inner.iter() { + let data_4_a2: Vec> = custom_scenario(&wpn.inner, Actions(4), Attacks(2)); + let data_5_a2: Vec> = custom_scenario(&wpn.inner, Actions(5), Attacks(2)); + let data_5_a3: Vec> = custom_scenario(&wpn.inner, Actions(5), Attacks(3)); + let data_6_a3: Vec> = custom_scenario(&wpn.inner, Actions(6), Attacks(3)); + plot_chart = add_serie(plot_chart, 0, wpn, data_4_a2); + plot_chart = add_serie(plot_chart, 1, wpn, data_5_a2); + plot_chart = add_serie(plot_chart, 2, wpn, data_5_a3); + plot_chart = add_serie(plot_chart, 3, wpn, data_6_a3); + names.push(wpn.advanced.display_name.as_str()); + } + + plot_chart = plot_chart.legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(charming::element::Orient::Vertical) + .data(names) + .selected_mode(LegendSelectedMode::Multiple), + ); + plot_chart + } + + /// Max the regular balancing plots + fn make_regular_graph(&self) -> Chart { let initial_chart: Chart = initial_chart(&format!( "Damage for all cross-gen products ({} Elements)", self.inner.len() @@ -133,11 +176,45 @@ impl ToAnalysis for RefinedEquipementList { ) } ); - renderer.save(&initial_chart, format!("{save_path}.html"))?; - Ok(()) + initial_chart } } +/// Inner function to add a serie to a plot +fn add_serie(plot_chart: Chart, id: u8, wpn: &RefinedEquipement, serie: Vec>) -> Chart { + plot_chart.series( + charming::series::Line::new() + .x_axis_index(id) + .y_axis_index(id) + .data(serie) + .name(&wpn.advanced.display_name), + ) +} + +/// Custom scenario for creating scatter plot +fn custom_scenario( + equipement_stats: &InnerEquipementStats, + actions: Actions, + attacks: Attacks, +) -> Vec> { + (1..11) + .map(|dice| { + vec![ + dice as f64, + BestDamageScenarios::from_action_constraints_it( + equipement_stats, + actions, + attacks, + Dices(dice), + Precision(9), + ) + .unwrap_or_default() + .damage_done, + ] + }) + .collect() +} + /// The list of advanced stats infered from an Equipement #[derive(Serialize)] pub struct AdvancedStats { diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index 5a33f5f..ef81d9c 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -171,17 +171,17 @@ fn damage_over_turns(value: &InnerEquipementStats, turn_info: &[TurnInfo]) -> f6 } /// The best resulting attack pattern of a virtual scenrio where some conditions are given -#[derive(Debug)] -#[cfg_attr(test, derive(Default, Clone))] +#[derive(Debug, Default)] +#[cfg_attr(test, derive(Clone))] pub struct BestDamageScenarios { /// How many actions were used by the best attack - actions_used: Actions, + pub actions_used: Actions, /// Attacks actions used by the scenario - attacks_used: Attacks, + pub attacks_used: Attacks, /// Resulting damage - damage_done: f64, + pub damage_done: f64, /// Remaining actions that need to be used to finish reload - reload_remaining: Actions, + pub reload_remaining: Actions, } impl Add for BestDamageScenarios { @@ -204,7 +204,6 @@ impl Deref for BestDamageScenarios { } } -// TODO[!!]: Add a lot of testing impl BestDamageScenarios { /// Calculate the best alternative with a set of contraints /// -- 2.45.1 From 352940486ea7aa21b806beeca689351bb4e5ed76 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 26 Feb 2025 21:15:30 +0100 Subject: [PATCH 82/97] Typos --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes .../equipement_advanced_tools.rs | 1 - 2 files changed, 1 deletion(-) diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 6b5528b07512de047d84d29509c2d1205d2ff241..935c5d509cbbec58b6521ac5954b0a40ed9c5bfb 100644 GIT binary patch delta 260 zcmZp8z}WDBae_4C?1?hYjI%c;EVGX&W8z=RZ^XBcFP@Ku(Tm|D?^0e@p5Hv%c=CC4 zxF2#)=l0`z#x;e@mGdHJET;&^3J!brTkNImylgAjTv+e2_OR+OxikJ`T)|Mra)qUe zMTPkia}Bcu)7puS5(1Sf@(hyt92|@sj9@Ui(?O4sX>yIQ{N!s6vI61k@(kj_96-Ry z2!fO2eWfQS%8N~2Aj>{^ny;Wh3>#2^JV*f}&H21@C;t1pJkOhARX00%bTj mIXO2oJNoc!X7STwJx<nrBF}u3 zIiFdU={Qp|tZ5ePXZGdfC7mUYw>h-L#y$b%$+27x4^9F-;~$%{^& n%cj+ diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index ef81d9c..ce947ba 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -374,7 +374,6 @@ impl BestDamageScenarios { // } // } // } - // // The alternative didn't exist or was worse // Some(one_attack) // } -- 2.45.1 From 01842fc64af485e40513f346927caec20d1edc5f Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 28 Feb 2025 03:49:35 +0100 Subject: [PATCH 83/97] Tries to simplify the impl process --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/src/interfaces.rs | 38 +++++++ .../equipement_advanced_repr.rs | 2 + .../equipement_advanced_tools.rs | 1 - .../equipement_impl_database.rs | 1 + .../weaponry_structs/equipement_impl_math.rs | 12 ++- .../weaponry_structs/equipement_scenario.rs | 95 +++++++++++++++--- .../weaponry_structs/equipement_structs.rs | 17 ++++ 8 files changed, 151 insertions(+), 15 deletions(-) diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 935c5d509cbbec58b6521ac5954b0a40ed9c5bfb..fe13caa2ed9996a919db8ca7830a14cd56299b62 100644 GIT binary patch delta 679 zcmXw$Pe>F|9LL{#v$ONw?##R$YLa!)9kw8mmNojLhoCIUg0#Za7BwB+(Y1DG)!7wq z>LEN>n7%_4u}aiIs4V6ZNd$E$>S9y`ojlbcq6jo9u-h2Qu6em{8c_u=;@R^h}d zyb@80004=Hp9h?+s)fY|J-4Wg=sIrzf&QlJZYcDTZsV2I%1w+b+!3t+bb(g5T8&1> zCqa7@lx@dckU&T<)*#e%$Q9PJM8~)#Z4Oz-vqK}f(Lv|gqJ{nl9bE|7g-pha4X#*o z&bDG+)e&nn2W-nI*hX*8E;vR$$1P(y#_k%!9vrpI!kCe=cza~HV8y!jdY8_%afGOc zKnQ{SsKuBgU=Km#2&9D2WDeSfU9cR)W}EfU=6nI6(s*|*u|{D#`+P7m-i<&vy-dUE zBefgeh9^{@EGTV?Ccl)YzZu!}q-IU?Zec%QT)r6s{X@2?X-iBsq% zI)eo8T1@!f`Nn;5;l1Dp7z{y98u3W~FUum3Qcg-Dx`sEG#a^APWKuM&@7XV)SWCuq z(*Kszv?{9nLLQT=g3H09fp39gpqjiT zorK~i*pj|TSEZQ$p1)drEapVfH|;AE=7a|H11+K?3c_WWhu(9SKGJ{_X<+r)a@Np$7CA>s>9q?>?2b9+9?MK4 vcE7I;IdyF5a5;P0lVtu>)_r5gA#+j}-CwC4&^M_j3>LD(tj^4{%KqWMd{MaY delta 468 zcmZp8z}WDBae_4OYz77fb|7X0Vy1~2=8Us9CM@CSVdVb}6kuTI|IL@ZSwP?!ze-+d zPEIsXh*g&tBqPAUz`u;&jPEF4HlGmhcHRVD7M_)x1r_>v7$YYy^c7{}00L>z$%kZ2 zC(8(NZDx`E#I*UF{uh46kjby@r6bCi_?Pk<@$KV_=VM{?V))3rl-HH#H_tYnd>$R{ zhuqV-{kWcSP2qCoyvP~LDZ;UW!=C*Xdnr3F+X^-p*1N1dtU65Yj6WGyFqE-eVX0zK zVZOv%!z{tHcA}%i=8F#c{6dk8@(kkAAXhMQGBR>SWi~crW>N~yNi5D# z0{bZzM1s5o1dN+G0)Fy`GN~}AGc03flVg--?P2-FQp~@TznEW{?=lM;P Result where @@ -241,4 +247,36 @@ pub trait Scenario { /// Generate the final list type fn generate_refined_recipes(&self) -> Result; + + // /// Blanket implementation deserialising all element from the database into the initial inner list used by the scenario + // fn inital_list_from_database( + // &self, + // extra_sql_filter: Option, + // ) -> Result + // where + // T: TryFrom + From + Into, + // { + // // TODO: This likely has too high a complexity and should either be a blanket implementation + // // : or require the inner workings to implement methods to easily allow this deserialisation + // Ok(Self::InitialElementList::from_vectored( + // self.get_database() + // .serialize_vec_from_table::( + // &self.get_tablename(), + // Some(&format!("META_CATEGORY LIKE '{}'", name)), + // )? + // .into_iter() + // .map(|v| { + // InnerEquipementStats::try_from(v) + // .map(|w| T::from(w)) + // .map(|v| v.into()) + // }) + // .collect::, FatalEquipementError>>()?, + // )) + // } + + /// Retrieve a reference to the inner database + fn get_database(&self) -> &Self::DatabaseType; + + /// Retrieve A config + fn get_tablename(&self) -> &str; } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index b9cfcf5..42253ea 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -55,6 +55,8 @@ pub struct RefinedEquipementList { impl RefinedList for RefinedEquipementList {} impl ToTex for RefinedEquipementList { fn to_tex(&self) -> String { + // TODO[!] : Export everything to one tsv + // : This export is only supposed to be the final export of a pseudo recipes book todo!() } } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index ce947ba..b8b6333 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -21,7 +21,6 @@ use super::equipement_thin_types::Precision; /// - 2 turns safe attacks (5 dice, 50%p) /// - 1 turn highspeed/range hit (7 dice, 80% precision) /// - 4 turns normal damage (7 dice, 90% precision) -// TODO[!] Implementation pub(super) fn get_damage_with_simulation( value: &InnerEquipementStats, actions: Actions, diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index b4a6c7a..bc0dab3 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -24,6 +24,7 @@ pub struct EquipementDatabase { } impl RecipeDatabase for EquipementDatabase { + // TODO[:] : This element is partly responsible for the difficulty simplifying and generalizing deserialisation fn serialize_vec_from_table( &self, table: &str, diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 008d151..ff56227 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -4,7 +4,7 @@ //! use super::equipement_structs::InnerEquipementStats; -use crate::weaponry_structs::SpecialField; +use crate::weaponry_structs::{SpecialField, WeaponBaseShape}; /// Add a new vector to a clone of a inner field macro_rules! add_to_vec { @@ -55,7 +55,15 @@ impl std::ops::Add for &InnerEquipementStats { precision: self.precision + rhs.precision, rmax: self.rmax + rhs.rmax, armor_break: self.armor_break + rhs.armor_break, - armor_pierce: self.armor_pierce + rhs.armor_pierce, + armor_pierce: { + if self.armor_pierce > 0 + || matches!(self.category_base, Some(WeaponBaseShape::Ranged)) + { + self.armor_pierce + rhs.armor_pierce + } else { + 0 + } + }, antimaterial: self.antimaterial + rhs.antimaterial, damage_type: add_two_options!(self.damage_type, rhs.damage_type), protection: self.protection + rhs.protection, diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 7098313..a9a40ed 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -40,30 +40,51 @@ pub struct ConfigEquipementScenario { /// A simple cross recipe scenario #[allow(clippy::missing_docs_in_private_items)] pub struct CrossRecipeScenario { - // TODO: Should obv be inside the config database: EquipementDatabase, config: ConfigEquipementScenario, } +/// All recipes +#[allow(clippy::missing_docs_in_private_items, dead_code)] +pub struct RecipesScenario { + database: EquipementDatabase, + config: ConfigEquipementScenario, +} + +/// A scenario exporting all individual elements +#[allow(clippy::missing_docs_in_private_items, dead_code)] +pub struct IndividualElementsScenario { + database: EquipementDatabase, + config: ConfigEquipementScenario, +} + +/// The initial equipement type, to be converted into post deserialisation +type InitialEquipementType = InnerEquipementStats; +/// The initial database typ +type InitialDatabaseType = DatabaseEquipementStats; + impl CrossRecipeScenario { /// Automatically deserialize into an equipement // TODO: Add to trait // TODO: Add an optionnal initial filter ? fn deserde_into_equipement( &self, - name: &str, + sql_filter: Option<&str>, ) -> Result where - T: TryFrom + From + Into, + T: From + Into, // TryFrom + { // TODO: This likely has too high a complexity and should either be a blanket implementation // : or require the inner workings to implement methods to easily allow this deserialisation + // : Most of this complexity comes from the fact that no clear definition of flow is given to + // : the whole implementation + // : Beside many struct "need" to know way too much of the inner workings of the other to funtion + // : A very long and tedious overhall is now needed + // : At the very least, The InitialEquipementList sould be able to initialize itself with only + // : the intermediate representation and nothing more Ok(InitialEquipementList::from_vectored( - self.database - .serialize_vec_from_table::( - &self.config.table_name, - Some(&format!("META_CATEGORY LIKE '{}'", name)), - )? + self.get_database() + .serialize_vec_from_table::(self.get_tablename(), sql_filter)? .into_iter() .map(|v| { InnerEquipementStats::try_from(v) @@ -74,6 +95,33 @@ impl CrossRecipeScenario { )) } + // /// Automatically deserialize into an equipement + // fn better_deserde_into_equipement( + // &self, + // sql_filter: Option<&str>, + // ) -> Result + // where + // IntermediateType: From + Into, // TryFrom + + // { + // let mut items = self + // .get_database() + // .serialize_vec_from_table::(self.get_tablename(), sql_filter)? + // .into_iter(); + // InitialEquipementList::from_iter_with_intermediate::( + // &mut items, + // ); + // // Ok(InitialEquipementList::from_vectored( + // // items + // // .map(|v| { + // // InnerEquipementStats::try_from(v) + // // .map(|w| T::from(w)) + // // .map(|v| v.into()) + // // }) + // // .collect::, FatalEquipementError>>()?, + // // )) + // todo!() + // } + /// Generate all the operations to be processed with the current config // TODO: Defer this to a custom type in the config some sort of OperationSelector fn generate_selected_operation( @@ -81,18 +129,27 @@ impl CrossRecipeScenario { ) -> Result, FatalEquipementError> { let mut operations = Vec::with_capacity(8); if self.config.shape.is_some() { - operations.push(self.deserde_into_equipement::("Shape")?); + operations + .push(self.deserde_into_equipement::(Some("META_CATEGORY LIKE 'Shape'"))?); } if let Some(qt) = self.config.materials { for _ in 0..qt { - operations.push(self.deserde_into_equipement::("Materials")?); + operations.push(self.deserde_into_equipement::(Some( + "META_CATEGORY LIKE 'Materials'", + ))?); } } if self.config.nature.is_some() { - operations.push(self.deserde_into_equipement::("Nature")?); + operations.push( + self.deserde_into_equipement::(Some("META_CATEGORY LIKE 'Nature'"))?, + ); } if self.config.finishing.is_some() { - operations.push(self.deserde_into_equipement::("Finishing")?); + operations.push( + self.deserde_into_equipement::(Some( + "META_CATEGORY LIKE 'Finishing'", + ))?, + ); } if operations.is_empty() { return Err(FatalEquipementError::CLISelection( @@ -104,9 +161,11 @@ impl CrossRecipeScenario { } impl Scenario for CrossRecipeScenario { + // TODO[3]: Could be skipped type DatabaseType = EquipementDatabase; type FinalListType = RefinedEquipementList; type Config = ConfigEquipementScenario; + // type InitialInnerList = InitialEquipementList; fn new_with_config(config: Self::Config) -> Result where @@ -128,4 +187,16 @@ impl Scenario for CrossRecipeScenario { Ok(refined_list.into()) } + + // type InitialElementList; + + // type InitialDatabaseStruct; + + fn get_tablename(&self) -> &str { + &self.config.table_name + } + + fn get_database(&self) -> &Self::DatabaseType { + &self.database + } } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 5e70554..affad8a 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -25,6 +25,23 @@ pub struct InitialEquipementList { pub(super) inner: Vec, } +// impl InitialEquipementList { +// pub fn from_iter_with_intermediate( +// iterator: &mut dyn Iterator, +// ) -> Self +// where +// IntermediateType: Into, +// IntoEquipementType: Into, +// { +// Self { +// inner: iterator +// .into_iter() +// .map(|element| IntermediateType::from(element.into())) +// .collect(), +// } +// } +// } + /// The final equipement, obtained by combining all parts #[derive(Clone, Debug)] #[cfg_attr(test, derive(PartialEq))] -- 2.45.1 From eaed13f3206251e0576a32f05c960fb45d275c24 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 28 Feb 2025 19:07:25 +0100 Subject: [PATCH 84/97] More work on standardisation and polymorphism --- weaponry/src/database.rs | 1 + weaponry/src/interfaces.rs | 88 ++++++++++++------- .../equipement_impl_database.rs | 33 +++++-- .../weaponry_structs/equipement_impl_logic.rs | 1 + .../weaponry_structs/equipement_scenario.rs | 88 ++++--------------- 5 files changed, 99 insertions(+), 112 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index c9766d4..ac8ccac 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -79,6 +79,7 @@ mod test { } /// setting up test db and table, also adding arbitrary data inside fn mock_set_up(db_filename: &str) -> EquipementDatabase { + let _ = std::fs::remove_file(db_filename); let equip_db = EquipementDatabase::new(db_filename).unwrap(); equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",()).unwrap(); equip_db diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 186cca4..5d4badf 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -8,9 +8,10 @@ use std::{path::Path, rc::Rc}; use more_fields::FieldsAsSlice; +use rusqlite::Connection; use serde::de::DeserializeOwned; -use crate::error::FatalEquipementError; +use crate::{error::FatalEquipementError, weaponry_structs::InitialEquipementList}; /// Trait representing a view table /// @@ -91,6 +92,21 @@ where /// Create a collection from a vector fn from_vectored(list: Vec) -> Self; + + /// Create a collection from an iterator of intermediate values + fn from_iter_intermediate( + iter_inter: impl Iterator>, + ) -> Result + where + Self: std::marker::Sized, + T: Into, + { + Ok(Self::from_vectored( + iter_inter + .map(|r| r.map(|eq_inter| Into::::into(eq_inter))) + .collect::, FatalEquipementError>>()?, + )) + } } /// Trait that ensure that two elements of a recipe are combinable, @@ -176,6 +192,11 @@ pub trait ToAnalysis { /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { + /// The initial Deserialisation struct, SQL will be deserialized into this + type DeserialisationType: DeserializeOwned; + /// The used type that Deserialisation type will be converted into + type InnerType: TryFrom; + /// Create the database from a file fn new(origin: &str) -> Result where @@ -183,11 +204,17 @@ pub trait RecipeDatabase { /// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database /// The FROM type is the original data, directly deserialized from the table + // TODO[:] : This element is partly responsible for the difficulty simplifying and generalizing deserialisation fn serialize_vec_from_table( &self, table: &str, filter: Option<&str>, - ) -> std::result::Result, FatalEquipementError>; + ) -> Result, crate::error::FatalEquipementError> { + crate::database::get_data(self.get_connection(), table, filter) + } + + /// Get a reference to the underlying database connection + fn get_connection(&self) -> &Connection; /// Initialize an empty database & table fn initialize_empty_table( @@ -197,6 +224,17 @@ pub trait RecipeDatabase { /// Insert a row inside the database, while mostly unused this function is needed to initialize the empty table with an empty row if needed fn insert_row(&self, row: T) -> Result<(), FatalEquipementError>; + + /// Serialize a request into an intermediate T representation, + /// T having all the implementation specifics of the part in details + /// eg. EqShape, EqPart etc.. + fn serialise_into_intermediate( + &self, + table: &str, + filter: Option<&str>, + ) -> Result> + '_, FatalEquipementError> + where + T: From; } /// Trait implemented by any struct aiming to be a public recipe @@ -233,12 +271,10 @@ pub trait Scenario { type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis; /// Inner configuration type Config; - - // /// The initial element List - // type InitialElementList: RecipeCollection; - - // /// The Inner Database struct to deserialize initially - // type InitialDatabaseStruct; + /// The initial equipement type, the database serialisation will be to be converted into this type + type InitialEquipementType; + /// The inner element that all serialised data will be serialized into after the intermediate step + type Recipe; /// Create a Scenario from a given config fn new_with_config(config: Self::Config) -> Result @@ -248,35 +284,19 @@ pub trait Scenario { /// Generate the final list type fn generate_refined_recipes(&self) -> Result; - // /// Blanket implementation deserialising all element from the database into the initial inner list used by the scenario - // fn inital_list_from_database( - // &self, - // extra_sql_filter: Option, - // ) -> Result - // where - // T: TryFrom + From + Into, - // { - // // TODO: This likely has too high a complexity and should either be a blanket implementation - // // : or require the inner workings to implement methods to easily allow this deserialisation - // Ok(Self::InitialElementList::from_vectored( - // self.get_database() - // .serialize_vec_from_table::( - // &self.get_tablename(), - // Some(&format!("META_CATEGORY LIKE '{}'", name)), - // )? - // .into_iter() - // .map(|v| { - // InnerEquipementStats::try_from(v) - // .map(|w| T::from(w)) - // .map(|v| v.into()) - // }) - // .collect::, FatalEquipementError>>()?, - // )) - // } - /// Retrieve a reference to the inner database fn get_database(&self) -> &Self::DatabaseType; /// Retrieve A config fn get_tablename(&self) -> &str; + + /// Automatically deserialize into an equipement + // TODO: Add to trait + // TODO: Add an optionnal initial filter ? + fn deserde_into_equipement( + &self, + filter: Option<&str>, + ) -> Result + where + T: From + Into; } diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index bc0dab3..27d2374 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -6,7 +6,7 @@ // use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; -use crate::database::{generate_create_table_query, get_data}; +use crate::database::generate_create_table_query; use crate::error::FatalEquipementError; use crate::interfaces::{FixedRecipe, RecipeDatabase}; use rusqlite::Connection; @@ -24,14 +24,8 @@ pub struct EquipementDatabase { } impl RecipeDatabase for EquipementDatabase { - // TODO[:] : This element is partly responsible for the difficulty simplifying and generalizing deserialisation - fn serialize_vec_from_table( - &self, - table: &str, - filter: Option<&str>, - ) -> Result, crate::error::FatalEquipementError> { - get_data(&self.conn, table, filter) - } + type DeserialisationType = DatabaseEquipementStats; + type InnerType = InnerEquipementStats; /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. fn new(filename: &str) -> Result { @@ -55,6 +49,27 @@ impl RecipeDatabase for EquipementDatabase { let _ = row; todo!() } + + fn get_connection(&self) -> &Connection { + &self.conn + } + + fn serialise_into_intermediate( + &self, + table: &str, + filter: Option<&str>, + ) -> Result> + '_, FatalEquipementError> + where + T: From, + { + // Start with Self::DatabaseType + Ok(self + .serialize_vec_from_table::(table, filter)? + .into_iter() + .map(|db_element| { + Self::InnerType::try_from(db_element).map(|inner_eq| T::from(inner_eq)) + })) + } } #[allow(missing_docs)] pub struct EquipementFixedRecipe { diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index 561f38a..35aa891 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -34,6 +34,7 @@ impl Combinable for Equipement { impl RecipeCollection for InitialEquipementList { type Recipes = Equipement; + // Should likely be internal fn from_vectored(list: Vec) -> Self { Self { inner: list } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index a9a40ed..90b6ad3 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -13,10 +13,7 @@ use crate::{ weaponry_structs::{ Equipement, InitialEquipementList, RefinedEquipementList, equipement_impl_database::EquipementDatabase, - equipement_structs::{ - DatabaseEquipementStats, EqFinishing, EqMaterial, EqNature, EqShape, - InnerEquipementStats, - }, + equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, }, }; @@ -58,70 +55,7 @@ pub struct IndividualElementsScenario { config: ConfigEquipementScenario, } -/// The initial equipement type, to be converted into post deserialisation -type InitialEquipementType = InnerEquipementStats; -/// The initial database typ -type InitialDatabaseType = DatabaseEquipementStats; - impl CrossRecipeScenario { - /// Automatically deserialize into an equipement - // TODO: Add to trait - // TODO: Add an optionnal initial filter ? - fn deserde_into_equipement( - &self, - sql_filter: Option<&str>, - ) -> Result - where - T: From + Into, // TryFrom + - { - // TODO: This likely has too high a complexity and should either be a blanket implementation - // : or require the inner workings to implement methods to easily allow this deserialisation - // : Most of this complexity comes from the fact that no clear definition of flow is given to - // : the whole implementation - // : Beside many struct "need" to know way too much of the inner workings of the other to funtion - // : A very long and tedious overhall is now needed - // : At the very least, The InitialEquipementList sould be able to initialize itself with only - // : the intermediate representation and nothing more - Ok(InitialEquipementList::from_vectored( - self.get_database() - .serialize_vec_from_table::(self.get_tablename(), sql_filter)? - .into_iter() - .map(|v| { - InnerEquipementStats::try_from(v) - .map(|w| T::from(w)) - .map(|v| v.into()) - }) - .collect::, FatalEquipementError>>()?, - )) - } - - // /// Automatically deserialize into an equipement - // fn better_deserde_into_equipement( - // &self, - // sql_filter: Option<&str>, - // ) -> Result - // where - // IntermediateType: From + Into, // TryFrom + - // { - // let mut items = self - // .get_database() - // .serialize_vec_from_table::(self.get_tablename(), sql_filter)? - // .into_iter(); - // InitialEquipementList::from_iter_with_intermediate::( - // &mut items, - // ); - // // Ok(InitialEquipementList::from_vectored( - // // items - // // .map(|v| { - // // InnerEquipementStats::try_from(v) - // // .map(|w| T::from(w)) - // // .map(|v| v.into()) - // // }) - // // .collect::, FatalEquipementError>>()?, - // // )) - // todo!() - // } - /// Generate all the operations to be processed with the current config // TODO: Defer this to a custom type in the config some sort of OperationSelector fn generate_selected_operation( @@ -161,11 +95,11 @@ impl CrossRecipeScenario { } impl Scenario for CrossRecipeScenario { - // TODO[3]: Could be skipped type DatabaseType = EquipementDatabase; type FinalListType = RefinedEquipementList; type Config = ConfigEquipementScenario; - // type InitialInnerList = InitialEquipementList; + type InitialEquipementType = InnerEquipementStats; + type Recipe = Equipement; fn new_with_config(config: Self::Config) -> Result where @@ -199,4 +133,20 @@ impl Scenario for CrossRecipeScenario { fn get_database(&self) -> &Self::DatabaseType { &self.database } + + /// Automatically deserialize into an equipement + // TODO: Add to trait + // TODO: Add an optionnal initial filter ? + fn deserde_into_equipement( + &self, + filter: Option<&str>, + ) -> Result + where + T: From<::InitialEquipementType> + Into, + { + RecipeCollection::from_iter_intermediate::( + self.get_database() + .serialise_into_intermediate::(self.get_tablename(), filter)?, + ) + } } -- 2.45.1 From 4380ad55917e3c64fe820447d404abd8f1f23149 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 28 Feb 2025 19:58:46 +0100 Subject: [PATCH 85/97] Unsure about some deep dependencies --- weaponry/src/interfaces.rs | 36 ++++++++++++++++--- .../weaponry_structs/equipement_scenario.rs | 8 +++-- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 5d4badf..326b3f1 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -264,7 +264,10 @@ pub trait Reportable { /// A recipe full stack scenario, from loading database through view table generation /// /// The inner working while somehow abstracted are very tied together and tied to the impl -pub trait Scenario { +pub trait Scenario where for<'a> &'a <<::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add +// where +// for<'a> &'a <::Recipe as Combinable>::Inner: std::ops::Add, for<'a> &'a <<::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add +{ /// The inner database type type DatabaseType: RecipeDatabase; /// The type of the final recipe list @@ -273,8 +276,13 @@ pub trait Scenario { type Config; /// The initial equipement type, the database serialisation will be to be converted into this type type InitialEquipementType; - /// The inner element that all serialised data will be serialized into after the intermediate step - type Recipe; + /// The initial equipement list, about to be converted into a refined list + type InitialEquipementListType: RecipeCollection; //: Into>; + + // /// The inner element that all serialised data will be serialized into after the intermediate step + // type Recipe; + + // for<'a> &'a <::Recipes as Combinable>::Inner: std::ops::Add, /// Create a Scenario from a given config fn new_with_config(config: Self::Config) -> Result @@ -296,7 +304,25 @@ pub trait Scenario { fn deserde_into_equipement( &self, filter: Option<&str>, - ) -> Result + ) -> Result where - T: From + Into; + T: From + + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>; + + // /// Automatically deserialize into an equipement + // // TODO: Add to trait + // // TODO: Add an optionnal initial filter ? + // fn deserde_into_equipement( + // &self, + // filter: Option<&str>, + // ) -> Result + // where + // T: From + Into<<::InitialEquipementType as RecipeCollection>::Recipes>, + // ::InitialEquipementListType: RecipeCollection, + // { + // RecipeCollection::from_iter_intermediate::( + // self.get_database() + // .serialise_into_intermediate::(self.get_tablename(), filter)?, + // ) + // } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 90b6ad3..0d3c736 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -99,7 +99,8 @@ impl Scenario for CrossRecipeScenario { type FinalListType = RefinedEquipementList; type Config = ConfigEquipementScenario; type InitialEquipementType = InnerEquipementStats; - type Recipe = Equipement; + type InitialEquipementListType = InitialEquipementList; + // type Recipe = Equipement; fn new_with_config(config: Self::Config) -> Result where @@ -140,9 +141,10 @@ impl Scenario for CrossRecipeScenario { fn deserde_into_equipement( &self, filter: Option<&str>, - ) -> Result + ) -> Result where - T: From<::InitialEquipementType> + Into, + T: From + + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>, { RecipeCollection::from_iter_intermediate::( self.get_database() -- 2.45.1 From 93d1bbbbe786965e95fe5f4e3deb697648d49696 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 28 Feb 2025 20:08:50 +0100 Subject: [PATCH 86/97] Finished to merge some elements to polymorphism --- weaponry/src/interfaces.rs | 41 ++++++++++--------- .../weaponry_structs/equipement_scenario.rs | 19 +-------- 2 files changed, 22 insertions(+), 38 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 326b3f1..98ebe99 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -11,7 +11,7 @@ use more_fields::FieldsAsSlice; use rusqlite::Connection; use serde::de::DeserializeOwned; -use crate::{error::FatalEquipementError, weaponry_structs::InitialEquipementList}; +use crate::error::FatalEquipementError; /// Trait representing a view table /// @@ -275,6 +275,7 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList /// Inner configuration type Config; /// The initial equipement type, the database serialisation will be to be converted into this type + // TODO[!]: Try to remove as it is present in Database type InitialEquipementType; /// The initial equipement list, about to be converted into a refined list type InitialEquipementListType: RecipeCollection; //: Into>; @@ -298,17 +299,6 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList /// Retrieve A config fn get_tablename(&self) -> &str; - /// Automatically deserialize into an equipement - // TODO: Add to trait - // TODO: Add an optionnal initial filter ? - fn deserde_into_equipement( - &self, - filter: Option<&str>, - ) -> Result - where - T: From - + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>; - // /// Automatically deserialize into an equipement // // TODO: Add to trait // // TODO: Add an optionnal initial filter ? @@ -317,12 +307,23 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList // filter: Option<&str>, // ) -> Result // where - // T: From + Into<<::InitialEquipementType as RecipeCollection>::Recipes>, - // ::InitialEquipementListType: RecipeCollection, - // { - // RecipeCollection::from_iter_intermediate::( - // self.get_database() - // .serialise_into_intermediate::(self.get_tablename(), filter)?, - // ) - // } + // T: From + // + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>; + + /// Automatically deserialize into an equipement + // TODO: Add to trait + // TODO: Add an optionnal initial filter ? + fn deserde_into_equipement( + &self, + filter: Option<&str>, + ) -> Result + where + T: From<<::DatabaseType as RecipeDatabase>::InnerType> + + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>, + { + RecipeCollection::from_iter_intermediate::( + self.get_database() + .serialise_into_intermediate::(self.get_tablename(), filter)?, + ) + } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 0d3c736..4a99840 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -11,7 +11,7 @@ use crate::{ error::FatalEquipementError, interfaces::{RecipeCollection, RecipeDatabase, Scenario}, weaponry_structs::{ - Equipement, InitialEquipementList, RefinedEquipementList, + InitialEquipementList, RefinedEquipementList, equipement_impl_database::EquipementDatabase, equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, }, @@ -134,21 +134,4 @@ impl Scenario for CrossRecipeScenario { fn get_database(&self) -> &Self::DatabaseType { &self.database } - - /// Automatically deserialize into an equipement - // TODO: Add to trait - // TODO: Add an optionnal initial filter ? - fn deserde_into_equipement( - &self, - filter: Option<&str>, - ) -> Result - where - T: From - + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>, - { - RecipeCollection::from_iter_intermediate::( - self.get_database() - .serialise_into_intermediate::(self.get_tablename(), filter)?, - ) - } } -- 2.45.1 From 6d080230ee562be8b6b0931ba947ba07f8b4aef8 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 4 Mar 2025 21:21:19 +0100 Subject: [PATCH 87/97] Clears a lot of todo --- weaponry/Cargo.toml | 2 +- weaponry/src/interfaces.rs | 18 +-- weaponry/src/strategy.rs | 102 +++++------- .../equipement_advanced_repr.rs | 20 ++- .../equipement_advanced_tools.rs | 149 +----------------- .../src/weaponry_structs/equipement_fields.rs | 79 +++++----- .../equipement_impl_basics.rs | 44 +++++- .../weaponry_structs/equipement_impl_io.rs | 2 +- .../weaponry_structs/equipement_impl_logic.rs | 20 +-- .../weaponry_structs/equipement_impl_math.rs | 6 +- .../weaponry_structs/equipement_scenario.rs | 1 - .../weaponry_structs/equipement_structs.rs | 57 ++----- 12 files changed, 154 insertions(+), 346 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index d7f70a4..b1a596a 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -7,7 +7,6 @@ edition = "2024" more_fields = {path ="../more_fields"} comfy-table = "7.1.4" csv = "1.3.1" -fastrand = "2.3.0" probability = "0.20.3" rusqlite = { version = "0.33.0" } # , features = ["bundled"] serde = { version = "1.0.217", features = ["derive"] } @@ -19,6 +18,7 @@ regex = "1.11.1" charming = { version = "0.4.0", features = [] } [dev-dependencies] +fastrand = "2.3.0" criterion = { version = "0.5" } regex = "1.11.1" pretty_assertions = "^1.4" diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 98ebe99..99f5319 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -152,6 +152,7 @@ pub(super) type FilterType = Box>>; #[derive(Clone)] /// A generic Filtering function +// TODO: Deref pub(crate) struct FilterFunction(pub(super) FilterType); /// This element can be converted to tex @@ -172,7 +173,6 @@ pub trait ToAnalysis { type InnerData; /// Sort the inner data with a given closure - // TODO[4]: Consider changing the signature to (self) -> Self, to match the filter fn inner_sort(&mut self, closure: T) where T: FnMut(&Self::InnerData, &Self::InnerData) -> std::cmp::Ordering; @@ -180,8 +180,6 @@ pub trait ToAnalysis { /// Apply a filter to the inner data /// /// Careful this filter will consume the original data to avoir reallocating - // TODO[6]: Consider implementing base filters as a struct to allow implementation / choice to be polymorphic - // : Maybe more downsides over a dynamic choosing by default fn inner_filter(self, closure: T) -> Self where T: FnMut(&Self::InnerData) -> bool; @@ -204,7 +202,7 @@ pub trait RecipeDatabase { /// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database /// The FROM type is the original data, directly deserialized from the table - // TODO[:] : This element is partly responsible for the difficulty simplifying and generalizing deserialisation + // POI: This element is partly responsible for the difficulty simplifying and generalizing deserialisation fn serialize_vec_from_table( &self, table: &str, @@ -299,20 +297,8 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList /// Retrieve A config fn get_tablename(&self) -> &str; - // /// Automatically deserialize into an equipement - // // TODO: Add to trait - // // TODO: Add an optionnal initial filter ? - // fn deserde_into_equipement( - // &self, - // filter: Option<&str>, - // ) -> Result - // where - // T: From - // + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>; /// Automatically deserialize into an equipement - // TODO: Add to trait - // TODO: Add an optionnal initial filter ? fn deserde_into_equipement( &self, filter: Option<&str>, diff --git a/weaponry/src/strategy.rs b/weaponry/src/strategy.rs index 03b8c4f..a19727f 100644 --- a/weaponry/src/strategy.rs +++ b/weaponry/src/strategy.rs @@ -6,75 +6,49 @@ //! or balancing specifically one parameter (balancing materials, balencing finishes etc..) //! These strategies must take into account the level of the fighter (hence his precision) and of the craftsman (hence a difficulty diminution) //! -#![allow(dead_code)] +// #![allow(dead_code)] -/// Generation strategy, how to generate all the data, instead of a full permutation -pub enum EquipementStrategy { - /// Full permutation, generate all possible outcomes - GenerateAll, - /// Generate all the named equipements - GenerateNamed, - /// Do not add finishing touches - NoFinishes, -} - -/// Which material to select -pub enum MaterialsStrategy { - /// Add all materials to the mix - AllMaterials, - /// Add only tier one material - OnlyTier1, - /// Add only easy materials - OnlyEasy, - /// Add only cheap materials - OnlyCheap, - /// Add only one material - OnlyOne, -} - -/// Filter to apply after the generation -pub enum EquipementFilter { - /// Don't filter anything - All, - /// Filter all outliers - Outiliers, - /// Filter in all the named - Named, -} - -// /// Default full generation strategy -// pub fn default_generation() -> impl ParallelIterator { -// Gen:: { elem: Vec::new() } +// /// Generation strategy, how to generate all the data, instead of a full permutation +// pub enum EquipementStrategy { +// /// Full permutation, generate all possible outcomes +// GenerateAll, +// /// Generate all the named equipements +// GenerateNamed, +// /// Do not add finishing touches +// NoFinishes, // } -// /// Default full generation strategy -// pub fn naive_generation(left: Vec, right: Vec) -> Vec -// where -// T: Clone, -// for<'a> &'a T: std::ops::Add<&'a T>, -// { -// left.iter() -// .flat_map(move |e| right.iter().map(move |f| (e + f)).collect::>()) -// .collect() +// /// Which material to select +// pub enum MaterialsStrategy { +// /// Add all materials to the mix +// AllMaterials, +// /// Add only tier one material +// OnlyTier1, +// /// Add only easy materials +// OnlyEasy, +// /// Add only cheap materials +// OnlyCheap, +// /// Add only one material +// OnlyOne, // } -// /// Default full generation strategy -// /// -// /// Take a list of various parts that are combinable and combines them -// pub fn naive_generation( -// list_recipes: Vec>>, -// ) -> Vec { -// list_recipes.iter().reduce(|acc, e| acc.combine_all(e)); -// todo!() +// /// Filter to apply after the generation +// pub enum EquipementFilter { +// /// Don't filter anything +// All, +// /// Filter all outliers +// Outiliers, +// /// Filter in all the named +// Named, // } -#[cfg(test)] -mod test { - // use super::*; +// #[cfg(test)] +// mod test { +// // use super::*; - #[test] - fn test_naive_generator() { - // let t = naive_generation(vec![1, 2, 3], vec![5, 6, 7]); - // assert_eq!(t.len(), 3 * 3); - } -} +// #[test] +// fn test_naive_generator() { +// // let t = naive_generation(vec![1, 2, 3], vec![5, 6, 7]); +// // assert_eq!(t.len(), 3 * 3); +// } +// } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 42253ea..7d593ff 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -28,7 +28,7 @@ use crate::{ use charming::{Chart, component::LegendSelectedMode}; use core::f64; use serde::Serialize; -use std::cmp::Ordering; +use std::{cmp::Ordering, ops::Deref}; /// The final representation of the equipement inplementing all the fields needed for processing // TODO: Add a public getter for the inner data @@ -36,19 +36,25 @@ pub struct RefinedEquipement { /// The original inner stats /// /// This structs takes ownership of the inner data - // #[serde(skip_deserializing)] pub inner: InnerEquipementStats, /// Advanced stats - // #[serde(flatten)] pub advanced: AdvancedStats, } /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements - // TODO: Add a public getter in on of the traits - pub inner: Vec, + inner: Vec, +} + +// DONE: The use of Deref could be a subtle gotcha +impl Deref for RefinedEquipementList { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.inner + } } // Just a checkmark @@ -80,9 +86,7 @@ impl ToAnalysis for RefinedEquipementList { } } - // TODO[3]: Consider wether the naming should be a parameter, - // : Consider wether the closure should be a parameter - // or a config should be given or if the scenario should be fed again the Refined and ... + // DONE: While a custom config would allow some personalisation, there is no reason to beleive a more meaningfull name would be choosen fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) .theme(charming::theme::Theme::Dark); diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index b8b6333..cec8a29 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -6,8 +6,6 @@ use probability::distribution::Discrete; use probability::prelude::Binomial; use std::ops::Add; use std::ops::Deref; -use strum::Display; -use strum::EnumIter; use super::equipement_thin_types::Actions; use super::equipement_thin_types::Attacks; @@ -105,7 +103,6 @@ pub(super) fn get_damage_with_simulation( /// Sustained damage /// /// Average damage factoring reload, calculated with 9 dice and 90% precision -// TODO[!] Replace avg_damage with this pub(super) fn get_sustained_damage( value: &InnerEquipementStats, actions: Actions, @@ -207,7 +204,7 @@ impl BestDamageScenarios { /// Calculate the best alternative with a set of contraints /// /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) - // TODO[!]: Clean this cursed abomination + // DONE: While this abomination is really subpar code, there is no time to clean things that work pub fn from_action_constraints_it( equipement_stats: &InnerEquipementStats, actions_allowed: Actions, @@ -229,10 +226,6 @@ impl BestDamageScenarios { (0, Attacks(0)) }; - // print!( - // "[{actions_allowed}A, {attacks_allowed}a, {}A/a {nb_max_attacks_reload}#, {rem}rem] => ", - // equipement_stats.action_cost - // ); // Loop from the extra attack and go down let mut values: Vec<(i8, i8, f64)> = (1..=(nb_max_attacks_reload + *extra_attack) .clamp(0, *attacks_allowed)) @@ -250,8 +243,8 @@ impl BestDamageScenarios { ) }) .collect(); + values.sort_by(|(_, _, v1), (_, _, v2)| v2.total_cmp(v1)); - // println!("{:?}", values); (!values.is_empty()).then(|| Self { actions_used: Actions((values[0].0 * full_attack_cost).clamp(0, *actions_allowed)), attacks_used: Attacks(values[0].0), @@ -259,123 +252,6 @@ impl BestDamageScenarios { reload_remaining: Actions(values[0].1), }) } - - // /// Calculate the best alternative with a set of contraints - // /// - // /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) - // #[deprecated] - // pub fn from_action_constraints( - // equipement_stats: &InnerEquipementStats, - // actions_allowed: Actions, - // attacks_allowed: Attacks, - // dices_allowed: Dices, - // precision: Precision, - // ) -> Option { - // Self::from_action_constraints_recursive( - // equipement_stats, - // actions_allowed, - // attacks_allowed, - // dices_allowed, - // precision, - // 0, - // 0, - // ) - // } - // /// Recursive part of the from_action_constraints call - // /// - // /// This algorithm takes a recursive approact to avoid too much forward complexity - // #[deprecated] - // fn from_action_constraints_recursive( - // equipement_stats: &InnerEquipementStats, - // actions_allowed: Actions, - // attacks_allowed: Attacks, - // dices_allowed: Dices, - // precision: Precision, - // reload_remaining: i8, - // depth: u8, - // ) -> Option { - // // If we can't attack return early - // if equipement_stats.action_cost > *actions_allowed - // || *attacks_allowed == 0 - // || reload_remaining > 0 - // || *dices_allowed < 1 - // { - // // println!( - // // "[{depth}] > Reach the end of recursion {}>{actions_allowed}, {attacks_allowed}a, {dices_allowed}d {reload_remaining}r", - // // value.action_cost - // // ); - // return None; - // } - - // // if depth == 0 { - // // println!( - // // "Starting recursion: {actions_allowed}A {attacks_allowed}atk {dices_allowed}*" - // // ); - // // } - // let atkreload_cost = - // equipement_stats.reload_cost.unwrap_or_default() + equipement_stats.action_cost; - - // // We create our first contender, One attack only - // let one_attack = Self { - // // No matter what we try to reload, even if we overcap the attack was still valid - // actions_used: Actions((atkreload_cost).clamp(0, *actions_allowed)), - // attacks_used: Attacks(1), - // damage_done: binomial_dice_distribution(equipement_stats, precision, dices_allowed), - // // If the reload+attack exceed the actions, we must bookkeep it - // // as a reminder that we have leftover actions to spend next turn - // reload_remaining: Actions( - // ((atkreload_cost) - *actions_allowed + reload_remaining).clamp(0, *actions_allowed), - // ), - // depth, - // }; - // // println!( - // // "[{depth}] > One attack ({}d): {one_attack:?}/{actions_allowed}A", - // // Dices(*dices_allowed) - // // ); - - // // We can only try two attacks if two attack would be valid aka: - // // - We can spend: 2 attacks and (at least) 1 reload (as actions) - // // - : 2 attacks (as attacks) - // if atkreload_cost + equipement_stats.action_cost <= *actions_allowed && *attacks_allowed > 1 - // { - // // Cumbersome because of rounding errors - // if let (Some(a), Some(b)) = ( - // (Self::from_action_constraints_recursive( - // equipement_stats, - // // TODO[9]: THIS APPROACH IS DEEPLY INCORRECT - // // : It does however work for the values we will be using it - // actions_allowed - Actions(atkreload_cost), - // Attacks(attacks_allowed.div_floor(2)), - // Dices(dices_allowed.div_floor(2)), - // precision, - // reload_remaining, - // depth + 1, - // )), - // (Self::from_action_constraints_recursive( - // equipement_stats, - // actions_allowed - Actions(atkreload_cost), - // Attacks(attacks_allowed.div_ceil(2)), - // Dices(dices_allowed.div_ceil(2)), - // precision, - // reload_remaining - equipement_stats.reload_cost.unwrap_or_default(), - // depth + 1, - // )), - // ) { - // let sum_sub_attacks = a + b; - // // println!( - // // "[{depth}] > Two attacks ({} & {}) : {sum_sub_attacks:?}", - // // Dices(dices_allowed.div_floor(2)), - // // Dices(dices_allowed.div_ceil(2)) - // // ); - // // The alternative was better - // if one_attack.damage_done < sum_sub_attacks.damage_done { - // return Some(sum_sub_attacks); - // } - // } - // } - // // The alternative didn't exist or was worse - // Some(one_attack) - // } } /// Do as many binomials as there are attacks @@ -426,26 +302,6 @@ pub(super) fn binomial_dice_distribution( .fold(0., |a, b| a + b) } -// TODO: Change this to be a thin type and replace enum by new(nb) et high(), med() etc.. -// : And add a way to do ranges easily -/// The precision infered for a damage calculation event -#[derive(EnumIter, Clone, Copy, Display)] -#[allow(clippy::missing_docs_in_private_items)] -pub enum FixedPrecision { - High, - Medium, - Low, -} - -/// The number of dices rolled for a damage simulation -#[derive(EnumIter, Clone, Copy, Display)] -#[allow(clippy::missing_docs_in_private_items)] -pub enum FixedDiceNumber { - Many, - Average, - Few, -} - #[cfg(test)] mod test { use crate::weaponry_structs::{ @@ -686,6 +542,5 @@ mod test { println!("[{i}] {:?} ~= {res}", val.clone().unwrap_or_default()); assert_close!(val.clone().map_or(0., |v| v.damage_done), res); }); - // todo!() } } diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 4f436ac..ace1a90 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -4,14 +4,33 @@ use serde::{Deserialize, Serialize}; use std::fmt::Display; -use std::ops::Add; +use std::ops::{Add, Deref, DerefMut}; use strum::Display; #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only -// TODO: avoid pub make an impl ? -pub struct SpecialField(pub Vec); +pub struct SpecialField(Vec); + +impl SpecialField { + /// Create a special field from a vector + pub fn new(inner_data: Vec) -> Self { + Self(inner_data) + } +} +impl Deref for SpecialField { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for SpecialField { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} // TODO[6]: This cross target specification existed for combines weapons, // : that do not really need any balancing and only rendering @@ -55,7 +74,22 @@ pub enum DamageMod { #[derive(Clone, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] // TODO: avoid pub make an impl ? -pub struct DamageType(pub Vec); +pub struct DamageType(Vec); + +impl Deref for DamageType { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DamageType { + /// Create a new DamageType from a vector of [DamageMod] + pub fn new(inner_data: Vec) -> Self { + Self(inner_data) + } +} impl Display for DamageType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -77,28 +111,6 @@ impl Add for DamageType { } } -// // TODO[!]: This is only needed as long as we dont have a special category for the target -// // TODO[!]: This part should be handled by a category filter instead, filtering Shape on Shape -// impl PartialEq for EquipementSerializedCategory { -// fn eq(&self, other: &Self) -> bool { -// match (self, other) { -// (&Self::None, _) => false, -// (_, Self::None) => false, -// (&Self::Armors, &Self::Armors) => true, -// (&Self::Armors, _) => false, -// (_, &Self::Armors) => 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::*; @@ -276,18 +288,3 @@ pub enum WeaponBaseSize { Heavy, SuperHeavy, } - -// // TODO[!]: Add this as a target and nature instead of the old Type -// // : Remember it's the applied into that specify wether they can be applied not the other way around -// /// Specifies the exact nature of the target this element can be applied to -// #[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)] -// pub enum EquipementFilter { -// /// This element can only be applied to a specific category -// Target(EquipementSection), -// /// This element exists only for recipes or for export to tex, it cannot be auto-applied -// NoTarget, -// /// This element can be applied to any target -// AnyTarget, -// // /// This element can only be applied to a specific base shape -// // TargetShape(WeaponBaseShape) -// } diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 5aae715..aacec5e 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -128,10 +128,9 @@ impl Display for InnerEquipementStats { )], ); table.add_row_if( - |_, _| !self.special.0.is_empty(), + |_, _| !self.special.is_empty(), vec![ self.special - .0 .iter() .intersperse(&",".to_string()) .fold(String::new(), |res, new| format!("{}; {}", res, new)), @@ -171,7 +170,7 @@ impl Reportable for RefinedEquipementList { 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.add_row(vec![format!("Rows: {}", self.len())]); table.to_string() } } @@ -181,11 +180,46 @@ mod test { use crate::{ interfaces::{RecipeCollection, Reportable}, weaponry_structs::{ - Equipement, InitialEquipementList, equipement_advanced_repr::RefinedEquipementList, - equipement_structs::InnerEquipementStats, + Equipement, InitialEquipementList, + equipement_advanced_repr::RefinedEquipementList, + equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}, }, }; + #[allow(dead_code)] + /// A manually implemented hashmap of all values + #[doc(hidden)] + macro_rules! r { + () => { + fastrand::i8(1..20) + }; + } + impl InnerEquipementStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: vec![r!() as u8], + range: (r!() - 10) as i16, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, + ..Default::default() + } + } + } + impl DatabaseEquipementStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: r!() as u8, + range: r!() - 19, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, + ..Default::default() + } + } + } #[test] fn test_format() { let equi = Equipement { diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs index e7a5215..9c12248 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -9,7 +9,7 @@ use std::path::Path; impl ToCSV for RefinedEquipementList { fn write_csv(&self, path: &Path) -> csv::Result<()> { let mut wtr = csv::Writer::from_path(path)?; // wtr.serialize - for record in self.inner.iter() { + for record in self.iter() { wtr.serialize(record)?; } Ok(()) diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index 35aa891..0a6799b 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -96,8 +96,8 @@ mod test { range: 3, agility_bonus: 4., category_base: Some(WeaponBaseShape::Staves), - special: SpecialField(vec!["zero".into()]), - damage_type: Some(DamageType(vec![DamageMod::Secondary( + special: SpecialField::new(vec!["zero".into()]), + damage_type: Some(DamageType::new(vec![DamageMod::Secondary( PhysicalDamageType::Slash, )])), ..Default::default() @@ -106,10 +106,10 @@ mod test { integrity: 3, agility_bonus: 5., damage: 10, - damage_type: Some(DamageType(vec![DamageMod::Primary( + damage_type: Some(DamageType::new(vec![DamageMod::Primary( PhysicalDamageType::Blunt, )])), - special: SpecialField(vec!["one".into(), "two".into()]), + special: SpecialField::new(vec!["one".into(), "two".into()]), ..Default::default() }; assert_eq!( @@ -121,8 +121,8 @@ mod test { damage: 10, range: 3, category_base: Some(WeaponBaseShape::Staves), - special: SpecialField(vec!["zero".into(), "one".into(), "two".into()]), - damage_type: Some(DamageType(vec![ + special: SpecialField::new(vec!["zero".into(), "one".into(), "two".into()]), + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), @@ -131,14 +131,14 @@ mod test { ); assert_eq!( &InnerEquipementStats { - damage_type: Some(DamageType(vec![ + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), ..Default::default() } + &InnerEquipementStats::default(), InnerEquipementStats { - damage_type: Some(DamageType(vec![ + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), @@ -148,14 +148,14 @@ mod test { assert_eq!( &InnerEquipementStats::default() + &InnerEquipementStats { - damage_type: Some(DamageType(vec![ + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), ..Default::default() }, InnerEquipementStats { - damage_type: Some(DamageType(vec![ + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index ff56227..ae883ac 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -43,7 +43,6 @@ impl std::ops::Add for &InnerEquipementStats { fn add(self, rhs: Self) -> Self::Output { InnerEquipementStats { - // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless id: add_to_vec!(self.id, rhs.id), name: add_to_vec!(self.name, rhs.name), rarity: self.rarity + rhs.rarity, @@ -74,8 +73,6 @@ impl std::ops::Add for &InnerEquipementStats { parry: self.parry + rhs.parry, speed: self.speed + rhs.speed, stealth: self.stealth + rhs.stealth, - // 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), @@ -93,8 +90,7 @@ impl std::ops::Add for SpecialField { fn add(self, rhs: Self) -> Self::Output { let mut c = self.clone(); - // TODO: Overcopy, kinda meaningless optimisation tho - c.0.append(&mut rhs.clone().0); + c.append(&mut rhs.clone()); c } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 4a99840..c767e34 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -57,7 +57,6 @@ pub struct IndividualElementsScenario { impl CrossRecipeScenario { /// Generate all the operations to be processed with the current config - // TODO: Defer this to a custom type in the config some sort of OperationSelector fn generate_selected_operation( &self, ) -> Result, FatalEquipementError> { diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index affad8a..8ad1f54 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -56,7 +56,7 @@ impl Default for Equipement { fn default() -> Self { Self { filter_function: FilterFunction::new(filter_id_unique()), - stats: InnerEquipementStats::random_new(), + stats: InnerEquipementStats::default(), } } } @@ -84,8 +84,8 @@ pub(crate) fn filter_id_unique_and_right_category() } } impl FilterFunction { - /// Generate a new filter - // TODO: This static lifetime is basically telling us that an owned value is needed + /// Generate and save a new filter, + /// the use of a static reference allows for reuse of a generic filter pub fn new(filter: &'static FilterFunctionType) -> Self { Self(Box::new(Rc::new(filter))) } @@ -136,9 +136,9 @@ pub struct InnerEquipementStats { } // TODO: This implementation of default is painfull -// TODO: Have either an auto-macro implementation or a manual one -// TODO: This implementation is Quasi-redondant -// TODO: Have a way to limit code duplication +// : Have either an auto-macro implementation or a manual one +// : This implementation is Quasi-redondant +// : Have a way to limit code duplication #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, FieldsAsSlice, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] @@ -233,43 +233,6 @@ impl Default for DatabaseEquipementStats { } } -#[allow(dead_code)] -/// A manually implemented hashmap of all values -#[doc(hidden)] -macro_rules! r { - () => { - fastrand::i8(1..20) - }; -} -// TODO: Make this a test requirement or hide it behind a profile -impl InnerEquipementStats { - /// Testing function to fuzz data - pub fn random_new() -> Self { - Self { - id: vec![r!() as u8], - range: (r!() - 10) as i16, - damage: r!() - 10, - p_damage: r!() - 10, - protection: r!() - 10, - ..Default::default() - } - } -} -// TODO: Make this a test requirement or hide it behind a profile -impl DatabaseEquipementStats { - /// Testing function to fuzz data - pub fn random_new() -> Self { - Self { - id: r!() as u8, - range: r!() - 19, - damage: r!() - 10, - p_damage: r!() - 10, - protection: r!() - 10, - ..Default::default() - } - } -} - /// Shape of the equipement, first mandatory part of an equipement #[derive(Default)] pub struct EqShape { @@ -327,7 +290,8 @@ impl From for EqFinishing { #[cfg(test)] mod test { use super::{ - EqFinishing, EqMaterial, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, + EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, + InnerEquipementStats, }; use crate::interfaces::RecipeCollection; @@ -352,9 +316,8 @@ mod test { #[test] fn test_creating_all_equipements() { let shape = vec![EqShape::default().into(), EqShape::default().into()]; - // Commented because of the generic nature and the from not a tryfrom - // TODO: Reinstate this part - // let nature = vec![EqNature::default().into(), EqNature::default().into()]; + + let _nature: Vec = vec![EqNature::default().into(), EqNature::default().into()]; let material = vec![EqMaterial::default().into(), EqMaterial::default().into()]; let finishing = vec![EqFinishing::default().into(), EqMaterial::default().into()]; -- 2.45.1 From b4933813909ed9665a5669dab3a0282a479b5332 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 4 Mar 2025 22:25:52 +0100 Subject: [PATCH 88/97] Removes a couple more todo --- weaponry/src/interfaces.rs | 4 +- .../src/weaponry_structs/equipement_fields.rs | 106 +++++++++--------- .../equipement_impl_basics.rs | 1 + .../equipement_impl_database.rs | 1 - .../weaponry_structs/equipement_structs.rs | 19 +--- weaponry/src/weaponry_structs/mod.rs | 5 + 6 files changed, 62 insertions(+), 74 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 99f5319..ba67fe1 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -152,7 +152,9 @@ pub(super) type FilterType = Box>>; #[derive(Clone)] /// A generic Filtering function -// TODO: Deref +// DONE: Not implementing deref and allowing for a super pub allows +// implementation to be a little more flexible, however this might +// also be an oversight pub(crate) struct FilterFunction(pub(super) FilterType); /// This element can be converted to tex diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index ace1a90..5780cbc 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -127,65 +127,65 @@ mod test { unimplemented!() } } -// TODO[!]: Implement all the soundness below +// // TODO[!]: Implement all the soundness below -/// The final enum of all categories to be given to the character sheet -/// -/// This enum is only created at the end of the refining process with all the given information -/// Note that some weapons might not be created or might be too niche to be created by the recipes -/// however the full cross implementation should cover all weapons or reconsider the validity of said implementation -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum FinalWeaponCategory { - Hast(HastSpecialties), - Slash(SlashSpecialties), - Blunt(BluntSpecialties), - Collosal(ColossalSpeciaties), - Ranged(RangedSpecialties), - Throw(ThrowSpecialties), -} +// /// The final enum of all categories to be given to the character sheet +// /// +// /// This enum is only created at the end of the refining process with all the given information +// /// Note that some weapons might not be created or might be too niche to be created by the recipes +// /// however the full cross implementation should cover all weapons or reconsider the validity of said implementation +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum FinalWeaponCategory { +// Hast(HastSpecialties), +// Slash(SlashSpecialties), +// Blunt(BluntSpecialties), +// Collosal(ColossalSpeciaties), +// Ranged(RangedSpecialties), +// Throw(ThrowSpecialties), +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum HastSpecialties { - Lance, - Staff, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum HastSpecialties { +// Lance, +// Staff, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum SlashSpecialties { - Sword, - #[deprecated] - Dagger, - Axe, - Claws, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum SlashSpecialties { +// Sword, +// #[deprecated] +// Dagger, +// Axe, +// Claws, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum BluntSpecialties { - Hammer, - Improvised, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum BluntSpecialties { +// Hammer, +// Improvised, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum ColossalSpeciaties { - Rhodarak, - Haroth, - Kahml, - Landscapper, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum ColossalSpeciaties { +// Rhodarak, +// Haroth, +// Kahml, +// Landscapper, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum RangedSpecialties { - Bow, - Crossbow, - Cannon, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum RangedSpecialties { +// Bow, +// Crossbow, +// Cannon, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum ThrowSpecialties { - Light, - Lances, - Improvised, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum ThrowSpecialties { +// Light, +// Lances, +// Improvised, +// } // TODO[4]: Have a final weapon category tied to the speciality, if any appliable to the character // : Since this is not needed for balencing, this will be left alone for a while @@ -214,7 +214,6 @@ pub enum EquipementSerializedCategory { /// Shield generic category, will be converted into EquipementSection Shields, /// A custom None category, used to forbid a part to be cast upon or from - // TODO: Check the soundness of this implementation None, /// Light size, will be converted to a WeaponBaseSize Light, @@ -240,7 +239,6 @@ pub enum WeaponBaseShape { Armors, Shields, Exotic, - // TODO[!]: Check the soundness of this, as it is not used currently None, } diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index aacec5e..f7ec799 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -30,6 +30,7 @@ impl From for Equipement { } } } + impl From for Equipement { fn from(val: EqMaterial) -> Self { Self { diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 27d2374..a1c06b0 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -164,7 +164,6 @@ fn get_sub_categories_from_serde(category: &str) -> Result (Some(WeaponBaseShape::Exotic), None), EquipementSerializedCategory::Armors => (Some(WeaponBaseShape::Armors), None), EquipementSerializedCategory::Shields => (Some(WeaponBaseShape::Shields), None), - // EquipementSerializedCategory::Weapons => todo!(), EquipementSerializedCategory::None => (Some(WeaponBaseShape::None), None), EquipementSerializedCategory::Light => (None, Some(WeaponBaseSize::Light)), EquipementSerializedCategory::Medium => (None, Some(WeaponBaseSize::Medium)), diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 8ad1f54..c7a5a86 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -25,23 +25,6 @@ pub struct InitialEquipementList { pub(super) inner: Vec, } -// impl InitialEquipementList { -// pub fn from_iter_with_intermediate( -// iterator: &mut dyn Iterator, -// ) -> Self -// where -// IntermediateType: Into, -// IntoEquipementType: Into, -// { -// Self { -// inner: iterator -// .into_iter() -// .map(|element| IntermediateType::from(element.into())) -// .collect(), -// } -// } -// } - /// The final equipement, obtained by combining all parts #[derive(Clone, Debug)] #[cfg_attr(test, derive(PartialEq))] @@ -78,7 +61,7 @@ pub(crate) fn filter_id_unique_and_right_category() (Some(a), Some(b)) => a.can_apply_onto(b), // TODO: Unsound to have a generic nature, this should be caught at serialisation // There is no target and the part about to be added is generic - (None, _) => true, // panic!("The EqNature about to be added cannot be generic"), + (None, _) => panic!("The EqNature about to be added cannot be generic"), (Some(_), None) => panic!("The part about to be added unto cannot be generic"), } } diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index c2280af..d03f50d 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -44,3 +44,8 @@ pub use equipement_fields::{ }; // Likely ? Final Re-Exports pub use equipement_scenario::CrossRecipeScenario; + +// // TODO[!]: Add a sensible prelude +// mod prelude{ + +// } -- 2.45.1 From 4f2bb22420a8800c2dfaa8488470fc2a130ebb39 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 5 Mar 2025 07:00:50 +0100 Subject: [PATCH 89/97] Code coverage (with some shenenigans) --- weaponry/src/database.rs | 17 ++--- weaponry/src/interfaces.rs | 13 ++-- weaponry/src/lib.rs | 1 + .../equipement_advanced_tools.rs | 73 ++++++++++++++++++- .../weaponry_structs/equipement_structs.rs | 6 +- 5 files changed, 89 insertions(+), 21 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index ac8ccac..755a68c 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -34,16 +34,13 @@ fn generate_select_query( table_name: &str, filter: Option<&str>, ) -> String { - format!( - "SELECT {} FROM {}{};", - T::attributes_slice() - .iter() - .map(|(k, _v)| k.to_owned()) - .collect::>() - .join(","), - table_name, - filter.map_or_else(String::default, |j| " WHERE ".to_string() + j) - ) + let fields = T::attributes_slice() + .iter() + .map(|(k, _v)| k.to_owned()) + .collect::>() + .join(","); + let filter = filter.map_or_else(String::default, |j| " WHERE ".to_string() + j); + format!("SELECT {} FROM {}{};", fields, table_name, filter) } /// Generate create table_name with fields as columns diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index ba67fe1..bdafb57 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -61,24 +61,25 @@ where /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection /// /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch + // #[coverage(off)] // Tarpaulin cannot deal with iter and long lines fn combine_all(&mut self, other: &G) where G: RecipeCollection, { self.assign_inner( self.ref_inner() - .iter() + .iter() // Iterate over every recipe .flat_map(|inner_recipes| { other - .ref_inner() - .iter() + .ref_inner() // Take a reference of recipe + .iter() // Iterate overe every recipe .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes)) .map(|external_recipes: &Self::Recipes| { inner_recipes.add_ref_to_self(external_recipes) }) - .collect::>() - }) - .collect::>(), + .collect::>() // Collect all a vector of recipe + }) // Flatten all the vector of recipes into a big vector + .collect::>(), // Updates the inner collection to the collected recipes ); } diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index 8d2e64e..e035bd5 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -2,6 +2,7 @@ // File: weaponry/src/lib.rs //! Weaponry module, handling all weaponry creation and analysis +#![feature(coverage_attribute)] #![feature(int_roundings)] #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![feature(iter_intersperse, generic_arg_infer)] diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index cec8a29..39d045b 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -81,7 +81,7 @@ pub(super) fn get_damage_with_simulation( precision: Precision(9), }, ]; - if value.speed >= 0 { + if (value.speed >= 5) || (value.range > 0) { turns.push(TurnInfo { actions, attacks, @@ -309,7 +309,10 @@ mod test { equipement_thin_types::{Actions, Attacks}, }; - use super::{BestDamageScenarios, Dices, Precision, binomial_dice_distribution}; + use super::{ + BestDamageScenarios, Dices, Precision, binomial_dice_distribution, + get_damage_with_simulation, + }; fn new_inner_eq() -> InnerEquipementStats { InnerEquipementStats { @@ -374,6 +377,7 @@ mod test { p_damage: 2, precision: 0, rmax: 2, + speed: 10, action_cost: 2, ..Default::default() }; @@ -382,6 +386,7 @@ mod test { p_damage: 2, precision: 0, rmax: 2, + range: 10, action_cost: 2, reload_cost: Some(2), ..Default::default() @@ -543,4 +548,68 @@ mod test { assert_close!(val.clone().map_or(0., |v| v.damage_done), res); }); } + + #[test] + fn test_scenario_damage() { + let eq1 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + action_cost: 2, + ..Default::default() + }; + let eq2 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + speed: 10, + action_cost: 2, + ..Default::default() + }; + let eq3 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + range: 10, + action_cost: 2, + reload_cost: Some(2), + ..Default::default() + }; + assert_close!( + get_damage_with_simulation(&eq1, Actions(2), Attacks(1)), + 8.3998 + ); + assert_close!( + get_damage_with_simulation(&eq2, Actions(2), Attacks(1)), + 9.6936 + ); + assert_close!( + get_damage_with_simulation(&eq3, Actions(2), Attacks(1)), + 9.6936 + ); + } + #[test] + fn test_basic_impl_damage_scenario() { + let eq1 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + action_cost: 2, + ..Default::default() + }; + let d1 = BestDamageScenarios::from_action_constraints_it( + &eq1, + Actions(2), + Attacks(2), + Dices(2), + Precision(2), + ) + .unwrap(); + let d2 = d1.clone() + d1; + let _deref_damage = *d2; + } } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index c7a5a86..0014d36 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -61,8 +61,8 @@ pub(crate) fn filter_id_unique_and_right_category() (Some(a), Some(b)) => a.can_apply_onto(b), // TODO: Unsound to have a generic nature, this should be caught at serialisation // There is no target and the part about to be added is generic - (None, _) => panic!("The EqNature about to be added cannot be generic"), - (Some(_), None) => panic!("The part about to be added unto cannot be generic"), + (None, _) => false, //panic!("The part about to be added cannot be generic"), + (Some(_), None) => false, //panic!("The part about to be added unto cannot be generic"), } } } @@ -300,7 +300,7 @@ mod test { fn test_creating_all_equipements() { let shape = vec![EqShape::default().into(), EqShape::default().into()]; - let _nature: Vec = vec![EqNature::default().into(), EqNature::default().into()]; + // let _nature: Vec = vec![EqNature::default().into(), EqNature::default().into()]; let material = vec![EqMaterial::default().into(), EqMaterial::default().into()]; let finishing = vec![EqFinishing::default().into(), EqMaterial::default().into()]; -- 2.45.1 From 5a84833922c8fe777c468ba6f9f82ad34594a5b9 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 5 Mar 2025 20:05:36 +0100 Subject: [PATCH 90/97] More code coverage --- weaponry/src/interfaces.rs | 12 ++++++++++++ .../src/weaponry_structs/equipement_advanced_repr.rs | 3 ++- weaponry/src/weaponry_structs/equipement_scenario.rs | 7 +++++++ weaponry/src/weaponry_structs/equipement_structs.rs | 3 +-- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index bdafb57..8589d89 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -316,3 +316,15 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList ) } } +#[cfg(test)] +mod test { + use super::RecipeCollection; + use crate::weaponry_structs::{InitialEquipementList, equipement_structs::EqShape}; + + #[test] + fn test_from_iter_intermediate() { + let _b = ::from_iter_intermediate::( + [Ok(EqShape::default()), Ok(EqShape::default())].into_iter(), + ); + } +} diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 7d593ff..87e6575 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -45,7 +45,8 @@ pub struct RefinedEquipement { /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements - inner: Vec, + // TODO[!]: The use of pub stays for the usage of the example showcasing the macro in export + pub inner: Vec, } // DONE: The use of Deref could be a subtle gotcha diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index c767e34..4c9b839 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -57,6 +57,7 @@ pub struct IndividualElementsScenario { impl CrossRecipeScenario { /// Generate all the operations to be processed with the current config + // TODO[!]: Consider adding to interface fn generate_selected_operation( &self, ) -> Result, FatalEquipementError> { @@ -134,3 +135,9 @@ impl Scenario for CrossRecipeScenario { &self.database } } + +#[cfg(test)] +mod test { + #[test] + fn test_scenario() {} +} diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 0014d36..29cc8c1 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -273,8 +273,7 @@ impl From for EqFinishing { #[cfg(test)] mod test { use super::{ - EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, - InnerEquipementStats, + EqFinishing, EqMaterial, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, }; use crate::interfaces::RecipeCollection; -- 2.45.1 From b85545559668a79d49e604cc63f67ec9b69e2e4b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 5 Mar 2025 20:28:08 +0100 Subject: [PATCH 91/97] adds xtask, lot of bloat tho ? --- .gitignore | 1 + Cargo.toml | 2 +- more_fields_macro/src/lib.rs | 2 ++ xtask/Cargo.toml | 7 +++++++ xtask/src/main.rs | 3 +++ 5 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 xtask/Cargo.toml create mode 100644 xtask/src/main.rs diff --git a/.gitignore b/.gitignore index deed149..13d712b 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ callgrind* cache.out tarpaulin-report.html *.bkp +coverage/ diff --git a/Cargo.toml b/Cargo.toml index b294bf4..0b4e538 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ [workspace] members = [ "cli_parser", "config", "graphs", "make", "more_fields", "more_fields_macro", "ravenous-tools", "stats", - "tablegen", "weaponry", + "tablegen", "weaponry", "xtask", ] resolver = "3" diff --git a/more_fields_macro/src/lib.rs b/more_fields_macro/src/lib.rs index 4bfca29..f133eaf 100644 --- a/more_fields_macro/src/lib.rs +++ b/more_fields_macro/src/lib.rs @@ -12,6 +12,7 @@ // use proc_macro::TokenStream; // use quote::quote; // use syn::{Data, DeriveInput, Fields, parse_macro_input}; +#![feature(coverage_attribute)] extern crate proc_macro; use proc_macro::{Span, TokenStream}; @@ -21,6 +22,7 @@ use syn::Ident; use syn::parse_macro_input; use syn::{Data, Fields}; +#[coverage(off)] #[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB))] pub fn derive_iterable(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 0000000..2cdf5a3 --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "xtask" +edition = "2024" +version.workspace = true + +[dependencies] +xtaskops = "0.4.2" diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 0000000..90528e7 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = xtaskops::tasks::main(); +} -- 2.45.1 From d7e7ffcb17af5e99a997daba20c7b0f935d7f313 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 6 Mar 2025 01:37:24 +0100 Subject: [PATCH 92/97] Cleanup and adds a Flow doc --- README.md | 2 +- make/src/lib.rs | 2 +- more_fields_macro/src/lib.rs | 10 +- weaponry/examples/graph.rs | 180 --------------- weaponry/examples/usage_import_tex.rs | 215 ------------------ weaponry/flow_and_structure.md | 40 ++++ weaponry/src/interfaces.rs | 4 +- .../src/weaponry_structs/equipement_fields.rs | 4 +- .../weaponry_structs/equipement_scenario.rs | 61 ++++- .../weaponry_structs/equipement_structs.rs | 2 +- 10 files changed, 104 insertions(+), 416 deletions(-) delete mode 100644 weaponry/examples/graph.rs delete mode 100644 weaponry/examples/usage_import_tex.rs create mode 100644 weaponry/flow_and_structure.md diff --git a/README.md b/README.md index 64c2c63..77ed0ed 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) +![version](badges/version.svg) ![code coverage](badges/plastic.svg) # ravenous-tools diff --git a/make/src/lib.rs b/make/src/lib.rs index bc35f63..2ecb392 100644 --- a/make/src/lib.rs +++ b/make/src/lib.rs @@ -2,7 +2,7 @@ // File: make/src/lib.rs //! The module `makepdf` is responsible for making a pdf using pdflatex. //! -//! The main function, [`make_pdf`](crate::makepdf::make_pdf), orchestrates the entire process of preparing, +//! The main function, [`make_pdf`], orchestrates the entire process of preparing, //! building, and cleaning up LaTeX files to produce a final PDF. It relies on several other modules //! within the `makepdf` workspace to perform specific tasks. //! diff --git a/more_fields_macro/src/lib.rs b/more_fields_macro/src/lib.rs index f133eaf..25ad5d2 100644 --- a/more_fields_macro/src/lib.rs +++ b/more_fields_macro/src/lib.rs @@ -1,13 +1,13 @@ // Workspace: more_fields_macro // File: more_fields_macro/src/lib.rs //! A very simple proc macro in chage of giving a field slice over ("name","sql_type") -//! This macro is a fork of the excellent work of : https://crates.io/crates/struct_iterable +//! This macro is a fork of the excellent work of : //! //! Other ressources include: -//! - https://github.com/rust-lang/reference/blob/master/src/procedural-macros.md#attribute-macros -//! - https://docs.rs/syn/latest/syn/struct.Attribute.html -//! - https://docs.rs/syn/latest/syn/struct.Attribute.html#parsing-from-tokens-to-attribute -//! - https://docs.rs/syn/latest/syn/struct.Ident.html +//! - +//! - +//! - +//! - //! // use proc_macro::TokenStream; // use quote::quote; diff --git a/weaponry/examples/graph.rs b/weaponry/examples/graph.rs deleted file mode 100644 index 053cb0a..0000000 --- a/weaponry/examples/graph.rs +++ /dev/null @@ -1,180 +0,0 @@ -// use charming::{ -// Chart, WasmRenderer, -// component::{Axis, Title}, -// element::AxisType, -// series::Line, -// }; -// use leptos::prelude::*; -// use leptos_use::use_interval_fn; -// use leptos_use::utils::Pausable; - -// #[component] -// fn App() -> impl IntoView { -// let data = RwSignal::new(vec![150, 230, 224, 218, 135, 147, 260]); -// let action = Action::new(move |_input: &()| { -// let local = data.get(); -// async move { -// let chart = Chart::new() -// .title(Title::new().text("Demo: Leptos + Charming")) -// .x_axis(Axis::new().type_(AxisType::Category).data(vec!["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])) -// .y_axis(Axis::new().type_(AxisType::Value)) -// .series(Line::new().data(local)); - -// let renderer = WasmRenderer::new(600, 400); -// renderer.render("chart", &chart).unwrap(); -// } -// }); - -// let Pausable { pause, resume, is_active: _ } = use_interval_fn( -// move || { -// data.update(|d| d.rotate_right(1)); -// action.dispatch(()); -// }, -// 1000, -// ); - -// action.dispatch(()); - -// view! { -//
-//
-// -// -//
-// } -// } - -// fn main() { -// mount_to_body(|| view! { }) -// } -use charming::{ - Chart, - component::{ - Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, - ToolboxDataZoom, VisualMap, VisualMapType, - }, - element::{AxisType, Tooltip, Trigger}, - series::Line, -}; -// use rand::Rng; - -pub fn chart() -> Chart { - let raw_data = vec![ - ("2000-06-05", 116), - ("2000-06-06", 129), - ("2000-06-07", 135), - ("2000-06-08", 86), - ("2000-06-09", 73), - ("2000-06-10", 85), - ("2000-06-11", 73), - ("2000-06-12", 68), - ("2000-06-13", 92), - ("2000-06-14", 130), - ("2000-06-15", 245), - ("2000-06-16", 139), - ("2000-06-17", 115), - ("2000-06-18", 111), - ("2000-06-19", 309), - ("2000-06-20", 206), - ("2000-06-21", 137), - ("2000-06-22", 128), - ("2000-06-23", 85), - ("2000-06-24", 94), - ("2000-06-25", 71), - ("2000-06-26", 106), - ("2000-06-27", 84), - ("2000-06-28", 93), - ("2000-06-29", 85), - ("2000-06-30", 73), - ("2000-07-01", 83), - ("2000-07-02", 125), - ("2000-07-03", 107), - ("2000-07-04", 82), - ("2000-07-05", 44), - ("2000-07-06", 72), - ("2000-07-07", 106), - ("2000-07-08", 107), - ("2000-07-09", 66), - ("2000-07-10", 91), - ("2000-07-11", 92), - ("2000-07-12", 113), - ("2000-07-13", 107), - ("2000-07-14", 131), - ("2000-07-15", 111), - ("2000-07-16", 64), - ("2000-07-17", 69), - ("2000-07-18", 88), - ("2000-07-19", 77), - ("2000-07-20", 83), - ("2000-07-21", 111), - ("2000-07-22", 57), - ("2000-07-23", 55), - ("2000-07-24", 60), - ]; - - let mut data_list = vec![]; - let mut value_list = vec![]; - - raw_data.into_iter().for_each(|(date, value)| { - data_list.push(date); - value_list.push(value); - }); - - Chart::new() - .title( - Title::new() - .text("Gradient along the y axis") - .left("center"), - ) - // .title(Title::new().text("Gradient along the x axis").left("center").top("55%")) - .tooltip(Tooltip::new().trigger(Trigger::Axis)) - .visual_map( - VisualMap::new() - .show(false) - .type_(VisualMapType::Continuous) - .series_index(0) - .min(0) - .max(400), - ) - // .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(1).dimension(0).min(0).max(10).max((data_list.len() - 1) as f64)) - .x_axis( - Axis::new() - .data(data_list.to_vec()) - .type_(AxisType::Category) - .boundary_gap(false), - ) - // .x_axis(Axis::new().data(data_list.to_vec()).grid_index(1)) - .y_axis(Axis::new()) - // .y_axis(Axis::new().grid_index(1)) - .grid(Grid::new()) - // .grid(Grid::new().top("60%")) - .series(Line::new().show_symbol(false).data(value_list.clone())) - .data_zoom( - DataZoom::new() - .type_(DataZoomType::Inside) - .start(0) - .end(100), - ) - .data_zoom(DataZoom::new().start(0).end(100)) - .toolbox( - Toolbox::new().feature( - Feature::new() - .data_zoom(ToolboxDataZoom::new().y_axis_index("none")) - .restore(Restore::new()) - .save_as_image(SaveAsImage::new()), - ), - ) - .tooltip(Tooltip::new().trigger(Trigger::Axis)) - // .series(Line::new().show_symbol(false).x_axis_index(1).y_axis_index(1).data(value_list)) -} - -fn main() { - let chart = chart(); - use charming::HtmlRenderer; - - let mut renderer = HtmlRenderer::new("MOOO", 1800, 1800).theme(charming::theme::Theme::Dark); - // // Render the chart as HTML string. - // let html_str = renderer.render(&chart).unwrap(); - // Save the chart as HTML file. - renderer.save(&chart, "./chart.html").unwrap(); -} diff --git a/weaponry/examples/usage_import_tex.rs b/weaponry/examples/usage_import_tex.rs deleted file mode 100644 index a8a4721..0000000 --- a/weaponry/examples/usage_import_tex.rs +++ /dev/null @@ -1,215 +0,0 @@ -// Workspace: weaponry -// File: examples/usage_import_tex.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/flow_and_structure.md b/weaponry/flow_and_structure.md new file mode 100644 index 0000000..d5cba4e --- /dev/null +++ b/weaponry/flow_and_structure.md @@ -0,0 +1,40 @@ +# Introduction +The generic nature of the recipe generator makes it rather complicated to navigate and comprehend; +however while suffering from many developpement mistakes and shortcommings, a good deal of code reuse was averted + +# Structure +The inner structures follow the following. + +| Underlaying data | Encapsulating Element | Encapsulating list of elements | +|-----------------------|----------------------------|--------------------------------| +| DatabaseInner (DeSer) | None | None | +| BaseInner (Converted) | InitialElement | InitialElementList | +| AdvancedInner (Calc) | RefinedElement (+BaseInner)| RefinedElementList | + + +# Explainations +| Category | Explainations | Traits | Impls | +|---------------------|------------------------------|----------------------------------------|------------------------| +| DatabaseInner | Deserialization InnerData | FieldsAsSclice | DatabaseEquipementStats| +| BaseInner | BuildingBlock InnerData | FieldAsSlice, Add, From | InnerEquipementStats | +| AdvancedInner | Calculated data for analysis | Serialize, From | AdvancedStats | +| IntermediateElement | Setup InitialElement | | EqFinishing, etc.. | +| InitialElement | Real Elements by Combination | From, Combinable | Equipement | +| RefinedElement | Export & Analysis | Serialize | RefinedEquipement | +| InitialElementList | Create list by cross combin. | RecipeCollection | InitialEquipementList | +| RefinedElementList | Analysis & Export | From) -> Self; - /// Create a collection from an iterator of intermediate values + /// Create a collection from an iterator of intermediate values T fn from_iter_intermediate( iter_inter: impl Iterator>, ) -> Result @@ -302,7 +302,7 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList /// Automatically deserialize into an equipement - fn deserde_into_equipement( + fn deserde_into_processed_representation( &self, filter: Option<&str>, ) -> Result diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 5780cbc..e3924e7 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -58,7 +58,7 @@ pub enum PhysicalDamageType { /// Weapon damage, combining the base weapon damage type and it's level /// -/// Signifying wether the damage is pure or [secondary] or [[tertiary]] +/// Signifying wether the damage is pure or \[secondary\] or \[\[tertiary\]\] #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Display, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] @@ -85,7 +85,7 @@ impl Deref for DamageType { } impl DamageType { - /// Create a new DamageType from a vector of [DamageMod] + /// Create a new DamageType from a vector of *DamageMod* pub fn new(inner_data: Vec) -> Self { Self(inner_data) } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 4c9b839..d228346 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -63,24 +63,27 @@ impl CrossRecipeScenario { ) -> Result, FatalEquipementError> { let mut operations = Vec::with_capacity(8); if self.config.shape.is_some() { - operations - .push(self.deserde_into_equipement::(Some("META_CATEGORY LIKE 'Shape'"))?); + operations.push(self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE 'Shape'", + ))?); } if let Some(qt) = self.config.materials { for _ in 0..qt { - operations.push(self.deserde_into_equipement::(Some( - "META_CATEGORY LIKE 'Materials'", - ))?); + operations.push( + self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE 'Materials'", + ))?, + ); } } if self.config.nature.is_some() { - operations.push( - self.deserde_into_equipement::(Some("META_CATEGORY LIKE 'Nature'"))?, - ); + operations.push(self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE 'Nature'", + ))?); } if self.config.finishing.is_some() { operations.push( - self.deserde_into_equipement::(Some( + self.deserde_into_processed_representation::(Some( "META_CATEGORY LIKE 'Finishing'", ))?, ); @@ -138,6 +141,46 @@ impl Scenario for CrossRecipeScenario { #[cfg(test)] mod test { + use more_fields::FieldsAsSlice; + + use crate::{ + interfaces::{RecipeDatabase, Scenario}, + weaponry_structs::{ + equipement_impl_database::EquipementDatabase, + equipement_structs::{DatabaseEquipementStats, EqFinishing, InnerEquipementStats}, + }, + }; + + use super::{ConfigEquipementScenario, CrossRecipeScenario}; + + struct TestStruct { + id: usize, + name: String, + } #[test] fn test_scenario() {} + #[test] + fn test_deserde_into() { + let b = CrossRecipeScenario { + database: EquipementDatabase { + conn: rusqlite::Connection::open_in_memory().unwrap(), + }, + config: ConfigEquipementScenario { + table_name: "TestStruct".to_owned(), + db_path: "None".to_owned(), + shape: None, + materials: None, + nature: None, + finishing: None, + }, + }; + + b.get_database().conn.execute("CREATE TABLE IF NOT EXISTS Finishing (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",[]).unwrap(); + b.get_database() + .initialize_empty_table::("Finishing") + .unwrap(); + // let r = b + // .deserde_into_processed_representation::(None) + // .unwrap(); + } } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 29cc8c1..28891e6 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -104,7 +104,7 @@ pub struct InnerEquipementStats { /// /// The categories are: Staves, Blunt, Slash, Ranged, Armors, Shields, Exotic, None, pub category_base: Option, - /// The category size as [WeaponBaseSize] + /// The category size as WeaponBaseSize /// /// Categories are : (Light, Medium, Heavy and SuperHeavy) pub category_size: Option, -- 2.45.1 From fadd82ff3b38a80dffeb12bde44306e05517105c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 6 Mar 2025 04:43:37 +0100 Subject: [PATCH 93/97] Updates coverage --- Cargo.toml | 4 +- README.md | 2 +- badges/coverage.svg | 2 +- weaponry/Cargo.toml | 3 ++ weaponry/src/database.rs | 18 +++++--- weaponry/src/error.rs | 3 ++ weaponry/src/interfaces.rs | 45 ++++++++++++++++--- .../equipement_impl_advanced.rs | 1 + .../equipement_impl_database.rs | 34 +++----------- .../weaponry_structs/equipement_impl_math.rs | 20 +++++++++ .../weaponry_structs/equipement_scenario.rs | 25 ++++++----- .../weaponry_structs/equipement_thin_types.rs | 16 +++++++ xtask/Cargo.toml | 7 --- xtask/src/main.rs | 3 -- 14 files changed, 115 insertions(+), 68 deletions(-) delete mode 100644 xtask/Cargo.toml delete mode 100644 xtask/src/main.rs diff --git a/Cargo.toml b/Cargo.toml index 0b4e538..3d16c47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ [workspace] members = [ "cli_parser", "config", "graphs", "make", "more_fields", "more_fields_macro", "ravenous-tools", "stats", - "tablegen", "weaponry", "xtask", + "tablegen", "weaponry", ] resolver = "3" @@ -31,5 +31,3 @@ lto = false codegen-units = 256 incremental = true panic = "abort" - - diff --git a/README.md b/README.md index 77ed0ed..4c10907 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![version](badges/version.svg) ![code coverage](badges/plastic.svg) +![version](badges/version.svg) ![code coverage](badges/coverage.svg) # ravenous-tools diff --git a/badges/coverage.svg b/badges/coverage.svg index 950fe17..c78d807 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 17%test-coverage17% +test-coverage: 23%test-coverage23% diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index b1a596a..43e3a6f 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -28,3 +28,6 @@ clap = { version = "4.5.30", features = ["derive"] } [[bench]] name = "iter_creation" harness = false + +# [lints.rust] +# unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] } diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 755a68c..5f5c048 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -30,17 +30,21 @@ where /// Generate a SELECT query with fields generated from a struct. Returns a SQL request as a String #[inline] +#[coverage(off)] // INCORRECT: Error with line report fn generate_select_query( table_name: &str, filter: Option<&str>, ) -> String { - let fields = T::attributes_slice() - .iter() - .map(|(k, _v)| k.to_owned()) - .collect::>() - .join(","); - let filter = filter.map_or_else(String::default, |j| " WHERE ".to_string() + j); - format!("SELECT {} FROM {}{};", fields, table_name, filter) + format!( + "SELECT {} FROM {}{};", + T::attributes_slice() + .iter() + .map(|(k, _v)| k.to_owned()) + .collect::>() + .join(","), + table_name, + filter.map_or_else(String::default, |j| " WHERE ".to_string() + j) + ) } /// Generate create table_name with fields as columns diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index d2396e7..ffc4737 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -42,6 +42,9 @@ pub enum FatalEquipementError { #[error("Couldn't parse the CLI argument given \"{0}\"")] CLIParseError(String), + + #[error("Couldn't serialize the object to make a query: \n{0}")] + SerdeRSQLite(#[from] serde_rusqlite::Error), } // #[derive(Error, Debug)] diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index c9be6bf..f442d08 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -9,7 +9,7 @@ use std::{path::Path, rc::Rc}; use more_fields::FieldsAsSlice; use rusqlite::Connection; -use serde::de::DeserializeOwned; +use serde::{Serialize, de::DeserializeOwned}; use crate::error::FatalEquipementError; @@ -95,6 +95,7 @@ where fn from_vectored(list: Vec) -> Self; /// Create a collection from an iterator of intermediate values T + #[coverage(off)] // INCORRECT: Error with line report fn from_iter_intermediate( iter_inter: impl Iterator>, ) -> Result @@ -218,18 +219,50 @@ pub trait RecipeDatabase { fn get_connection(&self) -> &Connection; /// Initialize an empty database & table - fn initialize_empty_table( + fn initialize_empty_table( &self, table: &str, - ) -> Result<(), FatalEquipementError>; + ) -> Result<(), crate::error::FatalEquipementError> { + // A vector of + self.get_connection().execute( + crate::database::generate_create_table_query(table, T::attributes_slice()).as_str(), + (), + )?; + Ok(()) + } /// Insert a row inside the database, while mostly unused this function is needed to initialize the empty table with an empty row if needed - fn insert_row(&self, row: T) -> Result<(), FatalEquipementError>; + #[coverage(off)] // INCORRECT: Error with line report + fn insert_row( + &self, + table_name: &str, + row: T, + ) -> Result<(), FatalEquipementError> { + let query = format!( + "INSERT INTO {} ({}) VALUES ({});", + table_name, + T::attributes_slice() + .iter() + .map(|(k, _v)| *k) + .collect::>() + .join(","), + T::attributes_slice() + .iter() + .map(|(k, _v)| ":".to_owned() + *k) + .collect::>() + .join(","), + ); + self.get_connection().execute( + &query, + serde_rusqlite::to_params_named(row)?.to_slice().as_slice(), + )?; + Ok(()) + } /// Serialize a request into an intermediate T representation, /// T having all the implementation specifics of the part in details /// eg. EqShape, EqPart etc.. - fn serialise_into_intermediate( + fn serialize_into_intermediate( &self, table: &str, filter: Option<&str>, @@ -312,7 +345,7 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList { RecipeCollection::from_iter_intermediate::( self.get_database() - .serialise_into_intermediate::(self.get_tablename(), filter)?, + .serialize_into_intermediate::(self.get_tablename(), filter)?, ) } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_advanced.rs b/weaponry/src/weaponry_structs/equipement_impl_advanced.rs index cf2e3a5..6fa4647 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_advanced.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_advanced.rs @@ -18,6 +18,7 @@ impl Default for FilterFunction { } } impl PartialEq for FilterFunction { + #[coverage(off)] // INCORRECT: Error with line report fn eq(&self, _other: &Self) -> bool { true } diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index a1c06b0..790f309 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -2,19 +2,12 @@ // File: weaponry/src/weaponry_structs/equipement_impl_database.rs //! All database specific implementations -// use crate::interfaces::DbSerializable; - -// use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; - -use crate::database::generate_create_table_query; -use crate::error::FatalEquipementError; -use crate::interfaces::{FixedRecipe, RecipeDatabase}; -use rusqlite::Connection; -use serde::de::DeserializeOwned; - use super::EquipementSerializedCategory; use super::equipement_fields::{WeaponBaseShape, WeaponBaseSize}; use super::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; +use crate::error::FatalEquipementError; +use crate::interfaces::{FixedRecipe, RecipeDatabase}; +use rusqlite::Connection; /// Struct for database connection. #[derive(Debug)] @@ -27,34 +20,18 @@ impl RecipeDatabase for EquipementDatabase { type DeserialisationType = DatabaseEquipementStats; type InnerType = InnerEquipementStats; - /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. fn new(filename: &str) -> Result { Ok(EquipementDatabase { conn: Connection::open(filename)?, }) } - fn initialize_empty_table( - &self, - table: &str, - ) -> Result<(), crate::error::FatalEquipementError> { - // A vector of - let attr_map = T::attributes_slice(); - self.conn - .execute(generate_create_table_query(table, attr_map).as_str(), ())?; - Ok(()) - } - - fn insert_row(&self, row: T) -> Result<(), FatalEquipementError> { - let _ = row; - todo!() - } - fn get_connection(&self) -> &Connection { &self.conn } - fn serialise_into_intermediate( + #[coverage(off)] // INCORRECT: Error with line report + fn serialize_into_intermediate( &self, table: &str, filter: Option<&str>, @@ -154,6 +131,7 @@ impl TryFrom for InnerEquipementStats { type SubCategories = (Option, Option); /// Infer all subcategories from a deserialized DatabaseCategory +#[coverage(off)] // A test would literally be a copy paste of this match fn get_sub_categories_from_serde(category: &str) -> Result { Ok(if let Some(category) = from_serde!(category)? { match category { diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index ae883ac..32ad6f3 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -94,3 +94,23 @@ impl std::ops::Add for SpecialField { c } } + +#[cfg(test)] +mod test { + #[test] + fn test_macros() { + assert_eq!(first_correct_option!(None::, None::), None); + assert_eq!(first_correct_option!(Some(3), None::), Some(3)); + assert_eq!(first_correct_option!(None::, Some(4)), Some(4)); + assert_eq!(first_correct_option!(Some(1), Some(3)), Some(1)); + + assert_eq!(add_two_options!(Some(1), Some(3)), Some(4)); + assert_eq!(add_two_options!(Some(3), None::), Some(3)); + assert_eq!(add_two_options!(None::, Some(4)), Some(4)); + + let a = vec![1, 2]; + let b = vec![3]; + + assert_eq!(add_to_vec!(a, b), vec![1, 2, 3]); + } +} diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index d228346..1722064 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -141,22 +141,16 @@ impl Scenario for CrossRecipeScenario { #[cfg(test)] mod test { - use more_fields::FieldsAsSlice; - use crate::{ interfaces::{RecipeDatabase, Scenario}, weaponry_structs::{ equipement_impl_database::EquipementDatabase, - equipement_structs::{DatabaseEquipementStats, EqFinishing, InnerEquipementStats}, + equipement_structs::{DatabaseEquipementStats, EqFinishing}, }, }; use super::{ConfigEquipementScenario, CrossRecipeScenario}; - struct TestStruct { - id: usize, - name: String, - } #[test] fn test_scenario() {} #[test] @@ -166,7 +160,7 @@ mod test { conn: rusqlite::Connection::open_in_memory().unwrap(), }, config: ConfigEquipementScenario { - table_name: "TestStruct".to_owned(), + table_name: "Finishing".to_owned(), db_path: "None".to_owned(), shape: None, materials: None, @@ -175,12 +169,19 @@ mod test { }, }; - b.get_database().conn.execute("CREATE TABLE IF NOT EXISTS Finishing (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",[]).unwrap(); b.get_database() .initialize_empty_table::("Finishing") .unwrap(); - // let r = b - // .deserde_into_processed_representation::(None) - // .unwrap(); + b.get_database() + .insert_row::( + "Finishing", + DatabaseEquipementStats::random_new(), + ) + .unwrap(); + ::get_database(&b); + let r = b + .deserde_into_processed_representation::(None) + .unwrap(); + assert_eq!(r.inner.len(), 1); } } diff --git a/weaponry/src/weaponry_structs/equipement_thin_types.rs b/weaponry/src/weaponry_structs/equipement_thin_types.rs index 201ce45..ce834cf 100644 --- a/weaponry/src/weaponry_structs/equipement_thin_types.rs +++ b/weaponry/src/weaponry_structs/equipement_thin_types.rs @@ -102,3 +102,19 @@ impl Display for Dices { ::fmt(&self.0, f) } } + +#[cfg(test)] +mod test { + use crate::weaponry_structs::equipement_thin_types::{Actions, Attacks, Dices, Precision}; + + #[test] + fn test_displays() { + println!( + "{}, {}, {}, {}", + Attacks(0), + Actions(1), + Precision(2), + Dices(3) + ); + } +} diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml deleted file mode 100644 index 2cdf5a3..0000000 --- a/xtask/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "xtask" -edition = "2024" -version.workspace = true - -[dependencies] -xtaskops = "0.4.2" diff --git a/xtask/src/main.rs b/xtask/src/main.rs deleted file mode 100644 index 90528e7..0000000 --- a/xtask/src/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - let _ = xtaskops::tasks::main(); -} -- 2.45.1 From 3b94b71782af0a8b490cd2f70abde303f27f1d0a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 21 Mar 2025 12:40:53 -0500 Subject: [PATCH 94/97] Cleanup --- .run_status.toml | 8 + badges/coverage.svg | 2 +- weaponry/.run_status.toml | 8 + weaponry/src/lib.rs | 1 - weaponry/src/strategy.rs | 54 ------- .../equipement_impl_advanced.rs | 37 ----- .../equipement_impl_basics.rs | 144 +++++++++++++++++- .../weaponry_structs/equipement_impl_io.rs | 2 + .../weaponry_structs/equipement_impl_math.rs | 116 -------------- .../src/weaponry_structs/equipement_views.rs | 29 ---- weaponry/src/weaponry_structs/mod.rs | 3 - 11 files changed, 157 insertions(+), 247 deletions(-) create mode 100644 .run_status.toml create mode 100644 weaponry/.run_status.toml delete mode 100644 weaponry/src/strategy.rs delete mode 100644 weaponry/src/weaponry_structs/equipement_impl_advanced.rs delete mode 100644 weaponry/src/weaponry_structs/equipement_impl_math.rs delete mode 100644 weaponry/src/weaponry_structs/equipement_views.rs diff --git a/.run_status.toml b/.run_status.toml new file mode 100644 index 0000000..d94ea54 --- /dev/null +++ b/.run_status.toml @@ -0,0 +1,8 @@ +[last_run_clean] +run_status = "Success" +lines_parsed = 133 +coverage = 23.38 + +[last_run_clean.run_duration] +secs = 66 +nanos = 917039211 diff --git a/badges/coverage.svg b/badges/coverage.svg index c78d807..b1210c9 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 23%test-coverage23% +test-coverage: 23%test-coverage23% diff --git a/weaponry/.run_status.toml b/weaponry/.run_status.toml new file mode 100644 index 0000000..4ac0f3f --- /dev/null +++ b/weaponry/.run_status.toml @@ -0,0 +1,8 @@ +[last_run_clean] +run_status = "Success" +lines_parsed = 57 +coverage = 60.03 + +[last_run_clean.run_duration] +secs = 19 +nanos = 961545465 diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index e035bd5..840bc6c 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -11,7 +11,6 @@ mod database; pub mod error; pub mod export; pub mod interfaces; -mod strategy; pub mod weaponry_structs; /// Signals the function running is unfinished diff --git a/weaponry/src/strategy.rs b/weaponry/src/strategy.rs deleted file mode 100644 index a19727f..0000000 --- a/weaponry/src/strategy.rs +++ /dev/null @@ -1,54 +0,0 @@ -// Workspace: weaponry -// File: weaponry/src/strategy.rs -//! All different algorythms and strategies to create a weapon -//! -//! These strategies can lock a parameter to allow a more fine tuned balancing -//! or balancing specifically one parameter (balancing materials, balencing finishes etc..) -//! These strategies must take into account the level of the fighter (hence his precision) and of the craftsman (hence a difficulty diminution) -//! -// #![allow(dead_code)] - -// /// Generation strategy, how to generate all the data, instead of a full permutation -// pub enum EquipementStrategy { -// /// Full permutation, generate all possible outcomes -// GenerateAll, -// /// Generate all the named equipements -// GenerateNamed, -// /// Do not add finishing touches -// NoFinishes, -// } - -// /// Which material to select -// pub enum MaterialsStrategy { -// /// Add all materials to the mix -// AllMaterials, -// /// Add only tier one material -// OnlyTier1, -// /// Add only easy materials -// OnlyEasy, -// /// Add only cheap materials -// OnlyCheap, -// /// Add only one material -// OnlyOne, -// } - -// /// Filter to apply after the generation -// pub enum EquipementFilter { -// /// Don't filter anything -// All, -// /// Filter all outliers -// Outiliers, -// /// Filter in all the named -// Named, -// } - -// #[cfg(test)] -// mod test { -// // use super::*; - -// #[test] -// fn test_naive_generator() { -// // let t = naive_generation(vec![1, 2, 3], vec![5, 6, 7]); -// // assert_eq!(t.len(), 3 * 3); -// } -// } diff --git a/weaponry/src/weaponry_structs/equipement_impl_advanced.rs b/weaponry/src/weaponry_structs/equipement_impl_advanced.rs deleted file mode 100644 index 6fa4647..0000000 --- a/weaponry/src/weaponry_structs/equipement_impl_advanced.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Workspace: weaponry -// File: weaponry/src/weaponry_structs/equipement_impl_advanced.rs -//! Advanced implementation, reserved for traits and impls that are implemented only once on the main equipement and it's helper -//! -//! These impls are here to either prettify output, or allow for smoother implementation of other traits and inner workings - -use crate::interfaces::FilterFunction; -use std::{fmt::Debug, rc::Rc}; - -impl Debug for FilterFunction { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "Filter:{}", std::any::type_name::()) - } -} -impl Default for FilterFunction { - fn default() -> Self { - FilterFunction(Box::new(Rc::new(|_, _| true))) - } -} -impl PartialEq for FilterFunction { - #[coverage(off)] // INCORRECT: Error with line report - fn eq(&self, _other: &Self) -> bool { - true - } -} - -#[cfg(test)] -mod test { - use crate::{interfaces::FilterFunction, weaponry_structs::Equipement}; - - #[test] - fn test_filter_weapons() { - let _ = format!("{:?}", FilterFunction::::default()); - let r = FilterFunction::::new(&|_, _| false) == FilterFunction::default(); - assert!(r); - } -} diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index f7ec799..01f4383 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -8,17 +8,20 @@ //! Implementations to transform all Specialized equipement into a generic Equipement //! A specific implementation could be preferable, but this simplicity might allow for easier developpement -use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; -use std::fmt::Display; - +use super::equipement_structs::InnerEquipementStats; use crate::interfaces::{FilterFunction, Reportable}; +use crate::weaponry_structs::{SpecialField, WeaponBaseShape}; +use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; +use std::{ + fmt::{Debug, Display}, + rc::Rc, +}; use super::{ Equipement, InitialEquipementList, equipement_advanced_repr::RefinedEquipementList, equipement_structs::{ - EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats, - filter_id_unique_and_right_category, + EqFinishing, EqMaterial, EqNature, EqShape, filter_id_unique_and_right_category, }, }; @@ -176,10 +179,116 @@ impl Reportable for RefinedEquipementList { } } +impl Debug for FilterFunction { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Filter:{}", std::any::type_name::()) + } +} +impl Default for FilterFunction { + fn default() -> Self { + FilterFunction(Box::new(Rc::new(|_, _| true))) + } +} +impl PartialEq for FilterFunction { + #[coverage(off)] // INCORRECT: Error with line report + fn eq(&self, _other: &Self) -> bool { + true + } +} + +/// Add a new vector to a clone of a inner field +macro_rules! add_to_vec { + ($self: expr, $rhs: expr) => {{ + let mut new = $self.clone(); + new.append(&mut $rhs.clone()); + new + }}; +} + +/// Adds either of the vectors or merge them +macro_rules! add_two_options { + ($self: expr, $rhs: expr) => {{ + match ($self.as_ref(), $rhs.as_ref()) { + (None, None) => None, + (None, Some(a)) => Some(a.clone()), + (Some(a), None) => Some(a.clone()), + (Some(a), Some(b)) => Some(a.clone() + b.clone()), + } + }}; +} + +/// Clones the first option that has some data +macro_rules! first_correct_option { + ($self:expr, $rhs:expr) => { + match ($self.as_ref(), $rhs.as_ref()) { + (Some(a), _) => Some(a.clone()), + (_, Some(b)) => Some(b.clone()), + _ => None, + } + }; +} + +impl std::ops::Add for &InnerEquipementStats { + type Output = InnerEquipementStats; + + fn add(self, rhs: Self) -> Self::Output { + InnerEquipementStats { + id: add_to_vec!(self.id, rhs.id), + name: add_to_vec!(self.name, rhs.name), + rarity: self.rarity + rhs.rarity, + cost: self.cost + rhs.cost, + difficulty: self.difficulty + rhs.difficulty, + tier: self.tier + rhs.tier, + damage: self.damage + rhs.damage, + p_damage: self.p_damage + rhs.p_damage, + precision: self.precision + rhs.precision, + rmax: self.rmax + rhs.rmax, + armor_break: self.armor_break + rhs.armor_break, + armor_pierce: { + if self.armor_pierce > 0 + || matches!(self.category_base, Some(WeaponBaseShape::Ranged)) + { + self.armor_pierce + rhs.armor_pierce + } else { + 0 + } + }, + antimaterial: self.antimaterial + rhs.antimaterial, + damage_type: add_two_options!(self.damage_type, rhs.damage_type), + protection: self.protection + rhs.protection, + integrity: self.integrity + rhs.integrity, + 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, + 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, + agility_bonus: self.agility_bonus + rhs.agility_bonus, + category_base: first_correct_option!(self.category_base, rhs.category_base), + category_size: first_correct_option!(self.category_size, rhs.category_size), + target_category: first_correct_option!(self.target_category, rhs.target_category), + } + } +} + +impl std::ops::Add for SpecialField { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + let mut c = self.clone(); + c.append(&mut rhs.clone()); + c + } +} + #[cfg(test)] mod test { use crate::{ - interfaces::{RecipeCollection, Reportable}, + interfaces::{FilterFunction, RecipeCollection, Reportable}, weaponry_structs::{ Equipement, InitialEquipementList, equipement_advanced_repr::RefinedEquipementList, @@ -187,6 +296,12 @@ mod test { }, }; + #[test] + fn test_filter_weapons() { + let _ = format!("{:?}", FilterFunction::::default()); + let r = FilterFunction::::new(&|_, _| false) == FilterFunction::default(); + assert!(r); + } #[allow(dead_code)] /// A manually implemented hashmap of all values #[doc(hidden)] @@ -238,4 +353,21 @@ mod test { println!("{}", feqlist.get_report(None)); println!("{}", eqlist.get_report(None)); } + + #[test] + fn test_macros() { + assert_eq!(first_correct_option!(None::, None::), None); + assert_eq!(first_correct_option!(Some(3), None::), Some(3)); + assert_eq!(first_correct_option!(None::, Some(4)), Some(4)); + assert_eq!(first_correct_option!(Some(1), Some(3)), Some(1)); + + assert_eq!(add_two_options!(Some(1), Some(3)), Some(4)); + assert_eq!(add_two_options!(Some(3), None::), Some(3)); + assert_eq!(add_two_options!(None::, Some(4)), Some(4)); + + let a = vec![1, 2]; + let b = vec![3]; + + assert_eq!(add_to_vec!(a, b), vec![1, 2, 3]); + } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs index 9c12248..4db5645 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -16,6 +16,8 @@ impl ToCSV for RefinedEquipementList { } } +// impl To + #[cfg(test)] mod test { // use super::*; diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs deleted file mode 100644 index 32ad6f3..0000000 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ /dev/null @@ -1,116 +0,0 @@ -// Workspace: weaponry -// File: weaponry/src/weaponry_structs/equipement_math.rs -//! Implements base math for each field -//! - -use super::equipement_structs::InnerEquipementStats; -use crate::weaponry_structs::{SpecialField, WeaponBaseShape}; - -/// Add a new vector to a clone of a inner field -macro_rules! add_to_vec { - ($self: expr, $rhs: expr) => {{ - let mut new = $self.clone(); - new.append(&mut $rhs.clone()); - new - }}; -} - -/// Adds either of the vectors or merge them -macro_rules! add_two_options { - ($self: expr, $rhs: expr) => {{ - match ($self.as_ref(), $rhs.as_ref()) { - (None, None) => None, - (None, Some(a)) => Some(a.clone()), - (Some(a), None) => Some(a.clone()), - (Some(a), Some(b)) => Some(a.clone() + b.clone()), - } - }}; -} - -/// Clones the first option that has some data -macro_rules! first_correct_option { - ($self:expr, $rhs:expr) => { - match ($self.as_ref(), $rhs.as_ref()) { - (Some(a), _) => Some(a.clone()), - (_, Some(b)) => Some(b.clone()), - _ => None, - } - }; -} - -impl std::ops::Add for &InnerEquipementStats { - type Output = InnerEquipementStats; - - fn add(self, rhs: Self) -> Self::Output { - InnerEquipementStats { - id: add_to_vec!(self.id, rhs.id), - name: add_to_vec!(self.name, rhs.name), - rarity: self.rarity + rhs.rarity, - cost: self.cost + rhs.cost, - difficulty: self.difficulty + rhs.difficulty, - tier: self.tier + rhs.tier, - damage: self.damage + rhs.damage, - p_damage: self.p_damage + rhs.p_damage, - precision: self.precision + rhs.precision, - rmax: self.rmax + rhs.rmax, - armor_break: self.armor_break + rhs.armor_break, - armor_pierce: { - if self.armor_pierce > 0 - || matches!(self.category_base, Some(WeaponBaseShape::Ranged)) - { - self.armor_pierce + rhs.armor_pierce - } else { - 0 - } - }, - antimaterial: self.antimaterial + rhs.antimaterial, - damage_type: add_two_options!(self.damage_type, rhs.damage_type), - protection: self.protection + rhs.protection, - integrity: self.integrity + rhs.integrity, - 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, - 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, - agility_bonus: self.agility_bonus + rhs.agility_bonus, - category_base: first_correct_option!(self.category_base, rhs.category_base), - category_size: first_correct_option!(self.category_size, rhs.category_size), - target_category: first_correct_option!(self.target_category, rhs.target_category), - } - } -} - -impl std::ops::Add for SpecialField { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - let mut c = self.clone(); - c.append(&mut rhs.clone()); - c - } -} - -#[cfg(test)] -mod test { - #[test] - fn test_macros() { - assert_eq!(first_correct_option!(None::, None::), None); - assert_eq!(first_correct_option!(Some(3), None::), Some(3)); - assert_eq!(first_correct_option!(None::, Some(4)), Some(4)); - assert_eq!(first_correct_option!(Some(1), Some(3)), Some(1)); - - assert_eq!(add_two_options!(Some(1), Some(3)), Some(4)); - assert_eq!(add_two_options!(Some(3), None::), Some(3)); - assert_eq!(add_two_options!(None::, Some(4)), Some(4)); - - let a = vec![1, 2]; - let b = vec![3]; - - assert_eq!(add_to_vec!(a, b), vec![1, 2, 3]); - } -} diff --git a/weaponry/src/weaponry_structs/equipement_views.rs b/weaponry/src/weaponry_structs/equipement_views.rs deleted file mode 100644 index a5c4ec4..0000000 --- a/weaponry/src/weaponry_structs/equipement_views.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Workspace: weaponry -// File: weaponry/src/weaponry_structs/equipement_views.rs -//! Implement the view trait to allow for a list of "Points of Interest" to be created -//! This list is imperative to allow several criterias to be looked up one after the other to gather as many points of data as possible -//! -//! It is mandatory that these points of interest link back to the original data by index and not by reference, to allow this operation to be thread safe -// TODO[3]: Consider deletion of this module and the associated view table - -#![allow(dead_code)] - -use crate::interfaces::ViewTable; - -use super::equipement_advanced_repr::RefinedEquipementList; - -/// A rather full view of an equipement, this multi field allow for a great amount of different operations but incurrs a rather hefty calculation price -struct EquipementFullView {} - -impl ViewTable for EquipementFullView { - type InterestElementList = RefinedEquipementList; - - fn index_of_interest_points(&self) -> Vec { - todo!() - } - - fn find_points_of_interest(representation: &Self::InterestElementList) -> Self { - let _ = representation; - todo!() - } -} diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index d03f50d..c35a0a7 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -18,16 +18,13 @@ mod equipement_advanced_repr; mod equipement_advanced_tools; mod equipement_fields; -mod equipement_impl_advanced; mod equipement_impl_basics; pub mod equipement_impl_database; mod equipement_impl_io; mod equipement_impl_logic; -mod equipement_impl_math; pub mod equipement_scenario; pub mod equipement_structs; pub mod equipement_thin_types; -mod equipement_views; // Republishes the most used symbols // All generic structs -- 2.45.1 From 30057dd7cfcf4b0c3213a1de5ec5d0ba2b61e945 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 22 Mar 2025 10:34:12 -0500 Subject: [PATCH 95/97] Adds a part of CLI & export --- .run_status.toml | 8 +- badges/coverage.svg | 2 +- cli_parser/src/lib.rs | 14 +- config/src/analysis.rs | 54 ++++++ config/src/lib.rs | 1 + helper_config.toml | 5 + ravenous-tools/Cargo.toml | 1 + ravenous-tools/src/main.rs | 2 + weaponry/Cargo.toml | 2 + weaponry/src/analysis.rs | 160 ++++++++++++++++++ weaponry/src/lib.rs | 2 + .../equipement_advanced_repr.rs | 9 +- .../weaponry_structs/equipement_impl_io.rs | 10 +- weaponry/src/weaponry_structs/mod.rs | 1 + 14 files changed, 254 insertions(+), 17 deletions(-) create mode 100644 config/src/analysis.rs create mode 100644 weaponry/src/analysis.rs diff --git a/.run_status.toml b/.run_status.toml index d94ea54..d6c2a0d 100644 --- a/.run_status.toml +++ b/.run_status.toml @@ -1,8 +1,8 @@ [last_run_clean] run_status = "Success" -lines_parsed = 133 -coverage = 23.38 +lines_parsed = 134 +coverage = 22.47 [last_run_clean.run_duration] -secs = 66 -nanos = 917039211 +secs = 70 +nanos = 324790325 diff --git a/badges/coverage.svg b/badges/coverage.svg index b1210c9..6f62b2a 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 23%test-coverage23% +test-coverage: 22%test-coverage22% diff --git a/cli_parser/src/lib.rs b/cli_parser/src/lib.rs index 1a04de7..d5e56d2 100644 --- a/cli_parser/src/lib.rs +++ b/cli_parser/src/lib.rs @@ -4,6 +4,7 @@ use clap::{Args, Parser, Subcommand}; use config::{ + analysis::AnalysisConfig, graph::GraphConfig, make::{ HELP_BLOCK_SELECTION, HELP_BUILD_TARGET_LIST, HELP_VERBOSITY_LEVEL, MakeTargets, @@ -42,8 +43,8 @@ pub enum Commands { Make(MakeConfig), /// Make all graphs Graphs(GraphConfig), - // /// Generate analysis data - // Analysis(AnalysisConfig) + /// Generate analysis data + Analysis(AnalysisConfig), } #[derive(Debug, Args)] @@ -64,6 +65,8 @@ pub struct ConfigArgs { #[derive(Deserialize)] /// The config struct, holding all runtime information pub struct Config { + /// Config specific for data generation + pub data_generation: Datagen, /// Config specific for the classes table generation pub classes: Classes, /// Config for all the tables @@ -83,6 +86,13 @@ pub struct Classes { pub end: String, } +#[derive(Deserialize)] +/// The data generation configuration +pub struct Datagen { + /// Where to find the data generation database + pub database: String, +} + // The make structs #[derive(Args, Debug, Clone)] diff --git a/config/src/analysis.rs b/config/src/analysis.rs new file mode 100644 index 0000000..8e5ca1f --- /dev/null +++ b/config/src/analysis.rs @@ -0,0 +1,54 @@ +// Workspace: config +// File: config/src/graph.rs +//! The inner config for the analysis module +//! + +use clap::{Parser, ValueEnum}; + +#[derive(Parser, Debug)] +/// Basic analisys CLI +pub struct AnalysisConfig { + #[arg(help = format!("The target to perform an analysis on [{:?}]", AnalysisTarget::value_variants()))] + /// The analysis target + pub target: AnalysisTarget, + + /// The path to save to. + pub path: Option, + /// Wether to generate shapes + #[arg(short('S'), long, default_value_t)] + pub no_shapes: bool, + /// Wether to generate materials + #[arg(short, long)] + pub materials: Option, + /// Wether to generate all natures + #[arg(short('N'), long)] + pub no_natures: bool, + /// Wether to generate all finishing + #[arg(short, long, default_value_t = false)] + pub finishing: bool, + #[arg(long, default_value_t = String::from("safe"))] + /// What function to sort by + pub sort: String, + // An html export path -h or -o + // A csv export path -c or --csv + // A presort --sort + // A prefilter with some filters ? + // - weapons + // - shields + // - armors + // - damage + // Data manipulation ?? + // - decimate + // - average per category +} + +#[derive(ValueEnum, Clone, Debug)] +/// The type of analysis to perform +pub enum AnalysisTarget { + /// Analysis over weapons + Weapon, + /// Analysis over armors + Armors, + /// Analysis over shields + Shields, +} diff --git a/config/src/lib.rs b/config/src/lib.rs index 94b3c35..a09949f 100644 --- a/config/src/lib.rs +++ b/config/src/lib.rs @@ -7,6 +7,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] // Internal Modules +pub mod analysis; pub mod graph; pub mod make; pub mod statsolver; diff --git a/helper_config.toml b/helper_config.toml index 305c592..d77bfaf 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -1,3 +1,8 @@ +[data_generation] +# This value should be overwriten by a relative path +database = "../ravenous-tools/weaponry/databases/weapons.db" + + [classes] header = '''\begin{}[ presep = 0pt, postsep = 0pt, diff --git a/ravenous-tools/Cargo.toml b/ravenous-tools/Cargo.toml index b2609e0..0494e55 100644 --- a/ravenous-tools/Cargo.toml +++ b/ravenous-tools/Cargo.toml @@ -11,6 +11,7 @@ cli_parser = {path = "../cli_parser"} # config = {path = "../config"} stats = {path = "../stats"} make = {path = "../make"} +weaponry = {path = "../weaponry"} anyhow = "1.0.95" clap = { version = "4.5.28", features = ["derive"] } diff --git a/ravenous-tools/src/main.rs b/ravenous-tools/src/main.rs index 6ec40bf..b2d5faa 100644 --- a/ravenous-tools/src/main.rs +++ b/ravenous-tools/src/main.rs @@ -10,6 +10,7 @@ use graphs::make_graphs; use make::make_pdf; use stats::stat_solver; use tablegen::table_gen; +use weaponry::analysis::launch_analysis; // External imports use anyhow::{Context, Result}; @@ -31,6 +32,7 @@ fn main() -> Result<()> { Commands::Stats(args) => stat_solver(&args, &config), Commands::Make(args) => make_pdf(&args, &config), Commands::Graphs(args) => make_graphs(&args, &config), + Commands::Analysis(args) => Ok(launch_analysis(&args, &config)?), // Not using anyhow but a custom error } } diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 43e3a6f..3a99bfc 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -4,6 +4,8 @@ version = "0.1.0" edition = "2024" [dependencies] +config = {path = "../config"} +cli_parser = {path = "../cli_parser"} more_fields = {path ="../more_fields"} comfy-table = "7.1.4" csv = "1.3.1" diff --git a/weaponry/src/analysis.rs b/weaponry/src/analysis.rs new file mode 100644 index 0000000..9a6d6f8 --- /dev/null +++ b/weaponry/src/analysis.rs @@ -0,0 +1,160 @@ +// Workspace: weaponry +// File: weaponry/src/analysis.rs +//! The one stop shop for analysis + +use std::{cmp::Ordering, path::Path}; + +use cli_parser::Config; +use config::analysis::AnalysisConfig; + +use crate::{ + error::FatalEquipementError, + interfaces::{Reportable, Scenario, ToAnalysis, ToCSV, ToTex}, + weaponry_structs::{ + CrossRecipeScenario, RefinedEquipement, RefinedEquipementList, + equipement_scenario::ConfigEquipementScenario, + }, +}; + +/// Launch the analysis of the selected data and export it to html for human processing +pub fn launch_analysis(args: &AnalysisConfig, config: &Config) -> Result<(), FatalEquipementError> { + match args.target { + config::analysis::AnalysisTarget::Weapon => create_graphs( + args, + config, + Box::new(|e: &RefinedEquipement| { + e.inner.category_base.as_ref().is_some_and(|v| { + !matches!(v, crate::weaponry_structs::WeaponBaseShape::Shields) + && !matches!(v, crate::weaponry_structs::WeaponBaseShape::Armors) + }) + }), + ), + config::analysis::AnalysisTarget::Armors => create_graphs( + args, + config, + Box::new(|e: &RefinedEquipement| { + e.inner + .category_base + .as_ref() + .is_some_and(|v| matches!(v, crate::weaponry_structs::WeaponBaseShape::Armors)) + }), + ), + config::analysis::AnalysisTarget::Shields => create_graphs( + args, + config, + Box::new(|e: &RefinedEquipement| { + e.inner + .category_base + .as_ref() + .is_some_and(|v| matches!(v, crate::weaponry_structs::WeaponBaseShape::Shields)) + }), + ), + } + Ok(()) +} + +/// Create all graphs with +fn create_graphs(args: &AnalysisConfig, config: &Config, filter: DynamicFilterType) { + let save_path = args.path.clone().unwrap_or("data/first_data".into()); + let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario { + table_name: "Equipements".into(), + db_path: config.data_generation.database.clone(), + shape: (!args.no_shapes).then_some(()), + materials: args.materials, + nature: (!args.no_natures).then_some(()), + finishing: args.finishing.then_some(()), + }) + .unwrap(); + + let mut refined_list = scenarios + .generate_refined_recipes() + .unwrap() + // .inner_filter(|e| (e.advanced.max_damage_per_attack > 0.)) + .inner_filter(filter); + + match cmd_to_filter(&args.sort) { + Ok(cmd) => { + refined_list.inner_sort(cmd); + } + Err(FatalEquipementError::CLIParseError(a)) => { + println!("Argument incorrect '{a}'. Ignoring the sort.") + } + Err(e) => panic!("{e}"), + } + // if args.html_export{} + refined_list.write_html(&save_path).unwrap(); + + // if args.csv_export{} + // export_as_csv(&refined_list, &save_path); + + // if args.tex_export{} + export_as_tex(&refined_list, &save_path); +} + +#[allow(dead_code)] +/// Export as a csv a refine equipement list +/// +/// Rarely used and likely on it's way to deprecation +fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { + println!("{}", refined_list.get_report(Some("Refined List"))); + println!( + "Saved initial data as {}.html: {:?}", + save_path, + refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) + ); +} +/// Export as a tex file in the given directory +/// +/// Generic function dispatching any specific demand to different functions +fn export_as_tex(refined_list: &RefinedEquipementList, save_path: &str) { + println!("{}", refined_list.to_tex()); // TexType + // println!( + // "Saved initial data as {}.html: {:?}", + // save_path, + // refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) + // ); +} + +/// A dynamic filtertype, as a boxed function over two equipement references +// #[allow(dead_code)] +type DynamicSortType = Box Ordering>; + +/// A dynamic filter type +type DynamicFilterType = Box bool>; + +/// Create a filter from a user typed filter +/// +/// This informal implementation function as a mini language, +/// without any form of formalism, consistency or fixed API +fn cmd_to_filter(og_entry: &str) -> Result { + let (category, entry) = if og_entry.starts_with("cat+") { + (true, og_entry.split_at(4).1) + } else { + (false, og_entry) + }; + + macro_rules! return_if_starts_with { + ($iden:ident) => { + if stringify!($iden).starts_with(entry) { + return match category { + true => Ok(Box::new(crate::sort_by_cat_then!($iden))), + false => Ok(Box::new(crate::sort_by!($iden))), + }; + }; + }; + } + return_if_starts_with!(max_damage_per_attack); + return_if_starts_with!(armor_break_per_attack); + return_if_starts_with!(expected_armor_break_per_attack); + return_if_starts_with!(avg_damage_2a_safe); + return_if_starts_with!(avg_damage_2a_huge_hit); + return_if_starts_with!(speed); + return_if_starts_with!(scenario_damage); + return_if_starts_with!(defensive); + return_if_starts_with!(earlygame_sustained_damage_per_turn); + return_if_starts_with!(midgame_sustained_damage_per_turn); + return_if_starts_with!(endgame_sustained_damage_per_turn); + return_if_starts_with!(variance); + return_if_starts_with!(variance_pct); + Err(FatalEquipementError::CLIParseError(og_entry.to_string())) +} diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index 840bc6c..d21aa92 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -7,10 +7,12 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![feature(iter_intersperse, generic_arg_infer)] +pub mod analysis; mod database; pub mod error; pub mod export; pub mod interfaces; +#[macro_use] pub mod weaponry_structs; /// Signals the function running is unfinished diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 87e6575..0c6ed8c 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -18,7 +18,7 @@ use crate::{ add_field_to_chart, error::FatalEquipementError, export::{initial_chart, initial_plot_chart}, - interfaces::{RecipeCollection, RefinedList, ToAnalysis, ToTex}, + interfaces::{RecipeCollection, RefinedList, ToAnalysis}, weaponry_structs::{ Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats, @@ -60,13 +60,6 @@ impl Deref for RefinedEquipementList { // Just a checkmark impl RefinedList for RefinedEquipementList {} -impl ToTex for RefinedEquipementList { - fn to_tex(&self) -> String { - // TODO[!] : Export everything to one tsv - // : This export is only supposed to be the final export of a pseudo recipes book - todo!() - } -} impl ToAnalysis for RefinedEquipementList { type InnerData = RefinedEquipement; diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs index 4db5645..acafc60 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -3,7 +3,7 @@ //! All implementation IO specific (mainly export and serde) use super::equipement_advanced_repr::RefinedEquipementList; -use crate::interfaces::ToCSV; +use crate::interfaces::{ToCSV, ToTex}; use std::path::Path; impl ToCSV for RefinedEquipementList { @@ -16,7 +16,13 @@ impl ToCSV for RefinedEquipementList { } } -// impl To +impl ToTex for RefinedEquipementList { + // Nom & \rotbx{Rareté} & \rotbx{Dégâts} & + & \rotbx{R.Max} & \rotbx{Armr.B} & \rotbx{Protbx} & \rotbx{Int.} & \rotbx{Deux M} & \rotbx{Une M} & \rotbx{Esq.} & \rotbx{Parr.} & \rotbx{Vitesse} & \rotbx{Discr.} & \rotbx{Catégorie} & \rotbx{Modes} & \rotbx{Spécial} \\ + fn to_tex(&self) -> String { + self.inner.iter().for_each(|m| println!("{:?}", m.inner)); + todo!() + } +} #[cfg(test)] mod test { diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index c35a0a7..21051c9 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -15,6 +15,7 @@ // #[global_allocator] // static GLOBAL: Jemalloc = Jemalloc; +#[macro_use] mod equipement_advanced_repr; mod equipement_advanced_tools; mod equipement_fields; -- 2.45.1 From db22d38b988160f7c8c2ee1f04484345babaa8d6 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 2 May 2026 03:33:06 +0200 Subject: [PATCH 96/97] Commented export to run the program Still a big wip --- weaponry/src/analysis.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/weaponry/src/analysis.rs b/weaponry/src/analysis.rs index 9a6d6f8..7188e54 100644 --- a/weaponry/src/analysis.rs +++ b/weaponry/src/analysis.rs @@ -88,7 +88,7 @@ fn create_graphs(args: &AnalysisConfig, config: &Config, filter: DynamicFilterTy // export_as_csv(&refined_list, &save_path); // if args.tex_export{} - export_as_tex(&refined_list, &save_path); + // export_as_tex(&refined_list, &save_path); } #[allow(dead_code)] -- 2.45.1 From 321051a443fb40dd187421839006ea93376be4fb Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 10 Jul 2026 21:03:45 +0200 Subject: [PATCH 97/97] small weapon update --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index fe13caa2ed9996a919db8ca7830a14cd56299b62..7b39a9eee9905def91c71039a5d000aa1384b9e0 100644 GIT binary patch delta 339 zcmV-Z0j&Oj-~oW(0gxL3pphIy1)u;fjr*}=rw;)KvkVaJ4`l^G00003Aq@Zk03ieV z01u829S*4uN)7J~kqtNu*$jCMFAM4mqYGdQ6$;A=f(jZ5$O(A~1qhJ{NC(^pa|aFv zsRls>+y!_A5d^>lU<3LCtOHsAwF3eIr~*;~003SAF#$2Lft&*gWFa2_87Bw`2$QQq zU6Yp-D6_9cun3b(LASGCPM-mjUqEuQFa!`79t2PX2cHK`2GIt21|J2<1$PA?1iJ)K zlL%lalSE)?v5=z!18FTElW=YslO#j40RWTNLskI*lPyGA0SJ?bME{e~KzjiIlLJCg z2LMbW9{?F8laXW;lWsyZv+ZXS2(nNF5H1x5-2e{94pI%?4O$HC44(`&3%d(P3c?C> l3MUEK35f|i22v-N)518v1?L5a0-^#`0s{ci1uq2E1b+lA z1J?s{0|)?^m2O