diff --git a/.ignore b/.ignore index 8e062ad..523ea06 100644 --- a/.ignore +++ b/.ignore @@ -1 +1,2 @@ *.drawio +*.db 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/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 23800e1..bd52679 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -4,32 +4,55 @@ //! //! 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()); 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(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + 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) + }) + }); + + 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(); @@ -42,17 +65,30 @@ 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, + // 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)] @@ -64,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/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/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/export.rs b/weaponry/src/export.rs index dea3e48..455d894 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_attack, /// ) /// } /// ); @@ -44,26 +40,47 @@ /// 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 +// 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,)*)} ) => { - let data_collection = $base_struct.inner.iter().map(|$closure_name| ( $($fields,)*) ); - let ($names, $($table_names),*) = data_collection.collect::<(Vec<$name_type>, $(Vec<$table_type>,)*)>(); - let $chart = $chart - .x_axis( - charming::component::Axis::new() - .data($names.to_vec()) - .type_(charming::element::AxisType::Category), - ); - $( - let $chart = $chart - .series( - charming::series::Line::new() - .data($table_names) - .name(stringify!($table_names)), // .line_style(LineStyle::new().color("paleblue")), - ); - )* + 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() + // .stack("Total") + .data($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"), + )])), + ); + )* + + $chart.legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(charming::element::Orient::Vertical) + .data(vec![ + $(stringify!($table_names),)* + ]), + ) + }; } } @@ -75,18 +92,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 44b93ee..d33eee2 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -156,14 +156,22 @@ 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; + /// 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; + /// 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/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 5e73461..982b22c 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 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, - interfaces::{RefinedList, ToAnalysis, ToTex}, + export::initial_chart, + interfaces::{RecipeCollection, RefinedList, ToAnalysis, ToTex}, + weaponry_structs::{ + Equipement, InitialEquipementList, + equipement_structs::InnerEquipementStats, + equipement_thin_types::{Dices, Precision}, + }, }; use charming::Chart; -use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; -use probability::prelude::{Binomial, Discrete}; +use core::f64; use serde::Serialize; -use strum::{Display, EnumIter, IntoEnumIterator}; - -use super::{ - Equipement, InitialEquipementList, WeaponMacroCategory, - equipement_structs::InnerEquipementStats, -}; +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 @@ -42,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 @@ -85,42 +69,195 @@ 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, + // : 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) .theme(charming::theme::Theme::Dark); - 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)); + let initial_chart: Chart = initial_chart(&format!( + "Damage for all cross-gen products ({} Elements)", + self.inner.len() + )); + macro_rules! round { + ($a:expr) => { + ($a * 100.).round() / 100. + }; + } add_field_to_chart!( self, initial_chart, ( index # &String, - dps_safe # f64, - max_damage_per_action # f64, - armor_break_per_turn # 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, + // speed # f64, + variance # f64, + variance_pct # 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_action, - ref_equipement.advanced.damage_per_turn, - ref_equipement.advanced.armor_break_per_turn, + 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.variance), + round!(ref_equipement.advanced.variance_pct ), + 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 ), ) } ); - renderer.save(&initial_chart, format!("{save_path}.html"))?; Ok(()) } } +/// The list of advanced stats infered from an Equipement +#[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, + // /// 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_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 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, + /// 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, + /// 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)) 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, + speed: value.speed.into(), + armor_break_per_attack, + // 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, + 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), + 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), + ), + } + } +} + +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 { @@ -133,254 +270,31 @@ 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]); 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 -#[allow(missing_docs, clippy::missing_docs_in_private_items)] -#[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 armor_break_per_attack: f64, - pub armor_break_per_turn: f64, - pub armor_break_per_action: f64, - pub damage_matrix: DamageMatrix, - pub category: Option, - /// Armor break factoring in the damage output: While a weapon might have high AB, not having any damage will seriously hinder that AB - pub expected_armor_break_per_turn: f64, - /// Dps with two actions and 5 dices - pub dps_safe: f64, - // /// Dps with four actions and 11 dices - // pub dps_unsafe: f64, - // All other criterias are already in the inner as raw criterias -} -impl From<&InnerEquipementStats> for AdvancedStats { - fn from(value: &InnerEquipementStats) -> Self { - let damage_per_attack = - (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; - let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack); - let damage_matrix = DamageMatrix::calculate_for(value); - Self { - category: value.macro_category.clone(), - display_name: value.name.join(" "), - damage_per_attack, - damage_per_turn: damage_per_attack * 2., - 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), - dps_safe: damage_matrix.get_safe_dmg(value.action_cost), - // dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), - damage_matrix, +#[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, } - } -} - -/// A damage matrix, crossing damage conditions (high dice to low dice) with precision (high precision to low precision) -/// -/// This simulation does only calculate a very limited preset of damage values -#[cfg_attr(test, derive(Debug))] -pub struct DamageMatrix { - /// The inner damage matrix - damage_matrix: Vec, -} -impl DamageMatrix { - /// Get the damage value from given condition - pub fn get_damage(&self, precision: Precision, dices: DiceNumber) -> f64 { - self.damage_matrix[precision 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(Precision::Low, DiceNumber::Few) - + self.get_damage(Precision::Medium, DiceNumber::Few) - + self.get_damage(Precision::High, DiceNumber::Few)) - / 3. - } - /// The "unsage" damage, as in, full dice, 2 attacks - // TODO: This damages does max(Max dices * 1, 5 dices * 2), which might not be optimal - pub fn get_unsafe_dmg(&self, attack_cost: i8) -> f64 { - f64::max( - self.get_safe_dmg(attack_cost) * 2., - (self.get_damage(Precision::Low, DiceNumber::Many) - + self.get_damage(Precision::Medium, DiceNumber::Many) - + self.get_damage(Precision::High, DiceNumber::Many)) - / 3., - ) - } -} -impl Serialize for DamageMatrix { - 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 Precision::iter() - .map(|e| format!("{:.3}", e)) - .collect::>(), - ); - table.set_header(headers); - table.add_rows(DiceNumber::iter().map(|dices| { - vec![format!("{:.3}", dices)].into_iter().chain( - Precision::iter() - .map(move |precision| format!("{:5.2}", self.get_damage(precision, dices))), - ) - })); - write!(f, "{}", table) - } -} - -impl DamageMatrix { - /// Calculate the DamageMatrix for a given InnerEquipementStats - fn calculate_for(value: &InnerEquipementStats) -> Self { - DamageMatrix { - damage_matrix: (DiceNumber::iter() - .flat_map(|dices| { - Precision::iter() - .map(move |prec| { - binomial_dice_distribution(value, prec.value(), dices.value()) - }) - .collect::>() - }) - .collect::>()), - } - } -} - -/// Calculate the binomial distribution and average the damage from there -fn binomial_dice_distribution( - equipement: &InnerEquipementStats, - precision: usize, - dices: usize, -) -> f64 { - let p = ((precision as i8 + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); - let binomial = Binomial::new(dices, p); - - (0..dices + 1) - .map(|target_dices| { - let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize; - if target_dices >= 1 { - (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 Precision { - High, - Medium, - Low, -} - -/// The number of dices rolled for a damage simulation -#[derive(EnumIter, Clone, Copy, Display)] -#[allow(clippy::missing_docs_in_private_items)] -pub enum DiceNumber { - Many, - Average, - Few, -} - -impl Precision { - #[inline] - /// Associate a value to the different values - fn value(&self) -> usize { - match self { - Precision::High => 9, - Precision::Medium => 6, - Precision::Low => 4, - } - } -} -impl DiceNumber { - #[inline] - /// Associate a value to the different values - fn value(&self) -> usize { - match self { - DiceNumber::Many => 7, - DiceNumber::Average => 5, - DiceNumber::Few => 3, - } - } -} - -#[cfg(test)] -mod test { - use crate::weaponry_structs::{ - equipement_advanced_repr::{DamageMatrix, DiceNumber, Precision}, - 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, - p_damage: 2, - precision: 0, - rmax: 3, - armor_break: 2, - ..Default::default() - } - } - - #[test] - fn test_creation() { - let mat = DamageMatrix::calculate_for(&new_inner_eq()); - println!("{}", mat); - println!( - "(High,Many): {}, (Low,Few): {}", - mat.get_damage(Precision::High, DiceNumber::Many), - mat.get_damage(Precision::Low, DiceNumber::Few) - ); - } } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs new file mode 100644 index 0000000..a4e7cef --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -0,0 +1,619 @@ +// 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::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 +/// - 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, + actions: Actions, + attacks: Attacks, +) -> f64 { + 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), + }); + } + + damage_over_turns(value, &turns) / 10. +} + +/// Sustained damage +/// +/// Average damage factoring reload, calculated with 9 dice and 90% precision +// TODO[!] Replace avg_damage with this +pub(super) fn get_sustained_damage( + value: &InnerEquipementStats, + actions: Actions, + attacks: Attacks, + dices: Dices, + precision: Precision, +) -> f64 { + // Actions total and damage total are arbitrarely choosen + + let l = &[TurnInfo { + actions, + attacks, + dices, + precision, + }; 10]; + damage_over_turns(value, l) / 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 = Actions(0); + let mut total_damage = 0.; + for TurnInfo { + actions, + attacks, + dices, + precision, + } in turn_info + { + if let Some(BestDamageScenarios { + actions_used: _, + attacks_used: _, + damage_done, + reload_remaining, + depth: _, + }) = BestDamageScenarios::from_action_constraints( + value, + *actions - reloading_left, + *attacks, + *dices, + *precision, + ) { + reloading_left = reload_remaining; + total_damage += damage_done; + } + } + total_damage +} + +/// 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: Actions, + /// Attacks actions used by the scenario + attacks_used: Attacks, + /// Resulting damage + damage_done: f64, + /// Remaining actions that need to be used to finish reload + reload_remaining: Actions, + /// A debug value, should be taken down in final builds + // TODO[6]: Remove debug once the tests are done + depth: u8, +} + +impl Add for BestDamageScenarios { + 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) + pub fn from_action_constraints( + equipement_stats: &InnerEquipementStats, + actions_allowed: Actions, + attacks_allowed: Attacks, + dices_allowed: Dices, + precision: Precision, + ) -> Option { + Self::from_action_constraints_recursive( + equipement_stats, + actions_allowed, + attacks_allowed, + dices_allowed, + precision, + 0, + 0, + ) + } + /// Recursive part of the from_action_constraints call + /// + /// This algorithm takes a recursive approact to avoid too much forward complexity + fn from_action_constraints_recursive( + equipement_stats: &InnerEquipementStats, + actions_allowed: Actions, + attacks_allowed: Attacks, + dices_allowed: Dices, + precision: Precision, + reload_remaining: i8, + depth: u8, + ) -> Option { + // If we can't attack return early + if equipement_stats.action_cost > *actions_allowed + || *attacks_allowed == 0 + || reload_remaining > 0 + || *dices_allowed < 1 + { + // println!( + // "[{depth}] > Reach the end of recursion {}>{actions_allowed}, {attacks_allowed}a, {dices_allowed}d {reload_remaining}r", + // value.action_cost + // ); + return None; + } + + // if depth == 0 { + // println!( + // "Starting recursion: {actions_allowed}A {attacks_allowed}atk {dices_allowed}*" + // ); + // } + let atkreload_cost = + equipement_stats.reload_cost.unwrap_or_default() + equipement_stats.action_cost; + + // We create our first contender, One attack only + let one_attack = Self { + // No matter what we try to reload, even if we overcap the attack was still valid + actions_used: Actions((atkreload_cost).clamp(0, *actions_allowed)), + attacks_used: Attacks(1), + damage_done: binomial_dice_distribution(equipement_stats, precision, dices_allowed), + // If the reload+attack exceed the actions, we must bookkeep it + // as a reminder that we have leftover actions to spend next turn + reload_remaining: Actions( + ((atkreload_cost) - *actions_allowed + reload_remaining).clamp(0, *actions_allowed), + ), + depth, + }; + // println!( + // "[{depth}] > One attack ({}d): {one_attack:?}/{actions_allowed}A", + // Dices(*dices_allowed) + // ); + + // We can only try two attacks if two attack would be valid aka: + // - We can spend: 2 attacks and (at least) 1 reload (as actions) + // - : 2 attacks (as attacks) + if atkreload_cost + equipement_stats.action_cost <= *actions_allowed && *attacks_allowed > 1 + { + // Cumbersome because of rounding errors + if let (Some(a), Some(b)) = ( + (Self::from_action_constraints_recursive( + equipement_stats, + // TODO[9]: THIS APPROACH IS DEEPLY INCORRECT + // : It does however work for the values we will be using it + actions_allowed - Actions(atkreload_cost), + Attacks(attacks_allowed.div_floor(2)), + Dices(dices_allowed.div_floor(2)), + precision, + reload_remaining, + depth + 1, + )), + (Self::from_action_constraints_recursive( + equipement_stats, + actions_allowed - Actions(atkreload_cost), + Attacks(attacks_allowed.div_ceil(2)), + Dices(dices_allowed.div_ceil(2)), + precision, + reload_remaining - equipement_stats.reload_cost.unwrap_or_default(), + depth + 1, + )), + ) { + let sum_sub_attacks = a + b; + // println!( + // "[{depth}] > Two attacks ({} & {}) : {sum_sub_attacks:?}", + // Dices(dices_allowed.div_floor(2)), + // Dices(dices_allowed.div_ceil(2)) + // ); + // The alternative was better + if one_attack.damage_done < sum_sub_attacks.damage_done { + return Some(sum_sub_attacks); + } + } + } + + // The alternative didn't exist or was worse + Some(one_attack) + } +} + +/// 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 + .saturating_sub(1) + .clamp(0, equipement.rmax as usize)) 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, +} + +/// 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, + equipement_thin_types::{Actions, Attacks}, + }; + + use super::{BestDamageScenarios, Dices, Precision, binomial_dice_distribution}; + + fn new_inner_eq() -> InnerEquipementStats { + InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + armor_break: 2, + ..Default::default() + } + } + + macro_rules! assert_close { + ($a:expr, $b:expr) => { + println!("{} ~= {}", $a, $b); + assert!(($a - $b).abs() < 1E-3); + }; + } + + 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!( + average_damage(&eq, &[Precision(9)], &[Dices(9)]), + 13.999999999 + ); + assert_close!( + average_damage(&eq, &[Precision(4)], &[Dices(4)]), + 10.1119999 + ); + } + + #[test] + fn test_damage_optimisation() { + let eq = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + action_cost: 1, + ..Default::default() + }; + let eq2 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + action_cost: 2, + ..Default::default() + }; + let eq3 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + action_cost: 2, + reload_cost: Some(2), + ..Default::default() + }; + let known_data = &[ + ( + BestDamageScenarios::from_action_constraints( + &eq, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), + 14., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq, + Actions(2), + Attacks(2), + Dices(3), + Precision(10), + ), + 22., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq, + Actions(3), + Attacks(3), + Dices(3), + Precision(10), + ), + 30., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq, + Actions(3), + Attacks(3), + Dices(6), + Precision(10), + ), + 36., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq, + Actions(3), + Attacks(3), + Dices(6), + Precision(10), + ), + 36., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(1), + Attacks(1), + Dices(3), + Precision(10), + ), + 0., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), + 14., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(4), + Attacks(2), + Dices(3), + Precision(10), + ), + 22., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(5), + Attacks(3), + Dices(6), + Precision(10), + ), + 28., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(6), + Attacks(3), + Dices(6), + Precision(10), + ), + 36., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), + 14., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(4), + Attacks(2), + Dices(3), + Precision(10), + ), + 14., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(6), + Attacks(2), + Dices(3), + Precision(10), + ), + 22., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(6), + Attacks(3), + Dices(6), + Precision(10), + ), + 28., + ), + ( + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(10), + Attacks(3), + Dices(6), + Precision(10), + ), + 36., + ), + ]; + 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_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index d6aa96c..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; @@ -119,13 +78,14 @@ 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))] pub enum WeaponCategory { Exotic, - Dagger, + // HeavyExotic ? + Dagger, // Light sword ? Kill it tbh Claws, Blade, Haroth, @@ -143,27 +103,8 @@ pub enum WeaponCategory { // Shield, } -// TODO: This is the real initial category -/// The list of initial weapon meta categories -#[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, 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 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) { @@ -200,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_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, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 15ceb05..c26d605 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 /// @@ -107,9 +107,9 @@ 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: 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, @@ -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/equipement_thin_types.rs b/weaponry/src/weaponry_structs/equipement_thin_types.rs new file mode 100644 index 0000000..201ce45 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_thin_types.rs @@ -0,0 +1,104 @@ +// 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 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; + 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/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..66d8417 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; @@ -25,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 @@ -34,10 +36,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;