From 8a2114da74d191467f45b764a962317f7462920a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 06:53:00 +0100 Subject: [PATCH 01/10] 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 02/10] 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 03/10] 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 04/10] 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 05/10] 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 06/10] 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 07/10] 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 08/10] 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 09/10] 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 10/10] 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