diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index ae487b4..d7f70a4 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -16,12 +16,14 @@ serde_json = { version = "1.0.138", features = ["alloc"] } strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" regex = "1.11.1" +charming = { version = "0.4.0", features = [] } [dev-dependencies] criterion = { version = "0.5" } regex = "1.11.1" pretty_assertions = "^1.4" logos = "^0.15" +clap = { version = "4.5.30", features = ["derive"] } [[bench]] name = "iter_creation" diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 1ad235a..2dd4033 100644 Binary files a/weaponry/databases/weapons.db and b/weaponry/databases/weapons.db differ diff --git a/weaponry/examples/.rustfmt.toml b/weaponry/examples/.rustfmt.toml index 98b9e7f..9a9035c 100644 --- a/weaponry/examples/.rustfmt.toml +++ b/weaponry/examples/.rustfmt.toml @@ -1 +1 @@ -max_width = 278 +# max_width = 278 diff --git a/weaponry/examples/graph.rs b/weaponry/examples/graph.rs new file mode 100644 index 0000000..c4a20fb --- /dev/null +++ b/weaponry/examples/graph.rs @@ -0,0 +1,149 @@ +// use charming::{ +// Chart, WasmRenderer, +// component::{Axis, Title}, +// element::AxisType, +// series::Line, +// }; +// use leptos::prelude::*; +// use leptos_use::use_interval_fn; +// use leptos_use::utils::Pausable; + +// #[component] +// fn App() -> impl IntoView { +// let data = RwSignal::new(vec![150, 230, 224, 218, 135, 147, 260]); +// let action = Action::new(move |_input: &()| { +// let local = data.get(); +// async move { +// let chart = Chart::new() +// .title(Title::new().text("Demo: Leptos + Charming")) +// .x_axis(Axis::new().type_(AxisType::Category).data(vec!["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])) +// .y_axis(Axis::new().type_(AxisType::Value)) +// .series(Line::new().data(local)); + +// let renderer = WasmRenderer::new(600, 400); +// renderer.render("chart", &chart).unwrap(); +// } +// }); + +// let Pausable { pause, resume, is_active: _ } = use_interval_fn( +// move || { +// data.update(|d| d.rotate_right(1)); +// action.dispatch(()); +// }, +// 1000, +// ); + +// action.dispatch(()); + +// view! { +//
+//
+// +// +//
+// } +// } + +// fn main() { +// mount_to_body(|| view! { }) +// } +use charming::{ + Chart, + component::{Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, ToolboxDataZoom, VisualMap, VisualMapType}, + element::{AxisType, Tooltip, Trigger}, + series::Line, +}; +// use rand::Rng; + +pub fn chart() -> Chart { + let raw_data = vec![ + ("2000-06-05", 116), + ("2000-06-06", 129), + ("2000-06-07", 135), + ("2000-06-08", 86), + ("2000-06-09", 73), + ("2000-06-10", 85), + ("2000-06-11", 73), + ("2000-06-12", 68), + ("2000-06-13", 92), + ("2000-06-14", 130), + ("2000-06-15", 245), + ("2000-06-16", 139), + ("2000-06-17", 115), + ("2000-06-18", 111), + ("2000-06-19", 309), + ("2000-06-20", 206), + ("2000-06-21", 137), + ("2000-06-22", 128), + ("2000-06-23", 85), + ("2000-06-24", 94), + ("2000-06-25", 71), + ("2000-06-26", 106), + ("2000-06-27", 84), + ("2000-06-28", 93), + ("2000-06-29", 85), + ("2000-06-30", 73), + ("2000-07-01", 83), + ("2000-07-02", 125), + ("2000-07-03", 107), + ("2000-07-04", 82), + ("2000-07-05", 44), + ("2000-07-06", 72), + ("2000-07-07", 106), + ("2000-07-08", 107), + ("2000-07-09", 66), + ("2000-07-10", 91), + ("2000-07-11", 92), + ("2000-07-12", 113), + ("2000-07-13", 107), + ("2000-07-14", 131), + ("2000-07-15", 111), + ("2000-07-16", 64), + ("2000-07-17", 69), + ("2000-07-18", 88), + ("2000-07-19", 77), + ("2000-07-20", 83), + ("2000-07-21", 111), + ("2000-07-22", 57), + ("2000-07-23", 55), + ("2000-07-24", 60), + ]; + + let mut data_list = vec![]; + let mut value_list = vec![]; + + raw_data.into_iter().for_each(|(date, value)| { + data_list.push(date); + value_list.push(value); + }); + + Chart::new() + .title(Title::new().text("Gradient along the y axis").left("center")) + // .title(Title::new().text("Gradient along the x axis").left("center").top("55%")) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) + .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(0).min(0).max(400)) + // .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(1).dimension(0).min(0).max(10).max((data_list.len() - 1) as f64)) + .x_axis(Axis::new().data(data_list.to_vec()).type_(AxisType::Category).boundary_gap(false)) + // .x_axis(Axis::new().data(data_list.to_vec()).grid_index(1)) + .y_axis(Axis::new()) + // .y_axis(Axis::new().grid_index(1)) + .grid(Grid::new()) + // .grid(Grid::new().top("60%")) + .series(Line::new().show_symbol(false).data(value_list.clone())) + .data_zoom(DataZoom::new().type_(DataZoomType::Inside).start(0).end(100)) + .data_zoom(DataZoom::new().start(0).end(100)) + .toolbox(Toolbox::new().feature(Feature::new().data_zoom(ToolboxDataZoom::new().y_axis_index("none")).restore(Restore::new()).save_as_image(SaveAsImage::new()))) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) + // .series(Line::new().show_symbol(false).x_axis_index(1).y_axis_index(1).data(value_list)) +} + +fn main() { + let chart = chart(); + use charming::HtmlRenderer; + + let mut renderer = HtmlRenderer::new("MOOO", 1800, 1800).theme(charming::theme::Theme::Dark); + // // Render the chart as HTML string. + // let html_str = renderer.render(&chart).unwrap(); + // Save the chart as HTML file. + renderer.save(&chart, "./chart.html").unwrap(); +} diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index f12cdb3..23800e1 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -3,32 +3,64 @@ //! Test use case of a scenario //! //! - +use clap::Parser; use std::path::Path; +use weaponry::interfaces::ToAnalysis; // TODO : All of these should likely be in the prelude if used like this -use weaponry::interfaces::{Reportable, Scenario, ToCSV}; use weaponry::weaponry_structs::CrossRecipeScenario; -use weaponry::weaponry_structs::equipement_scenario::ConfigMock; +use weaponry::weaponry_structs::equipement_scenario::ConfigEquipementScenario; +use weaponry::{ + interfaces::{Reportable, Scenario, ToCSV}, + weaponry_structs::RefinedEquipementList, +}; // use weaponry::interfaces:: fn main() { - let save_path = "data/first_data.csv"; - let scenarios = CrossRecipeScenario::new_with_config(ConfigMock {}).unwrap(); - let refined_list = scenarios.generate_refined_recipes().unwrap(); - println!("{}", refined_list.get_report(Some("Refined List"))); - println!("Saved initial data as {}: {:?}", save_path, refined_list.write_csv(Path::new(save_path))); + let args = CLIArgs::parse(); + let save_path = args.path.unwrap_or("data/first_data".into()); + let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario { + table_name: "Equipements".into(), + db_path: "./databases/weapons.db".into(), + shape: args.shapes.then_some(()), + materials: args.materials, + nature: args.natures.then_some(()), + finishing: args.finishing.then_some(()), + }) + .unwrap(); + let mut refined_list = scenarios.generate_refined_recipes().unwrap(); + refined_list.inner_sort(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + + // if args.html_export{} + refined_list.write_html(&save_path).unwrap(); + + // if args.csv_export{} + // export_as_csv(&refined_list, save_path); +} +#[derive(Parser, Debug)] +/// Basic cli +pub struct CLIArgs { + /// The path to save to. + pub path: Option, + /// Wether to generate shapes + #[arg(short, long, default_value_t = true)] + pub shapes: bool, + /// Wether to generate materials + #[arg(short, long)] + pub materials: Option, + /// Wether to generate all natures + #[arg(short, long, default_value_t = true)] + pub natures: bool, + /// Wether to generate all finishing + #[arg(short, long, default_value_t = false)] + pub finishing: bool, } -// // Load DB -// let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); -// // Do a first deserialisation -// let initial_deserialisation = db.serialize_vec_from_table::("Equipements", None).unwrap(); -// // Follow up by parsing this deserialisation by a transformation into the right intermediate representation -// let intermediate_deserialisation = initial_deserialisation.into_iter().map(InnerEquipementStats::try_from).collect::>(); - -// // // Inspect the sucesses/filures -// // let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize)); -// // println!("Succeded in parsing {}/{}", f.0, f.1); - -// // println!("Final data {:#?}", intermediate_deserialisation); -// // println!("Failed to parse: {:#?}", intermediate_deserialisation.into_iter().filter_map(|v| v.err()).collect::>()); +#[allow(dead_code)] +fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { + println!("{}", refined_list.get_report(Some("Refined List"))); + println!( + "Saved initial data as {}.html: {:?}", + save_path, + refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) + ); +} diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index 808b9d8..fba7e58 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -3,6 +3,7 @@ //! Inner weaponry error definition #![allow(missing_docs, clippy::missing_docs_in_private_items)] +use charming::EchartsError; use thiserror::Error; #[derive(Error, Debug)] @@ -32,22 +33,28 @@ pub enum FatalEquipementError { #[error("Couldn't convert into type {origin_type} with data {data}")] Conversion { origin_type: String, data: String }, + + #[error("An error occured with your current CLI configuration: {0}")] + CLISelection(String), + + #[error("Couldn't save the chart as an error occured during the process : {0}")] + SaveCharmingChart(#[from] EchartsError), } -#[derive(Error, Debug)] -/// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program -pub enum LocalEquipementError { - #[error("Very simple error")] - Oops, -} +// #[derive(Error, Debug)] +// /// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program +// pub enum LocalEquipementError { +// #[error("Very simple error")] +// Oops, +// } -#[derive(Error, Debug)] -/// An equipement error, either unrecoverable, indicating a that the execution -/// flow must be stopped and only an user input can solve the issue -pub enum EquipementError { - #[error("An unrecoverable error occured: {0}")] - Fatal(#[from] FatalEquipementError), +// #[derive(Error, Debug)] +// /// An equipement error, either unrecoverable, indicating a that the execution +// /// flow must be stopped and only an user input can solve the issue +// pub enum EquipementError { +// #[error("An unrecoverable error occured: {0}")] +// Fatal(#[from] FatalEquipementError), - #[error("A local error occured an wasn't recovered from: {0}")] - Local(#[from] LocalEquipementError), -} +// #[error("A local error occured an wasn't recovered from: {0}")] +// Local(#[from] LocalEquipementError), +// } diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs new file mode 100644 index 0000000..dea3e48 --- /dev/null +++ b/weaponry/src/export.rs @@ -0,0 +1,109 @@ +// Workspace: weaponry +// File: weaponry/src/export.rs +//! Module regrouping all generic function related to the exporting +//! +//! Mostly graphs and csv auto conversion + +/// A very complex macro created to add criterias to the graph +/// without repeating self explanatory parameter names in strings +/// +/// The syntax involved in the usage of this macro hence become esoteric +/// +/// # Example +/// ``` +/// # use weaponry::interfaces::RecipeCollection; +/// # use weaponry::add_field_to_chart; +/// # use weaponry::weaponry_structs::RefinedEquipementList; +/// # use weaponry::export::initial_chart; +/// # let self_ = RefinedEquipementList::default(); +/// # let initial_chart: charming::Chart = initial_chart("Damage for all cross-gen products"); +/// add_field_to_chart!( +/// self_, // Usually used inside the implementation and therefore self there +/// initial_chart, +/// ( +/// index # &String, +/// dps_safe # f64, +/// max_damage_per_action # f64, +/// armor_break_per_turn # f64, +/// ), +/// |ref_equipement| { +/// ( +/// &ref_equipement.advanced.display_name, +/// ref_equipement.advanced.max_damage_per_action, +/// ref_equipement.advanced.damage_per_turn, +/// ref_equipement.advanced.armor_break_per_turn, +/// ) +/// } +/// ); +/// ``` +/// +/// # Complexity and maintanability +/// +/// While the added complexity cannot be understated, the whole existence of this macro is +/// first and foremost based on the desire NOT to iterate multiple times on a dataset +/// which could easily reach 600k elements +/// +/// Knowing this tradeoff, the difficulty to maintain is considered an acceptable tradeoff +#[macro_export] +macro_rules! add_field_to_chart { + ($base_struct:expr, $chart:ident, ($names:ident # $name_type:ty, $($table_names:ident # $table_type:ty),* $(,)*), | $closure_name:ident | {($($fields:expr,)*)} + ) => { + let data_collection = $base_struct.inner.iter().map(|$closure_name| ( $($fields,)*) ); + let ($names, $($table_names),*) = data_collection.collect::<(Vec<$name_type>, $(Vec<$table_type>,)*)>(); + let $chart = $chart + .x_axis( + charming::component::Axis::new() + .data($names.to_vec()) + .type_(charming::element::AxisType::Category), + ); + $( + let $chart = $chart + .series( + charming::series::Line::new() + .data($table_names) + .name(stringify!($table_names)), // .line_style(LineStyle::new().color("paleblue")), + ); + )* + } +} + +/// Generate a generic graph, ready to be filled with data +pub fn initial_chart(chart_name: &str) -> charming::Chart { + charming::Chart::new() + .title( + charming::component::Title::new() + .text(chart_name) + .left("center"), + ) + .legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(charming::element::Orient::Vertical) + .data(vec![ + "dps_safe", + "max_damage_per_action", + "max_damage_per_turn", + "armor_break_per_turn", + ]), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .data_zoom( + charming::component::DataZoom::new() + .type_(charming::component::DataZoomType::Inside) + .start(0) + .end(100), + ) + .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .toolbox( + charming::component::Toolbox::new().feature( + charming::component::Feature::new() + .data_zoom(charming::component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(charming::component::Restore::new()) + .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .y_axis(charming::component::Axis::new()) + .grid(charming::component::Grid::new().contain_label(true)) +} diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 05a8d0e..44b93ee 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -10,7 +10,7 @@ use std::{path::Path, rc::Rc}; use more_fields::FieldsAsSlice; use serde::de::DeserializeOwned; -use crate::error::{EquipementError, FatalEquipementError}; +use crate::error::FatalEquipementError; /// Trait representing a view table /// @@ -42,7 +42,7 @@ pub trait ViewTable { /// While it is possible to enforce from_recipe_collection, doing so would require the viewtable /// lock itseld to a particular recipe. /// While it is the case as of now, matters are not yet set in stone -pub trait RefinedList { +pub trait RefinedList: ToTex + ToCSV + ToAnalysis { // Must implement From, is it worth adding as a prerequite type ? // type OriginCollection: Into; } @@ -150,6 +150,22 @@ pub trait ToCSV { fn write_csv(&self, path: &Path) -> csv::Result<()>; } +/// This element can be converted to an interactive .html +pub trait ToAnalysis { + /// The explicit type of the underlying data + type InnerData; + + /// Sort the inner data with a given closure + fn inner_sort(&mut self, closure: T) + where + T: FnMut(&Self::InnerData, &Self::InnerData) -> std::cmp::Ordering; + + /// Write as html + fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>; + + // TODO: Add sorting methods as no analysis can be done without filtering and sorting +} + /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { /// Create the database from a file @@ -205,45 +221,16 @@ pub trait Reportable { pub trait Scenario { /// The inner database type type DatabaseType: RecipeDatabase; - /// The type of viewtable that must be returned by the scenario - // Could also use dyn dispatch but since all of it is so tied down... - type ViewTableType: ViewTable; /// The type of the final recipe list - type FinalListType: RefinedList; + type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis; /// Inner configuration type Config; /// Create a Scenario from a given config - fn new_with_config(config: Self::Config) -> Result + fn new_with_config(config: Self::Config) -> Result where Self: Sized; - // /// Load all database into intermediate representation - // fn load_from_database() -> Result - // where - // Self: std::marker::Sized; - - // /// Configure the scenario to the user's needs - // fn configure_scenario(&mut self, config: Self::Config) -> Result<(), FatalEquipementError>; - - // All these steps should be implemented but not required - // enforcing them helps writing new impls more easily but is not really nice in any way - // - // /// Process the inner representations and get a list of results - // fn process_inner_representation(&self) -> Result<(), FatalEquipementError>; //Result<(), EquipementError> - - // /// Process inner recipes into a Final list - // /// - // /// This will generate the recipe list using the prefered method of the Scenario (Fixed Recipes or Cross Recipes or Whatever) - // fn process_recipes(&self); - - // /// Process the recipes into a Refined Recipes - // fn refine_recipes(&self); - /// Generate the final list type - fn generate_refined_recipes(&self) -> Result; - - /// Gather the selected view tables - /// All the inner generation is done gradually and populate all section to finally generate the views - fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType; + fn generate_refined_recipes(&self) -> Result; } diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index cf331bd..4392409 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -7,6 +7,7 @@ mod database; pub mod error; +pub mod export; pub mod interfaces; mod strategy; pub mod weaponry_structs; diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index d03f9c2..5e73461 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -9,28 +9,37 @@ //! of all the fields even when the user will not be interested in them #![allow(dead_code)] +use crate::{add_field_to_chart, export::initial_chart, interfaces::RecipeCollection}; use core::f64; -use std::fmt::Display; +use std::{cmp::Ordering, fmt::Display}; -use crate::interfaces::RefinedList; +use crate::{ + error::FatalEquipementError, + interfaces::{RefinedList, ToAnalysis, ToTex}, +}; +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, equipement_structs::InnerEquipementStats}; +use super::{ + Equipement, InitialEquipementList, WeaponMacroCategory, + equipement_structs::InnerEquipementStats, +}; /// The final representation of the equipement inplementing all the fields needed for processing +// TODO: Add a public getter for the inner data pub struct RefinedEquipement { /// The original inner stats /// /// This structs takes ownership of the inner data // #[serde(skip_deserializing)] - inner: InnerEquipementStats, + pub inner: InnerEquipementStats, /// Advanced stats // #[serde(flatten)] - advanced: AdvancedStats, + pub advanced: AdvancedStats, } impl Serialize for RefinedEquipement { @@ -54,11 +63,63 @@ impl From for RefinedEquipement { /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements - pub(super) inner: Vec, + // TODO: Add a public getter in on of the traits + pub inner: Vec, } // Just a checkmark impl RefinedList for RefinedEquipementList {} +impl ToTex for RefinedEquipementList { + fn to_tex(&self) -> String { + todo!() + } +} + +impl ToAnalysis for RefinedEquipementList { + type InnerData = RefinedEquipement; + + fn inner_sort(&mut self, closure: T) + where + T: FnMut(&RefinedEquipement, &RefinedEquipement) -> Ordering, + { + self.inner.sort_by(closure) + } + + // TODO[3]: Consider wether the naming should be a parameter, + // or a config should be given or if the scenario should be fed again the Refined and ... + fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { + 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)); + + add_field_to_chart!( + self, + initial_chart, + ( + index # &String, + dps_safe # f64, + max_damage_per_action # f64, + armor_break_per_turn # f64, + ), + |ref_equipement| { + ( + &ref_equipement.advanced.display_name, + ref_equipement.advanced.max_damage_per_action, + ref_equipement.advanced.damage_per_turn, + ref_equipement.advanced.armor_break_per_turn, + ) + } + ); + + renderer.save(&initial_chart, format!("{save_path}.html"))?; + Ok(()) + } +} impl From for RefinedEquipementList { fn from(value: InitialEquipementList) -> Self { @@ -72,10 +133,8 @@ impl From for RefinedEquipementList { } } -#[cfg(test)] -use crate::interfaces::RecipeCollection; - -#[cfg(test)] +// #[cfg(test)] +// Used in exemples impl Default for RefinedEquipementList { fn default() -> Self { let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); @@ -85,19 +144,25 @@ impl Default for RefinedEquipementList { /// The list of advanced stats infered from an Equipement // TODO: The two philosophies to drop the old inner or convert the useful fields are considered right now +// TODO: This whole public might be overkill ? A good inner view or scenario could implement what is needed #[allow(missing_docs, clippy::missing_docs_in_private_items)] #[derive(Serialize)] pub struct AdvancedStats { - display_name: String, - damage_per_attack: f64, - damage_per_turn: f64, - damage_per_action: f64, - armor_break_per_attack: f64, - armor_break_per_turn: f64, - armor_break_per_action: f64, - damage_matrix: DamageMatrix, + pub display_name: String, + pub damage_per_attack: f64, + pub damage_per_turn: f64, + pub 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 - expected_armor_break_per_turn: f64, + pub expected_armor_break_per_turn: f64, + /// Dps with two actions and 5 dices + pub dps_safe: f64, + // /// Dps with four actions and 11 dices + // pub dps_unsafe: f64, // All other criterias are already in the inner as raw criterias } impl From<&InnerEquipementStats> for AdvancedStats { @@ -105,11 +170,13 @@ impl From<&InnerEquipementStats> for AdvancedStats { let damage_per_attack = (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack); + let damage_matrix = DamageMatrix::calculate_for(value); Self { + category: value.macro_category.clone(), display_name: value.name.join(" "), damage_per_attack, damage_per_turn: damage_per_attack * 2., - damage_per_action: damage_per_attack / (value.action_cost as f64), + max_damage_per_action: damage_per_attack / (value.action_cost as f64), armor_break_per_attack, armor_break_per_turn: armor_break_per_attack * 2., armor_break_per_action: armor_break_per_attack / value.action_cost as f64, @@ -117,8 +184,9 @@ impl From<&InnerEquipementStats> for AdvancedStats { // Adds the base strength, substracts the expected protection expected_armor_break_per_turn: (damage_per_attack + 6. - 8.) .min(armor_break_per_attack), - damage_matrix: value.into(), - // armor_break_matrix: , + dps_safe: damage_matrix.get_safe_dmg(value.action_cost), + // dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), + damage_matrix, } } } @@ -127,7 +195,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { /// /// This simulation does only calculate a very limited preset of damage values #[cfg_attr(test, derive(Debug))] -struct DamageMatrix { +pub struct DamageMatrix { /// The inner damage matrix damage_matrix: Vec, } @@ -136,6 +204,27 @@ impl DamageMatrix { pub fn get_damage(&self, precision: Precision, dices: DiceNumber) -> f64 { self.damage_matrix[precision as usize + 3 * dices as usize] } + + /// The "safe" damage, as in 5 dices, 2 attacks + // TODO: This safe damage actually uses 5 dices * 2 instead of doing max(5 * 1 , 2 * 1 + 3 * 1) + pub fn get_safe_dmg(&self, attack_cost: i8) -> f64 { + let _ = attack_cost; + (self.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 @@ -172,8 +261,9 @@ impl Display for DamageMatrix { } } -impl From<&InnerEquipementStats> for DamageMatrix { - fn from(value: &InnerEquipementStats) -> Self { +impl DamageMatrix { + /// Calculate the DamageMatrix for a given InnerEquipementStats + fn calculate_for(value: &InnerEquipementStats) -> Self { DamageMatrix { damage_matrix: (DiceNumber::iter() .flat_map(|dices| { @@ -189,17 +279,23 @@ impl From<&InnerEquipementStats> for DamageMatrix { } /// Calculate the binomial distribution and average the damage from there -fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, dices: usize) -> f64 { - let p = ((precision as i8 + value.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); +fn binomial_dice_distribution( + equipement: &InnerEquipementStats, + precision: usize, + dices: usize, +) -> f64 { + let p = ((precision as i8 + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); let binomial = Binomial::new(dices, p); (0..dices + 1) .map(|target_dices| { let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize; if target_dices >= 1 { - (value.damage as f64 - + value.p_damage as f64 - * (target_dices.clamp(0, value.rmax as usize).saturating_sub(1)) as f64) + (equipement.damage as f64 + + equipement.p_damage as f64 + * (target_dices + .clamp(0, equipement.rmax as usize) + .saturating_sub(1)) as f64) * probability_success } else { 0. @@ -208,6 +304,8 @@ fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, di .fold(0., |a, b| a + b) } +// TODO: Change this to be a thin type and replace enum by new(nb) et high(), med() etc.. +// : And add a way to do ranges easily /// The precision infered for a damage calculation event #[derive(EnumIter, Clone, Copy, Display)] #[allow(clippy::missing_docs_in_private_items)] @@ -233,7 +331,7 @@ impl Precision { match self { Precision::High => 9, Precision::Medium => 6, - Precision::Low => 3, + Precision::Low => 4, } } } @@ -259,7 +357,7 @@ mod test { #[test] fn test_binomial() { let damage = new_inner_eq(); - let mat: DamageMatrix = DamageMatrix::from(&damage); + let mat: DamageMatrix = DamageMatrix::calculate_for(&damage); println!("{:#?}", damage); println!("{:#?}", mat); } @@ -277,7 +375,7 @@ mod test { #[test] fn test_creation() { - let mat = DamageMatrix::from(&new_inner_eq()); + let mat = DamageMatrix::calculate_for(&new_inner_eq()); println!("{}", mat); println!( "(High,Many): {}, (Low,Few): {}", diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 4e199f4..4c069e9 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -16,7 +16,10 @@ use crate::interfaces::{FilterFunction, Reportable}; use super::{ Equipement, InitialEquipementList, equipement_advanced_repr::RefinedEquipementList, - equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, + equipement_structs::{ + EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats, + filter_id_unique_and_right_category, + }, }; impl From for Equipement { @@ -31,55 +34,21 @@ impl From for Equipement { fn from(val: EqMaterial) -> Self { Self { stats: val.stats, - ..Default::default() + filter_function: FilterFunction::new(filter_id_unique_and_right_category()), } } } -// TODO: Change this into tryfrom impl From for Equipement { fn from(val: EqNature) -> Self { Self { stats: val.stats, - // TODO : Checks that this is exactly desired behavious - // :Also check for Cross Weapon/Armor contamination // Checks that the nature is compatible with the previous iteration - filter_function: FilterFunction::new(&|sel, lhs| { - // println!( - // "Trying to match {:?} with {:?}. {:?} {:?}", - // sel.name, lhs.name, sel.target, lhs.macro_category - // ); - - match (&sel.target, &lhs.macro_category) { - // There is a specific target and the part about to be added has a category - (Some(a), Some(b)) => { - // println!("{} {}", a, b); - a == b - } - // There is no target and the part about to be added is generic - // TODO: Unsound to have a generic nature, this should be caught at serialisation - (None, _) => panic!("The EqNature about to be added cannot be generic"), - // There is a specific target but the part about to be added is generic - // TODO: Impossible - (Some(_), None) => panic!("The part about to be added unto cannot be generic"), - // // There is restriction on the target and the recipient - // (None, Some(_)) => true, - } - }), + filter_function: FilterFunction::new(filter_id_unique_and_right_category()), } } } -// (Some(a), Some(b)) => { -// println!("{} {}", a, b); -// a == b -// } -// // There is no target and the part about to be added is generic -// (None, None) => true, -// // There is a specific target but the part about to be added is generic -// (Some(_), None) => true, -// // There is restriction on the target and the recipient -// (None, Some(_)) => true, impl From for Equipement { fn from(val: EqFinishing) -> Self { Self { diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index ebc47db..7f4ef60 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -61,6 +61,7 @@ pub struct EquipementFixedRecipe { #[allow(missing_docs)] pub struct MockRecipe {} +// TODO[1] : Add fixed recipes impl FixedRecipe for EquipementFixedRecipe { type KeyList = MockRecipe; @@ -73,6 +74,7 @@ impl FixedRecipe for EquipementFixedRecipe { } } +// TODO[3]: Migrate ASAP from this manual implementation /// Macro converting a value using serde and mapping an in house error macro_rules! from_serde { ($value: expr) => { diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs index ee62cf8..e7a5215 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -2,11 +2,9 @@ // File: weaponry/src/weaponry_structs/equipement_impl_io.rs //! All implementation IO specific (mainly export and serde) -use std::path::Path; - -use crate::interfaces::ToCSV; - use super::equipement_advanced_repr::RefinedEquipementList; +use crate::interfaces::ToCSV; +use std::path::Path; impl ToCSV for RefinedEquipementList { fn write_csv(&self, path: &Path) -> csv::Result<()> { diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 5e11109..4e180cb 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -7,52 +7,48 @@ //! and therefore mostly serves as a TO-DO list //! -#![allow(dead_code)] -use crate::error::FatalEquipementError; -#[allow(unused_imports)] -use crate::interfaces::Reportable; -use crate::weaponry_structs::InitialEquipementList; -use crate::weaponry_structs::equipement_structs::DatabaseEquipementStats; -use crate::weaponry_structs::equipement_structs::EqFinishing; -use crate::weaponry_structs::equipement_structs::EqMaterial; -use crate::weaponry_structs::equipement_structs::EqNature; -use crate::weaponry_structs::equipement_structs::EqShape; use crate::{ - error::EquipementError, - interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable}, + error::FatalEquipementError, + interfaces::{RecipeCollection, RecipeDatabase, Scenario}, + weaponry_structs::{ + Equipement, InitialEquipementList, RefinedEquipementList, + equipement_impl_database::EquipementDatabase, + equipement_structs::{ + DatabaseEquipementStats, EqFinishing, EqMaterial, EqNature, EqShape, + InnerEquipementStats, + }, + }, }; -use super::Equipement; -use super::equipement_advanced_repr::RefinedEquipementList; -use super::equipement_impl_database::EquipementDatabase; -use super::equipement_structs::InnerEquipementStats; - -/// Mock config -pub struct ConfigMock {} -/// Mock Viewtable -pub struct ViewtableMock {} -impl ViewTable for ViewtableMock { - type InterestElementList = RefinedEquipementList; - - fn index_of_interest_points(&self) -> Vec { - todo!() - } - - fn find_points_of_interest(representation: &Self::InterestElementList) -> Self { - let _ = representation; - todo!() - } +/// Base Equipement Scenario config +pub struct ConfigEquipementScenario { + /// Table Name + pub table_name: String, + /// Database path + pub db_path: String, + // TODO[2]: Add something smart here to take care of the selection process + /// Wether the shapes are selected + pub shape: Option<()>, + /// Wether the materials are selected, and how many iteration there are + pub materials: Option, + /// Wether the natures are selected + pub nature: Option<()>, + /// Wether the finishing touches are selected + pub finishing: Option<()>, } /// A simple cross recipe scenario #[allow(clippy::missing_docs_in_private_items)] pub struct CrossRecipeScenario { + // TODO: Should obv be inside the config database: EquipementDatabase, - config: ConfigMock, + config: ConfigEquipementScenario, } impl CrossRecipeScenario { /// Automatically deserialize into an equipement + // TODO: Add to trait + // TODO: Add an optionnal filter fn deserde_into_equipement( &self, name: &str, @@ -60,10 +56,12 @@ impl CrossRecipeScenario { where T: TryFrom + From + Into, { + // TODO: This likely has too high a complexity and should either be a blanket implementation + // : or require the inner workings to implement methods to easily allow this deserialisation Ok(InitialEquipementList::from_vectored( self.database .serialize_vec_from_table::( - &name, + &self.config.table_name, Some(&format!("META_CATEGORY LIKE '{}'", name)), )? .into_iter() @@ -75,60 +73,59 @@ impl CrossRecipeScenario { .collect::, FatalEquipementError>>()?, )) } + + /// Generate all the operations to be processed with the current config + // TODO: Defer this to a custom type in the config some sort of OperationSelector + fn generate_selected_operation( + &self, + ) -> Result, FatalEquipementError> { + let mut operations = Vec::with_capacity(8); + if self.config.shape.is_some() { + operations.push(self.deserde_into_equipement::("Shape")?); + } + if let Some(qt) = self.config.materials { + for _ in 0..qt { + operations.push(self.deserde_into_equipement::("Materials")?); + } + } + if self.config.nature.is_some() { + operations.push(self.deserde_into_equipement::("Nature")?); + } + if self.config.finishing.is_some() { + operations.push(self.deserde_into_equipement::("Finishing")?); + } + if operations.is_empty() { + return Err(FatalEquipementError::CLISelection( + "No step was selected for generation, please select at least one step".into(), + )); + }; + Ok(operations) + } } impl Scenario for CrossRecipeScenario { type DatabaseType = EquipementDatabase; - type ViewTableType = ViewtableMock; type FinalListType = RefinedEquipementList; - type Config = ConfigMock; + type Config = ConfigEquipementScenario; - fn new_with_config(config: Self::Config) -> Result + fn new_with_config(config: Self::Config) -> Result where Self: Sized, { Ok(Self { - // TODO: Correct this relative path abomination - database: Self::DatabaseType::new("./databases/weapons.db")?, + database: Self::DatabaseType::new(&config.db_path)?, config, }) } - fn generate_refined_recipes(&self) -> Result { - // TODO: Depending on config, a different filter might be given here - let eq_shape = self.deserde_into_equipement::("Shape")?; - let eq_material = self.deserde_into_equipement::("Materials")?; - let eq_nature = self.deserde_into_equipement::("Nature")?; - #[allow(unused_variables)] - let eq_finishing = self.deserde_into_equipement::("Finishing")?; + fn generate_refined_recipes(&self) -> Result { + let operations = self.generate_selected_operation()?; - // println!( - // "{}\n{}\n{}\n{}", - // eq_shape.get_report(Some("EqShape ")), - // eq_material.get_report(Some("EqMaterials")), - // eq_nature.get_report(Some("EqNature ")), - // eq_finishing.get_report(Some("EqFinishing")) - // ); + let mut opertation_it = operations.into_iter(); + let mut refined_list = opertation_it.next().unwrap(); - // No op, just clarity - // TODO: Depending on config this step might differ - let mut f_list = eq_shape; - // println!("{}", f_list.get_report(Some("Initial Weapons "))); - f_list.combine_all(&eq_material); - // println!("{}", f_list.get_report(Some("Combined with Materials"))); - f_list.combine_all(&eq_nature); - // println!("{}", f_list.get_report(Some("Combined with Natures "))); - // f_list.combine_all(&eq_finishing); - // println!("{}", f_list.get_report(Some("Combined with Finishing"))); - // TODO: The finishes are interesting if they are configured or at least tamed a little - // TODO: As a high cost finish cannot hope to compete with a low one - // TODO: and therefore need a special metric and fixed entry data to be mesured - Ok(f_list.into()) - } + opertation_it.for_each(|operation| refined_list.combine_all(&operation)); - fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType { - // TODO: Change this depending on the config ? or maybe a scenario is inerently tied to a viewtable ? - // The polymorphism will depend on many factors not yet known :( - Self::ViewTableType::find_points_of_interest(&equipement_list) + Ok(refined_list.into()) } } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 4e92388..15ceb05 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -33,18 +33,45 @@ pub struct Equipement { impl Default for Equipement { fn default() -> Self { Self { - filter_function: FilterFunction::new(default_filter()), + filter_function: FilterFunction::new(filter_id_unique()), stats: InnerEquipementStats::random_new(), } } } /// The default filter to use, usefull to implement a new filter function that also uses the default filter -pub(crate) fn default_filter() +pub(crate) fn filter_id_unique() -> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { - &|self_, lhs| !self_.id.iter().any(|a| *a == lhs.id[0]) + &|self_, lhs| lhs.id.iter().all(|a| *a != self_.id[0]) } +/// Create a new filter function mandating the object be of the right category +pub(crate) fn filter_id_unique_and_right_category() +-> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { + &|sel, lhs| { + // println!( + // "Trying to match {:?} with {:?}. {:?} {:?}", + // sel.name, lhs.name, sel.target, lhs.macro_category + // ); + lhs.id.iter().all(|a| *a != sel.id[0]) + & match (&sel.target, &lhs.macro_category) { + // There is a specific target and the part about to be added has a category + (Some(a), Some(b)) => { + // println!("{} {}", a, b); + a == b + } + // There is no target and the part about to be added is generic + // TODO: Unsound to have a generic nature, this should be caught at serialisation + // TODO: Testing a generic anyway + (None, _) => true, // panic!("The EqNature about to be added cannot be generic"), + // There is a specific target but the part about to be added is generic + // TODO: Impossible + (Some(_), None) => panic!("The part about to be added unto cannot be generic"), + // // There is restriction on the target and the recipient + // (None, Some(_)) => true, + } + } +} impl FilterFunction { /// Generate a new filter // TODO: This static lifetime is basically telling us that an owned value is needed @@ -281,8 +308,7 @@ impl From for EqFinishing { #[cfg(test)] mod test { use super::{ - EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, - InnerEquipementStats, + EqFinishing, EqMaterial, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, }; use crate::interfaces::RecipeCollection; diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index f347a40..5a09399 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -33,6 +33,7 @@ pub use equipement_structs::{Equipement, InitialEquipementList}; // All generic fields // #[allow(unused_imports)] +pub use crate::weaponry_structs::equipement_advanced_repr::RefinedEquipementList; pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{ DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMacroCategory,